PreviewImageActivity.java 20 KB

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