PreviewImageActivity.java 21 KB

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