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 }
320
321 @Override
322 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
323 activity.getMenuInflater().inflate(R.menu.conversations, menu);
324
325 final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
326 final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
327 final MenuItem menuMute = menu.findItem(R.id.action_mute);
328 final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
329 final MenuItem menuOngoingCall = menu.findItem(R.id.action_ongoing_call);
330 final MenuItem menuTogglePinned = menu.findItem(R.id.action_toggle_pinned);
331
332 int pos = ((AdapterContextMenuInfo) menuInfo).position;
333 if (pos < 0) return;
334 Conversation conversation = conversations.get(pos);
335 if (conversation != null) {
336 if (conversation.getMode() == Conversation.MODE_MULTI) {
337 menuContactDetails.setVisible(false);
338 menuMucDetails.setTitle(conversation.getMucOptions().isPrivateAndNonAnonymous() ? R.string.action_muc_details : R.string.channel_details);
339 menuOngoingCall.setVisible(false);
340 } else {
341 final XmppConnectionService service = activity == null ? null : activity.xmppConnectionService;
342 final Optional<OngoingRtpSession> ongoingRtpSession = service == null ? Optional.absent() : service.getJingleConnectionManager().getOngoingRtpConnection(conversation.getContact());
343 if (ongoingRtpSession.isPresent()) {
344 menuOngoingCall.setVisible(true);
345 } else {
346 menuOngoingCall.setVisible(false);
347 }
348 menuContactDetails.setVisible(!conversation.withSelf());
349 menuMucDetails.setVisible(false);
350 }
351 if (conversation.isMuted()) {
352 menuMute.setVisible(false);
353 } else {
354 menuUnmute.setVisible(false);
355 }
356 if (conversation.getBooleanAttribute(Conversation.ATTRIBUTE_PINNED_ON_TOP, false)) {
357 menuTogglePinned.setTitle(R.string.remove_from_favorites);
358 } else {
359 menuTogglePinned.setTitle(R.string.add_to_favorites);
360 }
361 }
362 super.onCreateContextMenu(menu, view, menuInfo);
363 }
364
365 @Override
366 public boolean onContextItemSelected(MenuItem item) {
367 int pos = ((AdapterContextMenuInfo) item.getMenuInfo()).position;
368 if (conversations == null || conversations.size() < pos || pos < 0) return false;
369
370 Conversation conversation = conversations.get(((AdapterContextMenuInfo) item.getMenuInfo()).position);
371 ConversationFragment fragment = new ConversationFragment();
372 fragment.setHasOptionsMenu(false);
373 fragment.onAttach(activity);
374 fragment.reInit(conversation, null);
375 boolean r = fragment.onOptionsItemSelected(item);
376 refresh();
377 return r;
378 }
379
380 @Override
381 public void onBackendConnected() {
382 refresh();
383 }
384
385 @Override
386 public void onSaveInstanceState(Bundle bundle) {
387 super.onSaveInstanceState(bundle);
388 ScrollState scrollState = getScrollState();
389 if (scrollState != null) {
390 bundle.putParcelable(STATE_SCROLL_POSITION, scrollState);
391 }
392 }
393
394 private ScrollState getScrollState() {
395 if (this.binding == null) {
396 return null;
397 }
398 LinearLayoutManager layoutManager = (LinearLayoutManager) this.binding.list.getLayoutManager();
399 int position = layoutManager.findFirstVisibleItemPosition();
400 final View view = this.binding.list.getChildAt(0);
401 if (view != null) {
402 return new ScrollState(position,view.getTop());
403 } else {
404 return new ScrollState(position, 0);
405 }
406 }
407
408 @Override
409 public void onStart() {
410 super.onStart();
411 Log.d(Config.LOGTAG, "ConversationsOverviewFragment.onStart()");
412 if (activity.xmppConnectionService != null) {
413 refresh();
414 }
415 }
416
417 @Override
418 public void onResume() {
419 super.onResume();
420 Log.d(Config.LOGTAG, "ConversationsOverviewFragment.onResume()");
421 }
422
423 @Override
424 public boolean onOptionsItemSelected(final MenuItem item) {
425 if (MenuDoubleTabUtil.shouldIgnoreTap()) {
426 return false;
427 }
428 switch (item.getItemId()) {
429 case R.id.action_search:
430 startActivity(new Intent(getActivity(), SearchActivity.class));
431 return true;
432 case R.id.action_easy_invite:
433 selectAccountToStartEasyInvite();
434 return true;
435 }
436 return super.onOptionsItemSelected(item);
437 }
438
439 private void selectAccountToStartEasyInvite() {
440 final List<Account> accounts = EasyOnboardingInvite.getSupportingAccounts(activity.xmppConnectionService);
441 if (accounts.size() == 0) {
442 //This can technically happen if opening the menu item races with accounts reconnecting or something
443 Toast.makeText(getActivity(),R.string.no_active_accounts_support_this, Toast.LENGTH_LONG).show();
444 } else if (accounts.size() == 1) {
445 openEasyInviteScreen(accounts.get(0));
446 } else {
447 final AtomicReference<Account> selectedAccount = new AtomicReference<>(accounts.get(0));
448 final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
449 alertDialogBuilder.setTitle(R.string.choose_account);
450 final String[] asStrings = Collections2.transform(accounts, a -> a.getJid().asBareJid().toEscapedString()).toArray(new String[0]);
451 alertDialogBuilder.setSingleChoiceItems(asStrings, 0, (dialog, which) -> selectedAccount.set(accounts.get(which)));
452 alertDialogBuilder.setNegativeButton(R.string.cancel, null);
453 alertDialogBuilder.setPositiveButton(R.string.ok, (dialog, which) -> openEasyInviteScreen(selectedAccount.get()));
454 alertDialogBuilder.create().show();
455 }
456 }
457
458 private void openEasyInviteScreen(final Account account) {
459 EasyOnboardingInviteActivity.launch(account, activity);
460 }
461
462 @Override
463 void refresh() {
464 if (this.binding == null || this.activity == null) {
465 Log.d(Config.LOGTAG,"ConversationsOverviewFragment.refresh() skipped updated because view binding or activity was null");
466 return;
467 }
468 this.activity.xmppConnectionService.populateWithOrderedConversations(this.conversations);
469 Conversation removed = this.swipedConversation.peek();
470 if (removed != null) {
471 if (removed.isRead()) {
472 this.conversations.remove(removed);
473 } else {
474 pendingActionHelper.execute();
475 }
476 }
477 this.conversationsAdapter.notifyDataSetChanged();
478 ScrollState scrollState = pendingScrollState.pop();
479 if (scrollState != null) {
480 setScrollPosition(scrollState);
481 }
482 }
483
484 private void setScrollPosition(ScrollState scrollPosition) {
485 if (scrollPosition != null) {
486 LinearLayoutManager layoutManager = (LinearLayoutManager) binding.list.getLayoutManager();
487 layoutManager.scrollToPositionWithOffset(scrollPosition.position, scrollPosition.offset);
488 }
489 }
490}