OCFileListFragment.java 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * @author David A. Velasco
  7. * Copyright (C) 2011 Bartek Przybylski
  8. * Copyright (C) 2016 ownCloud Inc.
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License version 2,
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. */
  23. package com.owncloud.android.ui.fragment;
  24. import android.content.Context;
  25. import android.content.Intent;
  26. import android.content.SharedPreferences;
  27. import android.os.Build;
  28. import android.os.Bundle;
  29. import android.preference.PreferenceManager;
  30. import android.support.v4.widget.DrawerLayout;
  31. import android.support.v4.widget.SwipeRefreshLayout;
  32. import android.util.SparseBooleanArray;
  33. import android.view.ActionMode;
  34. import android.view.LayoutInflater;
  35. import android.view.Menu;
  36. import android.view.MenuInflater;
  37. import android.view.MenuItem;
  38. import android.view.View;
  39. import android.view.ViewGroup;
  40. import android.widget.AbsListView;
  41. import android.widget.AdapterView;
  42. import android.widget.ListView;
  43. import android.widget.TextView;
  44. import android.widget.Toast;
  45. import com.owncloud.android.MainApp;
  46. import com.owncloud.android.R;
  47. import com.owncloud.android.authentication.AccountUtils;
  48. import com.owncloud.android.datamodel.FileDataStorageManager;
  49. import com.owncloud.android.datamodel.OCFile;
  50. import com.owncloud.android.files.FileMenuFilter;
  51. import com.owncloud.android.lib.common.utils.Log_OC;
  52. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  53. import com.owncloud.android.ui.activity.FileActivity;
  54. import com.owncloud.android.ui.activity.FileDisplayActivity;
  55. import com.owncloud.android.ui.activity.FolderPickerActivity;
  56. import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
  57. import com.owncloud.android.ui.activity.UploadFilesActivity;
  58. import com.owncloud.android.ui.adapter.FileListListAdapter;
  59. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  60. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  61. import com.owncloud.android.ui.dialog.RemoveFilesDialogFragment;
  62. import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
  63. import com.owncloud.android.ui.helpers.SparseBooleanArrayParcelable;
  64. import com.owncloud.android.ui.interfaces.ExtendedListFragmentInterface;
  65. import com.owncloud.android.ui.preview.PreviewImageFragment;
  66. import com.owncloud.android.ui.preview.PreviewMediaFragment;
  67. import com.owncloud.android.ui.preview.PreviewTextFragment;
  68. import com.owncloud.android.utils.DisplayUtils;
  69. import com.owncloud.android.utils.FileStorageUtils;
  70. import java.io.File;
  71. import java.util.ArrayList;
  72. import java.util.List;
  73. /**
  74. * A Fragment that lists all files and folders in a given path.
  75. *
  76. * TODO refactor to get rid of direct dependency on FileDisplayActivity
  77. */
  78. public class OCFileListFragment extends ExtendedListFragment implements ExtendedListFragmentInterface {
  79. private static final String TAG = OCFileListFragment.class.getSimpleName();
  80. private static final String MY_PACKAGE = OCFileListFragment.class.getPackage() != null ?
  81. OCFileListFragment.class.getPackage().getName() : "com.owncloud.android.ui.fragment";
  82. public final static String ARG_JUST_FOLDERS = MY_PACKAGE + ".JUST_FOLDERS";
  83. public final static String ARG_ALLOW_CONTEXTUAL_ACTIONS = MY_PACKAGE + ".ALLOW_CONTEXTUAL";
  84. public final static String ARG_HIDE_FAB = MY_PACKAGE + ".HIDE_FAB";
  85. private static final String KEY_FILE = MY_PACKAGE + ".extra.FILE";
  86. private static final String KEY_FAB_EVER_CLICKED = "FAB_EVER_CLICKED";
  87. private static final String GRID_IS_PREFERED_PREFERENCE = "gridIsPrefered";
  88. private static final String DIALOG_CREATE_FOLDER = "DIALOG_CREATE_FOLDER";
  89. private FileFragment.ContainerActivity mContainerActivity;
  90. private OCFile mFile = null;
  91. private FileListListAdapter mAdapter;
  92. private boolean mJustFolders;
  93. private int mSystemBarActionModeColor;
  94. private int mSystemBarColor;
  95. private int mProgressBarActionModeColor;
  96. private int mProgressBarColor;
  97. private boolean mHideFab = true;
  98. private boolean miniFabClicked = false;
  99. private ActionMode mActiveActionMode;
  100. private OCFileListFragment.MultiChoiceModeListener mMultiChoiceModeListener;
  101. @Override
  102. public void onCreate(Bundle savedInstanceState) {
  103. super.onCreate(savedInstanceState);
  104. setHasOptionsMenu(true);
  105. mSystemBarActionModeColor = getResources().getColor(R.color.action_mode_status_bar_background);
  106. mSystemBarColor = getResources().getColor(R.color.primary_dark);
  107. mProgressBarActionModeColor = getResources().getColor(R.color.action_mode_background);
  108. mProgressBarColor = getResources().getColor(R.color.primary);
  109. mMultiChoiceModeListener = new MultiChoiceModeListener();
  110. }
  111. /**
  112. * {@inheritDoc}
  113. */
  114. @Override
  115. public void onAttach(Context context) {
  116. super.onAttach(context);
  117. Log_OC.i(TAG, "onAttach");
  118. try {
  119. mContainerActivity = (FileFragment.ContainerActivity) context;
  120. } catch (ClassCastException e) {
  121. throw new ClassCastException(context.toString() + " must implement " +
  122. FileFragment.ContainerActivity.class.getSimpleName());
  123. }
  124. try {
  125. setOnRefreshListener((OnEnforceableRefreshListener) context);
  126. } catch (ClassCastException e) {
  127. throw new ClassCastException(context.toString() + " must implement " +
  128. SwipeRefreshLayout.OnRefreshListener.class.getSimpleName());
  129. }
  130. }
  131. /**
  132. * {@inheritDoc}
  133. */
  134. @Override
  135. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  136. Log_OC.i(TAG, "onCreateView() start");
  137. View v = super.onCreateView(inflater, container, savedInstanceState);
  138. Bundle args = getArguments();
  139. boolean allowContextualActions = (args != null) && args.getBoolean(ARG_ALLOW_CONTEXTUAL_ACTIONS, false);
  140. if (allowContextualActions) {
  141. setChoiceModeAsMultipleModal(savedInstanceState);
  142. }
  143. Log_OC.i(TAG, "onCreateView() end");
  144. return v;
  145. }
  146. @Override
  147. public void onDetach() {
  148. setOnRefreshListener(null);
  149. mContainerActivity = null;
  150. super.onDetach();
  151. }
  152. /**
  153. * {@inheritDoc}
  154. */
  155. @Override
  156. public void onActivityCreated(Bundle savedInstanceState) {
  157. super.onActivityCreated(savedInstanceState);
  158. Log_OC.i(TAG, "onActivityCreated() start");
  159. if (savedInstanceState != null) {
  160. mFile = savedInstanceState.getParcelable(KEY_FILE);
  161. }
  162. if (mJustFolders) {
  163. setFooterEnabled(false);
  164. } else {
  165. setFooterEnabled(true);
  166. }
  167. Bundle args = getArguments();
  168. mJustFolders = (args != null) && args.getBoolean(ARG_JUST_FOLDERS, false);
  169. mAdapter = new FileListListAdapter(
  170. mJustFolders,
  171. getActivity(),
  172. mContainerActivity,
  173. this
  174. );
  175. setListAdapter(mAdapter);
  176. mHideFab = (args != null) && args.getBoolean(ARG_HIDE_FAB, false);
  177. if (mHideFab) {
  178. setFabEnabled(false);
  179. } else {
  180. setFabEnabled(true);
  181. registerFabListeners();
  182. // detect if a mini FAB has ever been clicked
  183. final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
  184. if(prefs.getLong(KEY_FAB_EVER_CLICKED, 0) > 0) {
  185. miniFabClicked = true;
  186. }
  187. // add labels to the min FABs when none of them has ever been clicked on
  188. if(!miniFabClicked) {
  189. setFabLabels();
  190. } else {
  191. removeFabLabels();
  192. }
  193. }
  194. }
  195. /**
  196. * adds labels to all mini FABs.
  197. */
  198. private void setFabLabels() {
  199. getFabUpload().setTitle(getResources().getString(R.string.actionbar_upload));
  200. getFabMkdir().setTitle(getResources().getString(R.string.actionbar_mkdir));
  201. getFabUploadFromApp().setTitle(getResources().getString(R.string.actionbar_upload_from_apps));
  202. }
  203. /**
  204. * registers all listeners on all mini FABs.
  205. */
  206. private void registerFabListeners() {
  207. registerFabUploadListeners();
  208. registerFabMkDirListeners();
  209. registerFabUploadFromAppListeners();
  210. }
  211. /**
  212. * registers {@link android.view.View.OnClickListener} and {@link android.view.View.OnLongClickListener}
  213. * on the Upload mini FAB for the linked action and {@link Toast} showing the underlying action.
  214. */
  215. private void registerFabUploadListeners() {
  216. getFabUpload().setOnClickListener(new View.OnClickListener() {
  217. @Override
  218. public void onClick(View v) {
  219. UploadFilesActivity.startUploadActivityForResult(getActivity(), ((FileActivity) getActivity())
  220. .getAccount(), FileDisplayActivity.REQUEST_CODE__SELECT_FILES_FROM_FILE_SYSTEM);
  221. getFabMain().collapse();
  222. recordMiniFabClick();
  223. }
  224. });
  225. getFabUpload().setOnLongClickListener(new View.OnLongClickListener() {
  226. @Override
  227. public boolean onLongClick(View v) {
  228. Toast.makeText(getActivity(), R.string.actionbar_upload, Toast.LENGTH_SHORT).show();
  229. return true;
  230. }
  231. });
  232. }
  233. /**
  234. * registers {@link android.view.View.OnClickListener} and {@link android.view.View.OnLongClickListener}
  235. * on the 'Create Dir' mini FAB for the linked action and {@link Toast} showing the underlying action.
  236. */
  237. private void registerFabMkDirListeners() {
  238. getFabMkdir().setOnClickListener(new View.OnClickListener() {
  239. @Override
  240. public void onClick(View v) {
  241. CreateFolderDialogFragment dialog =
  242. CreateFolderDialogFragment.newInstance(mFile);
  243. dialog.show(getActivity().getSupportFragmentManager(), DIALOG_CREATE_FOLDER);
  244. getFabMain().collapse();
  245. recordMiniFabClick();
  246. }
  247. });
  248. getFabMkdir().setOnLongClickListener(new View.OnLongClickListener() {
  249. @Override
  250. public boolean onLongClick(View v) {
  251. Toast.makeText(getActivity(), R.string.actionbar_mkdir, Toast.LENGTH_SHORT).show();
  252. return true;
  253. }
  254. });
  255. }
  256. /**
  257. * registers {@link android.view.View.OnClickListener} and {@link android.view.View.OnLongClickListener}
  258. * on the Upload from App mini FAB for the linked action and {@link Toast} showing the underlying action.
  259. */
  260. private void registerFabUploadFromAppListeners() {
  261. getFabUploadFromApp().setOnClickListener(new View.OnClickListener() {
  262. @Override
  263. public void onClick(View v) {
  264. Intent action = new Intent(Intent.ACTION_GET_CONTENT);
  265. action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
  266. //Intent.EXTRA_ALLOW_MULTIPLE is only supported on api level 18+, Jelly Bean
  267. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  268. action.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
  269. }
  270. getActivity().startActivityForResult(
  271. Intent.createChooser(action, getString(R.string.upload_chooser_title)),
  272. FileDisplayActivity.REQUEST_CODE__SELECT_CONTENT_FROM_APPS
  273. );
  274. getFabMain().collapse();
  275. recordMiniFabClick();
  276. }
  277. });
  278. getFabUploadFromApp().setOnLongClickListener(new View.OnLongClickListener() {
  279. @Override
  280. public boolean onLongClick(View v) {
  281. Toast.makeText(getActivity(),
  282. R.string.actionbar_upload_from_apps,
  283. Toast.LENGTH_SHORT).show();
  284. return true;
  285. }
  286. });
  287. }
  288. /**
  289. * records a click on a mini FAB and thus:
  290. * <ol>
  291. * <li>persists the click fact</li>
  292. * <li>removes the mini FAB labels</li>
  293. * </ol>
  294. */
  295. private void recordMiniFabClick() {
  296. // only record if it hasn't been done already at some other time
  297. if(!miniFabClicked) {
  298. final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
  299. sp.edit().putLong(KEY_FAB_EVER_CLICKED, 1).apply();
  300. miniFabClicked = true;
  301. }
  302. }
  303. /**
  304. * removes the labels on all known min FABs.
  305. */
  306. private void removeFabLabels() {
  307. getFabUpload().setTitle(null);
  308. getFabMkdir().setTitle(null);
  309. getFabUploadFromApp().setTitle(null);
  310. ((TextView) getFabUpload().getTag(
  311. com.getbase.floatingactionbutton.R.id.fab_label)).setVisibility(View.GONE);
  312. ((TextView) getFabMkdir().getTag(
  313. com.getbase.floatingactionbutton.R.id.fab_label)).setVisibility(View.GONE);
  314. ((TextView) getFabUploadFromApp().getTag(
  315. com.getbase.floatingactionbutton.R.id.fab_label)).setVisibility(View.GONE);
  316. }
  317. @Override
  318. public void finishedFiltering() {
  319. updateFooter();
  320. }
  321. /**
  322. * Handler for multiple selection mode.
  323. *
  324. * Manages input from the user when one or more files or folders are selected in the list.
  325. *
  326. * Also listens to changes in navigation drawer to hide and recover multiple selection when it's opened
  327. * and closed.
  328. */
  329. private class MultiChoiceModeListener
  330. implements AbsListView.MultiChoiceModeListener, DrawerLayout.DrawerListener {
  331. private static final String KEY_ACTION_MODE_CLOSED_BY_DRAWER = "KILLED_ACTION_MODE";
  332. private static final String KEY_SELECTION_WHEN_CLOSED_BY_DRAWER = "CHECKED_ITEMS";
  333. /**
  334. * True when action mode is finished because the drawer was opened
  335. */
  336. private boolean mActionModeClosedByDrawer = false;
  337. /**
  338. * Selected items in list when action mode is closed by drawer
  339. */
  340. private SparseBooleanArray mSelectionWhenActionModeClosedByDrawer = null;
  341. @Override
  342. public void onDrawerSlide(View drawerView, float slideOffset) {
  343. // nothing to do
  344. }
  345. @Override
  346. public void onDrawerOpened(View drawerView) {
  347. // nothing to do
  348. }
  349. /**
  350. * When the navigation drawer is closed, action mode is recovered in the same state as was
  351. * when the drawer was (started to be) opened.
  352. *
  353. * @param drawerView Navigation drawer just closed.
  354. */
  355. @Override
  356. public void onDrawerClosed(View drawerView) {
  357. if (mSelectionWhenActionModeClosedByDrawer !=null && mActionModeClosedByDrawer) {
  358. for (int i = 0; i< mSelectionWhenActionModeClosedByDrawer.size(); i++) {
  359. if (mSelectionWhenActionModeClosedByDrawer.valueAt(i)) {
  360. getListView().setItemChecked(
  361. mSelectionWhenActionModeClosedByDrawer.keyAt(i),
  362. true
  363. );
  364. }
  365. }
  366. }
  367. mSelectionWhenActionModeClosedByDrawer = null;
  368. }
  369. /**
  370. * If the action mode is active when the navigation drawer starts to move, the action
  371. * mode is closed and the selection stored to be recovered when the drawer is closed.
  372. *
  373. * @param newState One of STATE_IDLE, STATE_DRAGGING or STATE_SETTLING.
  374. */
  375. @Override
  376. public void onDrawerStateChanged(int newState) {
  377. if (DrawerLayout.STATE_DRAGGING == newState && mActiveActionMode != null) {
  378. mSelectionWhenActionModeClosedByDrawer = getListView().getCheckedItemPositions().clone();
  379. mActiveActionMode.finish();
  380. mActionModeClosedByDrawer = true;
  381. }
  382. }
  383. /**
  384. * Update action mode bar when an item is selected / unselected in the list
  385. */
  386. @Override
  387. public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
  388. getListView().invalidateViews();
  389. mode.invalidate();
  390. }
  391. /**
  392. * Load menu and customize UI when action mode is started.
  393. */
  394. @Override
  395. public boolean onCreateActionMode(ActionMode mode, Menu menu) {
  396. mActiveActionMode = mode;
  397. MenuInflater inflater = getActivity().getMenuInflater();
  398. inflater.inflate(R.menu.file_actions_menu, menu);
  399. mode.invalidate();
  400. //set gray color
  401. DisplayUtils.colorStatusBar(getActivity(), mSystemBarActionModeColor);
  402. DisplayUtils.colorToolbarProgressBar(getActivity(), mProgressBarActionModeColor);
  403. // hide FAB in multi selection mode
  404. setFabEnabled(false);
  405. return true;
  406. }
  407. /**
  408. * Updates available action in menu depending on current selection.
  409. */
  410. @Override
  411. public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
  412. List<OCFile> checkedFiles = mAdapter.getCheckedItems(getListView());
  413. final int checkedCount = checkedFiles.size();
  414. String title = getResources().getQuantityString(
  415. R.plurals.items_selected_count,
  416. checkedCount,
  417. checkedCount
  418. );
  419. mode.setTitle(title);
  420. FileMenuFilter mf = new FileMenuFilter(
  421. checkedFiles,
  422. ((FileActivity) getActivity()).getAccount(),
  423. mContainerActivity,
  424. getActivity()
  425. );
  426. mf.filter(menu);
  427. return true;
  428. }
  429. /**
  430. * Starts the corresponding action when a menu item is tapped by the user.
  431. */
  432. @Override
  433. public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
  434. return onFileActionChosen(item.getItemId());
  435. }
  436. /**
  437. * Restores UI.
  438. */
  439. @Override
  440. public void onDestroyActionMode(ActionMode mode) {
  441. mActiveActionMode = null;
  442. // reset to previous color
  443. DisplayUtils.colorStatusBar(getActivity(), mSystemBarColor);
  444. DisplayUtils.colorToolbarProgressBar(getActivity(), mProgressBarColor);
  445. // show FAB on multi selection mode exit
  446. if(!mHideFab) {
  447. setFabEnabled(true);
  448. }
  449. }
  450. public void storeStateIn(Bundle outState) {
  451. outState.putBoolean(KEY_ACTION_MODE_CLOSED_BY_DRAWER, mActionModeClosedByDrawer);
  452. if (mSelectionWhenActionModeClosedByDrawer != null) {
  453. SparseBooleanArrayParcelable sbap = new SparseBooleanArrayParcelable(
  454. mSelectionWhenActionModeClosedByDrawer
  455. );
  456. outState.putParcelable(KEY_SELECTION_WHEN_CLOSED_BY_DRAWER, sbap);
  457. }
  458. }
  459. public void loadStateFrom(Bundle savedInstanceState) {
  460. mActionModeClosedByDrawer = savedInstanceState.getBoolean(
  461. KEY_ACTION_MODE_CLOSED_BY_DRAWER,
  462. mActionModeClosedByDrawer
  463. );
  464. SparseBooleanArrayParcelable sbap = savedInstanceState.getParcelable(
  465. KEY_SELECTION_WHEN_CLOSED_BY_DRAWER
  466. );
  467. if (sbap != null) {
  468. mSelectionWhenActionModeClosedByDrawer = sbap.getSparseBooleanArray();
  469. }
  470. }
  471. }
  472. /**
  473. * Init listener that will handle interactions in multiple selection mode.
  474. */
  475. private void setChoiceModeAsMultipleModal(Bundle savedInstanceState) {
  476. setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
  477. if (savedInstanceState != null) {
  478. mMultiChoiceModeListener.loadStateFrom(savedInstanceState);
  479. }
  480. setMultiChoiceModeListener(mMultiChoiceModeListener);
  481. ((FileActivity)getActivity()).addDrawerListener(mMultiChoiceModeListener);
  482. }
  483. /**
  484. * Saves the current listed folder.
  485. */
  486. @Override
  487. public void onSaveInstanceState(Bundle outState) {
  488. super.onSaveInstanceState(outState);
  489. outState.putParcelable(KEY_FILE, mFile);
  490. mMultiChoiceModeListener.storeStateIn(outState);
  491. }
  492. @Override
  493. public void onPrepareOptionsMenu (Menu menu) {
  494. changeGridIcon(menu); // this is enough if the option stays out of the action bar
  495. }
  496. /**
  497. * Call this, when the user presses the up button.
  498. *
  499. * Tries to move up the current folder one level. If the parent folder was removed from the
  500. * database, it continues browsing up until finding an existing folders.
  501. * <p/>
  502. * return Count of folder levels browsed up.
  503. */
  504. public int onBrowseUp() {
  505. OCFile parentDir;
  506. int moveCount = 0;
  507. if (mFile != null) {
  508. FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
  509. String parentPath = null;
  510. if (mFile.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
  511. parentPath = new File(mFile.getRemotePath()).getParent();
  512. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
  513. parentPath + OCFile.PATH_SEPARATOR;
  514. parentDir = storageManager.getFileByPath(parentPath);
  515. moveCount++;
  516. } else {
  517. parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
  518. }
  519. while (parentDir == null) {
  520. parentPath = new File(parentPath).getParent();
  521. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
  522. parentPath + OCFile.PATH_SEPARATOR;
  523. parentDir = storageManager.getFileByPath(parentPath);
  524. moveCount++;
  525. } // exit is granted because storageManager.getFileByPath("/") never returns null
  526. mFile = parentDir;
  527. listDirectory(mFile, MainApp.isOnlyOnDevice(), false);
  528. onRefresh(false);
  529. // restore index and top position
  530. restoreIndexAndTopPosition();
  531. } // else - should never happen now
  532. return moveCount;
  533. }
  534. @Override
  535. public void onItemClick(AdapterView<?> l, View v, int position, long id) {
  536. OCFile file = (OCFile) mAdapter.getItem(position);
  537. if (file != null) {
  538. if (file.isFolder()) {
  539. // update state and view of this fragment
  540. listDirectory(file, MainApp.isOnlyOnDevice(), false);
  541. // then, notify parent activity to let it update its state and view
  542. mContainerActivity.onBrowsedDownTo(file);
  543. // save index and top position
  544. saveIndexAndTopPosition(position);
  545. } else { /// Click on a file
  546. if (PreviewImageFragment.canBePreviewed(file)) {
  547. // preview image - it handles the download, if needed
  548. ((FileDisplayActivity)mContainerActivity).startImagePreview(file);
  549. } else if (PreviewTextFragment.canBePreviewed(file)){
  550. ((FileDisplayActivity)mContainerActivity).startTextPreview(file);
  551. } else if (file.isDown()) {
  552. if (PreviewMediaFragment.canBePreviewed(file)) {
  553. // media preview
  554. ((FileDisplayActivity) mContainerActivity).startMediaPreview(file, 0, true);
  555. } else {
  556. mContainerActivity.getFileOperationsHelper().openFile(file);
  557. }
  558. } else {
  559. // automatic download, preview on finish
  560. ((FileDisplayActivity) mContainerActivity).startDownloadForPreview(file);
  561. }
  562. }
  563. } else {
  564. Log_OC.d(TAG, "Null object in ListAdapter!!");
  565. }
  566. }
  567. /**
  568. * Start the appropriate action(s) on the currently selected files given menu selected by the user.
  569. *
  570. * @param menuId Identifier of the action menu selected by the user
  571. * @return 'true' if the menu selection started any action, 'false' otherwise.
  572. */
  573. public boolean onFileActionChosen(int menuId) {
  574. final ArrayList<OCFile> checkedFiles = mAdapter.getCheckedItems(getListView());
  575. if (checkedFiles.size() <= 0) {
  576. return false;
  577. }
  578. if (checkedFiles.size() == 1) {
  579. /// action only possible on a single file
  580. OCFile singleFile = checkedFiles.get(0);
  581. switch (menuId) {
  582. case R.id.action_share_file: {
  583. mContainerActivity.getFileOperationsHelper().showShareFile(singleFile);
  584. return true;
  585. }
  586. case R.id.action_open_file_with: {
  587. mContainerActivity.getFileOperationsHelper().openFile(singleFile);
  588. return true;
  589. }
  590. case R.id.action_rename_file: {
  591. RenameFileDialogFragment dialog = RenameFileDialogFragment.newInstance(singleFile);
  592. dialog.show(getFragmentManager(), FileDetailFragment.FTAG_RENAME_FILE);
  593. return true;
  594. }
  595. case R.id.action_see_details: {
  596. if (mActiveActionMode != null) {
  597. mActiveActionMode.finish();
  598. }
  599. mContainerActivity.showDetails(singleFile);
  600. return true;
  601. }
  602. case R.id.action_send_file: {
  603. // Obtain the file
  604. if (!singleFile.isDown()) { // Download the file
  605. Log_OC.d(TAG, singleFile.getRemotePath() + " : File must be downloaded");
  606. ((FileDisplayActivity) mContainerActivity).startDownloadForSending(singleFile);
  607. } else {
  608. mContainerActivity.getFileOperationsHelper().sendDownloadedFile(singleFile);
  609. }
  610. return true;
  611. }
  612. }
  613. }
  614. /// actions possible on a batch of files
  615. switch (menuId) {
  616. case R.id.action_remove_file: {
  617. RemoveFilesDialogFragment dialog = RemoveFilesDialogFragment.newInstance(checkedFiles);
  618. dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
  619. return true;
  620. }
  621. case R.id.action_download_file:
  622. case R.id.action_sync_file: {
  623. mContainerActivity.getFileOperationsHelper().syncFiles(checkedFiles);
  624. return true;
  625. }
  626. case R.id.action_cancel_sync: {
  627. ((FileDisplayActivity) mContainerActivity).cancelTransference(checkedFiles);
  628. return true;
  629. }
  630. case R.id.action_favorite_file: {
  631. mContainerActivity.getFileOperationsHelper().toggleFavorites(checkedFiles, true);
  632. return true;
  633. }
  634. case R.id.action_unfavorite_file: {
  635. mContainerActivity.getFileOperationsHelper().toggleFavorites(checkedFiles, false);
  636. return true;
  637. }
  638. case R.id.action_move: {
  639. Intent action = new Intent(getActivity(), FolderPickerActivity.class);
  640. action.putParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES, checkedFiles);
  641. action.putExtra(FolderPickerActivity.EXTRA_ACTION, getResources().getText(R.string.move_to));
  642. getActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__MOVE_FILES);
  643. return true;
  644. }
  645. case R.id.action_copy:
  646. Intent action = new Intent(getActivity(), FolderPickerActivity.class);
  647. action.putParcelableArrayListExtra(FolderPickerActivity.EXTRA_FILES, checkedFiles);
  648. action.putExtra(FolderPickerActivity.EXTRA_ACTION, getResources().getText(R.string.copy_to));
  649. getActivity().startActivityForResult(action, FileDisplayActivity.REQUEST_CODE__COPY_FILES);
  650. return true;
  651. default:
  652. return false;
  653. }
  654. }
  655. /**
  656. * Use this to query the {@link OCFile} that is currently
  657. * being displayed by this fragment
  658. *
  659. * @return The currently viewed OCFile
  660. */
  661. public OCFile getCurrentFile() {
  662. return mFile;
  663. }
  664. /**
  665. * Calls {@link OCFileListFragment#listDirectory(OCFile, boolean, boolean)} with a null parameter
  666. */
  667. public void listDirectory(boolean onlyOnDevice, boolean fromSearch){
  668. listDirectory(null, onlyOnDevice, fromSearch);
  669. }
  670. public void refreshDirectory(){
  671. listDirectory(getCurrentFile(), MainApp.isOnlyOnDevice(), false);
  672. }
  673. /**
  674. * Lists the given directory on the view. When the input parameter is null,
  675. * it will either refresh the last known directory. list the root
  676. * if there never was a directory.
  677. *
  678. * @param directory File to be listed
  679. */
  680. public void listDirectory(OCFile directory, boolean onlyOnDevice, boolean fromSearch) {
  681. FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
  682. if (storageManager != null) {
  683. // Check input parameters for null
  684. if (directory == null) {
  685. if (mFile != null) {
  686. directory = mFile;
  687. } else {
  688. directory = storageManager.getFileByPath("/");
  689. if (directory == null) {
  690. return; // no files, wait for sync
  691. }
  692. }
  693. }
  694. // If that's not a directory -> List its parent
  695. if (!directory.isFolder()) {
  696. Log_OC.w(TAG, "You see, that is not a directory -> " + directory.toString());
  697. directory = storageManager.getFileById(directory.getParentId());
  698. }
  699. if (searchView != null && !searchView.isIconified() && !fromSearch) {
  700. searchView.post(new Runnable() {
  701. @Override
  702. public void run() {
  703. searchView.setQuery("", false);
  704. searchView.onActionViewCollapsed();
  705. if (getActivity() != null) {
  706. FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) getActivity();
  707. if (getCurrentFile() != null) {
  708. fileDisplayActivity.setDrawerIndicatorEnabled(fileDisplayActivity.isRoot(getCurrentFile()));
  709. }
  710. }
  711. }
  712. });
  713. }
  714. mAdapter.swapDirectory(directory, storageManager, onlyOnDevice);
  715. if (mFile == null || !mFile.equals(directory)) {
  716. mCurrentListView.setSelection(0);
  717. }
  718. mFile = directory;
  719. updateLayout();
  720. }
  721. }
  722. private void updateFooter() {
  723. if (!mJustFolders) {
  724. int filesCount = 0, foldersCount = 0;
  725. int count = mAdapter.getCount();
  726. OCFile file;
  727. for (int i = 0; i < count; i++) {
  728. file = (OCFile) mAdapter.getItem(i);
  729. if (file.isFolder()) {
  730. foldersCount++;
  731. } else {
  732. if (!file.isHidden()) {
  733. filesCount++;
  734. }
  735. }
  736. }
  737. // set footer text
  738. setFooterText(generateFooterText(filesCount, foldersCount));
  739. }
  740. }
  741. private void updateLayout() {
  742. if (!mJustFolders) {
  743. updateFooter();
  744. // decide grid vs list view
  745. OwnCloudVersion version = AccountUtils.getServerVersion(
  746. ((FileActivity)mContainerActivity).getAccount());
  747. if (version != null && version.supportsRemoteThumbnails() &&
  748. isGridViewPreferred(mFile)) {
  749. switchToGridView();
  750. } else {
  751. switchToListView();
  752. }
  753. }
  754. invalidateActionMode();
  755. }
  756. private void invalidateActionMode() {
  757. if(mActiveActionMode != null){
  758. mActiveActionMode.invalidate();
  759. }
  760. }
  761. private String generateFooterText(int filesCount, int foldersCount) {
  762. String output;
  763. if (filesCount <= 0) {
  764. if (foldersCount <= 0) {
  765. output = "";
  766. } else if (foldersCount == 1) {
  767. output = getResources().getString(R.string.file_list__footer__folder);
  768. } else { // foldersCount > 1
  769. output = getResources().getString(R.string.file_list__footer__folders, foldersCount);
  770. }
  771. } else if (filesCount == 1) {
  772. if (foldersCount <= 0) {
  773. output = getResources().getString(R.string.file_list__footer__file);
  774. } else if (foldersCount == 1) {
  775. output = getResources().getString(R.string.file_list__footer__file_and_folder);
  776. } else { // foldersCount > 1
  777. output = getResources().getString(R.string.file_list__footer__file_and_folders, foldersCount);
  778. }
  779. } else { // filesCount > 1
  780. if (foldersCount <= 0) {
  781. output = getResources().getString(R.string.file_list__footer__files, filesCount);
  782. } else if (foldersCount == 1) {
  783. output = getResources().getString(R.string.file_list__footer__files_and_folder, filesCount);
  784. } else { // foldersCount > 1
  785. output = getResources().getString(
  786. R.string.file_list__footer__files_and_folders, filesCount, foldersCount
  787. );
  788. }
  789. }
  790. return output;
  791. }
  792. public void sortByName(boolean descending) {
  793. mAdapter.setSortOrder(FileStorageUtils.SORT_NAME, descending);
  794. }
  795. public void sortByDate(boolean descending) {
  796. mAdapter.setSortOrder(FileStorageUtils.SORT_DATE, descending);
  797. }
  798. public void sortBySize(boolean descending) {
  799. mAdapter.setSortOrder(FileStorageUtils.SORT_SIZE, descending);
  800. }
  801. /**
  802. * Determines if user set folder to grid or list view. If folder is not set itself,
  803. * it finds a parent that is set (at least root is set).
  804. * @param file Folder to check.
  805. * @return 'true' is folder should be shown in grid mode, 'false' if list mode is preferred.
  806. */
  807. public boolean isGridViewPreferred(OCFile file){
  808. if (file != null) {
  809. OCFile fileToTest = file;
  810. OCFile parentDir;
  811. String parentPath = null;
  812. FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
  813. SharedPreferences setting =
  814. getActivity().getSharedPreferences(
  815. GRID_IS_PREFERED_PREFERENCE, Context.MODE_PRIVATE
  816. );
  817. if (setting.contains(String.valueOf(fileToTest.getFileId()))) {
  818. return setting.getBoolean(String.valueOf(fileToTest.getFileId()), false);
  819. } else {
  820. do {
  821. if (fileToTest.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
  822. parentPath = new File(fileToTest.getRemotePath()).getParent();
  823. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
  824. parentPath + OCFile.PATH_SEPARATOR;
  825. parentDir = storageManager.getFileByPath(parentPath);
  826. } else {
  827. parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
  828. }
  829. while (parentDir == null) {
  830. parentPath = new File(parentPath).getParent();
  831. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath :
  832. parentPath + OCFile.PATH_SEPARATOR;
  833. parentDir = storageManager.getFileByPath(parentPath);
  834. }
  835. fileToTest = parentDir;
  836. } while (endWhile(parentDir, setting));
  837. return setting.getBoolean(String.valueOf(fileToTest.getFileId()), false);
  838. }
  839. } else {
  840. return false;
  841. }
  842. }
  843. private boolean endWhile(OCFile parentDir, SharedPreferences setting) {
  844. if (parentDir.getRemotePath().compareToIgnoreCase(OCFile.ROOT_PATH) == 0) {
  845. return false;
  846. } else {
  847. return !setting.contains(String.valueOf(parentDir.getFileId()));
  848. }
  849. }
  850. private void changeGridIcon(Menu menu){
  851. MenuItem menuItem = menu.findItem(R.id.action_switch_view);
  852. if (isGridViewPreferred(mFile)){
  853. menuItem.setTitle(getString(R.string.action_switch_list_view));
  854. menuItem.setIcon(R.drawable.ic_view_list);
  855. } else {
  856. menuItem.setTitle(getString(R.string.action_switch_grid_view));
  857. menuItem.setIcon(R.drawable.ic_view_module);
  858. }
  859. }
  860. public void setListAsPreferred() {
  861. saveGridAsPreferred(false);
  862. switchToListView();
  863. }
  864. public void setGridAsPreferred() {
  865. saveGridAsPreferred(true);
  866. switchToGridView();
  867. }
  868. private void saveGridAsPreferred(boolean setGrid){
  869. SharedPreferences setting = getActivity().getSharedPreferences(
  870. GRID_IS_PREFERED_PREFERENCE, Context.MODE_PRIVATE
  871. );
  872. SharedPreferences.Editor editor = setting.edit();
  873. editor.putBoolean(String.valueOf(mFile.getFileId()), setGrid);
  874. editor.apply();
  875. }
  876. }