PreviewImageActivity.java 20 KB

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