PreviewImageFragment.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012-2014 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 java.lang.ref.WeakReference;
  19. import android.accounts.Account;
  20. import android.annotation.SuppressLint;
  21. import android.app.Activity;
  22. import android.graphics.Bitmap;
  23. import android.graphics.BitmapFactory;
  24. import android.graphics.BitmapFactory.Options;
  25. import android.graphics.Point;
  26. import android.os.AsyncTask;
  27. import android.os.Bundle;
  28. import android.support.v4.app.FragmentStatePagerAdapter;
  29. import android.view.Display;
  30. import android.view.LayoutInflater;
  31. import android.view.View;
  32. import android.view.View.OnTouchListener;
  33. import android.view.ViewGroup;
  34. import android.widget.ImageView;
  35. import android.widget.ProgressBar;
  36. import android.widget.TextView;
  37. import com.actionbarsherlock.view.Menu;
  38. import com.actionbarsherlock.view.MenuInflater;
  39. import com.actionbarsherlock.view.MenuItem;
  40. import com.owncloud.android.R;
  41. import com.owncloud.android.datamodel.OCFile;
  42. import com.owncloud.android.files.FileMenuFilter;
  43. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  44. import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
  45. import com.owncloud.android.ui.fragment.FileFragment;
  46. import com.owncloud.android.utils.Log_OC;
  47. /**
  48. * This fragment shows a preview of a downloaded image.
  49. *
  50. * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
  51. *
  52. * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
  53. *
  54. * @author David A. Velasco
  55. */
  56. public class PreviewImageFragment extends FileFragment {
  57. public static final String EXTRA_FILE = "FILE";
  58. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  59. private View mView;
  60. private Account mAccount;
  61. private ImageView mImageView;
  62. private TextView mMessageView;
  63. private ProgressBar mProgressWheel;
  64. public Bitmap mBitmap = null;
  65. private static final String TAG = PreviewImageFragment.class.getSimpleName();
  66. private boolean mIgnoreFirstSavedState;
  67. /**
  68. * Creates a fragment to preview an image.
  69. *
  70. * When 'imageFile' or 'ocAccount' are null
  71. *
  72. * @param imageFile An {@link OCFile} to preview as an image in the fragment
  73. * @param ocAccount An ownCloud account; needed to start downloads
  74. * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
  75. */
  76. public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
  77. super(fileToDetail);
  78. mAccount = ocAccount;
  79. mIgnoreFirstSavedState = ignoreFirstSavedState;
  80. }
  81. /**
  82. * Creates an empty fragment for image previews.
  83. *
  84. * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
  85. *
  86. * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
  87. */
  88. public PreviewImageFragment() {
  89. super();
  90. mAccount = null;
  91. mIgnoreFirstSavedState = false;
  92. }
  93. /**
  94. * {@inheritDoc}
  95. */
  96. @Override
  97. public void onCreate(Bundle savedInstanceState) {
  98. super.onCreate(savedInstanceState);
  99. setHasOptionsMenu(true);
  100. }
  101. /**
  102. * {@inheritDoc}
  103. */
  104. @Override
  105. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  106. Bundle savedInstanceState) {
  107. super.onCreateView(inflater, container, savedInstanceState);
  108. mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
  109. mImageView = (ImageView)mView.findViewById(R.id.image);
  110. mImageView.setVisibility(View.GONE);
  111. mView.setOnTouchListener((OnTouchListener)getActivity());
  112. mMessageView = (TextView)mView.findViewById(R.id.message);
  113. mMessageView.setVisibility(View.GONE);
  114. mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
  115. mProgressWheel.setVisibility(View.VISIBLE);
  116. return mView;
  117. }
  118. /**
  119. * {@inheritDoc}
  120. */
  121. @Override
  122. public void onAttach(Activity activity) {
  123. super.onAttach(activity);
  124. if (!(activity instanceof OnTouchListener)) {
  125. throw new ClassCastException(activity.toString() +
  126. " must implement " + OnTouchListener.class.getSimpleName());
  127. }
  128. }
  129. /**
  130. * {@inheritDoc}
  131. */
  132. @Override
  133. public void onActivityCreated(Bundle savedInstanceState) {
  134. super.onActivityCreated(savedInstanceState);
  135. if (savedInstanceState != null) {
  136. if (!mIgnoreFirstSavedState) {
  137. OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
  138. setFile(file);
  139. mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
  140. } else {
  141. mIgnoreFirstSavedState = false;
  142. }
  143. }
  144. if (getFile() == null) {
  145. throw new IllegalStateException("Instanced with a NULL OCFile");
  146. }
  147. if (mAccount == null) {
  148. throw new IllegalStateException("Instanced with a NULL ownCloud Account");
  149. }
  150. if (!getFile().isDown()) {
  151. throw new IllegalStateException("There is no local file to preview");
  152. }
  153. }
  154. /**
  155. * {@inheritDoc}
  156. */
  157. @Override
  158. public void onSaveInstanceState(Bundle outState) {
  159. super.onSaveInstanceState(outState);
  160. outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
  161. outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
  162. }
  163. @Override
  164. public void onStart() {
  165. super.onStart();
  166. if (getFile() != null) {
  167. BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
  168. bl.execute(new String[]{getFile().getStoragePath()});
  169. }
  170. }
  171. /**
  172. * {@inheritDoc}
  173. */
  174. @Override
  175. public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  176. super.onCreateOptionsMenu(menu, inflater);
  177. inflater.inflate(R.menu.file_actions_menu, menu);
  178. }
  179. /**
  180. * {@inheritDoc}
  181. */
  182. @Override
  183. public void onPrepareOptionsMenu(Menu menu) {
  184. super.onPrepareOptionsMenu(menu);
  185. if (mContainerActivity.getStorageManager() != null) {
  186. // Update the file
  187. setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
  188. FileMenuFilter mf = new FileMenuFilter(
  189. getFile(),
  190. mContainerActivity.getStorageManager().getAccount(),
  191. mContainerActivity,
  192. getSherlockActivity()
  193. );
  194. mf.filter(menu);
  195. }
  196. // additional restriction for this fragment
  197. // TODO allow renaming in PreviewImageFragment
  198. MenuItem item = menu.findItem(R.id.action_rename_file);
  199. if (item != null) {
  200. item.setVisible(false);
  201. item.setEnabled(false);
  202. }
  203. // additional restriction for this fragment
  204. // TODO allow refresh file in PreviewImageFragment
  205. item = menu.findItem(R.id.action_sync_file);
  206. if (item != null) {
  207. item.setVisible(false);
  208. item.setEnabled(false);
  209. }
  210. }
  211. /**
  212. * {@inheritDoc}
  213. */
  214. @Override
  215. public boolean onOptionsItemSelected(MenuItem item) {
  216. switch (item.getItemId()) {
  217. case R.id.action_share_file: {
  218. mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
  219. return true;
  220. }
  221. case R.id.action_unshare_file: {
  222. mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
  223. return true;
  224. }
  225. case R.id.action_open_file_with: {
  226. openFile();
  227. return true;
  228. }
  229. case R.id.action_remove_file: {
  230. RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
  231. dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
  232. return true;
  233. }
  234. case R.id.action_see_details: {
  235. seeDetails();
  236. return true;
  237. }
  238. case R.id.action_send_file: {
  239. mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
  240. return true;
  241. }
  242. case R.id.action_sync_file: {
  243. mContainerActivity.getFileOperationsHelper().syncFile(getFile());
  244. return true;
  245. }
  246. default:
  247. return false;
  248. }
  249. }
  250. private void seeDetails() {
  251. mContainerActivity.showDetails(getFile());
  252. }
  253. @Override
  254. public void onResume() {
  255. super.onResume();
  256. }
  257. @Override
  258. public void onPause() {
  259. super.onPause();
  260. }
  261. @Override
  262. public void onDestroy() {
  263. if (mBitmap != null) {
  264. mBitmap.recycle();
  265. }
  266. super.onDestroy();
  267. }
  268. /**
  269. * Opens the previewed image with an external application.
  270. */
  271. private void openFile() {
  272. mContainerActivity.getFileOperationsHelper().openFile(getFile());
  273. finish();
  274. }
  275. private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
  276. /**
  277. * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
  278. *
  279. * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
  280. */
  281. private final WeakReference<ImageView> mImageViewRef;
  282. /**
  283. * Weak reference to the target {@link TextView} where error messages will be written.
  284. *
  285. * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
  286. */
  287. private final WeakReference<TextView> mMessageViewRef;
  288. /**
  289. * Weak reference to the target {@link Progressbar} shown while the load is in progress.
  290. *
  291. * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
  292. */
  293. private final WeakReference<ProgressBar> mProgressWheelRef;
  294. /**
  295. * Error message to show when a load fails
  296. */
  297. private int mErrorMessageId;
  298. /**
  299. * Constructor.
  300. *
  301. * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
  302. */
  303. public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
  304. mImageViewRef = new WeakReference<ImageView>(imageView);
  305. mMessageViewRef = new WeakReference<TextView>(messageView);
  306. mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
  307. }
  308. @SuppressWarnings("deprecation")
  309. @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
  310. @Override
  311. protected Bitmap doInBackground(String... params) {
  312. Bitmap result = null;
  313. if (params.length != 1) return result;
  314. String storagePath = params[0];
  315. try {
  316. // set desired options that will affect the size of the bitmap
  317. BitmapFactory.Options options = new Options();
  318. options.inScaled = true;
  319. options.inPurgeable = true;
  320. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
  321. options.inPreferQualityOverSpeed = false;
  322. }
  323. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
  324. options.inMutable = false;
  325. }
  326. // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
  327. options.inJustDecodeBounds = true;
  328. BitmapFactory.decodeFile(storagePath, options);
  329. int width = options.outWidth;
  330. int height = options.outHeight;
  331. int scale = 1;
  332. Display display = getActivity().getWindowManager().getDefaultDisplay();
  333. Point size = new Point();
  334. int screenWidth;
  335. int screenHeight;
  336. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
  337. display.getSize(size);
  338. screenWidth = size.x;
  339. screenHeight = size.y;
  340. } else {
  341. screenWidth = display.getWidth();
  342. screenHeight = display.getHeight();
  343. }
  344. if (width > screenWidth) {
  345. // second try to scale down the image , this time depending upon the screen size
  346. scale = (int) Math.floor((float)width / screenWidth);
  347. }
  348. if (height > screenHeight) {
  349. scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
  350. }
  351. options.inSampleSize = scale;
  352. // really load the bitmap
  353. options.inJustDecodeBounds = false; // the next decodeFile call will be real
  354. result = BitmapFactory.decodeFile(storagePath, options);
  355. //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
  356. if (result == null) {
  357. mErrorMessageId = R.string.preview_image_error_unknown_format;
  358. Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
  359. }
  360. } catch (OutOfMemoryError e) {
  361. mErrorMessageId = R.string.preview_image_error_unknown_format;
  362. Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
  363. } catch (NoSuchFieldError e) {
  364. mErrorMessageId = R.string.common_error_unknown;
  365. Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
  366. } catch (Throwable t) {
  367. mErrorMessageId = R.string.common_error_unknown;
  368. Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
  369. }
  370. return result;
  371. }
  372. @Override
  373. protected void onPostExecute(Bitmap result) {
  374. hideProgressWheel();
  375. if (result != null) {
  376. showLoadedImage(result);
  377. } else {
  378. showErrorMessage();
  379. }
  380. }
  381. private void showLoadedImage(Bitmap result) {
  382. if (mImageViewRef != null) {
  383. final ImageView imageView = mImageViewRef.get();
  384. if (imageView != null) {
  385. imageView.setImageBitmap(result);
  386. imageView.setVisibility(View.VISIBLE);
  387. mBitmap = result;
  388. } // else , silently finish, the fragment was destroyed
  389. }
  390. if (mMessageViewRef != null) {
  391. final TextView messageView = mMessageViewRef.get();
  392. if (messageView != null) {
  393. messageView.setVisibility(View.GONE);
  394. } // else , silently finish, the fragment was destroyed
  395. }
  396. }
  397. private void showErrorMessage() {
  398. if (mImageViewRef != null) {
  399. final ImageView imageView = mImageViewRef.get();
  400. if (imageView != null) {
  401. // shows the default error icon
  402. imageView.setVisibility(View.VISIBLE);
  403. } // else , silently finish, the fragment was destroyed
  404. }
  405. if (mMessageViewRef != null) {
  406. final TextView messageView = mMessageViewRef.get();
  407. if (messageView != null) {
  408. messageView.setText(mErrorMessageId);
  409. messageView.setVisibility(View.VISIBLE);
  410. } // else , silently finish, the fragment was destroyed
  411. }
  412. }
  413. private void hideProgressWheel() {
  414. if (mProgressWheelRef != null) {
  415. final ProgressBar progressWheel = mProgressWheelRef.get();
  416. if (progressWheel != null) {
  417. progressWheel.setVisibility(View.GONE);
  418. }
  419. }
  420. }
  421. }
  422. /**
  423. * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
  424. *
  425. * @param file File to test if can be previewed.
  426. * @return 'True' if the file can be handled by the fragment.
  427. */
  428. public static boolean canBePreviewed(OCFile file) {
  429. return (file != null && file.isImage());
  430. }
  431. /**
  432. * Finishes the preview
  433. */
  434. private void finish() {
  435. Activity container = getActivity();
  436. container.finish();
  437. }
  438. }