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