Merge remote-tracking branch 'origin/thumbnailOOM' into thumbnailOOM
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageFragment.java
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
22 import java.io.BufferedInputStream;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FilterInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.lang.ref.WeakReference;
29
30 import android.accounts.Account;
31 import android.annotation.SuppressLint;
32 import android.app.Activity;
33 import android.graphics.Bitmap;
34 import android.graphics.BitmapFactory;
35 import android.graphics.BitmapFactory.Options;
36 import android.graphics.Point;
37 import android.os.AsyncTask;
38 import android.os.Bundle;
39 import android.support.v4.app.FragmentStatePagerAdapter;
40 import android.view.Display;
41 import android.view.LayoutInflater;
42 import android.view.View;
43 import android.view.View.OnClickListener;
44 import android.view.ViewGroup;
45 import android.widget.ImageView;
46 import android.widget.ProgressBar;
47 import android.widget.TextView;
48
49 import com.actionbarsherlock.view.Menu;
50 import com.actionbarsherlock.view.MenuInflater;
51 import com.actionbarsherlock.view.MenuItem;
52 import com.owncloud.android.R;
53 import com.owncloud.android.datamodel.OCFile;
54 import com.owncloud.android.files.FileMenuFilter;
55 import com.owncloud.android.lib.common.utils.Log_OC;
56 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
57 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
58 import com.owncloud.android.ui.fragment.FileFragment;
59 import com.owncloud.android.utils.BitmapUtils;
60
61 import third_parties.michaelOrtiz.TouchImageViewCustom;
62
63
64 /**
65 * This fragment shows a preview of a downloaded image.
66 *
67 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
68 *
69 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
70 */
71 public class PreviewImageFragment extends FileFragment {
72
73 public static final String EXTRA_FILE = "FILE";
74 public static final String EXTRA_ACCOUNT = "ACCOUNT";
75
76 private View mView;
77 private Account mAccount;
78 private TouchImageViewCustom mImageView;
79 private TextView mMessageView;
80 private ProgressBar mProgressWheel;
81
82 public Bitmap mBitmap = null;
83
84 private static final String TAG = PreviewImageFragment.class.getSimpleName();
85
86 private boolean mIgnoreFirstSavedState;
87
88 private LoadBitmapTask mLoadBitmapTask = null;
89
90
91 /**
92 * Creates a fragment to preview an image.
93 *
94 * When 'imageFile' or 'ocAccount' are null
95 *
96 * @param imageFile An {@link OCFile} to preview as an image in the fragment
97 * @param ocAccount An ownCloud account; needed to start downloads
98 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
99 */
100 public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
101 super(fileToDetail);
102 mAccount = ocAccount;
103 mIgnoreFirstSavedState = ignoreFirstSavedState;
104 }
105
106
107 /**
108 * Creates an empty fragment for image previews.
109 *
110 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
111 *
112 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
113 */
114 public PreviewImageFragment() {
115 super();
116 mAccount = null;
117 mIgnoreFirstSavedState = false;
118 }
119
120
121 /**
122 * {@inheritDoc}
123 */
124 @Override
125 public void onCreate(Bundle savedInstanceState) {
126 super.onCreate(savedInstanceState);
127 setHasOptionsMenu(true);
128 }
129
130
131 /**
132 * {@inheritDoc}
133 */
134 @Override
135 public View onCreateView(LayoutInflater inflater, ViewGroup container,
136 Bundle savedInstanceState) {
137 super.onCreateView(inflater, container, savedInstanceState);
138 mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
139 mImageView = (TouchImageViewCustom) mView.findViewById(R.id.image);
140 mImageView.setVisibility(View.GONE);
141 mImageView.setOnClickListener(new OnClickListener() {
142 @Override
143 public void onClick(View v) {
144 ((PreviewImageActivity) getActivity()).toggleFullScreen();
145 }
146
147 });
148 mMessageView = (TextView)mView.findViewById(R.id.message);
149 mMessageView.setVisibility(View.GONE);
150 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
151 mProgressWheel.setVisibility(View.VISIBLE);
152 return mView;
153 }
154
155 /**
156 * {@inheritDoc}
157 */
158 @Override
159 public void onActivityCreated(Bundle savedInstanceState) {
160 super.onActivityCreated(savedInstanceState);
161 if (savedInstanceState != null) {
162 if (!mIgnoreFirstSavedState) {
163 OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
164 setFile(file);
165 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
166 } else {
167 mIgnoreFirstSavedState = false;
168 }
169 }
170 if (getFile() == null) {
171 throw new IllegalStateException("Instanced with a NULL OCFile");
172 }
173 if (mAccount == null) {
174 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
175 }
176 if (!getFile().isDown()) {
177 throw new IllegalStateException("There is no local file to preview");
178 }
179 }
180
181
182 /**
183 * {@inheritDoc}
184 */
185 @Override
186 public void onSaveInstanceState(Bundle outState) {
187 super.onSaveInstanceState(outState);
188 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
189 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
190 }
191
192
193 @Override
194 public void onStart() {
195 super.onStart();
196 if (getFile() != null) {
197 mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
198 mLoadBitmapTask.execute(new String[]{getFile().getStoragePath()});
199 }
200 }
201
202
203 @Override
204 public void onStop() {
205 Log_OC.d(TAG, "onStop starts");
206 if (mLoadBitmapTask != null) {
207 mLoadBitmapTask.cancel(true);
208 mLoadBitmapTask = null;
209 }
210 super.onStop();
211 }
212
213 /**
214 * {@inheritDoc}
215 */
216 @Override
217 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
218 super.onCreateOptionsMenu(menu, inflater);
219 inflater.inflate(R.menu.file_actions_menu, menu);
220 }
221
222 /**
223 * {@inheritDoc}
224 */
225 @Override
226 public void onPrepareOptionsMenu(Menu menu) {
227 super.onPrepareOptionsMenu(menu);
228
229 if (mContainerActivity.getStorageManager() != null) {
230 // Update the file
231 setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
232
233 FileMenuFilter mf = new FileMenuFilter(
234 getFile(),
235 mContainerActivity.getStorageManager().getAccount(),
236 mContainerActivity,
237 getSherlockActivity()
238 );
239 mf.filter(menu);
240 }
241
242 // additional restriction for this fragment
243 // TODO allow renaming in PreviewImageFragment
244 MenuItem item = menu.findItem(R.id.action_rename_file);
245 if (item != null) {
246 item.setVisible(false);
247 item.setEnabled(false);
248 }
249
250 // additional restriction for this fragment
251 // TODO allow refresh file in PreviewImageFragment
252 item = menu.findItem(R.id.action_sync_file);
253 if (item != null) {
254 item.setVisible(false);
255 item.setEnabled(false);
256 }
257
258 // additional restriction for this fragment
259 item = menu.findItem(R.id.action_move);
260 if (item != null) {
261 item.setVisible(false);
262 item.setEnabled(false);
263 }
264
265 }
266
267
268
269 /**
270 * {@inheritDoc}
271 */
272 @Override
273 public boolean onOptionsItemSelected(MenuItem item) {
274 switch (item.getItemId()) {
275 case R.id.action_share_file: {
276 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
277 return true;
278 }
279 case R.id.action_unshare_file: {
280 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
281 return true;
282 }
283 case R.id.action_open_file_with: {
284 openFile();
285 return true;
286 }
287 case R.id.action_remove_file: {
288 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
289 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
290 return true;
291 }
292 case R.id.action_see_details: {
293 seeDetails();
294 return true;
295 }
296 case R.id.action_send_file: {
297 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
298 return true;
299 }
300 case R.id.action_sync_file: {
301 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
302 return true;
303 }
304
305 default:
306 return false;
307 }
308 }
309
310
311 private void seeDetails() {
312 mContainerActivity.showDetails(getFile());
313 }
314
315
316 @Override
317 public void onResume() {
318 super.onResume();
319 }
320
321
322 @Override
323 public void onPause() {
324 super.onPause();
325 }
326
327 @Override
328 public void onDestroy() {
329 if (mBitmap != null) {
330 mBitmap.recycle();
331 System.gc();
332 // putting this in onStop() is just the same; the fragment is always destroyed by the ViewPager
333 // when swipes further than the valid offset, and onStop() is never called before than that
334 }
335 super.onDestroy();
336 }
337
338
339 /**
340 * Opens the previewed image with an external application.
341 */
342 private void openFile() {
343 mContainerActivity.getFileOperationsHelper().openFile(getFile());
344 finish();
345 }
346
347
348 private class LoadBitmapTask extends AsyncTask<String, Void, Bitmap> {
349
350 /**
351 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
352 *
353 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
354 */
355 private final WeakReference<ImageViewCustom> mImageViewRef;
356
357 /**
358 * Weak reference to the target {@link TextView} where error messages will be written.
359 *
360 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
361 */
362 private final WeakReference<TextView> mMessageViewRef;
363
364
365 /**
366 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
367 *
368 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
369 */
370 private final WeakReference<ProgressBar> mProgressWheelRef;
371
372
373 /**
374 * Error message to show when a load fails
375 */
376 private int mErrorMessageId;
377
378
379 /**
380 * Constructor.
381 *
382 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
383 */
384 public LoadBitmapTask(ImageViewCustom imageView, TextView messageView, ProgressBar progressWheel) {
385 mImageViewRef = new WeakReference<ImageViewCustom>(imageView);
386 mMessageViewRef = new WeakReference<TextView>(messageView);
387 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
388 }
389
390
391 @Override
392 protected Bitmap doInBackground(String... params) {
393 Bitmap result = null;
394 if (params.length != 1) return result;
395 String storagePath = params[0];
396 try {
397
398 if (isCancelled()) return result;
399
400 File picture = new File(storagePath);
401
402 if (picture != null) {
403 // Decode file into a bitmap in real size for being able to make zoom on
404 // the image
405 result = BitmapFactory.decodeStream(new FlushedInputStream
406 (new BufferedInputStream(new FileInputStream(picture))));
407 }
408
409 if (isCancelled()) return result;
410
411 if (result == null) {
412 mErrorMessageId = R.string.preview_image_error_unknown_format;
413 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
414 } else {
415 // Rotate image, obeying exif tag.
416 result = BitmapUtils.rotateImage(result, storagePath);
417 }
418
419 } catch (OutOfMemoryError e) {
420 Log_OC.w(TAG, "Out of memory rendering file " + storagePath + " in full size; scaling down");
421
422 if (isCancelled()) return result;
423
424 // If out of memory error when loading or rotating image, try to load it scaled
425 result = loadScaledImage(storagePath);
426
427 if (result == null) {
428 mErrorMessageId = R.string.preview_image_error_unknown_format;
429 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
430 } else {
431 // Rotate scaled image, obeying exif tag
432 result = BitmapUtils.rotateImage(result, storagePath);
433 }
434
435 } catch (NoSuchFieldError e) {
436 mErrorMessageId = R.string.common_error_unknown;
437 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file "
438 + storagePath, e);
439
440 } catch (Throwable t) {
441 mErrorMessageId = R.string.common_error_unknown;
442 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
443
444 }
445
446 return result;
447 }
448
449 @Override
450 protected void onCancelled(Bitmap result) {
451 if (result != null) {
452 result.recycle();
453 }
454 }
455
456 @Override
457 protected void onPostExecute(Bitmap result) {
458 hideProgressWheel();
459 if (result != null) {
460 showLoadedImage(result);
461 } else {
462 showErrorMessage();
463 }
464 if (mBitmap != result) {
465 // unused bitmap, release it! (just in case)
466 result.recycle();
467 }
468 }
469
470 @SuppressLint("InlinedApi")
471 private void showLoadedImage(Bitmap result) {
472 if (mImageViewRef != null) {
473 final ImageViewCustom imageView = mImageViewRef.get();
474 if (imageView != null) {
475 imageView.setImageBitmap(result);
476 imageView.setVisibility(View.VISIBLE);
477 mBitmap = result; // needs to be kept for recycling when not useful
478 }
479 }
480 if (mMessageViewRef != null) {
481 final TextView messageView = mMessageViewRef.get();
482 if (messageView != null) {
483 messageView.setVisibility(View.GONE);
484 } // else , silently finish, the fragment was destroyed
485 }
486 }
487
488 private void showErrorMessage() {
489 if (mImageViewRef != null) {
490 final ImageView imageView = mImageViewRef.get();
491 if (imageView != null) {
492 // shows the default error icon
493 imageView.setVisibility(View.VISIBLE);
494 } // else , silently finish, the fragment was destroyed
495 }
496 if (mMessageViewRef != null) {
497 final TextView messageView = mMessageViewRef.get();
498 if (messageView != null) {
499 messageView.setText(mErrorMessageId);
500 messageView.setVisibility(View.VISIBLE);
501 } // else , silently finish, the fragment was destroyed
502 }
503 }
504
505 private void hideProgressWheel() {
506 if (mProgressWheelRef != null) {
507 final ProgressBar progressWheel = mProgressWheelRef.get();
508 if (progressWheel != null) {
509 progressWheel.setVisibility(View.GONE);
510 }
511 }
512 }
513
514 }
515
516 /**
517 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
518 *
519 * @param file File to test if can be previewed.
520 * @return 'True' if the file can be handled by the fragment.
521 */
522 public static boolean canBePreviewed(OCFile file) {
523 return (file != null && file.isImage());
524 }
525
526
527 /**
528 * Finishes the preview
529 */
530 private void finish() {
531 Activity container = getActivity();
532 container.finish();
533 }
534
535 public TouchImageViewCustom getImageView() {
536 return mImageView;
537 }
538
539 static class FlushedInputStream extends FilterInputStream {
540 public FlushedInputStream(InputStream inputStream) {
541 super(inputStream);
542 }
543
544 @Override
545 public long skip(long n) throws IOException {
546 long totalBytesSkipped = 0L;
547 while (totalBytesSkipped < n) {
548 long bytesSkipped = in.skip(n - totalBytesSkipped);
549 if (bytesSkipped == 0L) {
550 int byteValue = read();
551 if (byteValue < 0) {
552 break; // we reached EOF
553 } else {
554 bytesSkipped = 1; // we read one byte
555 }
556 }
557 totalBytesSkipped += bytesSkipped;
558 }
559 return totalBytesSkipped;
560 }
561 }
562
563 /**
564 * Load image scaled
565 * @param storagePath: path of the image
566 * @return Bitmap
567 */
568 @SuppressWarnings("deprecation")
569 private Bitmap loadScaledImage(String storagePath) {
570
571 Log_OC.d(TAG, "Loading image scaled");
572
573 // set desired options that will affect the size of the bitmap
574 BitmapFactory.Options options = new Options();
575 options.inScaled = true;
576 options.inPurgeable = true;
577 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
578 options.inPreferQualityOverSpeed = false;
579 }
580 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
581 options.inMutable = false;
582 }
583 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
584 options.inJustDecodeBounds = true;
585 BitmapFactory.decodeFile(storagePath, options);
586
587 int width = options.outWidth;
588 int height = options.outHeight;
589 int scale = 1;
590
591 Display display = getActivity().getWindowManager().getDefaultDisplay();
592 Point size = new Point();
593 int screenWidth;
594 int screenHeight;
595 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
596 display.getSize(size);
597 screenWidth = size.x;
598 screenHeight = size.y;
599 } else {
600 screenWidth = display.getWidth();
601 screenHeight = display.getHeight();
602 }
603
604 if (width > screenWidth) {
605 // second try to scale down the image , this time depending upon the screen size
606 scale = (int) Math.floor((float)width / screenWidth);
607 }
608 if (height > screenHeight) {
609 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
610 }
611 options.inSampleSize = scale;
612
613 // really load the bitmap
614 options.inJustDecodeBounds = false; // the next decodeFile call will be real
615 return BitmapFactory.decodeFile(storagePath, options);
616
617 }
618 }