PreviewImageActivity.java 22 KB

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