ConversationsOverviewFragment.java

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