DrawerActivity.java 59 KB

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