1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
|
package it.niedermann.nextcloud.deck.ui;
import android.animation.AnimatorInflater;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteConstraintException;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupMenu;
import androidx.annotation.AnyThread;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.util.Pair;
import androidx.core.view.GravityCompat;
import androidx.core.view.ViewCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.preference.PreferenceManager;
import androidx.viewpager2.widget.ViewPager2;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayoutMediator;
import com.nextcloud.android.sso.AccountImporter;
import com.nextcloud.android.sso.exceptions.AccountImportCancelledException;
import com.nextcloud.android.sso.exceptions.NextcloudHttpRequestFailedException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import it.niedermann.android.crosstabdnd.CrossTabDragAndDrop;
import it.niedermann.android.tablayouthelper.TabLayoutHelper;
import it.niedermann.android.tablayouthelper.TabTitleGenerator;
import it.niedermann.nextcloud.deck.DeckApplication;
import it.niedermann.nextcloud.deck.DeckLog;
import it.niedermann.nextcloud.deck.R;
import it.niedermann.nextcloud.deck.api.IResponseCallback;
import it.niedermann.nextcloud.deck.api.ResponseCallback;
import it.niedermann.nextcloud.deck.databinding.ActivityMainBinding;
import it.niedermann.nextcloud.deck.databinding.NavHeaderMainBinding;
import it.niedermann.nextcloud.deck.exceptions.OfflineException;
import it.niedermann.nextcloud.deck.model.Account;
import it.niedermann.nextcloud.deck.model.Board;
import it.niedermann.nextcloud.deck.model.Stack;
import it.niedermann.nextcloud.deck.model.full.FullBoard;
import it.niedermann.nextcloud.deck.model.full.FullCard;
import it.niedermann.nextcloud.deck.model.full.FullStack;
import it.niedermann.nextcloud.deck.model.internal.FilterInformation;
import it.niedermann.nextcloud.deck.model.ocs.Capabilities;
import it.niedermann.nextcloud.deck.model.ocs.Version;
import it.niedermann.nextcloud.deck.persistence.sync.SyncManager;
import it.niedermann.nextcloud.deck.persistence.sync.adapters.db.util.WrappedLiveData;
import it.niedermann.nextcloud.deck.ui.about.AboutActivity;
import it.niedermann.nextcloud.deck.ui.accountswitcher.AccountSwitcherDialog;
import it.niedermann.nextcloud.deck.ui.archivedboards.ArchivedBoardsActvitiy;
import it.niedermann.nextcloud.deck.ui.board.ArchiveBoardListener;
import it.niedermann.nextcloud.deck.ui.board.DeleteBoardListener;
import it.niedermann.nextcloud.deck.ui.board.EditBoardDialogFragment;
import it.niedermann.nextcloud.deck.ui.board.EditBoardListener;
import it.niedermann.nextcloud.deck.ui.branding.BrandedActivity;
import it.niedermann.nextcloud.deck.ui.branding.BrandedAlertDialogBuilder;
import it.niedermann.nextcloud.deck.ui.branding.BrandedSnackbar;
import it.niedermann.nextcloud.deck.ui.card.CardAdapter;
import it.niedermann.nextcloud.deck.ui.card.EditActivity;
import it.niedermann.nextcloud.deck.ui.exception.ExceptionDialogFragment;
import it.niedermann.nextcloud.deck.ui.exception.ExceptionHandler;
import it.niedermann.nextcloud.deck.ui.filter.FilterDialogFragment;
import it.niedermann.nextcloud.deck.ui.filter.FilterViewModel;
import it.niedermann.nextcloud.deck.ui.pickstack.PickStackViewModel;
import it.niedermann.nextcloud.deck.ui.settings.SettingsActivity;
import it.niedermann.nextcloud.deck.ui.stack.DeleteStackDialogFragment;
import it.niedermann.nextcloud.deck.ui.stack.DeleteStackListener;
import it.niedermann.nextcloud.deck.ui.stack.EditStackDialogFragment;
import it.niedermann.nextcloud.deck.ui.stack.EditStackListener;
import it.niedermann.nextcloud.deck.ui.stack.OnScrollListener;
import it.niedermann.nextcloud.deck.ui.stack.StackAdapter;
import it.niedermann.nextcloud.deck.ui.stack.StackFragment;
import it.niedermann.nextcloud.deck.util.DrawerMenuUtil;
import static androidx.lifecycle.Transformations.distinctUntilChanged;
import static androidx.lifecycle.Transformations.map;
import static androidx.lifecycle.Transformations.switchMap;
import static it.niedermann.nextcloud.deck.DeckApplication.NO_ACCOUNT_ID;
import static it.niedermann.nextcloud.deck.DeckApplication.NO_BOARD_ID;
import static it.niedermann.nextcloud.deck.DeckApplication.NO_STACK_ID;
import static it.niedermann.nextcloud.deck.DeckApplication.readCurrentAccountId;
import static it.niedermann.nextcloud.deck.DeckApplication.readCurrentBoardId;
import static it.niedermann.nextcloud.deck.DeckApplication.readCurrentStackId;
import static it.niedermann.nextcloud.deck.DeckApplication.saveCurrentAccount;
import static it.niedermann.nextcloud.deck.DeckApplication.saveCurrentBoardId;
import static it.niedermann.nextcloud.deck.DeckApplication.saveCurrentStackId;
import static it.niedermann.nextcloud.deck.persistence.sync.adapters.db.util.LiveDataHelper.observeOnce;
import static it.niedermann.nextcloud.deck.ui.branding.BrandingUtil.applyBrandToFAB;
import static it.niedermann.nextcloud.deck.ui.branding.BrandingUtil.applyBrandToPrimaryTabLayout;
import static it.niedermann.nextcloud.deck.ui.branding.BrandingUtil.clearBrandColors;
import static it.niedermann.nextcloud.deck.ui.branding.BrandingUtil.getSecondaryForegroundColorDependingOnTheme;
import static it.niedermann.nextcloud.deck.ui.branding.BrandingUtil.saveBrandColors;
import static it.niedermann.nextcloud.deck.util.DeckColorUtil.contrastRatioIsSufficient;
import static it.niedermann.nextcloud.deck.util.DeckColorUtil.contrastRatioIsSufficientBigAreas;
import static it.niedermann.nextcloud.deck.util.DrawerMenuUtil.MENU_ID_ABOUT;
import static it.niedermann.nextcloud.deck.util.DrawerMenuUtil.MENU_ID_ADD_BOARD;
import static it.niedermann.nextcloud.deck.util.DrawerMenuUtil.MENU_ID_ARCHIVED_BOARDS;
import static it.niedermann.nextcloud.deck.util.DrawerMenuUtil.MENU_ID_SETTINGS;
public class MainActivity extends BrandedActivity implements DeleteStackListener, EditStackListener, DeleteBoardListener, EditBoardListener, ArchiveBoardListener, OnScrollListener, OnNavigationItemSelectedListener {
protected ActivityMainBinding binding;
protected NavHeaderMainBinding headerBinding;
protected MainViewModel mainViewModel;
private FilterViewModel filterViewModel;
private PickStackViewModel pickStackViewModel;
protected static final int ACTIVITY_SETTINGS = 2;
@NonNull
protected List<Account> accountsList = new ArrayList<>();
protected SharedPreferences sharedPreferences;
private StackAdapter stackAdapter;
long lastBoardId;
@NonNull
private List<Board> boardsList = new ArrayList<>();
private LiveData<List<Board>> boardsLiveData;
private Observer<List<Board>> boardsLiveDataObserver;
private Menu listMenu;
private LiveData<List<Stack>> stacksLiveData;
private LiveData<Boolean> hasArchivedBoardsLiveData;
private Observer<Boolean> hasArchivedBoardsLiveDataObserver;
private boolean currentBoardHasStacks = false;
private int currentBoardStacksCount = 0;
private boolean firstAccountAdded = false;
private ConnectivityManager.NetworkCallback networkCallback;
private String addList;
private String addBoard;
@Nullable
private TabLayoutMediator mediator;
@Nullable
private TabLayoutHelper tabLayoutHelper;
private boolean stackMoved;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setTheme(R.style.AppTheme);
binding = ActivityMainBinding.inflate(getLayoutInflater());
headerBinding = NavHeaderMainBinding.bind(binding.navigationView.getHeaderView(0));
setContentView(binding.getRoot());
mainViewModel = new ViewModelProvider(this).get(MainViewModel.class);
filterViewModel = new ViewModelProvider(this).get(FilterViewModel.class);
pickStackViewModel = new ViewModelProvider(this).get(PickStackViewModel.class);
addList = getString(R.string.add_list);
addBoard = getString(R.string.add_board);
setSupportActionBar(binding.toolbar);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, binding.drawerLayout, binding.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
binding.drawerLayout.addDrawerListener(toggle);
toggle.syncState();
binding.navigationView.setNavigationItemSelectedListener(this);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
DeckApplication.readCurrentAccountColor().observe(this, (accountColor) -> {
headerBinding.headerView.setBackgroundColor(accountColor);
@ColorInt final int headerTextColor = contrastRatioIsSufficientBigAreas(accountColor, Color.WHITE) ? Color.WHITE : Color.BLACK;
DrawableCompat.setTint(headerBinding.logo.getDrawable(), headerTextColor);
DrawableCompat.setTint(headerBinding.copyDebugLogs.getDrawable(), headerTextColor);
});
binding.filterText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filterViewModel.setFilterText(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
mainViewModel.isDebugModeEnabled().observe(this, (enabled) -> headerBinding.copyDebugLogs.setVisibility(enabled ? View.VISIBLE : View.GONE));
headerBinding.copyDebugLogs.setOnClickListener((v) -> {
try {
DeckLog.shareLogAsFile(this);
} catch (Exception e) {
ExceptionDialogFragment.newInstance(e, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName());
}
});
switchMap(mainViewModel.hasAccounts(), hasAccounts -> {
if (hasAccounts) {
return mainViewModel.readAccounts();
} else {
startActivityForResult(ImportAccountActivity.createIntent(this), ImportAccountActivity.REQUEST_CODE_IMPORT_ACCOUNT);
return null;
}
}).observe(this, (List<Account> accounts) -> {
if (accounts == null || accounts.size() == 0) {
// Last account has been deleted. hasAccounts LiveData will handle this, but we make sure, that branding is reset.
saveBrandColors(this, ContextCompat.getColor(this, R.color.defaultBrand));
return;
}
accountsList = accounts;
long lastAccountId = readCurrentAccountId(this);
for (Account account : accountsList) {
if (lastAccountId == account.getId() || lastAccountId == NO_ACCOUNT_ID) {
mainViewModel.setCurrentAccount(account);
if (!firstAccountAdded) {
DeckLog.info("Syncing the current account on app start");
registerAutoSyncOnNetworkAvailable();
firstAccountAdded = false;
}
break;
}
}
mainViewModel.getCurrentAccountLiveData().observe(this, (currentAccount) -> {
SingleAccountHelper.setCurrentAccount(getApplicationContext(), mainViewModel.getCurrentAccount().getName());
mainViewModel.recreateSyncManager();
saveCurrentAccount(this, mainViewModel.getCurrentAccount());
if (mainViewModel.getCurrentAccount().isMaintenanceEnabled()) {
refreshCapabilities(mainViewModel.getCurrentAccount());
}
lastBoardId = readCurrentBoardId(this, mainViewModel.getCurrentAccount().getId());
if (boardsLiveData != null && boardsLiveDataObserver != null) {
boardsLiveData.removeObserver(boardsLiveDataObserver);
}
boardsLiveData = mainViewModel.getBoards(currentAccount.getId(), false);
boardsLiveDataObserver = (boards) -> {
if (boards == null) {
throw new IllegalStateException("List<Board> boards must not be null.");
}
boardsList = boards;
Board currentBoard = null;
if (boardsList.size() > 0) {
boolean currentBoardIdWasInList = false;
for (int i = 0; i < boardsList.size(); i++) {
if (lastBoardId == boardsList.get(i).getLocalId() || lastBoardId == NO_BOARD_ID) {
currentBoard = boardsList.get(i);
setCurrentBoard(currentBoard);
currentBoardIdWasInList = true;
break;
}
}
if (!currentBoardIdWasInList) {
currentBoard = boardsList.get(0);
setCurrentBoard(currentBoard);
}
binding.filter.setOnClickListener((v) -> FilterDialogFragment.newInstance().show(getSupportFragmentManager(), EditStackDialogFragment.class.getCanonicalName()));
} else {
clearBrandColors(this);
clearCurrentBoard();
binding.filter.setOnClickListener(null);
}
final Board finalCurrentBoard = currentBoard;
if (hasArchivedBoardsLiveData != null && hasArchivedBoardsLiveDataObserver != null) {
hasArchivedBoardsLiveData.removeObserver(hasArchivedBoardsLiveDataObserver);
}
hasArchivedBoardsLiveData = mainViewModel.hasArchivedBoards(currentAccount.getId());
hasArchivedBoardsLiveDataObserver = (hasArchivedBoards) -> {
mainViewModel.setCurrentAccountHasArchivedBoards(Boolean.TRUE.equals(hasArchivedBoards));
inflateBoardMenu(finalCurrentBoard);
};
hasArchivedBoardsLiveData.observe(this, hasArchivedBoardsLiveDataObserver);
};
boardsLiveData.observe(this, boardsLiveDataObserver);
Glide
.with(binding.accountSwitcher.getContext())
.load(currentAccount.getAvatarUrl(binding.accountSwitcher.getWidth()))
.placeholder(R.drawable.ic_baseline_account_circle_24)
.error(R.drawable.ic_baseline_account_circle_24)
.apply(RequestOptions.circleCropTransform())
.into(binding.accountSwitcher);
DeckLog.verbose("Displaying maintenance mode info for", mainViewModel.getCurrentAccount().getName() + ":", mainViewModel.getCurrentAccount().isMaintenanceEnabled());
binding.infoBox.setVisibility(mainViewModel.getCurrentAccount().isMaintenanceEnabled() ? View.VISIBLE : View.GONE);
if (mainViewModel.isCurrentAccountIsSupportedVersion()) {
binding.infoBoxVersionNotSupported.setVisibility(View.GONE);
} else {
binding.infoBoxVersionNotSupported.setText(getString(R.string.info_box_version_not_supported, mainViewModel.getCurrentAccount().getServerDeckVersion(), Version.minimumSupported().getOriginalVersion()));
binding.infoBoxVersionNotSupported.setOnClickListener((v) -> startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(mainViewModel.getCurrentAccount().getUrl() + getString(R.string.url_fragment_update_deck)))));
binding.infoBoxVersionNotSupported.setVisibility(View.VISIBLE);
}
});
stackAdapter = new StackAdapter(this);
binding.viewPager.setAdapter(stackAdapter);
binding.viewPager.setOffscreenPageLimit(2);
CrossTabDragAndDrop<StackFragment, CardAdapter, FullCard> dragAndDrop = new CrossTabDragAndDrop<>(getResources(), ViewCompat.getLayoutDirection(binding.getRoot()) == ViewCompat.LAYOUT_DIRECTION_LTR);
dragAndDrop.register(binding.viewPager, binding.stackTitles, getSupportFragmentManager());
dragAndDrop.addItemMovedByDragListener((movedCard, stackId, position) -> {
mainViewModel.reorder(mainViewModel.getCurrentAccount().getId(), movedCard, stackId, position);
DeckLog.info("Card", movedCard.getCard().getTitle(), "was moved to Stack", stackId, "on position", position);
});
final PopupMenu listMenuPopup = new PopupMenu(this, binding.listMenuButton);
listMenu = listMenuPopup.getMenu();
getMenuInflater().inflate(R.menu.list_menu, listMenu);
listMenuPopup.setOnMenuItemClickListener(this::onOptionsItemSelected);
binding.listMenuButton.setOnClickListener((v) -> listMenuPopup.show());
binding.fab.setOnClickListener((v) -> {
if (this.boardsList.size() > 0) {
try {
Long stackId = stackAdapter.getItem(binding.viewPager.getCurrentItem()).getLocalId();
startActivity(EditActivity.createNewCardIntent(this, mainViewModel.getCurrentAccount(), mainViewModel.getCurrentBoardLocalId(), stackId));
} catch (IndexOutOfBoundsException e) {
EditStackDialogFragment.newInstance(NO_STACK_ID).show(getSupportFragmentManager(), addList);
}
} else {
EditBoardDialogFragment.newInstance().show(getSupportFragmentManager(), addBoard);
}
});
binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { /* Silence is gold */ }
@Override
public void onPageSelected(int position) {
final int currentViewPagerItem = binding.viewPager.getCurrentItem();
listMenu.findItem(R.id.move_list_left).setVisible(currentBoardHasStacks && currentViewPagerItem > 0);
listMenu.findItem(R.id.move_list_right).setVisible(currentBoardHasStacks && currentViewPagerItem < currentBoardStacksCount - 1);
binding.viewPager.post(() -> {
// stackAdapter size might differ from position when an account has been deleted
if (stackAdapter.getItemCount() > position) {
saveCurrentStackId(getApplicationContext(), mainViewModel.getCurrentAccount().getId(), mainViewModel.getCurrentBoardLocalId(), stackAdapter.getItem(position).getLocalId());
} else {
DeckLog.logError(new IllegalStateException("Tried to save current Stack which cannot be available (stackAdapter doesn't have this position)"));
}
});
showFabIfEditPermissionGranted();
}
@Override
public void onPageScrollStateChanged(int state) {
if (!binding.swipeRefreshLayout.isRefreshing()) {
binding.swipeRefreshLayout.setEnabled(state == ViewPager2.SCROLL_STATE_IDLE);
}
}
});
distinctUntilChanged(map(filterViewModel.getFilterInformation(), FilterInformation::hasActiveFilter))
.observe(this, (hasActiveFilter) -> binding.filterIndicator.setVisibility(hasActiveFilter ? View.VISIBLE : View.GONE));
// binding.archivedCards.setOnClickListener((v) -> startActivity(ArchivedCardsActvitiy.createIntent(this, mainViewModel.getCurrentAccount(), mainViewModel.getCurrentBoardLocalId(), mainViewModel.currentBoardHasEditPermission())));
binding.enableSearch.setOnClickListener((v) -> showFilterTextToolbar());
binding.toolbar.setOnClickListener((v) -> showFilterTextToolbar());
binding.swipeRefreshLayout.setOnRefreshListener(() -> {
DeckLog.info("Triggered manual refresh");
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
final NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
DeckLog.info("Clearing Glide memory cache");
Glide.get(this).clearMemory();
new Thread(() -> {
DeckLog.info("Clearing Glide disk cache");
Glide.get(getApplicationContext()).clearDiskCache();
}).start();
} else {
DeckLog.info("Do not clear Glide caches, because the user currently does not have a working internet connection");
}
} else {
DeckLog.warn(ConnectivityManager.class.getSimpleName(), "is null");
}
DeckLog.verbose("Trigger refresh capabilities for", mainViewModel.getCurrentAccount().getName());
refreshCapabilities(mainViewModel.getCurrentAccount());
DeckLog.verbose("Trigger synchronization for", mainViewModel.getCurrentAccount().getName());
mainViewModel.synchronize(new IResponseCallback<Boolean>(mainViewModel.getCurrentAccount()) {
@Override
public void onResponse(Boolean response) {
DeckLog.info("End of synchronization for " + mainViewModel.getCurrentAccount().getName() + " → Stop spinner.");
runOnUiThread(() -> binding.swipeRefreshLayout.setRefreshing(false));
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
DeckLog.info("End of synchronization for " + mainViewModel.getCurrentAccount().getName() + " → Stop spinner.");
showSyncFailedSnackbar(throwable);
runOnUiThread(() -> binding.swipeRefreshLayout.setRefreshing(false));
}
});
});
});
binding.accountSwitcher.setOnClickListener((v) -> AccountSwitcherDialog.newInstance()
.show(getSupportFragmentManager(), AccountSwitcherDialog.class.getSimpleName()));
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
@Override
public void applyBrand(@ColorInt int mainColor) {
applyBrandToPrimaryTabLayout(mainColor, binding.stackTitles);
applyBrandToFAB(mainColor, binding.fab);
// TODO We assume, that the background of the spinner is always white
binding.swipeRefreshLayout.setColorSchemeColors(contrastRatioIsSufficient(Color.WHITE, mainColor) ? mainColor : DeckApplication.isDarkTheme(this) ? Color.DKGRAY : colorAccent);
DrawableCompat.setTint(binding.filterIndicator.getDrawable(), getSecondaryForegroundColorDependingOnTheme(this, mainColor));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (tabLayoutHelper != null) {
tabLayoutHelper.release();
}
}
@Override
public void onCreateStack(String stackName) {
DeckLog.info("Create Stack in account", mainViewModel.getCurrentAccount().getName(), "on board", mainViewModel.getCurrentBoardLocalId());
mainViewModel.createStack(mainViewModel.getCurrentAccount().getId(), stackName, mainViewModel.getCurrentBoardLocalId(), new ResponseCallback<FullStack>() {
@Override
public void onResponse(FullStack response) {
runOnUiThread(() -> binding.viewPager.setCurrentItem(stackAdapter.getItemCount()));
}
@Override
public void onError(Throwable error) {
ResponseCallback.super.onError(error);
runOnUiThread(() -> BrandedSnackbar.make(binding.coordinatorLayout, Objects.requireNonNull(error.getLocalizedMessage()), Snackbar.LENGTH_LONG)
.setAction(R.string.simple_more, v -> ExceptionDialogFragment.newInstance(error, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()))
.show());
}
});
}
@Override
public void onUpdateStack(long localStackId, String stackName) {
mainViewModel.updateStackTitle(localStackId, stackName, new ResponseCallback<FullStack>() {
@Override
public void onResponse(FullStack response) {
DeckLog.info("Successfully updated", Stack.class.getSimpleName(), "to", stackName);
}
@Override
public void onError(Throwable throwable) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
});
}
@Override
public void onCreateBoard(String title, @ColorInt int color) {
if (boardsLiveData == null || boardsLiveDataObserver == null) {
throw new IllegalStateException("Cannot create board when noone observe boards yet. boardsLiveData or observer is null.");
}
boardsLiveData.removeObserver(boardsLiveDataObserver);
final Board boardToCreate = new Board(title, color);
boardToCreate.setPermissionEdit(true);
boardToCreate.setPermissionManage(true);
mainViewModel.createBoard(mainViewModel.getCurrentAccount().getId(), boardToCreate, new ResponseCallback<FullBoard>() {
@Override
public void onResponse(FullBoard response) {
runOnUiThread(() -> {
if (response != null) {
boardsList.add(response.getBoard());
setCurrentBoard(response.getBoard());
inflateBoardMenu(response.getBoard());
EditStackDialogFragment.newInstance(NO_STACK_ID).show(getSupportFragmentManager(), addList);
}
boardsLiveData.observe(MainActivity.this, boardsLiveDataObserver);
});
}
@Override
public void onError(Throwable throwable) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> BrandedSnackbar.make(binding.coordinatorLayout, R.string.synchronization_failed, Snackbar.LENGTH_LONG)
.setAction(R.string.simple_more, v -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()))
.show());
}
});
}
@Override
public void onUpdateBoard(FullBoard fullBoard) {
mainViewModel.updateBoard(fullBoard, new ResponseCallback<FullBoard>() {
@Override
public void onResponse(FullBoard response) {
DeckLog.info("Successfully updated board", fullBoard.getBoard().getTitle());
}
@Override
public void onError(Throwable throwable) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
});
}
private void refreshCapabilities(final Account account) {
DeckLog.verbose("Refreshing capabilities for", account.getName());
mainViewModel.refreshCapabilities(new IResponseCallback<Capabilities>(account) {
@Override
public void onResponse(Capabilities response) {
DeckLog.verbose("Finished refreshing capabilities for", account.getName(), "successfully.");
if (response.isMaintenanceEnabled()) {
DeckLog.verbose("Maintenance mode is enabled → Stop spinner.");
binding.swipeRefreshLayout.setRefreshing(false);
} else {
DeckLog.verbose("Maintenance mode is disabled → Stop spinner.");
// If we notice after updating the capabilities, that the new version is not supported, but it was previously, recreate the activity to make sure all elements are disabled properly
if (mainViewModel.getCurrentAccount().getServerDeckVersionAsObject().isSupported() && !response.getDeckVersion().isSupported()) {
ActivityCompat.recreate(MainActivity.this);
}
}
}
@Override
public void onError(Throwable throwable) {
DeckLog.warn("Error on refreshing capabilities for", account.getName(), "(" + throwable.getMessage() + ") → Stop spinner.");
binding.swipeRefreshLayout.setRefreshing(false);
if (throwable instanceof OfflineException) {
DeckLog.info("Cannot refresh capabilities because device is offline.");
} else {
super.onError(throwable);
ExceptionDialogFragment.newInstance(throwable, account).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName());
}
}
});
}
protected void clearCurrentBoard() {
binding.toolbar.setTitle(R.string.app_name_short);
binding.filterText.setHint(R.string.app_name_short);
binding.swipeRefreshLayout.setVisibility(View.GONE);
binding.listMenuButton.setVisibility(View.GONE);
binding.emptyContentViewStacks.setVisibility(View.GONE);
binding.emptyContentViewBoards.setVisibility(View.VISIBLE);
}
protected void setCurrentBoard(@NonNull Board board) {
if (stacksLiveData != null) {
stacksLiveData.removeObservers(this);
}
saveBrandColors(this, board.getColor());
mainViewModel.setCurrentBoard(board);
filterViewModel.clearFilterInformation(true);
lastBoardId = board.getLocalId();
saveCurrentBoardId(this, mainViewModel.getCurrentAccount().getId(), mainViewModel.getCurrentBoardLocalId());
binding.navigationView.setCheckedItem(boardsList.indexOf(board));
binding.toolbar.setTitle(board.getTitle());
binding.filterText.setHint(getString(R.string.search_in, board.getTitle()));
if (mainViewModel.currentBoardHasEditPermission()) {
binding.fab.show();
binding.listMenuButton.setVisibility(View.VISIBLE);
} else {
binding.fab.hide();
binding.listMenuButton.setVisibility(View.GONE);
binding.emptyContentViewStacks.hideDescription();
}
binding.emptyContentViewBoards.setVisibility(View.GONE);
binding.swipeRefreshLayout.setVisibility(View.VISIBLE);
stacksLiveData = mainViewModel.getStacksForBoard(mainViewModel.getCurrentAccount().getId(), board.getLocalId());
stacksLiveData.observe(this, (List<Stack> stacks) -> {
if (stacks == null) {
throw new IllegalStateException("Given List<FullStack> must not be null");
}
currentBoardStacksCount = stacks.size();
if (currentBoardStacksCount == 0) {
binding.emptyContentViewStacks.setVisibility(View.VISIBLE);
currentBoardHasStacks = false;
} else {
binding.emptyContentViewStacks.setVisibility(View.GONE);
currentBoardHasStacks = true;
}
listMenu.findItem(R.id.archive_cards).setVisible(currentBoardHasStacks);
int stackPositionInAdapter = 0;
stackAdapter.setStacks(stacks);
final long currentStackId = readCurrentStackId(this, mainViewModel.getCurrentAccount().getId(), mainViewModel.getCurrentBoardLocalId());
for (int i = 0; i < currentBoardStacksCount; i++) {
if (stacks.get(i).getLocalId() == currentStackId || currentStackId == NO_STACK_ID) {
stackPositionInAdapter = i;
break;
}
}
final int stackPositionInAdapterClone = stackPositionInAdapter;
final TabTitleGenerator tabTitleGenerator = position -> {
if (stacks.size() > position) {
return stacks.get(position).getTitle();
} else {
DeckLog.logError(new IllegalStateException("Could not generate tab title for position " + position + " because list size is only " + currentBoardStacksCount));
return "ERROR";
}
};
final TabLayoutMediator newMediator = new TabLayoutMediator(binding.stackTitles, binding.viewPager, (tab, position) -> tab.setText(tabTitleGenerator.getTitle(position)));
runOnUiThread(() -> {
setStackMediator(newMediator);
binding.viewPager.setCurrentItem(stackPositionInAdapterClone, false);
if (stackMoved) { // Required to make sure that the correct tab will be selected after moving stacks
binding.viewPager.post(() -> binding.viewPager.setCurrentItem(stackPositionInAdapterClone, false));
stackMoved = false;
}
updateTabLayoutHelper(tabTitleGenerator);
});
listMenu.findItem(R.id.rename_list).setVisible(currentBoardHasStacks);
listMenu.findItem(R.id.delete_list).setVisible(currentBoardHasStacks);
});
}
@UiThread
private void updateTabLayoutHelper(@NonNull TabTitleGenerator tabTitleGenerator) {
if (this.tabLayoutHelper == null) {
this.tabLayoutHelper = new TabLayoutHelper(binding.stackTitles, binding.viewPager, tabTitleGenerator);
} else {
tabLayoutHelper.setTabTitleGenerator(tabTitleGenerator);
}
}
@UiThread
private void setStackMediator(@NonNull final TabLayoutMediator newMediator) {
if (mediator != null) {
mediator.detach();
}
newMediator.attach();
this.mediator = newMediator;
}
@UiThread
protected void inflateBoardMenu(@Nullable Board currentBoard) {
binding.navigationView.setItemIconTintList(null);
final Menu menu = binding.navigationView.getMenu();
menu.clear();
DrawerMenuUtil.inflateBoards(this, menu, this.boardsList, mainViewModel.currentAccountHasArchivedBoards(), mainViewModel.getCurrentAccount().getServerDeckVersionAsObject().isSupported());
binding.navigationView.setCheckedItem(boardsList.indexOf(currentBoard));
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case MENU_ID_ABOUT:
startActivity(AboutActivity.createIntent(this, mainViewModel.getCurrentAccount()));
break;
case MENU_ID_SETTINGS:
startActivityForResult(SettingsActivity.createIntent(this), MainActivity.ACTIVITY_SETTINGS);
break;
case MENU_ID_ADD_BOARD:
EditBoardDialogFragment.newInstance().show(getSupportFragmentManager(), addBoard);
break;
case MENU_ID_ARCHIVED_BOARDS:
startActivity(ArchivedBoardsActvitiy.createIntent(MainActivity.this, mainViewModel.getCurrentAccount()));
break;
default:
setCurrentBoard(boardsList.get(item.getItemId()));
break;
}
binding.drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.archive_cards) {
final Stack stack = stackAdapter.getItem(binding.viewPager.getCurrentItem());
final long stackLocalId = stack.getLocalId();
observeOnce(mainViewModel.countCardsInStack(mainViewModel.getCurrentAccount().getId(), stackLocalId), MainActivity.this, (numberOfCards) -> {
new BrandedAlertDialogBuilder(this)
.setTitle(R.string.archive_cards)
.setMessage(getString(FilterInformation.hasActiveFilter(filterViewModel.getFilterInformation().getValue())
? R.string.do_you_want_to_archive_all_cards_of_the_filtered_list
: R.string.do_you_want_to_archive_all_cards_of_the_list, stack.getTitle()))
.setPositiveButton(R.string.simple_archive, (dialog, whichButton) -> {
final FilterInformation filterInformation = filterViewModel.getFilterInformation().getValue();
mainViewModel.archiveCardsInStack(mainViewModel.getCurrentAccount().getId(), stackLocalId, filterInformation == null ? new FilterInformation() : filterInformation, new ResponseCallback<Void>() {
@Override
public void onResponse(Void response) {
DeckLog.info("Successfully archived all cards in stack local id", stackLocalId);
}
@Override
public void onError(Throwable throwable) {
if (!SyncManager.ignoreExceptionOnVoidError(throwable)) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
}
});
})
.setNeutralButton(android.R.string.cancel, null)
.create()
.show();
});
return true;
} else if (itemId == R.id.add_list) {
EditStackDialogFragment.newInstance(NO_STACK_ID).show(getSupportFragmentManager(), addList);
return true;
} else if (itemId == R.id.rename_list) {
final long stackId = stackAdapter.getItem(binding.viewPager.getCurrentItem()).getLocalId();
observeOnce(mainViewModel.getStack(mainViewModel.getCurrentAccount().getId(), stackId), MainActivity.this, fullStack ->
EditStackDialogFragment.newInstance(fullStack.getLocalId(), fullStack.getStack().getTitle())
.show(getSupportFragmentManager(), EditStackDialogFragment.class.getCanonicalName()));
return true;
} else if (itemId == R.id.move_list_left) {
final long stackId = stackAdapter.getItem(binding.viewPager.getCurrentItem()).getLocalId();
// TODO error handling
final int stackLeftPosition = binding.viewPager.getCurrentItem() - 1;
final long stackLeftId = stackAdapter.getItem(stackLeftPosition).getLocalId();
mainViewModel.swapStackOrder(mainViewModel.getCurrentAccount().getId(), mainViewModel.getCurrentBoardLocalId(), new Pair<>(stackId, stackLeftId));
stackMoved = true;
return true;
} else if (itemId == R.id.move_list_right) {
final long stackId = stackAdapter.getItem(binding.viewPager.getCurrentItem()).getLocalId();
// TODO error handling
final int stackRightPosition = binding.viewPager.getCurrentItem() + 1;
final long stackRightId = stackAdapter.getItem(stackRightPosition).getLocalId();
mainViewModel.swapStackOrder(mainViewModel.getCurrentAccount().getId(), mainViewModel.getCurrentBoardLocalId(), new Pair<>(stackId, stackRightId));
stackMoved = true;
return true;
} else if (itemId == R.id.delete_list) {
final long stackId = stackAdapter.getItem(binding.viewPager.getCurrentItem()).getLocalId();
observeOnce(mainViewModel.countCardsInStack(mainViewModel.getCurrentAccount().getId(), stackId), MainActivity.this, (numberOfCards) -> {
if (numberOfCards != null && numberOfCards > 0) {
DeleteStackDialogFragment.newInstance(stackId, numberOfCards).show(getSupportFragmentManager(), DeleteStackDialogFragment.class.getCanonicalName());
} else {
onStackDeleted(stackId);
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
protected void showFabIfEditPermissionGranted() {
if (mainViewModel.currentBoardHasEditPermission()) {
binding.fab.show();
}
}
@Override
public void onScrollUp() {
showFabIfEditPermissionGranted();
}
@Override
public void onScrollDown() {
binding.fab.hide();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
AccountImporter.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case MainActivity.ACTIVITY_SETTINGS:
if (resultCode == RESULT_OK) {
ActivityCompat.recreate(this);
}
break;
case ImportAccountActivity.REQUEST_CODE_IMPORT_ACCOUNT:
if (resultCode == RESULT_OK) {
firstAccountAdded = true;
} else {
finish();
}
break;
default:
try {
AccountImporter.onActivityResult(requestCode, resultCode, data, this, (account) -> {
final WrappedLiveData<Account> accountLiveData = mainViewModel.createAccount(new Account(account.name, account.userId, account.url));
accountLiveData.observe(this, (createdAccount) -> {
if (!accountLiveData.hasError()) {
if (createdAccount == null) {
throw new IllegalStateException("Created account must not be null");
}
final SyncManager importSyncManager = new SyncManager(this, account.name);
importSyncManager.refreshCapabilities(new IResponseCallback<Capabilities>(createdAccount) {
@SuppressLint("StringFormatInvalid")
@Override
public void onResponse(Capabilities response) {
if (!response.isMaintenanceEnabled()) {
if (response.getDeckVersion().isSupported()) {
runOnUiThread(() -> {
mainViewModel.setSyncManager(importSyncManager);
final Snackbar importSnackbar = BrandedSnackbar.make(binding.coordinatorLayout, R.string.account_is_getting_imported, Snackbar.LENGTH_INDEFINITE);
importSnackbar.show();
importSyncManager.synchronize(new IResponseCallback<Boolean>(createdAccount) {
@Override
public void onResponse(Boolean response) {
importSnackbar.dismiss();
runOnUiThread(() -> BrandedSnackbar.make(binding.coordinatorLayout, getString(R.string.account_imported), Snackbar.LENGTH_LONG)
.setAction(R.string.simple_switch, (a) -> mainViewModel.setCurrentAccount(createdAccount))
.show());
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
runOnUiThread(() -> {
importSnackbar.dismiss();
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, createdAccount).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
});
}
});
});
} else {
DeckLog.warn("Cannot import account because server version is too low (" + response.getDeckVersion() + "). Minimum server version is currently", Version.minimumSupported());
runOnUiThread(() -> new BrandedAlertDialogBuilder(MainActivity.this)
.setTitle(R.string.update_deck)
.setMessage(getString(R.string.deck_outdated_please_update, response.getDeckVersion().getOriginalVersion()))
.setNegativeButton(R.string.simple_discard, null)
.setPositiveButton(R.string.simple_update, (dialog, whichButton) -> {
final Intent openURL = new Intent(Intent.ACTION_VIEW);
openURL.setData(Uri.parse(createdAccount.getUrl() + getString(R.string.url_fragment_update_deck)));
startActivity(openURL);
finish();
}).show());
mainViewModel.deleteAccount(createdAccount.getId());
}
} else {
DeckLog.warn("Cannot import account because server version is currently in maintenance mode.");
runOnUiThread(() -> new BrandedAlertDialogBuilder(MainActivity.this)
.setTitle(R.string.maintenance_mode)
.setMessage(getString(R.string.maintenance_mode_explanation, createdAccount.getUrl()))
.setPositiveButton(R.string.simple_close, null)
.show());
mainViewModel.deleteAccount(createdAccount.getId());
}
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
mainViewModel.deleteAccount(createdAccount.getId());
if (throwable instanceof OfflineException) {
DeckLog.warn("Cannot import account because device is currently offline.");
runOnUiThread(() -> new BrandedAlertDialogBuilder(MainActivity.this)
.setTitle(R.string.you_are_currently_offline)
.setMessage(R.string.you_have_to_be_connected_to_the_internet_in_order_to_add_an_account)
.setPositiveButton(R.string.simple_close, null)
.show());
} else {
ExceptionDialogFragment.newInstance(throwable, createdAccount).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName());
}
}
});
} else {
final Throwable error = accountLiveData.getError();
if (error instanceof SQLiteConstraintException) {
DeckLog.warn("Account already added");
BrandedSnackbar.make(binding.coordinatorLayout, R.string.account_already_added, Snackbar.LENGTH_LONG).show();
} else {
ExceptionDialogFragment.newInstance(error, createdAccount).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName());
}
}
});
});
} catch (AccountImportCancelledException e) {
DeckLog.info("Account import has been canceled.");
}
}
}
@Override
public void onBackPressed() {
if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
binding.drawerLayout.closeDrawer(GravityCompat.START);
} else if (binding.searchToolbar.getVisibility() == View.VISIBLE) {
hideFilterTextToolbar();
} else {
super.onBackPressed();
}
}
private void showFilterTextToolbar() {
binding.toolbar.setVisibility(View.GONE);
binding.searchToolbar.setVisibility(View.VISIBLE);
binding.searchToolbar.setNavigationOnClickListener(v1 -> onBackPressed());
binding.enableSearch.setVisibility(View.GONE);
binding.filterText.requestFocus();
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(binding.filterText, InputMethodManager.SHOW_IMPLICIT);
binding.toolbarCard.setStateListAnimator(AnimatorInflater.loadStateListAnimator(this, R.animator.appbar_elevation_on));
}
private void hideFilterTextToolbar() {
binding.filterText.setText(null);
final InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
binding.searchToolbar.setVisibility(View.GONE);
binding.enableSearch.setVisibility(View.VISIBLE);
binding.toolbar.setVisibility(View.VISIBLE);
binding.toolbarCard.setStateListAnimator(AnimatorInflater.loadStateListAnimator(this, R.animator.appbar_elevation_off));
}
private void registerAutoSyncOnNetworkAvailable() {
final ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
if (connectivityManager != null) {
if (networkCallback == null) {
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
DeckLog.log("Got Network connection");
mainViewModel.synchronize(new IResponseCallback<Boolean>(mainViewModel.getCurrentAccount()) {
@Override
public void onResponse(Boolean response) {
DeckLog.log("Auto-Sync after connection available successful");
}
@Override
public void onError(Throwable throwable) {
super.onError(throwable);
showSyncFailedSnackbar(throwable);
}
});
}
@Override
public void onLost(@NonNull Network network) {
DeckLog.log("Network lost");
}
};
}
try {
connectivityManager.unregisterNetworkCallback(networkCallback);
} catch (IllegalArgumentException ignored) {
}
connectivityManager.registerNetworkCallback(builder.build(), networkCallback);
}
}
@Override
public void onStackDeleted(Long stackLocalId) {
long stackId = stackAdapter.getItem(binding.viewPager.getCurrentItem()).getLocalId();
mainViewModel.deleteStack(mainViewModel.getCurrentAccount().getId(), stackId, mainViewModel.getCurrentBoardLocalId(), new ResponseCallback<Void>() {
@Override
public void onResponse(Void response) {
DeckLog.info("Successfully deleted stack with local id", stackLocalId, "and remote id", stackId);
}
@Override
public void onError(Throwable throwable) {
if (!SyncManager.ignoreExceptionOnVoidError(throwable)) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
}
});
}
@Override
public void onBoardDeleted(Board board) {
final int index = this.boardsList.indexOf(board);
if (board.getLocalId().equals(mainViewModel.getCurrentBoardLocalId())) {
if (index > 0) { // Select first board after deletion
setCurrentBoard(this.boardsList.get(0));
} else if (this.boardsList.size() > 1) { // Select second board after deletion
setCurrentBoard(this.boardsList.get(1));
} else { // No other board is available, open create dialog
clearBrandColors(this);
clearCurrentBoard();
EditBoardDialogFragment.newInstance().show(getSupportFragmentManager(), addBoard);
}
}
mainViewModel.deleteBoard(board, new ResponseCallback<Void>() {
@Override
public void onResponse(Void response) {
DeckLog.info("Successfully deleted board", board.getTitle());
}
@Override
public void onError(Throwable throwable) {
if (!SyncManager.ignoreExceptionOnVoidError(throwable)) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
}
});
binding.drawerLayout.closeDrawer(GravityCompat.START);
}
/**
* Displays a {@link BrandedSnackbar} for an exception of a failed sync, but only if the cause wasn't maintenance mode (this should be handled by a TextView instead of a snackbar).
*
* @param throwable the cause of the failed sync
*/
@AnyThread
private void showSyncFailedSnackbar(@NonNull Throwable throwable) {
if (!(throwable instanceof NextcloudHttpRequestFailedException) || ((NextcloudHttpRequestFailedException) throwable).getStatusCode() != HttpURLConnection.HTTP_UNAVAILABLE) {
runOnUiThread(() -> BrandedSnackbar.make(binding.coordinatorLayout, R.string.synchronization_failed, Snackbar.LENGTH_LONG)
.setAction(R.string.simple_more, v -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()))
.show());
}
}
@Override
public void onArchive(@NonNull Board board) {
mainViewModel.archiveBoard(board, new ResponseCallback<FullBoard>() {
@Override
public void onResponse(FullBoard response) {
DeckLog.info("Successfully archived board", board.getTitle());
}
@Override
public void onError(Throwable throwable) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
});
}
@Override
public void onClone(Board board) {
final String[] animals = {getString(R.string.clone_cards)};
final boolean[] checkedItems = {false};
new BrandedAlertDialogBuilder(this)
.setTitle(R.string.clone_board)
.setMultiChoiceItems(animals, checkedItems, (dialog, which, isChecked) -> checkedItems[0] = isChecked)
.setPositiveButton(R.string.simple_clone, (dialog, which) -> {
binding.drawerLayout.closeDrawer(GravityCompat.START);
final Snackbar snackbar = BrandedSnackbar.make(binding.coordinatorLayout, getString(R.string.cloning_board, board.getTitle()), Snackbar.LENGTH_INDEFINITE);
snackbar.show();
mainViewModel.cloneBoard(board.getAccountId(), board.getLocalId(), board.getAccountId(), board.getColor(), checkedItems[0], new ResponseCallback<FullBoard>() {
@Override
public void onResponse(FullBoard response) {
runOnUiThread(() -> {
snackbar.dismiss();
setCurrentBoard(response.getBoard());
BrandedSnackbar.make(binding.coordinatorLayout, getString(R.string.successfully_cloned_board, response.getBoard().getTitle()), Snackbar.LENGTH_LONG)
.setAction(R.string.edit, v -> EditBoardDialogFragment.newInstance(response.getLocalId()).show(getSupportFragmentManager(), EditBoardDialogFragment.class.getSimpleName()))
.show();
});
}
@Override
public void onError(Throwable throwable) {
ResponseCallback.super.onError(throwable);
runOnUiThread(() -> {
snackbar.dismiss();
ExceptionDialogFragment.newInstance(throwable, mainViewModel.getCurrentAccount()).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName());
});
}
});
})
.setNeutralButton(android.R.string.cancel, null)
.show();
}
}
|