forked from nextcloud/android
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDrawerActivity.java
1172 lines (1012 loc) · 47.4 KB
/
DrawerActivity.java
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
/*
* Nextcloud Android client application
*
* @author Andy Scherzinger
* @author Tobias Kaminsky
* @author Chris Narkiewicz <[email protected]>
* @author TSI-mc
* Copyright (C) 2016 Andy Scherzinger
* Copyright (C) 2017 Tobias Kaminsky
* Copyright (C) 2016 Nextcloud
* Copyright (C) 2016 ownCloud Inc.
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
* Copyright (C) 2020 Infomaniak Network SA
* Copyright (C) 2021 TSI-mc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.GenericRequestBuilder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.StreamEncoder;
import com.bumptech.glide.load.resource.file.FileToStreamDecoder;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.progressindicator.LinearProgressIndicator;
import com.nextcloud.client.account.User;
import com.nextcloud.client.di.Injectable;
import com.nextcloud.client.network.ClientFactory;
import com.nextcloud.client.onboarding.FirstRunActivity;
import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.common.NextcloudClient;
import com.nextcloud.java.util.Optional;
import com.nextcloud.ui.ChooseAccountDialogFragment;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.PassCodeManager;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
import com.owncloud.android.datamodel.ExternalLinksProvider;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.ExternalLink;
import com.owncloud.android.lib.common.ExternalLinkType;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.Quota;
import com.owncloud.android.lib.common.UserInfo;
import com.owncloud.android.lib.common.accounts.ExternalLinksOperation;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
import com.owncloud.android.operations.GetCapabilitiesOperation;
import com.owncloud.android.ui.activities.ActivitiesActivity;
import com.owncloud.android.ui.events.AccountRemovedEvent;
import com.owncloud.android.ui.events.ChangeMenuEvent;
import com.owncloud.android.ui.events.DummyDrawerEvent;
import com.owncloud.android.ui.events.SearchEvent;
import com.owncloud.android.ui.fragment.FileDetailsSharingProcessFragment;
import com.owncloud.android.ui.fragment.GalleryFragment;
import com.owncloud.android.ui.fragment.GroupfolderListFragment;
import com.owncloud.android.ui.fragment.OCFileListFragment;
import com.owncloud.android.ui.fragment.SharedListFragment;
import com.owncloud.android.ui.preview.PreviewTextStringFragment;
import com.owncloud.android.ui.trashbin.TrashbinActivity;
import com.owncloud.android.utils.BitmapUtils;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.DrawerMenuUtil;
import com.owncloud.android.utils.FilesSyncHelper;
import com.owncloud.android.utils.svg.MenuSimpleTarget;
import com.owncloud.android.utils.svg.SVGorImage;
import com.owncloud.android.utils.svg.SvgOrImageBitmapTranscoder;
import com.owncloud.android.utils.svg.SvgOrImageDecoder;
import com.owncloud.android.utils.theme.CapabilityUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
/**
* Base class to handle setup of the drawer implementation including user switching and avatar fetching and fallback
* generation.
*/
public abstract class DrawerActivity extends ToolbarActivity
implements DisplayUtils.AvatarGenerationListener, Injectable {
private static final String TAG = DrawerActivity.class.getSimpleName();
private static final String KEY_IS_ACCOUNT_CHOOSER_ACTIVE = "IS_ACCOUNT_CHOOSER_ACTIVE";
private static final String KEY_CHECKED_MENU_ITEM = "CHECKED_MENU_ITEM";
private static final int ACTION_MANAGE_ACCOUNTS = 101;
private static final int MENU_ORDER_EXTERNAL_LINKS = 3;
private static final int MENU_ITEM_EXTERNAL_LINK = 111;
private static final int MAX_LOGO_SIZE_PX = 1000;
private static final int RELATIVE_THRESHOLD_WARNING = 80;
/**
* Reference to the drawer layout.
*/
private DrawerLayout mDrawerLayout;
/**
* Reference to the drawer toggle.
*/
protected ActionBarDrawerToggle mDrawerToggle;
/**
* Reference to the navigation view.
*/
private NavigationView mNavigationView;
/**
* Reference to the navigation view header.
*/
private View mNavigationViewHeader;
/**
* Flag to signal if the account chooser is active.
*/
private boolean mIsAccountChooserActive;
/**
* Id of the checked menu item.
*/
private int mCheckedMenuItem = Menu.NONE;
/**
* container layout of the quota view.
*/
private LinearLayout mQuotaView;
/**
* progress bar of the quota view.
*/
private LinearProgressIndicator mQuotaProgressBar;
/**
* text view of the quota view.
*/
private TextView mQuotaTextPercentage;
private TextView mQuotaTextLink;
/**
* runnable that will be executed after the drawer has been closed.
*/
private Runnable pendingRunnable;
private ExternalLinksProvider externalLinksProvider;
private ArbitraryDataProvider arbitraryDataProvider;
@Inject
AppPreferences preferences;
@Inject
ClientFactory clientFactory;
/**
* Initializes the drawer, its content and highlights the menu item with the given id. This method needs to be
* called after the content view has been set.
*
* @param menuItemId the menu item to be checked/highlighted
*/
protected void setupDrawer(int menuItemId) {
setupDrawer();
setDrawerMenuItemChecked(menuItemId);
}
/**
* Initializes the drawer and its content. This method needs to be called after the content view has been set.
*/
protected void setupDrawer() {
mDrawerLayout = findViewById(R.id.drawer_layout);
mNavigationView = findViewById(R.id.nav_view);
if (mNavigationView != null) {
// Setting up drawer header
mNavigationViewHeader = mNavigationView.getHeaderView(0);
updateHeader();
setupDrawerMenu(mNavigationView);
getAndDisplayUserQuota();
setupQuotaElement();
}
setupDrawerToggle();
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
/**
* initializes and sets up the drawer toggle.
*/
private void setupDrawerToggle() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
supportInvalidateOptionsMenu();
mDrawerToggle.setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
if (pendingRunnable != null) {
new Handler().post(pendingRunnable);
pendingRunnable = null;
}
closeDrawer();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
mDrawerToggle.setDrawerIndicatorEnabled(true);
supportInvalidateOptionsMenu();
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerToggle.setDrawerSlideAnimationEnabled(true);
Drawable backArrow = ResourcesCompat.getDrawable(getResources(),
R.drawable.ic_arrow_back,
null);
viewThemeUtils.platform.tintToolbarArrowDrawable(this, mDrawerToggle, backArrow);
}
/**
* setup quota elements of the drawer.
*/
private void setupQuotaElement() {
mQuotaView = (LinearLayout) findQuotaViewById(R.id.drawer_quota);
mQuotaProgressBar = (LinearProgressIndicator) findQuotaViewById(R.id.drawer_quota_ProgressBar);
mQuotaTextPercentage = (TextView) findQuotaViewById(R.id.drawer_quota_percentage);
mQuotaTextLink = (TextView) findQuotaViewById(R.id.drawer_quota_link);
viewThemeUtils.material.colorProgressBar(mQuotaProgressBar);
}
public void updateHeader() {
if (getAccount() != null &&
getCapabilities().getServerBackground() != null) {
OCCapability capability = getCapabilities();
String logo = capability.getServerLogo();
int primaryColor = themeColorUtils.unchangedPrimaryColor(getAccount(), this);
// set background to primary color
LinearLayout drawerHeader = mNavigationViewHeader.findViewById(R.id.drawer_header_view);
drawerHeader.setBackgroundColor(primaryColor);
if (!TextUtils.isEmpty(logo) && URLUtil.isValidUrl(logo)) {
// background image
GenericRequestBuilder<Uri, InputStream, SVGorImage, Bitmap> requestBuilder = Glide.with(this)
.using(Glide.buildStreamModelLoader(Uri.class, this), InputStream.class)
.from(Uri.class)
.as(SVGorImage.class)
.transcode(new SvgOrImageBitmapTranscoder(128, 128), Bitmap.class)
.sourceEncoder(new StreamEncoder())
.cacheDecoder(new FileToStreamDecoder<>(new SvgOrImageDecoder()))
.decoder(new SvgOrImageDecoder());
// background image
SimpleTarget target = new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
Bitmap logo = resource;
int width = resource.getWidth();
int height = resource.getHeight();
int max = Math.max(width, height);
if (max > MAX_LOGO_SIZE_PX) {
logo = BitmapUtils.scaleBitmap(resource, MAX_LOGO_SIZE_PX, width, height, max);
}
Drawable[] drawables = {new ColorDrawable(primaryColor), new BitmapDrawable(logo)};
LayerDrawable layerDrawable = new LayerDrawable(drawables);
String name = capability.getServerName();
setDrawerHeaderLogo(layerDrawable, name);
}
};
requestBuilder
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.load(Uri.parse(logo))
.into(target);
}
}
}
private void setDrawerHeaderLogo(Drawable drawable, String name) {
ImageView imageHeader = mNavigationViewHeader.findViewById(R.id.drawer_header_logo);
imageHeader.setImageDrawable(drawable);
imageHeader.setScaleType(ImageView.ScaleType.FIT_START);
imageHeader.setAdjustViewBounds(true);
imageHeader.setMaxWidth(DisplayUtils.convertDpToPixel(100f, this));
MarginLayoutParams oldParam = (MarginLayoutParams) imageHeader.getLayoutParams();
MarginLayoutParams params = new MarginLayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT);
params.leftMargin = oldParam.leftMargin;
params.rightMargin = oldParam.rightMargin;
imageHeader.setLayoutParams(new LinearLayout.LayoutParams(params));
if (!TextUtils.isEmpty(name)) {
TextView serverName = mNavigationViewHeader.findViewById(R.id.drawer_header_server_name);
serverName.setText(name);
serverName.setTextColor(themeColorUtils.unchangedFontColor(this));
}
}
/**
* setup drawer content, basically setting the item selected listener.
*
* @param navigationView the drawers navigation view
*/
private void setupDrawerMenu(NavigationView navigationView) {
navigationView.setItemIconTintList(null);
// setup actions for drawer menu items
navigationView.setNavigationItemSelectedListener(
menuItem -> {
mDrawerLayout.closeDrawers();
// pending runnable will be executed after the drawer has been closed
pendingRunnable = () -> onNavigationItemClicked(menuItem);
return true;
});
User account = accountManager.getUser();
filterDrawerMenu(navigationView.getMenu(), account);
}
private void filterDrawerMenu(final Menu menu, @NonNull final User user) {
OCCapability capability = getCapabilities();
DrawerMenuUtil.filterSearchMenuItems(menu, user, getResources());
DrawerMenuUtil.filterTrashbinMenuItem(menu, capability);
DrawerMenuUtil.filterActivityMenuItem(menu, capability);
DrawerMenuUtil.filterGroupfoldersMenuItem(menu, capability);
DrawerMenuUtil.setupHomeMenuItem(menu, getResources());
DrawerMenuUtil.removeMenuItem(menu, R.id.nav_community,
!getResources().getBoolean(R.bool.participate_enabled));
DrawerMenuUtil.removeMenuItem(menu, R.id.nav_shared, !getResources().getBoolean(R.bool.shared_enabled));
DrawerMenuUtil.removeMenuItem(menu, R.id.nav_logout, !getResources().getBoolean(R.bool.show_drawer_logout));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(DummyDrawerEvent event) {
unsetAllDrawerMenuItems();
}
private void onNavigationItemClicked(final MenuItem menuItem) {
setDrawerMenuItemChecked(menuItem.getItemId());
int itemId = menuItem.getItemId();
if (itemId == R.id.nav_all_files) {
if (this instanceof FileDisplayActivity &&
!(((FileDisplayActivity) this).getLeftFragment() instanceof GalleryFragment) &&
!(((FileDisplayActivity) this).getLeftFragment() instanceof SharedListFragment) &&
!(((FileDisplayActivity) this).getLeftFragment() instanceof GroupfolderListFragment) &&
!(((FileDisplayActivity) this).getLeftFragment() instanceof PreviewTextStringFragment)) {
showFiles(false);
((FileDisplayActivity) this).browseToRoot();
EventBus.getDefault().post(new ChangeMenuEvent());
} else {
MainApp.showOnlyFilesOnDevice(false);
Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(FileDisplayActivity.ALL_FILES);
intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId());
startActivity(intent);
}
} else if (itemId == R.id.nav_favorites) {
handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.FAVORITE_SEARCH),
menuItem.getItemId());
} else if (itemId == R.id.nav_gallery) {
startPhotoSearch(menuItem);
} else if (itemId == R.id.nav_uploads) {
startActivity(UploadListActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else if (itemId == R.id.nav_trashbin) {
startActivity(TrashbinActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else if (itemId == R.id.nav_activity) {
startActivity(ActivitiesActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else if (itemId == R.id.nav_notifications) {
startActivity(NotificationsActivity.class);
} else if (itemId == R.id.nav_settings) {
startActivity(SettingsActivity.class);
} else if (itemId == R.id.nav_community) {
startActivity(CommunityActivity.class);
} else if (itemId == R.id.nav_logout) {
mCheckedMenuItem = -1;
menuItem.setChecked(false);
final Optional<User> optionalUser = getUser();
if (optionalUser.isPresent()) {
UserInfoActivity.openAccountRemovalConfirmationDialog(optionalUser.get(), getSupportFragmentManager());
}
} else if (itemId == R.id.nav_shared) {
startSharedSearch(menuItem);
} else if (itemId == R.id.nav_recently_modified) {
startRecentlyModifiedSearch(menuItem);
} else if (itemId == R.id.nav_groupfolders) {
MainApp.showOnlyFilesOnDevice(false);
Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(FileDisplayActivity.LIST_GROUPFOLDERS);
intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId());
startActivity(intent);
} else {
if (menuItem.getItemId() >= MENU_ITEM_EXTERNAL_LINK &&
menuItem.getItemId() <= MENU_ITEM_EXTERNAL_LINK + 100) {
// external link clicked
externalLinkClicked(menuItem);
} else {
Log_OC.w(TAG, "Unknown drawer menu item clicked: " + menuItem.getTitle());
}
}
}
private void startActivity(Class<? extends Activity> activity) {
startActivity(new Intent(getApplicationContext(), activity));
}
private void startActivity(Class<? extends Activity> activity, int flags) {
Intent intent = new Intent(getApplicationContext(), activity);
intent.setFlags(flags);
startActivity(intent);
}
public void showManageAccountsDialog() {
ChooseAccountDialogFragment choseAccountDialog = ChooseAccountDialogFragment.newInstance(accountManager.getUser());
choseAccountDialog.show(getSupportFragmentManager(), "fragment_chose_account");
}
public void openManageAccounts() {
Intent manageAccountsIntent = new Intent(getApplicationContext(), ManageAccountsActivity.class);
startActivityForResult(manageAccountsIntent, ACTION_MANAGE_ACCOUNTS);
}
public void openAddAccount() {
boolean isProviderOrOwnInstallationVisible = getResources()
.getBoolean(R.bool.show_provider_or_own_installation);
if (isProviderOrOwnInstallationVisible) {
Intent firstRunIntent = new Intent(getApplicationContext(), FirstRunActivity.class);
firstRunIntent.putExtra(FirstRunActivity.EXTRA_ALLOW_CLOSE, true);
startActivity(firstRunIntent);
} else {
startAccountCreation();
}
}
private void startSharedSearch(MenuItem menuItem) {
SearchEvent searchEvent = new SearchEvent("", SearchRemoteOperation.SearchType.SHARED_FILTER);
MainApp.showOnlyFilesOnDevice(false);
launchActivityForSearch(searchEvent, menuItem.getItemId());
}
private void startRecentlyModifiedSearch(MenuItem menuItem) {
SearchEvent searchEvent = new SearchEvent("", SearchRemoteOperation.SearchType.RECENTLY_MODIFIED_SEARCH);
MainApp.showOnlyFilesOnDevice(false);
launchActivityForSearch(searchEvent, menuItem.getItemId());
}
private void startPhotoSearch(MenuItem menuItem) {
SearchEvent searchEvent = new SearchEvent("image/%", SearchRemoteOperation.SearchType.PHOTO_SEARCH);
MainApp.showOnlyFilesOnDevice(false);
launchActivityForSearch(searchEvent, menuItem.getItemId());
}
private void handleSearchEvents(SearchEvent searchEvent, int menuItemId) {
if (this instanceof FileDisplayActivity) {
final Fragment leftFragment = ((FileDisplayActivity) this).getLeftFragment();
if (leftFragment instanceof GalleryFragment || leftFragment instanceof SharedListFragment) {
launchActivityForSearch(searchEvent, menuItemId);
} else {
EventBus.getDefault().post(searchEvent);
}
} else {
launchActivityForSearch(searchEvent, menuItemId);
}
}
private void launchActivityForSearch(SearchEvent searchEvent, int menuItemId) {
Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Intent.ACTION_SEARCH);
intent.putExtra(OCFileListFragment.SEARCH_EVENT, searchEvent);
intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItemId);
startActivity(intent);
}
/**
* sets the new/current account and restarts. In case the given account equals the actual/current account the call
* will be ignored.
*
* @param hashCode HashCode of account to be set
*/
public void accountClicked(int hashCode) {
final User currentUser = accountManager.getUser();
if (currentUser.hashCode() != hashCode && accountManager.setCurrentOwnCloudAccount(hashCode)) {
fetchExternalLinks(true);
restart();
}
}
private void externalLinkClicked(MenuItem menuItem) {
for (ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.LINK)) {
if (menuItem.getTitle().toString().equalsIgnoreCase(link.getName())) {
if (link.getRedirect()) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link.getUrl()));
DisplayUtils.startIntentIfAppAvailable(intent, this, R.string.no_browser_available);
} else {
Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, link.getName());
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, link.getUrl());
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true);
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, menuItem.getItemId());
startActivity(externalWebViewIntent);
}
}
}
}
/**
* checks if the drawer exists and is opened.
*
* @return <code>true</code> if the drawer is open, else <code>false</code>
*/
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
}
/**
* closes the drawer.
*/
public void closeDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
/**
* opens the drawer.
*/
public void openDrawer() {
if (mDrawerLayout != null) {
mDrawerLayout.openDrawer(GravityCompat.START);
updateExternalLinksInDrawer();
updateQuotaLink();
}
}
/**
* Enable or disable interaction with all drawers.
*
* @param lockMode The new lock mode for the given drawer. One of {@link DrawerLayout#LOCK_MODE_UNLOCKED}, {@link
* DrawerLayout#LOCK_MODE_LOCKED_CLOSED} or {@link DrawerLayout#LOCK_MODE_LOCKED_OPEN}.
*/
public void setDrawerLockMode(int lockMode) {
if (mDrawerLayout != null) {
mDrawerLayout.setDrawerLockMode(lockMode);
}
}
/**
* Enable or disable the drawer indicator.
*
* @param enable true to enable, false to disable
*/
public void setDrawerIndicatorEnabled(boolean enable) {
if (mDrawerToggle != null) {
mDrawerToggle.setDrawerIndicatorEnabled(enable);
}
}
/**
* Updates title bar and home buttons (state and icon). Assumes that navigation drawer is NOT visible.
*/
protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
super.updateActionBarTitleAndHomeButton(chosenFile);
// set home button properties
if (mDrawerToggle != null) {
if (chosenFile != null && isRoot(chosenFile)) {
mDrawerToggle.setDrawerIndicatorEnabled(true);
} else {
mDrawerToggle.setDrawerIndicatorEnabled(false);
}
}
}
/**
* shows or hides the quota UI elements.
*
* @param showQuota show/hide quota information
*/
private void showQuota(boolean showQuota) {
if (showQuota) {
mQuotaView.setVisibility(View.VISIBLE);
} else {
mQuotaView.setVisibility(View.GONE);
}
}
/**
* configured the quota to be displayed.
*
* @param usedSpace the used space
* @param totalSpace the total space
* @param relative the percentage of space already used
* @param quotaValue {@link GetUserInfoRemoteOperation#SPACE_UNLIMITED} or other to determinate state
*/
private void setQuotaInformation(long usedSpace, long totalSpace, int relative, long quotaValue) {
if (GetUserInfoRemoteOperation.SPACE_UNLIMITED == quotaValue) {
mQuotaTextPercentage.setText(String.format(
getString(R.string.drawer_quota_unlimited),
DisplayUtils.bytesToHumanReadable(usedSpace)));
} else {
mQuotaTextPercentage.setText(String.format(
getString(R.string.drawer_quota),
DisplayUtils.bytesToHumanReadable(usedSpace),
DisplayUtils.bytesToHumanReadable(totalSpace)));
}
mQuotaProgressBar.setProgress(relative);
if (relative < RELATIVE_THRESHOLD_WARNING) {
viewThemeUtils.material.colorProgressBar(mQuotaProgressBar);
} else {
viewThemeUtils.material.colorProgressBar(mQuotaProgressBar,
getResources().getColor(R.color.infolevel_warning));
}
updateQuotaLink();
showQuota(true);
}
private void unsetAllDrawerMenuItems() {
if (mNavigationView != null) {
mNavigationView.getMenu();
Menu menu = mNavigationView.getMenu();
for (int i = 0; i < menu.size(); i++) {
menu.getItem(i).setChecked(false);
}
}
mCheckedMenuItem = Menu.NONE;
}
private void updateQuotaLink() {
if (mQuotaTextLink != null) {
if (getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
List<ExternalLink> quotas = externalLinksProvider.getExternalLink(ExternalLinkType.QUOTA);
float density = getResources().getDisplayMetrics().density;
final int size = Math.round(24 * density);
if (quotas.size() > 0) {
final ExternalLink firstQuota = quotas.get(0);
mQuotaTextLink.setText(firstQuota.getName());
mQuotaTextLink.setClickable(true);
mQuotaTextLink.setVisibility(View.VISIBLE);
mQuotaTextLink.setOnClickListener(v -> {
Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, firstQuota.getName());
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, firstQuota.getUrl());
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true);
externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, -1);
startActivity(externalWebViewIntent);
});
SimpleTarget target = new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
Drawable test = resource.getCurrent();
test.setBounds(0, 0, size, size);
mQuotaTextLink.setCompoundDrawablesWithIntrinsicBounds(test, null, null, null);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
Drawable test = errorDrawable.getCurrent();
test.setBounds(0, 0, size, size);
mQuotaTextLink.setCompoundDrawablesWithIntrinsicBounds(test, null, null, null);
}
};
DisplayUtils.downloadIcon(getUserAccountManager(),
clientFactory,
this,
firstQuota.getIconUrl(),
target,
R.drawable.ic_link);
} else {
mQuotaTextLink.setVisibility(View.GONE);
}
} else {
mQuotaTextLink.setVisibility(View.GONE);
}
}
}
/**
* checks/highlights the provided menu item if the drawer has been initialized and the menu item exists.
*
* @param menuItemId the menu item to be highlighted
*/
protected void setDrawerMenuItemChecked(int menuItemId) {
if (mNavigationView != null && mNavigationView.getMenu().findItem(menuItemId) != null) {
viewThemeUtils.platform.colorNavigationView(mNavigationView);
mCheckedMenuItem = menuItemId;
mNavigationView.getMenu().findItem(menuItemId).setChecked(true);
} else {
Log_OC.w(TAG, "setDrawerMenuItemChecked has been called with invalid menu-item-ID");
}
}
/**
* Retrieves and shows the user quota if available
*/
private void getAndDisplayUserQuota() {
// set user space information
Thread t = new Thread(() -> {
final User user = accountManager.getUser();
if (user.isAnonymous()) {
return;
}
final Context context = MainApp.getAppContext();
NextcloudClient nextcloudClient = null;
try {
nextcloudClient = OwnCloudClientManagerFactory
.getDefaultSingleton()
.getNextcloudClientFor(user.toOwnCloudAccount(),
context);
} catch (OperationCanceledException | AuthenticatorException | IOException e) {
Log_OC.e(this, "Error retrieving user quota", e);
}
if (nextcloudClient == null) {
return;
}
RemoteOperationResult<UserInfo> result = new GetUserInfoRemoteOperation().execute(nextcloudClient);
if (result.isSuccess() && result.getResultData() != null) {
final UserInfo userInfo = result.getResultData();
final Quota quota = userInfo.getQuota();
if (quota != null) {
final long used = quota.getUsed();
final long total = quota.getTotal();
final int relative = (int) Math.ceil(quota.getRelative());
final long quotaValue = quota.getQuota();
runOnUiThread(() -> {
if (quotaValue > 0 || quotaValue == GetUserInfoRemoteOperation.SPACE_UNLIMITED
|| quotaValue == GetUserInfoRemoteOperation.QUOTA_LIMIT_INFO_NOT_AVAILABLE) {
/*
* show quota in case
* it is available and calculated (> 0) or
* in case of legacy servers (==QUOTA_LIMIT_INFO_NOT_AVAILABLE)
*/
setQuotaInformation(used, total, relative, quotaValue);
} else {
/*
* quotaValue < 0 means special cases like
* {@link RemoteGetUserQuotaOperation.SPACE_NOT_COMPUTED},
* {@link RemoteGetUserQuotaOperation.SPACE_UNKNOWN} or
* {@link RemoteGetUserQuotaOperation.SPACE_UNLIMITED}
* thus don't display any quota information.
*/
showQuota(false);
}
});
}
}
});
t.start();
}
private void updateExternalLinksInDrawer() {
if (mNavigationView != null && getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
mNavigationView.getMenu().removeGroup(R.id.drawer_menu_external_links);
int greyColor = ContextCompat.getColor(this, R.color.drawer_menu_icon);
for (final ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.LINK)) {
int id = mNavigationView.getMenu().add(R.id.drawer_menu_external_links,
MENU_ITEM_EXTERNAL_LINK + link.getId(), MENU_ORDER_EXTERNAL_LINKS, link.getName())
.setCheckable(true).getItemId();
MenuSimpleTarget target = new MenuSimpleTarget<Drawable>(id) {
@Override
public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
setExternalLinkIcon(getIdMenuItem(), resource, greyColor);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
setExternalLinkIcon(getIdMenuItem(), errorDrawable, greyColor);
}
};
DisplayUtils.downloadIcon(getUserAccountManager(),
clientFactory,
this,
link.getIconUrl(),
target,
R.drawable.ic_link);
}
setDrawerMenuItemChecked(mCheckedMenuItem);
}
}
private void setExternalLinkIcon(int id, Drawable drawable, int greyColor) {
MenuItem menuItem = mNavigationView.getMenu().findItem(id);
if (menuItem != null) {
if (drawable != null) {
menuItem.setIcon(viewThemeUtils.platform.colorDrawable(drawable, greyColor));
} else {
menuItem.setIcon(R.drawable.ic_link);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mIsAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false);
mCheckedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE);
}
externalLinksProvider = new ExternalLinksProvider(getContentResolver());
arbitraryDataProvider = new ArbitraryDataProviderImpl(this);
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, mIsAccountChooserActive);
outState.putInt(KEY_CHECKED_MENU_ITEM, mCheckedMenuItem);
}
@Override
public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mIsAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false);
mCheckedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE);
// check/highlight the menu item if present
if (mCheckedMenuItem > Menu.NONE || mCheckedMenuItem < Menu.NONE) {
setDrawerMenuItemChecked(mCheckedMenuItem);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
if (mDrawerToggle != null) {
mDrawerToggle.syncState();
if (isDrawerOpen()) {
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
updateExternalLinksInDrawer();
updateQuotaLink();
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mDrawerToggle != null) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
@Override
public void onBackPressed() {
if (isDrawerOpen()) {
closeDrawer();
return;
}
Fragment fileDetailsSharingProcessFragment =
getSupportFragmentManager().findFragmentByTag(FileDetailsSharingProcessFragment.TAG);
if (fileDetailsSharingProcessFragment != null) {
((FileDetailsSharingProcessFragment) fileDetailsSharingProcessFragment).onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
protected void onResume() {
super.onResume();
setDrawerMenuItemChecked(mCheckedMenuItem);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// update Account list and active account if Manage Account activity replies with
// - ACCOUNT_LIST_CHANGED = true
// - RESULT_OK
if (requestCode == ACTION_MANAGE_ACCOUNTS && resultCode == RESULT_OK
&& data.getBooleanExtra(ManageAccountsActivity.KEY_ACCOUNT_LIST_CHANGED, false)) {
// current account has changed
if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) {
setAccount(accountManager.getCurrentAccount(), false);
restart();
}
} else if (requestCode == PassCodeManager.PASSCODE_ACTIVITY && data != null) {
int result = data.getIntExtra(RequestCredentialsActivity.KEY_CHECK_RESULT,