DrawerActivity.java 61 KB

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