PreviewImageActivity.java 22 KB

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