DrawerActivity.java 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /*
  2. * Nextcloud Android client application
  3. *
  4. * @author Andy Scherzinger
  5. * @author Tobias Kaminsky
  6. * @author Chris Narkiewicz <hello@ezaquarii.com>
  7. * Copyright (C) 2016 Andy Scherzinger
  8. * Copyright (C) 2017 Tobias Kaminsky
  9. * Copyright (C) 2016 Nextcloud
  10. * Copyright (C) 2016 ownCloud Inc.
  11. * Copyright (C) 2020 Chris Narkiewicz <hello@ezaquarii.com>
  12. *
  13. * This program is free software; you can redistribute it and/or
  14. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  15. * License as published by the Free Software Foundation; either
  16. * version 3 of the License, or any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public
  24. * License along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. */
  26. package com.owncloud.android.ui.activity;
  27. import android.app.Activity;
  28. import android.content.Context;
  29. import android.content.Intent;
  30. import android.content.res.Configuration;
  31. import android.graphics.drawable.ColorDrawable;
  32. import android.graphics.drawable.Drawable;
  33. import android.graphics.drawable.LayerDrawable;
  34. import android.net.Uri;
  35. import android.os.Build;
  36. import android.os.Bundle;
  37. import android.os.Handler;
  38. import android.os.SystemClock;
  39. import android.text.Html;
  40. import android.text.TextUtils;
  41. import android.view.Menu;
  42. import android.view.MenuItem;
  43. import android.view.View;
  44. import android.view.ViewGroup;
  45. import android.webkit.URLUtil;
  46. import android.widget.ImageView;
  47. import android.widget.LinearLayout;
  48. import android.widget.ProgressBar;
  49. import android.widget.TextView;
  50. import com.bumptech.glide.Glide;
  51. import com.bumptech.glide.request.animation.GlideAnimation;
  52. import com.bumptech.glide.request.target.SimpleTarget;
  53. import com.google.android.material.button.MaterialButton;
  54. import com.google.android.material.navigation.NavigationView;
  55. import com.nextcloud.client.account.User;
  56. import com.nextcloud.client.di.Injectable;
  57. import com.nextcloud.client.network.ClientFactory;
  58. import com.nextcloud.client.onboarding.FirstRunActivity;
  59. import com.nextcloud.client.preferences.AppPreferences;
  60. import com.nextcloud.client.preferences.DarkMode;
  61. import com.nextcloud.java.util.Optional;
  62. import com.owncloud.android.MainApp;
  63. import com.owncloud.android.R;
  64. import com.owncloud.android.authentication.PassCodeManager;
  65. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  66. import com.owncloud.android.datamodel.ExternalLinksProvider;
  67. import com.owncloud.android.datamodel.FileDataStorageManager;
  68. import com.owncloud.android.datamodel.OCFile;
  69. import com.owncloud.android.lib.common.ExternalLink;
  70. import com.owncloud.android.lib.common.ExternalLinkType;
  71. import com.owncloud.android.lib.common.Quota;
  72. import com.owncloud.android.lib.common.UserInfo;
  73. import com.owncloud.android.lib.common.accounts.ExternalLinksOperation;
  74. import com.owncloud.android.lib.common.operations.RemoteOperation;
  75. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  76. import com.owncloud.android.lib.common.utils.Log_OC;
  77. import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
  78. import com.owncloud.android.lib.resources.status.CapabilityBooleanType;
  79. import com.owncloud.android.lib.resources.status.OCCapability;
  80. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  81. import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
  82. import com.owncloud.android.operations.GetCapabilitiesOperation;
  83. import com.owncloud.android.ui.TextDrawable;
  84. import com.owncloud.android.ui.activities.ActivitiesActivity;
  85. import com.owncloud.android.ui.events.AccountRemovedEvent;
  86. import com.owncloud.android.ui.events.ChangeMenuEvent;
  87. import com.owncloud.android.ui.events.DummyDrawerEvent;
  88. import com.owncloud.android.ui.events.SearchEvent;
  89. import com.owncloud.android.ui.fragment.OCFileListFragment;
  90. import com.owncloud.android.ui.fragment.PhotoFragment;
  91. import com.owncloud.android.ui.trashbin.TrashbinActivity;
  92. import com.owncloud.android.utils.DisplayUtils;
  93. import com.owncloud.android.utils.DrawerMenuUtil;
  94. import com.owncloud.android.utils.FilesSyncHelper;
  95. import com.owncloud.android.utils.ThemeUtils;
  96. import com.owncloud.android.utils.svg.MenuSimpleTarget;
  97. import org.greenrobot.eventbus.EventBus;
  98. import org.greenrobot.eventbus.Subscribe;
  99. import org.greenrobot.eventbus.ThreadMode;
  100. import org.parceler.Parcels;
  101. import java.util.ArrayList;
  102. import java.util.Collections;
  103. import java.util.List;
  104. import javax.inject.Inject;
  105. import androidx.annotation.NonNull;
  106. import androidx.appcompat.app.ActionBarDrawerToggle;
  107. import androidx.appcompat.app.AppCompatDelegate;
  108. import androidx.core.content.ContextCompat;
  109. import androidx.core.view.GravityCompat;
  110. import androidx.drawerlayout.widget.DrawerLayout;
  111. import kotlin.collections.CollectionsKt;
  112. /**
  113. * Base class to handle setup of the drawer implementation including user switching and avatar fetching and fallback
  114. * generation.
  115. */
  116. public abstract class DrawerActivity extends ToolbarActivity
  117. implements DisplayUtils.AvatarGenerationListener, Injectable {
  118. private static final String TAG = DrawerActivity.class.getSimpleName();
  119. private static final String KEY_IS_ACCOUNT_CHOOSER_ACTIVE = "IS_ACCOUNT_CHOOSER_ACTIVE";
  120. private static final String KEY_CHECKED_MENU_ITEM = "CHECKED_MENU_ITEM";
  121. private static final int ACTION_MANAGE_ACCOUNTS = 101;
  122. private static final int MENU_ORDER_ACCOUNT = 1;
  123. private static final int MENU_ORDER_ACCOUNT_FUNCTION = 2;
  124. private static final int MENU_ORDER_EXTERNAL_LINKS = 3;
  125. private static final int MENU_ITEM_EXTERNAL_LINK = 111;
  126. /**
  127. * menu account avatar radius.
  128. */
  129. private float mMenuAccountAvatarRadiusDimension;
  130. /**
  131. * current account avatar radius.
  132. */
  133. private float mCurrentAccountAvatarRadiusDimension;
  134. /**
  135. * other accounts avatar radius.
  136. */
  137. private float mOtherAccountAvatarRadiusDimension;
  138. /**
  139. * Reference to the drawer layout.
  140. */
  141. protected DrawerLayout mDrawerLayout;
  142. /**
  143. * Reference to the drawer toggle.
  144. */
  145. protected ActionBarDrawerToggle mDrawerToggle;
  146. /**
  147. * Reference to the navigation view.
  148. */
  149. private NavigationView mNavigationView;
  150. /**
  151. * Reference to the account chooser toggle.
  152. */
  153. private ImageView mAccountChooserToggle;
  154. /**
  155. * Reference to the middle account avatar.
  156. */
  157. private ImageView mAccountMiddleAccountAvatar;
  158. /**
  159. * Reference to the end account avatar.
  160. */
  161. private ImageView mAccountEndAccountAvatar;
  162. /**
  163. * Flag to signal if the account chooser is active.
  164. */
  165. private boolean mIsAccountChooserActive;
  166. /**
  167. * Id of the checked menu item.
  168. */
  169. private int mCheckedMenuItem = Menu.NONE;
  170. /**
  171. * accounts for the (max) three displayed accounts in the drawer header.
  172. */
  173. private List<User> mAvatars = Collections.emptyList();
  174. /**
  175. * container layout of the quota view.
  176. */
  177. private LinearLayout mQuotaView;
  178. /**
  179. * progress bar of the quota view.
  180. */
  181. private ProgressBar mQuotaProgressBar;
  182. /**
  183. * text view of the quota view.
  184. */
  185. private TextView mQuotaTextPercentage;
  186. private TextView mQuotaTextLink;
  187. /**
  188. * runnable that will be executed after the drawer has been closed.
  189. */
  190. private Runnable pendingRunnable;
  191. private ExternalLinksProvider externalLinksProvider;
  192. private ArbitraryDataProvider arbitraryDataProvider;
  193. @Inject
  194. AppPreferences preferences;
  195. @Inject
  196. ClientFactory clientFactory;
  197. /**
  198. * Initializes the drawer, its content and highlights the menu item with the given id.
  199. * This method needs to be called after the content view has been set.
  200. *
  201. * @param menuItemId the menu item to be checked/highlighted
  202. */
  203. protected void setupDrawer(int menuItemId) {
  204. setupDrawer();
  205. setDrawerMenuItemChecked(menuItemId);
  206. }
  207. /**
  208. * Initializes the drawer and its content.
  209. * This method needs to be called after the content view has been set.
  210. */
  211. protected void setupDrawer() {
  212. mDrawerLayout = findViewById(R.id.drawer_layout);
  213. mNavigationView = findViewById(R.id.nav_view);
  214. if (mNavigationView != null) {
  215. setupDrawerHeader();
  216. setupDrawerMenu(mNavigationView);
  217. setupQuotaElement();
  218. }
  219. setupDrawerToggle();
  220. if (getSupportActionBar() != null) {
  221. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  222. }
  223. }
  224. /**
  225. * initializes and sets up the drawer toggle.
  226. */
  227. private void setupDrawerToggle() {
  228. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
  229. /** Called when a drawer has settled in a completely closed state. */
  230. public void onDrawerClosed(View view) {
  231. super.onDrawerClosed(view);
  232. // standard behavior of drawer is to switch to the standard menu on closing
  233. if (mIsAccountChooserActive) {
  234. toggleAccountList();
  235. }
  236. supportInvalidateOptionsMenu();
  237. mDrawerToggle.setDrawerIndicatorEnabled(isDrawerIndicatorAvailable());
  238. if (pendingRunnable != null) {
  239. new Handler().post(pendingRunnable);
  240. pendingRunnable = null;
  241. }
  242. closeDrawer();
  243. }
  244. /** Called when a drawer has settled in a completely open state. */
  245. public void onDrawerOpened(View drawerView) {
  246. super.onDrawerOpened(drawerView);
  247. mDrawerToggle.setDrawerIndicatorEnabled(true);
  248. supportInvalidateOptionsMenu();
  249. }
  250. };
  251. // Set the drawer toggle as the DrawerListener
  252. mDrawerLayout.addDrawerListener(mDrawerToggle);
  253. mDrawerToggle.setDrawerIndicatorEnabled(true);
  254. mDrawerToggle.setDrawerSlideAnimationEnabled(true);
  255. Drawable backArrow = getResources().getDrawable(R.drawable.ic_arrow_back);
  256. mDrawerToggle.setHomeAsUpIndicator(ThemeUtils.tintDrawable(backArrow, ThemeUtils.appBarPrimaryFontColor(this)));
  257. mDrawerToggle.getDrawerArrowDrawable().setColor(ThemeUtils.appBarPrimaryFontColor(this));
  258. }
  259. /**
  260. * initializes and sets up the drawer header.
  261. */
  262. private void setupDrawerHeader() {
  263. mAccountMiddleAccountAvatar = (ImageView) findNavigationViewChildById(R.id.drawer_account_middle);
  264. mAccountEndAccountAvatar = (ImageView) findNavigationViewChildById(R.id.drawer_account_end);
  265. mAccountChooserToggle = (ImageView) findNavigationViewChildById(R.id.drawer_account_chooser_toggle);
  266. if (getResources().getBoolean(R.bool.allow_profile_click)) {
  267. mAccountChooserToggle.setImageResource(R.drawable.ic_down);
  268. findNavigationViewChildById(R.id.drawer_active_user)
  269. .setOnClickListener(new View.OnClickListener() {
  270. @Override
  271. public void onClick(View v) {
  272. toggleAccountList();
  273. }
  274. });
  275. } else {
  276. mAccountChooserToggle.setVisibility(View.GONE);
  277. }
  278. }
  279. /**
  280. * setup quota elements of the drawer.
  281. */
  282. private void setupQuotaElement() {
  283. mQuotaView = (LinearLayout) findQuotaViewById(R.id.drawer_quota);
  284. mQuotaProgressBar = (ProgressBar) findQuotaViewById(R.id.drawer_quota_ProgressBar);
  285. mQuotaTextPercentage = (TextView) findQuotaViewById(R.id.drawer_quota_percentage);
  286. mQuotaTextLink = (TextView) findQuotaViewById(R.id.drawer_quota_link);
  287. ThemeUtils.colorProgressBar(mQuotaProgressBar, ThemeUtils.primaryColor(this));
  288. }
  289. /**
  290. * setup drawer content, basically setting the item selected listener.
  291. *
  292. * @param navigationView the drawers navigation view
  293. */
  294. protected void setupDrawerMenu(NavigationView navigationView) {
  295. navigationView.setItemIconTintList(null);
  296. // setup actions for drawer menu items
  297. navigationView.setNavigationItemSelectedListener(
  298. new NavigationView.OnNavigationItemSelectedListener() {
  299. @Override
  300. public boolean onNavigationItemSelected(@NonNull final MenuItem menuItem) {
  301. mDrawerLayout.closeDrawers();
  302. // pending runnable will be executed after the drawer has been closed
  303. pendingRunnable = new Runnable() {
  304. @Override
  305. public void run() {
  306. onNavigationItemClicked(menuItem);
  307. }
  308. };
  309. return true;
  310. }
  311. });
  312. // handle correct state
  313. if (mIsAccountChooserActive) {
  314. navigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, true);
  315. } else {
  316. navigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false);
  317. }
  318. User account = accountManager.getUser();
  319. filterDrawerMenu(navigationView.getMenu(), account);
  320. }
  321. private void filterDrawerMenu(final Menu menu, @NonNull final User user) {
  322. FileDataStorageManager storageManager = new FileDataStorageManager(user.toPlatformAccount(),
  323. getContentResolver());
  324. OCCapability capability = storageManager.getCapability(user.getAccountName());
  325. DrawerMenuUtil.filterSearchMenuItems(menu, user, getResources(), true);
  326. DrawerMenuUtil.filterTrashbinMenuItem(menu, user, capability);
  327. DrawerMenuUtil.filterActivityMenuItem(menu, capability);
  328. DrawerMenuUtil.setupHomeMenuItem(menu, getResources());
  329. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_community,
  330. !getResources().getBoolean(R.bool.participate_enabled));
  331. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_shared, !getResources().getBoolean(R.bool.shared_enabled));
  332. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_contacts, !getResources().getBoolean(R.bool.contacts_backup)
  333. || !getResources().getBoolean(R.bool.show_drawer_contacts_backup));
  334. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_synced_folders,
  335. getResources().getBoolean(R.bool.syncedFolder_light));
  336. DrawerMenuUtil.removeMenuItem(menu, R.id.nav_logout, !getResources().getBoolean(R.bool.show_drawer_logout));
  337. }
  338. @Subscribe(threadMode = ThreadMode.MAIN)
  339. public void onMessageEvent(DummyDrawerEvent event) {
  340. unsetAllDrawerMenuItems();
  341. }
  342. private void onNavigationItemClicked(final MenuItem menuItem) {
  343. setDrawerMenuItemChecked(menuItem.getItemId());
  344. if (menuItem.getGroupId() == R.id.drawer_menu_accounts) {
  345. handleAccountItemClick(menuItem);
  346. return;
  347. }
  348. switch (menuItem.getItemId()) {
  349. case R.id.nav_all_files:
  350. showFiles(false);
  351. if ((this instanceof FileDisplayActivity) &&
  352. !(((FileDisplayActivity) this).getListOfFilesFragment() instanceof PhotoFragment)) {
  353. ((FileDisplayActivity) this).browseToRoot();
  354. EventBus.getDefault().post(new ChangeMenuEvent());
  355. } else {
  356. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  357. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  358. intent.setAction(FileDisplayActivity.ALL_FILES);
  359. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId());
  360. startActivity(intent);
  361. }
  362. break;
  363. case R.id.nav_favorites:
  364. handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.FAVORITE_SEARCH),
  365. menuItem.getItemId());
  366. break;
  367. case R.id.nav_photos:
  368. startPhotoSearch(menuItem);
  369. break;
  370. case R.id.nav_on_device:
  371. EventBus.getDefault().post(new ChangeMenuEvent());
  372. showFiles(true);
  373. break;
  374. case R.id.nav_uploads:
  375. startActivity(UploadListActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
  376. break;
  377. case R.id.nav_trashbin:
  378. startActivity(TrashbinActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
  379. break;
  380. case R.id.nav_activity:
  381. startActivity(ActivitiesActivity.class, Intent.FLAG_ACTIVITY_CLEAR_TOP);
  382. break;
  383. case R.id.nav_notifications:
  384. startActivity(NotificationsActivity.class);
  385. break;
  386. case R.id.nav_synced_folders:
  387. startActivity(SyncedFoldersActivity.class);
  388. break;
  389. case R.id.nav_contacts:
  390. startActivity(ContactsPreferenceActivity.class);
  391. break;
  392. case R.id.nav_settings:
  393. startActivity(SettingsActivity.class);
  394. break;
  395. case R.id.nav_community:
  396. startActivity(CommunityActivity.class);
  397. break;
  398. case R.id.nav_logout:
  399. mCheckedMenuItem = -1;
  400. menuItem.setChecked(false);
  401. final Optional<User> optionalUser = getUser();
  402. if (optionalUser.isPresent()) {
  403. UserInfoActivity.openAccountRemovalConfirmationDialog(optionalUser.get(), getSupportFragmentManager());
  404. }
  405. break;
  406. case R.id.nav_shared:
  407. handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.SHARED_FILTER),
  408. menuItem.getItemId());
  409. break;
  410. case R.id.nav_recently_modified:
  411. handleSearchEvents(new SearchEvent("", SearchRemoteOperation.SearchType.RECENTLY_MODIFIED_SEARCH),
  412. menuItem.getItemId());
  413. break;
  414. default:
  415. if (menuItem.getItemId() >= MENU_ITEM_EXTERNAL_LINK &&
  416. menuItem.getItemId() <= MENU_ITEM_EXTERNAL_LINK + 100) {
  417. // external link clicked
  418. externalLinkClicked(menuItem);
  419. } else {
  420. Log_OC.i(TAG, "Unknown drawer menu item clicked: " + menuItem.getTitle());
  421. }
  422. break;
  423. }
  424. }
  425. private void startActivity(Class<? extends Activity> activity) {
  426. startActivity(new Intent(getApplicationContext(), activity));
  427. }
  428. private void startActivity(Class<? extends Activity> activity, int flags) {
  429. Intent intent = new Intent(getApplicationContext(), activity);
  430. intent.setFlags(flags);
  431. startActivity(intent);
  432. }
  433. private void handleAccountItemClick(MenuItem menuItem) {
  434. switch (menuItem.getItemId()) {
  435. case R.id.drawer_menu_account_add:
  436. boolean isProviderOrOwnInstallationVisible = getResources()
  437. .getBoolean(R.bool.show_provider_or_own_installation);
  438. if (isProviderOrOwnInstallationVisible) {
  439. Intent firstRunIntent = new Intent(getApplicationContext(), FirstRunActivity.class);
  440. firstRunIntent.putExtra(FirstRunActivity.EXTRA_ALLOW_CLOSE, true);
  441. startActivity(firstRunIntent);
  442. } else {
  443. startAccountCreation();
  444. }
  445. break;
  446. case R.id.drawer_menu_account_manage:
  447. openManageAccounts();
  448. break;
  449. default:
  450. accountClicked(menuItem.getItemId());
  451. break;
  452. }
  453. }
  454. public void openManageAccounts() {
  455. Intent manageAccountsIntent = new Intent(getApplicationContext(), ManageAccountsActivity.class);
  456. startActivityForResult(manageAccountsIntent, ACTION_MANAGE_ACCOUNTS);
  457. }
  458. private void startPhotoSearch(MenuItem menuItem) {
  459. SearchEvent searchEvent = new SearchEvent("image/%", SearchRemoteOperation.SearchType.PHOTO_SEARCH);
  460. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  461. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  462. intent.setAction(Intent.ACTION_SEARCH);
  463. intent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(searchEvent));
  464. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItem.getItemId());
  465. startActivity(intent);
  466. }
  467. private void handleSearchEvents(SearchEvent searchEvent, int menuItemId) {
  468. if (this instanceof FileDisplayActivity) {
  469. if (((FileDisplayActivity) this).getListOfFilesFragment() instanceof PhotoFragment) {
  470. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  471. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  472. intent.setAction(Intent.ACTION_SEARCH);
  473. intent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(searchEvent));
  474. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItemId);
  475. startActivity(intent);
  476. } else {
  477. EventBus.getDefault().post(searchEvent);
  478. }
  479. } else {
  480. Intent intent = new Intent(getApplicationContext(), FileDisplayActivity.class);
  481. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  482. intent.setAction(Intent.ACTION_SEARCH);
  483. intent.putExtra(OCFileListFragment.SEARCH_EVENT, Parcels.wrap(searchEvent));
  484. intent.putExtra(FileDisplayActivity.DRAWER_MENU_ID, menuItemId);
  485. startActivity(intent);
  486. }
  487. }
  488. /**
  489. * show the file list to the user.
  490. *
  491. * @param onDeviceOnly flag to decide if all files or only the ones on the device should be shown
  492. */
  493. public abstract void showFiles(boolean onDeviceOnly);
  494. /**
  495. * sets the new/current account and restarts. In case the given account equals the actual/current account the
  496. * call will be ignored.
  497. *
  498. * @param hashCode HashCode of account to be set
  499. */
  500. private void accountClicked(int hashCode) {
  501. final User currentUser = accountManager.getUser();
  502. if (currentUser.hashCode() != hashCode && accountManager.setCurrentOwnCloudAccount(hashCode)) {
  503. fetchExternalLinks(true);
  504. restart();
  505. }
  506. }
  507. private void externalLinkClicked(MenuItem menuItem){
  508. for (ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.LINK)) {
  509. if (menuItem.getTitle().toString().equalsIgnoreCase(link.name)) {
  510. if (link.redirect) {
  511. Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link.url));
  512. DisplayUtils.startIntentIfAppAvailable(intent, this, R.string.no_browser_available);
  513. } else {
  514. Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
  515. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, link.name);
  516. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, link.url);
  517. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true);
  518. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, menuItem.getItemId());
  519. startActivity(externalWebViewIntent);
  520. }
  521. }
  522. }
  523. }
  524. /**
  525. * click method for mini avatars in drawer header.
  526. *
  527. * @param view the clicked ImageView
  528. */
  529. public void onAccountDrawerClick(View view) {
  530. accountClicked((int) view.getTag());
  531. }
  532. /**
  533. * checks if the drawer exists and is opened.
  534. *
  535. * @return <code>true</code> if the drawer is open, else <code>false</code>
  536. */
  537. public boolean isDrawerOpen() {
  538. return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
  539. }
  540. /**
  541. * closes the drawer.
  542. */
  543. public void closeDrawer() {
  544. if (mDrawerLayout != null) {
  545. mDrawerLayout.closeDrawer(GravityCompat.START);
  546. }
  547. }
  548. /**
  549. * opens the drawer.
  550. */
  551. public void openDrawer() {
  552. if (mDrawerLayout != null) {
  553. mDrawerLayout.openDrawer(GravityCompat.START);
  554. updateExternalLinksInDrawer();
  555. updateQuotaLink();
  556. }
  557. }
  558. /**
  559. * Enable or disable interaction with all drawers.
  560. *
  561. * @param lockMode The new lock mode for the given drawer. One of {@link DrawerLayout#LOCK_MODE_UNLOCKED},
  562. * {@link DrawerLayout#LOCK_MODE_LOCKED_CLOSED} or {@link DrawerLayout#LOCK_MODE_LOCKED_OPEN}.
  563. */
  564. public void setDrawerLockMode(int lockMode) {
  565. if (mDrawerLayout != null) {
  566. mDrawerLayout.setDrawerLockMode(lockMode);
  567. }
  568. }
  569. /**
  570. * Enable or disable the drawer indicator.
  571. *
  572. * @param enable true to enable, false to disable
  573. */
  574. public void setDrawerIndicatorEnabled(boolean enable) {
  575. if (mDrawerToggle != null) {
  576. mDrawerToggle.setDrawerIndicatorEnabled(enable);
  577. }
  578. }
  579. /**
  580. * updates the account list in the drawer.
  581. */
  582. public void updateAccountList() {
  583. List<User> users = accountManager.getAllUsers();
  584. ArrayList<User> persistingAccounts = new ArrayList<>();
  585. for (User user: users) {
  586. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(user.toPlatformAccount(),
  587. ManageAccountsActivity.PENDING_FOR_REMOVAL);
  588. if (!pendingForRemoval) {
  589. persistingAccounts.add(user);
  590. }
  591. }
  592. if (mNavigationView != null && mDrawerLayout != null) {
  593. if (persistingAccounts.size() > 0) {
  594. repopulateAccountList(persistingAccounts);
  595. setAccountInDrawer(accountManager.getUser());
  596. mAvatars = getUserAvatars();
  597. // activate second/end account avatar
  598. final User secondUser = mAvatars.size() > 1 ? mAvatars.get(1) : null;
  599. if (secondUser != null) {
  600. mAccountEndAccountAvatar.setTag(secondUser.hashCode());
  601. DisplayUtils.setAvatar(secondUser,
  602. this,
  603. mOtherAccountAvatarRadiusDimension,
  604. getResources(),
  605. mAccountEndAccountAvatar,
  606. this);
  607. mAccountEndAccountAvatar.setVisibility(View.VISIBLE);
  608. } else {
  609. mAccountEndAccountAvatar.setVisibility(View.GONE);
  610. }
  611. // activate third/middle account avatar
  612. final User thirdUser = mAvatars.size() > 2 ? mAvatars.get(2) : null;
  613. if (thirdUser != null) {
  614. mAccountMiddleAccountAvatar.setTag(thirdUser.hashCode());
  615. DisplayUtils.setAvatar(thirdUser,
  616. this,
  617. mOtherAccountAvatarRadiusDimension,
  618. getResources(),
  619. mAccountMiddleAccountAvatar,
  620. this);
  621. mAccountMiddleAccountAvatar.setVisibility(View.VISIBLE);
  622. } else {
  623. mAccountMiddleAccountAvatar.setVisibility(View.GONE);
  624. }
  625. } else {
  626. mAccountEndAccountAvatar.setVisibility(View.GONE);
  627. mAccountMiddleAccountAvatar.setVisibility(View.GONE);
  628. }
  629. }
  630. }
  631. /**
  632. * re-populates the account list.
  633. *
  634. * @param users list of users
  635. */
  636. private void repopulateAccountList(List<User> users) {
  637. // remove all accounts from list
  638. mNavigationView.getMenu().removeGroup(R.id.drawer_menu_accounts);
  639. // add all accounts to list
  640. for (User user: users) {
  641. try {
  642. // show all accounts except the currently active one and those pending for removal
  643. if (!getAccount().name.equals(user.getAccountName())) {
  644. MenuItem accountMenuItem = mNavigationView.getMenu().add(
  645. R.id.drawer_menu_accounts,
  646. user.hashCode(),
  647. MENU_ORDER_ACCOUNT,
  648. DisplayUtils.getAccountNameDisplayText(user))
  649. .setIcon(TextDrawable.createAvatar(user.toPlatformAccount(),
  650. mMenuAccountAvatarRadiusDimension));
  651. DisplayUtils.setAvatar(user, this, mMenuAccountAvatarRadiusDimension, getResources(),
  652. accountMenuItem, this);
  653. }
  654. } catch (Exception e) {
  655. Log_OC.e(TAG, "Error calculating RGB value for account menu item.", e);
  656. mNavigationView.getMenu().add(
  657. R.id.drawer_menu_accounts,
  658. user.hashCode(),
  659. MENU_ORDER_ACCOUNT,
  660. DisplayUtils.getAccountNameDisplayText(user))
  661. .setIcon(R.drawable.ic_user);
  662. }
  663. }
  664. // re-add add-account and manage-accounts
  665. mNavigationView.getMenu().add(R.id.drawer_menu_accounts, R.id.drawer_menu_account_add,
  666. MENU_ORDER_ACCOUNT_FUNCTION,
  667. getResources().getString(R.string.prefs_add_account)).setIcon(R.drawable.ic_account_plus);
  668. mNavigationView.getMenu().add(R.id.drawer_menu_accounts, R.id.drawer_menu_account_manage,
  669. MENU_ORDER_ACCOUNT_FUNCTION,
  670. getResources().getString(R.string.drawer_manage_accounts)).setIcon(R.drawable.nav_settings);
  671. // adding sets menu group back to visible, so safety check and setting invisible
  672. showMenu();
  673. }
  674. /**
  675. * Updates title bar and home buttons (state and icon).
  676. * Assumes that navigation drawer is NOT visible.
  677. */
  678. protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
  679. super.updateActionBarTitleAndHomeButton(chosenFile);
  680. // set home button properties
  681. if (mDrawerToggle != null) {
  682. if (chosenFile != null && isRoot(chosenFile)) {
  683. mDrawerToggle.setDrawerIndicatorEnabled(true);
  684. } else {
  685. mDrawerToggle.setDrawerIndicatorEnabled(false);
  686. }
  687. }
  688. }
  689. /**
  690. * sets the given account name in the drawer in case the drawer is available. The account name is shortened
  691. * beginning from the @-sign in the username.
  692. *
  693. * @param user the account to be set in the drawer
  694. */
  695. protected void setAccountInDrawer(User user) {
  696. if (mDrawerLayout != null && user != null) {
  697. TextView username = (TextView) findNavigationViewChildById(R.id.drawer_username);
  698. TextView usernameFull = (TextView) findNavigationViewChildById(R.id.drawer_username_full);
  699. String name = user.getAccountName();
  700. usernameFull.setText(DisplayUtils.convertIdn(name.substring(name.lastIndexOf('@') + 1),
  701. false));
  702. usernameFull.setTextColor(ThemeUtils.fontColor(this));
  703. username.setText(user.toOwnCloudAccount().getDisplayName());
  704. username.setTextColor(ThemeUtils.fontColor(this));
  705. View currentAccountView = findNavigationViewChildById(R.id.drawer_current_account);
  706. currentAccountView.setTag(name);
  707. DisplayUtils.setAvatar(user, this, mCurrentAccountAvatarRadiusDimension, getResources(),
  708. currentAccountView, this);
  709. // check and show quota info if available
  710. getAndDisplayUserQuota();
  711. }
  712. }
  713. /**
  714. * Toggle between standard menu and account list including saving the state.
  715. */
  716. private void toggleAccountList() {
  717. mIsAccountChooserActive = !mIsAccountChooserActive;
  718. showMenu();
  719. }
  720. /**
  721. * depending on the #mIsAccountChooserActive flag shows the account chooser or the standard menu.
  722. */
  723. private void showMenu() {
  724. if (mNavigationView != null) {
  725. if (mIsAccountChooserActive) {
  726. if (mAccountChooserToggle != null) {
  727. mAccountChooserToggle.setImageResource(R.drawable.ic_up);
  728. }
  729. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, true);
  730. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  731. mNavigationView.getMenu().findItem(R.id.drawer_menu_account_add) != null) {
  732. mNavigationView.getMenu().removeItem(R.id.drawer_menu_account_add);
  733. }
  734. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, false);
  735. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_external_links, false);
  736. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_bottom, false);
  737. } else {
  738. if (mAccountChooserToggle != null) {
  739. mAccountChooserToggle.setImageResource(R.drawable.ic_down);
  740. }
  741. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false);
  742. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, true);
  743. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_external_links, true);
  744. mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_bottom, true);
  745. }
  746. }
  747. }
  748. /**
  749. * shows or hides the quota UI elements.
  750. *
  751. * @param showQuota show/hide quota information
  752. */
  753. private void showQuota(boolean showQuota) {
  754. if (showQuota) {
  755. mQuotaView.setVisibility(View.VISIBLE);
  756. } else {
  757. mQuotaView.setVisibility(View.GONE);
  758. }
  759. }
  760. /**
  761. * configured the quota to be displayed.
  762. * @param usedSpace the used space
  763. * @param totalSpace the total space
  764. * @param relative the percentage of space already used
  765. * @param quotaValue {@link GetUserInfoRemoteOperation#SPACE_UNLIMITED} or other to determinate state
  766. */
  767. private void setQuotaInformation(long usedSpace, long totalSpace, int relative, long quotaValue) {
  768. if (GetUserInfoRemoteOperation.SPACE_UNLIMITED == quotaValue) {
  769. mQuotaTextPercentage.setText(String.format(
  770. getString(R.string.drawer_quota_unlimited),
  771. DisplayUtils.bytesToHumanReadable(usedSpace)));
  772. } else {
  773. mQuotaTextPercentage.setText(String.format(
  774. getString(R.string.drawer_quota),
  775. DisplayUtils.bytesToHumanReadable(usedSpace),
  776. DisplayUtils.bytesToHumanReadable(totalSpace)));
  777. }
  778. mQuotaProgressBar.setProgress(relative);
  779. ThemeUtils.colorProgressBar(mQuotaProgressBar, DisplayUtils.getRelativeInfoColor(this, relative));
  780. updateQuotaLink();
  781. showQuota(true);
  782. }
  783. protected void unsetAllDrawerMenuItems() {
  784. if (mNavigationView != null && mNavigationView.getMenu() != null) {
  785. Menu menu = mNavigationView.getMenu();
  786. for (int i = 0; i < menu.size(); i++) {
  787. menu.getItem(i).setChecked(false);
  788. }
  789. }
  790. mCheckedMenuItem = Menu.NONE;
  791. }
  792. private void updateQuotaLink() {
  793. if (mQuotaTextLink != null) {
  794. if (getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  795. List<ExternalLink> quotas = externalLinksProvider.getExternalLink(ExternalLinkType.QUOTA);
  796. float density = getResources().getDisplayMetrics().density;
  797. final int size = Math.round(24 * density);
  798. if (quotas.size() > 0) {
  799. final ExternalLink firstQuota = quotas.get(0);
  800. mQuotaTextLink.setText(firstQuota.name);
  801. mQuotaTextLink.setClickable(true);
  802. mQuotaTextLink.setVisibility(View.VISIBLE);
  803. mQuotaTextLink.setOnClickListener(new View.OnClickListener() {
  804. @Override
  805. public void onClick(View v) {
  806. Intent externalWebViewIntent = new Intent(getApplicationContext(), ExternalSiteWebView.class);
  807. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_TITLE, firstQuota.name);
  808. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_URL, firstQuota.url);
  809. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_SHOW_SIDEBAR, true);
  810. externalWebViewIntent.putExtra(ExternalSiteWebView.EXTRA_MENU_ITEM_ID, -1);
  811. startActivity(externalWebViewIntent);
  812. }
  813. });
  814. SimpleTarget target = new SimpleTarget<Drawable>() {
  815. @Override
  816. public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
  817. Drawable test = resource.getCurrent();
  818. test.setBounds(0, 0, size, size);
  819. mQuotaTextLink.setCompoundDrawablesWithIntrinsicBounds(test, null, null, null);
  820. }
  821. @Override
  822. public void onLoadFailed(Exception e, Drawable errorDrawable) {
  823. super.onLoadFailed(e, errorDrawable);
  824. Drawable test = errorDrawable.getCurrent();
  825. test.setBounds(0, 0, size, size);
  826. mQuotaTextLink.setCompoundDrawablesWithIntrinsicBounds(test, null, null, null);
  827. }
  828. };
  829. DisplayUtils.downloadIcon(getUserAccountManager(),
  830. clientFactory,
  831. this,
  832. firstQuota.iconUrl,
  833. target,
  834. R.drawable.ic_link,
  835. size,
  836. size);
  837. } else {
  838. mQuotaTextLink.setVisibility(View.GONE);
  839. }
  840. } else {
  841. mQuotaTextLink.setVisibility(View.GONE);
  842. }
  843. }
  844. }
  845. /**
  846. * checks/highlights the provided menu item if the drawer has been initialized and the menu item exists.
  847. *
  848. * @param menuItemId the menu item to be highlighted
  849. */
  850. protected void setDrawerMenuItemChecked(int menuItemId) {
  851. if (mNavigationView != null && mNavigationView.getMenu() != null &&
  852. mNavigationView.getMenu().findItem(menuItemId) != null) {
  853. MenuItem item = mNavigationView.getMenu().findItem(menuItemId);
  854. item.setChecked(true);
  855. // reset all tinted icons
  856. for (int i = 0; i < mNavigationView.getMenu().size(); i++) {
  857. MenuItem menuItem = mNavigationView.getMenu().getItem(i);
  858. if (menuItem.getIcon() != null) {
  859. menuItem.getIcon().clearColorFilter();
  860. if (menuItem.getGroupId() != R.id.drawer_menu_accounts
  861. || menuItem.getItemId() == R.id.drawer_menu_account_add
  862. || menuItem.getItemId() == R.id.drawer_menu_account_manage) {
  863. ThemeUtils.tintDrawable(
  864. menuItem.getIcon(), ContextCompat.getColor(this, R.color.drawer_menu_icon));
  865. }
  866. menuItem.setTitle(Html.fromHtml(
  867. "<font color='"
  868. + ThemeUtils.colorToHexString(ContextCompat.getColor(this, R.color.drawer_text_color))
  869. + "'>" + menuItem.getTitle()
  870. + "</font>"));
  871. }
  872. }
  873. int elementColor = ThemeUtils.elementColor(this);
  874. ThemeUtils.tintDrawable(item.getIcon(), elementColor);
  875. String colorHex = ThemeUtils.colorToHexString(elementColor);
  876. item.setTitle(Html.fromHtml("<font color='" + colorHex + "'>" + item.getTitle() + "</font>"));
  877. mCheckedMenuItem = menuItemId;
  878. } else {
  879. Log_OC.w(TAG, "setDrawerMenuItemChecked has been called with invalid menu-item-ID");
  880. }
  881. }
  882. /**
  883. * Retrieves and shows the user quota if available
  884. */
  885. private void getAndDisplayUserQuota() {
  886. // set user space information
  887. Thread t = new Thread(new Runnable() {
  888. public void run() {
  889. final User user = accountManager.getUser();
  890. if (user.isAnonymous()) {
  891. return;
  892. }
  893. final Context context = MainApp.getAppContext();
  894. RemoteOperationResult result = new GetUserInfoRemoteOperation().execute(user.toPlatformAccount(), context);
  895. if (result.isSuccess() && result.getData() != null) {
  896. final UserInfo userInfo = (UserInfo) result.getData().get(0);
  897. final Quota quota = userInfo.getQuota();
  898. if (quota != null) {
  899. final long used = quota.getUsed();
  900. final long total = quota.getTotal();
  901. final int relative = (int) Math.ceil(quota.getRelative());
  902. final long quotaValue = quota.getQuota();
  903. runOnUiThread(new Runnable() {
  904. @Override
  905. public void run() {
  906. if (quotaValue > 0 || quotaValue == GetUserInfoRemoteOperation.SPACE_UNLIMITED
  907. || quotaValue == GetUserInfoRemoteOperation.QUOTA_LIMIT_INFO_NOT_AVAILABLE) {
  908. /*
  909. * show quota in case
  910. * it is available and calculated (> 0) or
  911. * in case of legacy servers (==QUOTA_LIMIT_INFO_NOT_AVAILABLE)
  912. */
  913. setQuotaInformation(used, total, relative, quotaValue);
  914. } else {
  915. /*
  916. * quotaValue < 0 means special cases like
  917. * {@link RemoteGetUserQuotaOperation.SPACE_NOT_COMPUTED},
  918. * {@link RemoteGetUserQuotaOperation.SPACE_UNKNOWN} or
  919. * {@link RemoteGetUserQuotaOperation.SPACE_UNLIMITED}
  920. * thus don't display any quota information.
  921. */
  922. showQuota(false);
  923. }
  924. }
  925. });
  926. }
  927. }
  928. }
  929. });
  930. t.start();
  931. }
  932. public void updateExternalLinksInDrawer() {
  933. if (mNavigationView != null && getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  934. mNavigationView.getMenu().removeGroup(R.id.drawer_menu_external_links);
  935. float density = getResources().getDisplayMetrics().density;
  936. final int size = Math.round(24 * density);
  937. int greyColor = ContextCompat.getColor(this, R.color.drawer_menu_icon);
  938. for (final ExternalLink link : externalLinksProvider.getExternalLink(ExternalLinkType.LINK)) {
  939. int id = mNavigationView.getMenu().add(R.id.drawer_menu_external_links,
  940. MENU_ITEM_EXTERNAL_LINK + link.id, MENU_ORDER_EXTERNAL_LINKS, link.name)
  941. .setCheckable(true).getItemId();
  942. MenuSimpleTarget target = new MenuSimpleTarget<Drawable>(id) {
  943. @Override
  944. public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
  945. setExternalLinkIcon(getIdMenuItem(), resource, greyColor);
  946. }
  947. @Override
  948. public void onLoadFailed(Exception e, Drawable errorDrawable) {
  949. super.onLoadFailed(e, errorDrawable);
  950. setExternalLinkIcon(getIdMenuItem(), errorDrawable, greyColor);
  951. }
  952. };
  953. DisplayUtils.downloadIcon(getUserAccountManager(),
  954. clientFactory,
  955. this,
  956. link.iconUrl,
  957. target,
  958. R.drawable.ic_link,
  959. size,
  960. size);
  961. }
  962. setDrawerMenuItemChecked(mCheckedMenuItem);
  963. }
  964. }
  965. private void setExternalLinkIcon(int id, Drawable drawable, int greyColor) {
  966. MenuItem menuItem = mNavigationView.getMenu().findItem(id);
  967. if (menuItem != null) {
  968. if (drawable != null) {
  969. menuItem.setIcon(ThemeUtils.tintDrawable(drawable, greyColor));
  970. } else {
  971. menuItem.setIcon(R.drawable.ic_link);
  972. }
  973. }
  974. }
  975. public void updateHeaderBackground() {
  976. if (getAccount() != null &&
  977. getStorageManager().getCapability(getAccount().name).getServerBackground() != null) {
  978. final ViewGroup navigationHeader = (ViewGroup) findNavigationViewChildById(R.id.drawer_header_view);
  979. if (navigationHeader != null) {
  980. OCCapability capability = getStorageManager().getCapability(getAccount().name);
  981. String background = capability.getServerBackground();
  982. CapabilityBooleanType backgroundDefault = capability.getServerBackgroundDefault();
  983. CapabilityBooleanType backgroundPlain = capability.getServerBackgroundPlain();
  984. int primaryColor = ThemeUtils.primaryColor(getAccount(), false, this);
  985. if (backgroundDefault.isTrue() && backgroundPlain.isTrue()) {
  986. // use only solid color
  987. setNavigationHeaderBackground(new ColorDrawable(primaryColor), navigationHeader);
  988. } else if (backgroundDefault.isTrue() && backgroundPlain.isFalse()) {
  989. // use nc13 background image with themed color
  990. Drawable[] drawables = {new ColorDrawable(primaryColor),
  991. getResources().getDrawable(R.drawable.background)};
  992. LayerDrawable layerDrawable = new LayerDrawable(drawables);
  993. setNavigationHeaderBackground(layerDrawable, navigationHeader);
  994. } else {
  995. // use url
  996. if (URLUtil.isValidUrl(background) || background.isEmpty()) {
  997. // background image
  998. SimpleTarget target = new SimpleTarget<Drawable>() {
  999. @Override
  1000. public void onResourceReady(Drawable resource, GlideAnimation glideAnimation) {
  1001. Drawable[] drawables = {new ColorDrawable(primaryColor), resource};
  1002. LayerDrawable layerDrawable = new LayerDrawable(drawables);
  1003. setNavigationHeaderBackground(layerDrawable, navigationHeader);
  1004. }
  1005. @Override
  1006. public void onLoadFailed(Exception e, Drawable errorDrawable) {
  1007. Drawable[] drawables = {new ColorDrawable(primaryColor), errorDrawable};
  1008. LayerDrawable layerDrawable = new LayerDrawable(drawables);
  1009. setNavigationHeaderBackground(layerDrawable, navigationHeader);
  1010. }
  1011. };
  1012. int backgroundResource;
  1013. OwnCloudVersion ownCloudVersion = accountManager.getServerVersion(getAccount());
  1014. if (ownCloudVersion.compareTo(OwnCloudVersion.nextcloud_18) >= 0) {
  1015. backgroundResource = R.drawable.background_nc18;
  1016. } else {
  1017. backgroundResource = R.drawable.background;
  1018. }
  1019. Glide.with(this)
  1020. .load(background)
  1021. .centerCrop()
  1022. .placeholder(backgroundResource)
  1023. .error(backgroundResource)
  1024. .crossFade()
  1025. .into(target);
  1026. } else {
  1027. // plain color
  1028. setNavigationHeaderBackground(new ColorDrawable(primaryColor), navigationHeader);
  1029. }
  1030. }
  1031. }
  1032. }
  1033. }
  1034. private void setNavigationHeaderBackground(Drawable drawable, ViewGroup navigationHeader) {
  1035. final ImageView background = navigationHeader.findViewById(R.id.drawer_header_background);
  1036. background.setImageDrawable(drawable);
  1037. }
  1038. @Override
  1039. protected void onCreate(Bundle savedInstanceState) {
  1040. super.onCreate(savedInstanceState);
  1041. if (savedInstanceState != null) {
  1042. mIsAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false);
  1043. mCheckedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE);
  1044. }
  1045. mCurrentAccountAvatarRadiusDimension = getResources()
  1046. .getDimension(R.dimen.nav_drawer_header_avatar_radius);
  1047. mOtherAccountAvatarRadiusDimension = getResources()
  1048. .getDimension(R.dimen.nav_drawer_header_avatar_other_accounts_radius);
  1049. mMenuAccountAvatarRadiusDimension = getResources()
  1050. .getDimension(R.dimen.nav_drawer_menu_avatar_radius);
  1051. externalLinksProvider = new ExternalLinksProvider(getContentResolver());
  1052. arbitraryDataProvider = new ArbitraryDataProvider(getContentResolver());
  1053. }
  1054. @Override
  1055. protected void onSaveInstanceState(@NonNull Bundle outState) {
  1056. super.onSaveInstanceState(outState);
  1057. outState.putBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, mIsAccountChooserActive);
  1058. outState.putInt(KEY_CHECKED_MENU_ITEM, mCheckedMenuItem);
  1059. }
  1060. @Override
  1061. public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
  1062. super.onRestoreInstanceState(savedInstanceState);
  1063. mIsAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false);
  1064. mCheckedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE);
  1065. // (re-)setup drawer state
  1066. showMenu();
  1067. // check/highlight the menu item if present
  1068. if (mCheckedMenuItem > Menu.NONE || mCheckedMenuItem < Menu.NONE) {
  1069. setDrawerMenuItemChecked(mCheckedMenuItem);
  1070. }
  1071. }
  1072. @Override
  1073. protected void onPostCreate(Bundle savedInstanceState) {
  1074. super.onPostCreate(savedInstanceState);
  1075. // Sync the toggle state after onRestoreInstanceState has occurred.
  1076. if (mDrawerToggle != null) {
  1077. mDrawerToggle.syncState();
  1078. if (isDrawerOpen()) {
  1079. mDrawerToggle.setDrawerIndicatorEnabled(true);
  1080. }
  1081. }
  1082. updateAccountList();
  1083. updateExternalLinksInDrawer();
  1084. updateQuotaLink();
  1085. updateHeaderBackground();
  1086. }
  1087. @Override
  1088. public void onConfigurationChanged(@NonNull Configuration newConfig) {
  1089. super.onConfigurationChanged(newConfig);
  1090. if (mDrawerToggle != null) {
  1091. mDrawerToggle.onConfigurationChanged(newConfig);
  1092. }
  1093. }
  1094. @Override
  1095. public void onBackPressed() {
  1096. if (isDrawerOpen()) {
  1097. closeDrawer();
  1098. return;
  1099. }
  1100. super.onBackPressed();
  1101. }
  1102. @Override
  1103. protected void onResume() {
  1104. super.onResume();
  1105. if (AppCompatDelegate.getDefaultNightMode() != AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) {
  1106. getDelegate().setLocalNightMode(DarkMode.DARK == preferences.getDarkThemeMode() ?
  1107. AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
  1108. getDelegate().applyDayNight();
  1109. }
  1110. setDrawerMenuItemChecked(mCheckedMenuItem);
  1111. }
  1112. @Override
  1113. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  1114. super.onActivityResult(requestCode, resultCode, data);
  1115. // update Account list and active account if Manage Account activity replies with
  1116. // - ACCOUNT_LIST_CHANGED = true
  1117. // - RESULT_OK
  1118. if (requestCode == ACTION_MANAGE_ACCOUNTS && resultCode == RESULT_OK
  1119. && data.getBooleanExtra(ManageAccountsActivity.KEY_ACCOUNT_LIST_CHANGED, false)) {
  1120. // current account has changed
  1121. if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) {
  1122. setAccount(accountManager.getCurrentAccount(), false);
  1123. updateAccountList();
  1124. restart();
  1125. } else {
  1126. updateAccountList();
  1127. }
  1128. } else if (requestCode == PassCodeManager.PASSCODE_ACTIVITY &&
  1129. Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && data != null) {
  1130. int result = data.getIntExtra(RequestCredentialsActivity.KEY_CHECK_RESULT,
  1131. RequestCredentialsActivity.KEY_CHECK_RESULT_FALSE);
  1132. if (result == RequestCredentialsActivity.KEY_CHECK_RESULT_CANCEL) {
  1133. Log_OC.d(TAG, "PassCodeManager cancelled");
  1134. preferences.setLockTimestamp(0);
  1135. finish();
  1136. }
  1137. }
  1138. }
  1139. /**
  1140. * Finds a view that was identified by the id attribute from the drawer header.
  1141. *
  1142. * @param id the view's id
  1143. * @return The view if found or <code>null</code> otherwise.
  1144. */
  1145. private View findNavigationViewChildById(int id) {
  1146. NavigationView view = findViewById(R.id.nav_view);
  1147. if (view != null) {
  1148. return view.getHeaderView(0).findViewById(id);
  1149. } else {
  1150. return null;
  1151. }
  1152. }
  1153. /**
  1154. * Quota view can be either at navigation bottom or header
  1155. *
  1156. * @param id the view's id
  1157. * @return The view if found or <code>null</code> otherwise.
  1158. */
  1159. private View findQuotaViewById(int id) {
  1160. View v = ((NavigationView) findViewById(R.id.nav_view)).getHeaderView(0).findViewById(id);
  1161. if (v != null) {
  1162. return v;
  1163. } else {
  1164. return findViewById(id);
  1165. }
  1166. }
  1167. /**
  1168. * restart helper method which is called after a changing the current account.
  1169. */
  1170. protected abstract void restart();
  1171. /**
  1172. * Get list of users suitable for displaying in navigation drawer header.
  1173. * First item is always current {@link User}. Remaining items are other
  1174. * users possible to switch to.
  1175. *
  1176. * @return List of available users
  1177. */
  1178. @NonNull
  1179. private List<User> getUserAvatars() {
  1180. User currentUser = accountManager.getUser();
  1181. List<User> availableUsers = CollectionsKt.filter(accountManager.getAllUsers(), user ->
  1182. !TextUtils.equals(user.getAccountName(), currentUser.getAccountName()) &&
  1183. !arbitraryDataProvider.getBooleanValue(user.toPlatformAccount(),
  1184. ManageAccountsActivity.PENDING_FOR_REMOVAL)
  1185. );
  1186. availableUsers.add(0, currentUser);
  1187. return availableUsers;
  1188. }
  1189. @Override
  1190. public void avatarGenerated(Drawable avatarDrawable, Object callContext) {
  1191. if (callContext instanceof MenuItem) {
  1192. MenuItem menuItem = (MenuItem) callContext;
  1193. menuItem.setIcon(avatarDrawable);
  1194. } else if (callContext instanceof ImageView) {
  1195. ImageView imageView = (ImageView) callContext;
  1196. imageView.setImageDrawable(avatarDrawable);
  1197. } else if (callContext instanceof MaterialButton) {
  1198. MaterialButton materialButton = (MaterialButton) callContext;
  1199. materialButton.setIcon(avatarDrawable);
  1200. }
  1201. }
  1202. @Override
  1203. public boolean shouldCallGeneratedCallback(String tag, Object callContext) {
  1204. if (callContext instanceof MenuItem) {
  1205. MenuItem menuItem = (MenuItem) callContext;
  1206. return String.valueOf(menuItem.getTitle()).equals(tag);
  1207. } else if (callContext instanceof ImageView) {
  1208. ImageView imageView = (ImageView) callContext;
  1209. return String.valueOf(imageView.getTag()).equals(tag);
  1210. } else if (callContext instanceof MaterialButton) {
  1211. MaterialButton materialButton = (MaterialButton) callContext;
  1212. return String.valueOf(materialButton.getTag()).equals(tag);
  1213. }
  1214. return false;
  1215. }
  1216. /**
  1217. * Adds other listeners to react on changes of the drawer layout.
  1218. *
  1219. * @param listener Object interested in changes of the drawer layout.
  1220. */
  1221. public void addDrawerListener(DrawerLayout.DrawerListener listener) {
  1222. if (mDrawerLayout != null) {
  1223. mDrawerLayout.addDrawerListener(listener);
  1224. } else {
  1225. Log_OC.e(TAG, "Drawer layout not ready to add drawer listener");
  1226. }
  1227. }
  1228. public boolean isDrawerIndicatorAvailable() {
  1229. return true;
  1230. }
  1231. @Override
  1232. protected void onStart() {
  1233. super.onStart();
  1234. EventBus.getDefault().register(this);
  1235. }
  1236. @Override
  1237. protected void onStop() {
  1238. if (preferences.getLockTimestamp() != 0) {
  1239. preferences.setLockTimestamp(SystemClock.elapsedRealtime());
  1240. }
  1241. EventBus.getDefault().unregister(this);
  1242. super.onStop();
  1243. }
  1244. @Subscribe(threadMode = ThreadMode.MAIN)
  1245. public void onAccountRemovedEvent(AccountRemovedEvent event) {
  1246. updateAccountList();
  1247. restart();
  1248. }
  1249. /**
  1250. * Retrieves external links via api from 'external' app
  1251. */
  1252. public void fetchExternalLinks(final boolean force) {
  1253. if (getBaseContext().getResources().getBoolean(R.bool.show_external_links)) {
  1254. Thread t = new Thread(() -> {
  1255. // fetch capabilities as early as possible
  1256. if ((getCapabilities() == null || getCapabilities().getAccountName().isEmpty())
  1257. && getStorageManager() != null) {
  1258. GetCapabilitiesOperation getCapabilities = new GetCapabilitiesOperation();
  1259. getCapabilities.execute(getStorageManager(), getBaseContext());
  1260. }
  1261. User user = accountManager.getUser();
  1262. String name = user.getAccountName();
  1263. if (getStorageManager() != null && getStorageManager().getCapability(name) != null &&
  1264. getStorageManager().getCapability(name).getExternalLinks().isTrue()) {
  1265. int count = arbitraryDataProvider.getIntegerValue(FilesSyncHelper.GLOBAL,
  1266. FileActivity.APP_OPENED_COUNT);
  1267. if (count > 10 || count == -1 || force) {
  1268. if (force) {
  1269. Log_OC.d("ExternalLinks", "force update");
  1270. }
  1271. arbitraryDataProvider.storeOrUpdateKeyValue(FilesSyncHelper.GLOBAL,
  1272. FileActivity.APP_OPENED_COUNT, "0");
  1273. Log_OC.d("ExternalLinks", "update via api");
  1274. RemoteOperation getExternalLinksOperation = new ExternalLinksOperation();
  1275. RemoteOperationResult result = getExternalLinksOperation.execute(user.toPlatformAccount(), this);
  1276. if (result.isSuccess() && result.getData() != null) {
  1277. externalLinksProvider.deleteAllExternalLinks();
  1278. ArrayList<ExternalLink> externalLinks = (ArrayList<ExternalLink>) (Object) result.getData();
  1279. for (ExternalLink link : externalLinks) {
  1280. externalLinksProvider.storeExternalLink(link);
  1281. }
  1282. }
  1283. } else {
  1284. arbitraryDataProvider.storeOrUpdateKeyValue(FilesSyncHelper.GLOBAL,
  1285. FileActivity.APP_OPENED_COUNT, String.valueOf(count + 1));
  1286. }
  1287. } else {
  1288. externalLinksProvider.deleteAllExternalLinks();
  1289. Log_OC.d("ExternalLinks", "links disabled");
  1290. }
  1291. runOnUiThread(this::updateExternalLinksInDrawer);
  1292. });
  1293. t.start();
  1294. }
  1295. }
  1296. }