DrawerActivity.java 60 KB

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