PreviewImageActivity.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2016 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hd that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package com.owncloud.android.ui.preview;
  21. import android.annotation.SuppressLint;
  22. import android.content.BroadcastReceiver;
  23. import android.content.ComponentName;
  24. import android.content.Context;
  25. import android.content.Intent;
  26. import android.content.IntentFilter;
  27. import android.content.ServiceConnection;
  28. import android.os.Bundle;
  29. import android.os.IBinder;
  30. import android.support.v4.view.ViewPager;
  31. import android.support.v4.widget.DrawerLayout;
  32. import android.support.v7.app.ActionBar;
  33. import android.view.MenuItem;
  34. import android.view.View;
  35. import com.ortiz.touch.ExtendedViewPager;
  36. import com.owncloud.android.MainApp;
  37. import com.owncloud.android.R;
  38. import com.owncloud.android.authentication.AccountUtils;
  39. import com.owncloud.android.datamodel.FileDataStorageManager;
  40. import com.owncloud.android.datamodel.OCFile;
  41. import com.owncloud.android.datamodel.VirtualFolderType;
  42. import com.owncloud.android.files.services.FileDownloader;
  43. import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
  44. import com.owncloud.android.files.services.FileUploader;
  45. import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
  46. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  47. import com.owncloud.android.lib.common.operations.RemoteOperation;
  48. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  49. import com.owncloud.android.lib.common.utils.Log_OC;
  50. import com.owncloud.android.operations.RemoveFileOperation;
  51. import com.owncloud.android.operations.SynchronizeFileOperation;
  52. import com.owncloud.android.ui.activity.FileActivity;
  53. import com.owncloud.android.ui.activity.FileDisplayActivity;
  54. import com.owncloud.android.ui.fragment.FileFragment;
  55. import com.owncloud.android.utils.MimeTypeUtil;
  56. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  57. /**
  58. * Holds a swiping galley where image files contained in an ownCloud directory are shown
  59. */
  60. @SuppressWarnings("PMD.AvoidDuplicateLiterals")
  61. public class PreviewImageActivity extends FileActivity implements
  62. FileFragment.ContainerActivity,
  63. ViewPager.OnPageChangeListener, OnRemoteOperationListener {
  64. public static final String TAG = PreviewImageActivity.class.getSimpleName();
  65. public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
  66. private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
  67. private static final String KEY_SYSTEM_VISIBLE = "TRUE";
  68. public static final String EXTRA_VIRTUAL_TYPE = "EXTRA_VIRTUAL_TYPE";
  69. private ExtendedViewPager mViewPager;
  70. private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
  71. private int mSavedPosition = 0;
  72. private boolean mHasSavedPosition = false;
  73. private boolean mRequestWaitingForBinder;
  74. private DownloadFinishReceiver mDownloadFinishReceiver;
  75. private View mFullScreenAnchorView;
  76. @Override
  77. protected void onCreate(Bundle savedInstanceState) {
  78. super.onCreate(savedInstanceState);
  79. final ActionBar actionBar = getSupportActionBar();
  80. if (savedInstanceState != null && !savedInstanceState.getBoolean(KEY_SYSTEM_VISIBLE, true) &&
  81. actionBar != null) {
  82. actionBar.hide();
  83. }
  84. setContentView(R.layout.preview_image_activity);
  85. // Navigation Drawer
  86. setupDrawer();
  87. // ActionBar
  88. updateActionBarTitleAndHomeButton(null);
  89. mFullScreenAnchorView = getWindow().getDecorView();
  90. // to keep our UI controls visibility in line with system bars visibility
  91. mFullScreenAnchorView.setOnSystemUiVisibilityChangeListener
  92. (new View.OnSystemUiVisibilityChangeListener() {
  93. @Override
  94. public void onSystemUiVisibilityChange(int flags) {
  95. boolean visible = (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
  96. if (visible) {
  97. actionBar.show();
  98. setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
  99. } else {
  100. actionBar.hide();
  101. setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
  102. }
  103. }
  104. });
  105. if (savedInstanceState != null) {
  106. mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
  107. } else {
  108. mRequestWaitingForBinder = false;
  109. }
  110. }
  111. private void initViewPager() {
  112. // virtual folder
  113. if (getIntent().getSerializableExtra(EXTRA_VIRTUAL_TYPE) != null) {
  114. VirtualFolderType type = (VirtualFolderType) getIntent().getSerializableExtra(EXTRA_VIRTUAL_TYPE);
  115. mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(),
  116. type, getAccount(), getStorageManager());
  117. } else {
  118. // get parent from path
  119. String parentPath = getFile().getRemotePath().substring(0,
  120. getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
  121. OCFile parentFolder = getStorageManager().getFileByPath(parentPath);
  122. if (parentFolder == null) {
  123. // should not be necessary
  124. parentFolder = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  125. }
  126. mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(),
  127. parentFolder, getAccount(), getStorageManager(), MainApp.isOnlyOnDevice());
  128. }
  129. mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager);
  130. int position = mHasSavedPosition ? mSavedPosition : mPreviewImagePagerAdapter.getFilePosition(getFile());
  131. position = (position >= 0) ? position : 0;
  132. mViewPager.setAdapter(mPreviewImagePagerAdapter);
  133. mViewPager.setOnPageChangeListener(this);
  134. mViewPager.setCurrentItem(position);
  135. if (position == 0 && !getFile().isDown()) {
  136. // this is necessary because mViewPager.setCurrentItem(0) just after setting the
  137. // adapter does not result in a call to #onPageSelected(0)
  138. mRequestWaitingForBinder = true;
  139. }
  140. }
  141. @Override
  142. public void onStart() {
  143. super.onStart();
  144. }
  145. @Override
  146. protected void onSaveInstanceState(Bundle outState) {
  147. super.onSaveInstanceState(outState);
  148. outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
  149. outState.putBoolean(KEY_SYSTEM_VISIBLE, getSystemUIVisible());
  150. }
  151. @Override
  152. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  153. super.onRemoteOperationFinish(operation, result);
  154. if (operation instanceof RemoveFileOperation) {
  155. finish();
  156. } else if (operation instanceof SynchronizeFileOperation) {
  157. onSynchronizeFileOperationFinish(result);
  158. }
  159. }
  160. private void onSynchronizeFileOperationFinish(RemoteOperationResult result) {
  161. if (result.isSuccess()) {
  162. supportInvalidateOptionsMenu();
  163. }
  164. }
  165. @Override
  166. protected ServiceConnection newTransferenceServiceConnection() {
  167. return new PreviewImageServiceConnection();
  168. }
  169. /** Defines callbacks for service binding, passed to bindService() */
  170. private class PreviewImageServiceConnection implements ServiceConnection {
  171. @Override
  172. public void onServiceConnected(ComponentName component, IBinder service) {
  173. if (component.equals(new ComponentName(PreviewImageActivity.this,
  174. FileDownloader.class))) {
  175. mDownloaderBinder = (FileDownloaderBinder) service;
  176. if (mRequestWaitingForBinder) {
  177. mRequestWaitingForBinder = false;
  178. Log_OC.d(TAG, "Simulating reselection of current page after connection " +
  179. "of download binder");
  180. onPageSelected(mViewPager.getCurrentItem());
  181. }
  182. } else if (component.equals(new ComponentName(PreviewImageActivity.this,
  183. FileUploader.class))) {
  184. Log_OC.d(TAG, "Upload service connected");
  185. mUploaderBinder = (FileUploaderBinder) service;
  186. } else {
  187. return;
  188. }
  189. }
  190. @Override
  191. public void onServiceDisconnected(ComponentName component) {
  192. if (component.equals(new ComponentName(PreviewImageActivity.this,
  193. FileDownloader.class))) {
  194. Log_OC.d(TAG, "Download service suddenly disconnected");
  195. mDownloaderBinder = null;
  196. } else if (component.equals(new ComponentName(PreviewImageActivity.this,
  197. FileUploader.class))) {
  198. Log_OC.d(TAG, "Upload service suddenly disconnected");
  199. mUploaderBinder = null;
  200. }
  201. }
  202. }
  203. @Override
  204. public void onStop() {
  205. super.onStop();
  206. }
  207. @Override
  208. public void onDestroy() {
  209. super.onDestroy();
  210. }
  211. @Override
  212. public boolean onOptionsItemSelected(MenuItem item) {
  213. boolean returnValue = false;
  214. switch(item.getItemId()){
  215. case android.R.id.home:
  216. if (isDrawerOpen()) {
  217. closeDrawer();
  218. } else {
  219. backToDisplayActivity();
  220. }
  221. returnValue = true;
  222. break;
  223. default:
  224. returnValue = super.onOptionsItemSelected(item);
  225. break;
  226. }
  227. return returnValue;
  228. }
  229. @Override
  230. protected void onResume() {
  231. super.onResume();
  232. mDownloadFinishReceiver = new DownloadFinishReceiver();
  233. IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
  234. filter.addAction(FileDownloader.getDownloadAddedMessage());
  235. registerReceiver(mDownloadFinishReceiver, filter);
  236. }
  237. @Override
  238. protected void onPostResume() {
  239. super.onPostResume();
  240. }
  241. @Override
  242. public void onPause() {
  243. if (mDownloadFinishReceiver != null){
  244. unregisterReceiver(mDownloadFinishReceiver);
  245. mDownloadFinishReceiver = null;
  246. }
  247. super.onPause();
  248. }
  249. private void backToDisplayActivity() {
  250. finish();
  251. }
  252. @SuppressFBWarnings("DLS")
  253. @Override
  254. public void showDetails(OCFile file) {
  255. final Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  256. showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
  257. showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
  258. showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT,
  259. AccountUtils.getCurrentOwnCloudAccount(this));
  260. showDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  261. startActivity(showDetailsIntent);
  262. int pos = mPreviewImagePagerAdapter.getFilePosition(file);
  263. file = mPreviewImagePagerAdapter.getFileAt(pos);
  264. finish();
  265. }
  266. private void requestForDownload(OCFile file) {
  267. if (mDownloaderBinder == null) {
  268. Log_OC.d(TAG, "requestForDownload called without binder to download service");
  269. } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
  270. Intent i = new Intent(this, FileDownloader.class);
  271. i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
  272. i.putExtra(FileDownloader.EXTRA_FILE, file);
  273. startService(i);
  274. }
  275. }
  276. /**
  277. * This method will be invoked when a new page becomes selected. Animation is not necessarily
  278. * complete.
  279. *
  280. * @param position Position index of the new selected page
  281. */
  282. @Override
  283. public void onPageSelected(int position) {
  284. mSavedPosition = position;
  285. mHasSavedPosition = true;
  286. if (mDownloaderBinder == null) {
  287. mRequestWaitingForBinder = true;
  288. } else {
  289. OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
  290. getSupportActionBar().setTitle(currentFile.getFileName());
  291. setDrawerIndicatorEnabled(false);
  292. if (!currentFile.isDown()
  293. && !mPreviewImagePagerAdapter.pendingErrorAt(position)) {
  294. requestForDownload(currentFile);
  295. }
  296. // Call to reset image zoom to initial state
  297. ((PreviewImagePagerAdapter) mViewPager.getAdapter()).resetZoom();
  298. }
  299. }
  300. /**
  301. * Called when the scroll state changes. Useful for discovering when the user begins dragging,
  302. * when the pager is automatically settling to the current page. when it is fully stopped/idle.
  303. *
  304. * @param state The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
  305. */
  306. @Override
  307. public void onPageScrollStateChanged(int state) {
  308. // not used at the moment
  309. }
  310. /**
  311. * This method will be invoked when the current page is scrolled, either as part of a
  312. * programmatically initiated smooth scroll or a user initiated touch scroll.
  313. *
  314. * @param position Position index of the first page currently being displayed.
  315. * Page position+1 will be visible if positionOffset is
  316. * nonzero.
  317. * @param positionOffset Value from [0, 1) indicating the offset from the page
  318. * at position.
  319. * @param positionOffsetPixels Value in pixels indicating the offset from position.
  320. */
  321. @Override
  322. public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  323. // not used at the moment
  324. }
  325. /**
  326. * Class waiting for broadcast events from the {@link FileDownloader} service.
  327. *
  328. * Updates the UI when a download is started or finished, provided that it is relevant for the
  329. * folder displayed in the gallery.
  330. */
  331. private class DownloadFinishReceiver extends BroadcastReceiver {
  332. @Override
  333. public void onReceive(Context context, Intent intent) {
  334. String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
  335. String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
  336. if (getAccount().name.equals(accountName) &&
  337. downloadedRemotePath != null) {
  338. OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
  339. int position = mPreviewImagePagerAdapter.getFilePosition(file);
  340. boolean downloadWasFine = intent.getBooleanExtra(
  341. FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
  342. //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position))
  343. // <= mViewPager.getOffscreenPageLimit();
  344. if (position >= 0 &&
  345. intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
  346. if (downloadWasFine) {
  347. mPreviewImagePagerAdapter.updateFile(position, file);
  348. } else {
  349. mPreviewImagePagerAdapter.updateWithDownloadError(position);
  350. }
  351. mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation
  352. // of new fragments
  353. } else {
  354. Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
  355. }
  356. }
  357. removeStickyBroadcast(intent);
  358. }
  359. }
  360. public boolean getSystemUIVisible() {
  361. if (getSupportActionBar() != null) {
  362. return (getSupportActionBar().isShowing());
  363. }
  364. return true;
  365. }
  366. public void toggleFullScreen() {
  367. boolean visible = (mFullScreenAnchorView.getSystemUiVisibility()
  368. & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
  369. if (visible) {
  370. hideSystemUI(mFullScreenAnchorView);
  371. // actionBar.hide(); // propagated through
  372. // OnSystemUiVisibilityChangeListener()
  373. } else {
  374. showSystemUI(mFullScreenAnchorView);
  375. // actionBar.show(); // propagated through
  376. // OnSystemUiVisibilityChangeListener()
  377. }
  378. }
  379. @Override
  380. protected void onAccountSet(boolean stateWasRecovered) {
  381. super.onAccountSet(stateWasRecovered);
  382. if (getAccount() != null) {
  383. OCFile file = getFile();
  384. /// Validate handled file (first image to preview)
  385. if (file == null) {
  386. throw new IllegalStateException("Instanced with a NULL OCFile");
  387. }
  388. if (!MimeTypeUtil.isImage(file)) {
  389. throw new IllegalArgumentException("Non-image file passed as argument");
  390. }
  391. // Update file according to DB file, if it is possible
  392. if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID) {
  393. file = getStorageManager().getFileById(file.getFileId());
  394. }
  395. if (file != null) {
  396. /// Refresh the activity according to the Account and OCFile set
  397. setFile(file); // reset after getting it fresh from storageManager
  398. getSupportActionBar().setTitle(getFile().getFileName());
  399. //if (!stateWasRecovered) {
  400. initViewPager();
  401. //}
  402. } else {
  403. // handled file not in the current Account
  404. finish();
  405. }
  406. }
  407. }
  408. @Override
  409. public void onBrowsedDownTo(OCFile folder) {
  410. // TODO Auto-generated method stub
  411. }
  412. @Override
  413. public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
  414. // TODO Auto-generated method stub
  415. }
  416. @SuppressLint("InlinedApi")
  417. private void hideSystemUI(View anchorView) {
  418. anchorView.setSystemUiVisibility(
  419. View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hides NAVIGATION BAR; Android >= 4.0
  420. | View.SYSTEM_UI_FLAG_FULLSCREEN // hides STATUS BAR; Android >= 4.1
  421. | View.SYSTEM_UI_FLAG_IMMERSIVE // stays interactive; Android >= 4.4
  422. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
  423. | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
  424. | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
  425. );
  426. }
  427. @SuppressLint("InlinedApi")
  428. private void showSystemUI(View anchorView) {
  429. anchorView.setSystemUiVisibility(
  430. View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
  431. | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
  432. | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.
  433. );
  434. }
  435. }