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