DrawerActivity.java 59 KB

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