1/*
2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without modification,
5 * are permitted provided that the following conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above copyright notice, this
8 * list of conditions and the following disclaimer.
9 *
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation and/or
12 * other materials provided with the distribution.
13 *
14 * 3. Neither the name of the copyright holder nor the names of its contributors
15 * may be used to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30package eu.siacs.conversations.ui;
31
32import android.app.Activity;
33import android.app.AlertDialog;
34import android.app.Fragment;
35import android.content.Intent;
36import android.graphics.Canvas;
37import android.graphics.Paint;
38import android.os.Bundle;
39import android.util.Log;
40import android.view.LayoutInflater;
41import android.view.Menu;
42import android.view.MenuInflater;
43import android.view.MenuItem;
44import android.view.View;
45import android.view.ViewGroup;
46import android.widget.Toast;
47
48import androidx.databinding.DataBindingUtil;
49import androidx.recyclerview.widget.ItemTouchHelper;
50import androidx.recyclerview.widget.LinearLayoutManager;
51import androidx.recyclerview.widget.RecyclerView;
52
53import com.google.android.material.snackbar.Snackbar;
54import com.google.common.collect.Collections2;
55
56import java.util.ArrayList;
57import java.util.List;
58import java.util.concurrent.atomic.AtomicReference;
59
60import eu.siacs.conversations.Config;
61import eu.siacs.conversations.R;
62import eu.siacs.conversations.databinding.FragmentConversationsOverviewBinding;
63import eu.siacs.conversations.entities.Account;
64import eu.siacs.conversations.entities.Conversation;
65import eu.siacs.conversations.entities.Conversational;
66import eu.siacs.conversations.ui.adapter.ConversationAdapter;
67import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
68import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
69import eu.siacs.conversations.ui.util.MenuDoubleTabUtil;
70import eu.siacs.conversations.ui.util.PendingActionHelper;
71import eu.siacs.conversations.ui.util.PendingItem;
72import eu.siacs.conversations.ui.util.ScrollState;
73import eu.siacs.conversations.ui.util.StyledAttributes;
74import eu.siacs.conversations.utils.AccountUtils;
75import eu.siacs.conversations.utils.EasyOnboardingInvite;
76import eu.siacs.conversations.utils.ThemeHelper;
77
78import static androidx.recyclerview.widget.ItemTouchHelper.LEFT;
79import static androidx.recyclerview.widget.ItemTouchHelper.RIGHT;
80
81public class ConversationsOverviewFragment extends XmppFragment {
82
83 private static final String STATE_SCROLL_POSITION = ConversationsOverviewFragment.class.getName()+".scroll_state";
84
85 private final List<Conversation> conversations = new ArrayList<>();
86 private final PendingItem<Conversation> swipedConversation = new PendingItem<>();
87 private final PendingItem<ScrollState> pendingScrollState = new PendingItem<>();
88 private FragmentConversationsOverviewBinding binding;
89 private ConversationAdapter conversationsAdapter;
90 private XmppActivity activity;
91 private float mSwipeEscapeVelocity = 0f;
92 private final PendingActionHelper pendingActionHelper = new PendingActionHelper();
93
94 private final ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0,LEFT|RIGHT) {
95 @Override
96 public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
97 //todo maybe we can manually changing the position of the conversation
98 return false;
99 }
100
101 @Override
102 public float getSwipeEscapeVelocity (float defaultValue) {
103 return mSwipeEscapeVelocity;
104 }
105
106 @Override
107 public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
108 float dX, float dY, int actionState, boolean isCurrentlyActive) {
109 super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
110 if(actionState != ItemTouchHelper.ACTION_STATE_IDLE){
111 Paint paint = new Paint();
112 paint.setColor(StyledAttributes.getColor(activity,R.attr.conversations_overview_background));
113 paint.setStyle(Paint.Style.FILL);
114 c.drawRect(viewHolder.itemView.getLeft(),viewHolder.itemView.getTop()
115 ,viewHolder.itemView.getRight(),viewHolder.itemView.getBottom(), paint);
116 }
117 }
118
119 @Override
120 public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
121 super.clearView(recyclerView, viewHolder);
122 viewHolder.itemView.setAlpha(1f);
123 }
124
125 @Override
126 public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
127 pendingActionHelper.execute();
128 int position = viewHolder.getLayoutPosition();
129 try {
130 swipedConversation.push(conversations.get(position));
131 } catch (IndexOutOfBoundsException e) {
132 return;
133 }
134 conversationsAdapter.remove(swipedConversation.peek(), position);
135 activity.xmppConnectionService.markRead(swipedConversation.peek());
136
137 if (position == 0 && conversationsAdapter.getItemCount() == 0) {
138 final Conversation c = swipedConversation.pop();
139 activity.xmppConnectionService.archiveConversation(c);
140 return;
141 }
142 final boolean formerlySelected = ConversationFragment.getConversation(getActivity()) == swipedConversation.peek();
143 if (activity instanceof OnConversationArchived) {
144 ((OnConversationArchived) activity).onConversationArchived(swipedConversation.peek());
145 }
146 final Conversation c = swipedConversation.peek();
147 final int title;
148 if (c.getMode() == Conversational.MODE_MULTI) {
149 if (c.getMucOptions().isPrivateAndNonAnonymous()) {
150 title = R.string.title_undo_swipe_out_group_chat;
151 } else {
152 title = R.string.title_undo_swipe_out_channel;
153 }
154 } else {
155 title = R.string.title_undo_swipe_out_conversation;
156 }
157
158 final Snackbar snackbar = Snackbar.make(binding.list, title, 5000)
159 .setAction(R.string.undo, v -> {
160 pendingActionHelper.undo();
161 Conversation conversation = swipedConversation.pop();
162 conversationsAdapter.insert(conversation, position);
163 if (formerlySelected) {
164 if (activity instanceof OnConversationSelected) {
165 ((OnConversationSelected) activity).onConversationSelected(c);
166 }
167 }
168 LinearLayoutManager layoutManager = (LinearLayoutManager) binding.list.getLayoutManager();
169 if (position > layoutManager.findLastVisibleItemPosition()) {
170 binding.list.smoothScrollToPosition(position);
171 }
172 })
173 .addCallback(new Snackbar.Callback() {
174 @Override
175 public void onDismissed(Snackbar transientBottomBar, int event) {
176 switch (event) {
177 case DISMISS_EVENT_SWIPE:
178 case DISMISS_EVENT_TIMEOUT:
179 pendingActionHelper.execute();
180 break;
181 }
182 }
183 });
184
185 pendingActionHelper.push(() -> {
186 if (snackbar.isShownOrQueued()) {
187 snackbar.dismiss();
188 }
189 final Conversation conversation = swipedConversation.pop();
190 if(conversation != null){
191 if (!conversation.isRead() && conversation.getMode() == Conversation.MODE_SINGLE) {
192 return;
193 }
194 activity.xmppConnectionService.archiveConversation(c);
195 }
196 });
197
198 ThemeHelper.fix(snackbar);
199 snackbar.show();
200 }
201 };
202
203 private ItemTouchHelper touchHelper;
204
205 public static Conversation getSuggestion(Activity activity) {
206 final Conversation exception;
207 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
208 if (fragment instanceof ConversationsOverviewFragment) {
209 exception = ((ConversationsOverviewFragment) fragment).swipedConversation.peek();
210 } else {
211 exception = null;
212 }
213 return getSuggestion(activity, exception);
214 }
215
216 public static Conversation getSuggestion(Activity activity, Conversation exception) {
217 Fragment fragment = activity.getFragmentManager().findFragmentById(R.id.main_fragment);
218 if (fragment instanceof ConversationsOverviewFragment) {
219 List<Conversation> conversations = ((ConversationsOverviewFragment) fragment).conversations;
220 if (conversations.size() > 0) {
221 Conversation suggestion = conversations.get(0);
222 if (suggestion == exception) {
223 if (conversations.size() > 1) {
224 return conversations.get(1);
225 }
226 } else {
227 return suggestion;
228 }
229 }
230 }
231 return null;
232
233 }
234
235 @Override
236 public void onActivityCreated(Bundle savedInstanceState) {
237 super.onActivityCreated(savedInstanceState);
238 if (savedInstanceState == null) {
239 return;
240 }
241 pendingScrollState.push(savedInstanceState.getParcelable(STATE_SCROLL_POSITION));
242 }
243
244 @Override
245 public void onAttach(Activity activity) {
246 super.onAttach(activity);
247 if (activity instanceof XmppActivity) {
248 this.activity = (XmppActivity) activity;
249 } else {
250 throw new IllegalStateException("Trying to attach fragment to activity that is not an XmppActivity");
251 }
252 }
253 @Override
254 public void onDestroyView() {
255 Log.d(Config.LOGTAG,"ConversationsOverviewFragment.onDestroyView()");
256 super.onDestroyView();
257 this.binding = null;
258 this.conversationsAdapter = null;
259 this.touchHelper = null;
260 }
261 @Override
262 public void onDestroy() {
263 Log.d(Config.LOGTAG,"ConversationsOverviewFragment.onDestroy()");
264 super.onDestroy();
265
266 }
267 @Override
268 public void onPause() {
269 Log.d(Config.LOGTAG,"ConversationsOverviewFragment.onPause()");
270 pendingActionHelper.execute();
271 super.onPause();
272 }
273
274 @Override
275 public void onDetach() {
276 super.onDetach();
277 this.activity = null;
278 }
279
280 @Override
281 public void onCreate(Bundle savedInstanceState) {
282 super.onCreate(savedInstanceState);
283 setHasOptionsMenu(true);
284 }
285
286 @Override
287 public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
288 this.mSwipeEscapeVelocity = getResources().getDimension(R.dimen.swipe_escape_velocity);
289 this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversations_overview, container, false);
290 this.binding.fab.setOnClickListener((view) -> StartConversationActivity.launch(getActivity()));
291
292 this.conversationsAdapter = new ConversationAdapter(this.activity, this.conversations);
293 this.conversationsAdapter.setConversationClickListener((view, conversation) -> {
294 if (activity instanceof OnConversationSelected) {
295 ((OnConversationSelected) activity).onConversationSelected(conversation);
296 } else {
297 Log.w(ConversationsOverviewFragment.class.getCanonicalName(), "Activity does not implement OnConversationSelected");
298 }
299 });
300 this.binding.list.setAdapter(this.conversationsAdapter);
301 this.binding.list.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
302 this.touchHelper = new ItemTouchHelper(this.callback);
303 this.touchHelper.attachToRecyclerView(this.binding.list);
304 return binding.getRoot();
305 }
306
307 @Override
308 public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
309 menuInflater.inflate(R.menu.fragment_conversations_overview, menu);
310 AccountUtils.showHideMenuItems(menu);
311 final MenuItem easyOnboardInvite = menu.findItem(R.id.action_easy_invite);
312 easyOnboardInvite.setVisible(EasyOnboardingInvite.anyHasSupport(activity == null ? null : activity.xmppConnectionService));
313 }
314
315 @Override
316 public void onBackendConnected() {
317 refresh();
318 }
319
320 @Override
321 public void onSaveInstanceState(Bundle bundle) {
322 super.onSaveInstanceState(bundle);
323 ScrollState scrollState = getScrollState();
324 if (scrollState != null) {
325 bundle.putParcelable(STATE_SCROLL_POSITION, scrollState);
326 }
327 }
328
329 private ScrollState getScrollState() {
330 if (this.binding == null) {
331 return null;
332 }
333 LinearLayoutManager layoutManager = (LinearLayoutManager) this.binding.list.getLayoutManager();
334 int position = layoutManager.findFirstVisibleItemPosition();
335 final View view = this.binding.list.getChildAt(0);
336 if (view != null) {
337 return new ScrollState(position,view.getTop());
338 } else {
339 return new ScrollState(position, 0);
340 }
341 }
342
343 @Override
344 public void onStart() {
345 super.onStart();
346 Log.d(Config.LOGTAG, "ConversationsOverviewFragment.onStart()");
347 if (activity.xmppConnectionService != null) {
348 refresh();
349 }
350 }
351
352 @Override
353 public void onResume() {
354 super.onResume();
355 Log.d(Config.LOGTAG, "ConversationsOverviewFragment.onResume()");
356 }
357
358 @Override
359 public boolean onOptionsItemSelected(final MenuItem item) {
360 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
361 return false;
362 }
363 switch (item.getItemId()) {
364 case R.id.action_search:
365 startActivity(new Intent(getActivity(), SearchActivity.class));
366 return true;
367 case R.id.action_easy_invite:
368 selectAccountToStartEasyInvite();
369 return true;
370 }
371 return super.onOptionsItemSelected(item);
372 }
373
374 private void selectAccountToStartEasyInvite() {
375 final List<Account> accounts = EasyOnboardingInvite.getSupportingAccounts(activity.xmppConnectionService);
376 if (accounts.size() == 0) {
377 //This can technically happen if opening the menu item races with accounts reconnecting or something
378 Toast.makeText(getActivity(),R.string.no_active_accounts_support_this, Toast.LENGTH_LONG).show();
379 } else if (accounts.size() == 1) {
380 openEasyInviteScreen(accounts.get(0));
381 } else {
382 final AtomicReference<Account> selectedAccount = new AtomicReference<>(accounts.get(0));
383 final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
384 alertDialogBuilder.setTitle(R.string.choose_account);
385 final String[] asStrings = Collections2.transform(accounts, a -> a.getJid().asBareJid().toEscapedString()).toArray(new String[0]);
386 alertDialogBuilder.setSingleChoiceItems(asStrings, 0, (dialog, which) -> selectedAccount.set(accounts.get(which)));
387 alertDialogBuilder.setNegativeButton(R.string.cancel, null);
388 alertDialogBuilder.setPositiveButton(R.string.ok, (dialog, which) -> openEasyInviteScreen(selectedAccount.get()));
389 alertDialogBuilder.create().show();
390 }
391 }
392
393 private void openEasyInviteScreen(final Account account) {
394 EasyOnboardingInviteActivity.launch(account, activity);
395 }
396
397 @Override
398 void refresh() {
399 if (this.binding == null || this.activity == null) {
400 Log.d(Config.LOGTAG,"ConversationsOverviewFragment.refresh() skipped updated because view binding or activity was null");
401 return;
402 }
403 this.activity.xmppConnectionService.populateWithOrderedConversations(this.conversations);
404 Conversation removed = this.swipedConversation.peek();
405 if (removed != null) {
406 if (removed.isRead()) {
407 this.conversations.remove(removed);
408 } else {
409 pendingActionHelper.execute();
410 }
411 }
412 this.conversationsAdapter.notifyDataSetChanged();
413 ScrollState scrollState = pendingScrollState.pop();
414 if (scrollState != null) {
415 setScrollPosition(scrollState);
416 }
417 }
418
419 private void setScrollPosition(ScrollState scrollPosition) {
420 if (scrollPosition != null) {
421 LinearLayoutManager layoutManager = (LinearLayoutManager) binding.list.getLayoutManager();
422 layoutManager.scrollToPositionWithOffset(scrollPosition.position, scrollPosition.offset);
423 }
424 }
425}