DrawerActivity.java 61 KB

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