PreviewImageActivity.java 20 KB

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