PreviewImageActivity.java 21 KB

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