show thumbnail while waiting for resized image
[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.lang.ref.WeakReference;
23
24 import android.accounts.Account;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.graphics.Bitmap;
28 import android.graphics.Point;
29 import android.graphics.drawable.Drawable;
30 import android.os.AsyncTask;
31 import android.os.Bundle;
32 import android.support.v4.app.FragmentStatePagerAdapter;
33 import android.view.LayoutInflater;
34 import android.view.Menu;
35 import android.view.MenuInflater;
36 import android.view.MenuItem;
37 import android.view.View;
38 import android.view.View.OnClickListener;
39 import android.view.ViewGroup;
40 import android.widget.ImageView;
41 import android.widget.ProgressBar;
42 import android.widget.TextView;
43
44 import com.owncloud.android.MainApp;
45 import com.owncloud.android.R;
46 import com.owncloud.android.datamodel.OCFile;
47 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
48 import com.owncloud.android.files.FileMenuFilter;
49 import com.owncloud.android.lib.common.utils.Log_OC;
50 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
51 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
52 import com.owncloud.android.ui.fragment.FileFragment;
53 import com.owncloud.android.utils.BitmapUtils;
54 import com.owncloud.android.utils.DisplayUtils;
55
56 import third_parties.michaelOrtiz.TouchImageViewCustom;
57
58
59 /**
60 * This fragment shows a preview of a downloaded image.
61 *
62 * Trying to get an instance with a NULL {@link OCFile} will produce an
63 * {@link IllegalStateException}.
64 *
65 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on
66 * instantiation too.
67 */
68 public class PreviewImageFragment extends FileFragment {
69
70 public static final String EXTRA_FILE = "FILE";
71
72 private static final String ARG_FILE = "FILE";
73 private static final String ARG_IGNORE_FIRST = "IGNORE_FIRST";
74 private static final String ARG_SHOW_RESIZED_IMAGE = "SHOW_RESIZED_IMAGE";
75
76 private TouchImageViewCustom mImageView;
77 private TextView mMessageView;
78 private ProgressBar mProgressWheel;
79
80 private Boolean mShowResizedImage = false;
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 * Public factory method to create a new fragment that previews an image.
93 *
94 * Android strongly recommends keep the empty constructor of fragments as the only public
95 * constructor, and
96 * use {@link #setArguments(Bundle)} to set the needed arguments.
97 *
98 * This method hides to client objects the need of doing the construction in two steps.
99 *
100 * @param imageFile An {@link OCFile} to preview as an image in the fragment
101 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of
102 * {@link FragmentStatePagerAdapter}
103 * ; TODO better solution
104 */
105 public static PreviewImageFragment newInstance(OCFile imageFile, boolean ignoreFirstSavedState,
106 boolean showResizedImage){
107 PreviewImageFragment frag = new PreviewImageFragment();
108 frag.mShowResizedImage = showResizedImage;
109 Bundle args = new Bundle();
110 args.putParcelable(ARG_FILE, imageFile);
111 args.putBoolean(ARG_IGNORE_FIRST, ignoreFirstSavedState);
112 args.putBoolean(ARG_SHOW_RESIZED_IMAGE, showResizedImage);
113 frag.setArguments(args);
114 return frag;
115 }
116
117
118
119 /**
120 * Creates an empty fragment for image previews.
121 *
122 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
123 * (for instance, when the device is turned a aside).
124 *
125 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
126 * construction
127 */
128 public PreviewImageFragment() {
129 mIgnoreFirstSavedState = false;
130 }
131
132
133 /**
134 * {@inheritDoc}
135 */
136 @Override
137 public void onCreate(Bundle savedInstanceState) {
138 super.onCreate(savedInstanceState);
139 Bundle args = getArguments();
140 setFile((OCFile)args.getParcelable(ARG_FILE));
141 // TODO better in super, but needs to check ALL the class extending FileFragment;
142 // not right now
143
144 mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
145 mShowResizedImage = args.getBoolean(ARG_SHOW_RESIZED_IMAGE);
146 setHasOptionsMenu(true);
147 }
148
149
150 /**
151 * {@inheritDoc}
152 */
153 @Override
154 public View onCreateView(LayoutInflater inflater, ViewGroup container,
155 Bundle savedInstanceState) {
156 super.onCreateView(inflater, container, savedInstanceState);
157 View view = inflater.inflate(R.layout.preview_image_fragment, container, false);
158 mImageView = (TouchImageViewCustom) view.findViewById(R.id.image);
159 mImageView.setVisibility(View.GONE);
160 mImageView.setOnClickListener(new OnClickListener() {
161 @Override
162 public void onClick(View v) {
163 ((PreviewImageActivity) getActivity()).toggleFullScreen();
164 }
165
166 });
167 mMessageView = (TextView)view.findViewById(R.id.message);
168 mMessageView.setVisibility(View.GONE);
169 mProgressWheel = (ProgressBar)view.findViewById(R.id.progressWheel);
170 mProgressWheel.setVisibility(View.VISIBLE);
171 return view;
172 }
173
174 /**
175 * {@inheritDoc}
176 */
177 @Override
178 public void onActivityCreated(Bundle savedInstanceState) {
179 super.onActivityCreated(savedInstanceState);
180 if (savedInstanceState != null) {
181 if (!mIgnoreFirstSavedState) {
182 OCFile file = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
183 setFile(file);
184 } else {
185 mIgnoreFirstSavedState = false;
186 }
187 }
188 if (getFile() == null) {
189 throw new IllegalStateException("Instanced with a NULL OCFile");
190 }
191 }
192
193
194 /**
195 * {@inheritDoc}
196 */
197 @Override
198 public void onSaveInstanceState(Bundle outState) {
199 super.onSaveInstanceState(outState);
200 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
201 }
202
203
204 @Override
205 public void onStart() {
206 super.onStart();
207 if (getFile() != null) {
208 mImageView.setTag(getFile().getFileId());
209
210 if (mShowResizedImage){
211 Bitmap resizedImage = ThumbnailsCacheManager.getBitmapFromDiskCache(
212 String.valueOf("r" + getFile().getRemoteId()));
213
214 if (resizedImage != null && !getFile().needsUpdateThumbnail()){
215 mProgressWheel.setVisibility(View.GONE);
216 mImageView.setImageBitmap(resizedImage);
217 mImageView.setVisibility(View.VISIBLE);
218 mBitmap = resizedImage;
219 } else {
220 // show thumbnail while loading resized image
221 Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
222 String.valueOf("t" + getFile().getRemoteId()));
223
224 if (thumbnail != null){
225 mImageView.setImageBitmap(thumbnail);
226 mProgressWheel.setVisibility(View.VISIBLE);
227 mImageView.setVisibility(View.VISIBLE);
228 mBitmap = thumbnail;
229 } else {
230 thumbnail = ThumbnailsCacheManager.mDefaultImg;
231 }
232
233 // generate new resized image
234 if (ThumbnailsCacheManager.cancelPotentialWork(getFile(), mImageView) &&
235 mContainerActivity.getStorageManager() != null) {
236 final ThumbnailsCacheManager.ThumbnailGenerationTask task =
237 new ThumbnailsCacheManager.ThumbnailGenerationTask(
238 mImageView, mContainerActivity.getStorageManager(),
239 mContainerActivity.getStorageManager().getAccount(),
240 mProgressWheel);
241 if (resizedImage == null) {
242 resizedImage = thumbnail;
243 }
244 final ThumbnailsCacheManager.AsyncDrawable asyncDrawable =
245 new ThumbnailsCacheManager.AsyncDrawable(
246 MainApp.getAppContext().getResources(),
247 resizedImage,
248 task
249 );
250 mImageView.setImageDrawable(asyncDrawable);
251 task.execute(getFile(), false);
252 }
253 }
254 } else {
255 mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
256 mLoadBitmapTask.execute(getFile());
257 }
258 }
259 }
260
261
262 @Override
263 public void onStop() {
264 Log_OC.d(TAG, "onStop starts");
265 if (mLoadBitmapTask != null) {
266 mLoadBitmapTask.cancel(true);
267 mLoadBitmapTask = null;
268 }
269 super.onStop();
270 }
271
272 /**
273 * {@inheritDoc}
274 */
275 @Override
276 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
277 super.onCreateOptionsMenu(menu, inflater);
278 inflater.inflate(R.menu.file_actions_menu, menu);
279 }
280
281 /**
282 * {@inheritDoc}
283 */
284 @Override
285 public void onPrepareOptionsMenu(Menu menu) {
286 super.onPrepareOptionsMenu(menu);
287
288 if (mContainerActivity.getStorageManager() != null) {
289 // Update the file
290 setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
291
292 FileMenuFilter mf = new FileMenuFilter(
293 getFile(),
294 mContainerActivity.getStorageManager().getAccount(),
295 mContainerActivity,
296 getActivity()
297 );
298 mf.filter(menu);
299 }
300
301 // additional restriction for this fragment
302 // TODO allow renaming in PreviewImageFragment
303 MenuItem item = menu.findItem(R.id.action_rename_file);
304 if (item != null) {
305 item.setVisible(false);
306 item.setEnabled(false);
307 }
308
309 // additional restriction for this fragment
310 // TODO allow refresh file in PreviewImageFragment
311 item = menu.findItem(R.id.action_sync_file);
312 if (item != null) {
313 item.setVisible(false);
314 item.setEnabled(false);
315 }
316
317 // additional restriction for this fragment
318 item = menu.findItem(R.id.action_move);
319 if (item != null) {
320 item.setVisible(false);
321 item.setEnabled(false);
322 }
323
324 // additional restriction for this fragment
325 item = menu.findItem(R.id.action_copy);
326 if (item != null) {
327 item.setVisible(false);
328 item.setEnabled(false);
329 }
330
331 }
332
333
334 /**
335 * {@inheritDoc}
336 */
337 @Override
338 public boolean onOptionsItemSelected(MenuItem item) {
339 switch (item.getItemId()) {
340 case R.id.action_share_file: {
341 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
342 return true;
343 }
344 case R.id.action_share_with_users: {
345 mContainerActivity.getFileOperationsHelper().showShareFile(getFile());
346 return true;
347 }
348 case R.id.action_unshare_file: {
349 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
350 return true;
351 }
352 case R.id.action_open_file_with: {
353 openFile();
354 return true;
355 }
356 case R.id.action_remove_file: {
357 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
358 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
359 return true;
360 }
361 case R.id.action_see_details: {
362 seeDetails();
363 return true;
364 }
365 case R.id.action_send_file: {
366 if (getFile().isImage() && !getFile().isDown()){
367 mContainerActivity.getFileOperationsHelper().sendCachedImage(getFile());
368 return true;
369 } else {
370 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
371 return true;
372 }
373 }
374 case R.id.action_download_file:
375 case R.id.action_sync_file: {
376 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
377 return true;
378 }
379 case R.id.action_favorite_file:{
380 mContainerActivity.getFileOperationsHelper().toggleFavorite(getFile(), true);
381 return true;
382 }
383 case R.id.action_unfavorite_file:{
384 mContainerActivity.getFileOperationsHelper().toggleFavorite(getFile(), false);
385 return true;
386 }
387 default:
388 return false;
389 }
390 }
391
392
393 private void seeDetails() {
394 mContainerActivity.showDetails(getFile());
395 }
396
397 @Override
398 public void onResume() {
399 super.onResume();
400 }
401
402
403 @Override
404 public void onPause() {
405 super.onPause();
406 }
407
408 @Override
409 public void onDestroy() {
410 if (mBitmap != null) {
411 mBitmap.recycle();
412 System.gc();
413 // putting this in onStop() is just the same; the fragment is always destroyed by
414 // {@link FragmentStatePagerAdapter} when the fragment in swiped further than the
415 // valid offscreen distance, and onStop() is never called before than that
416 }
417 super.onDestroy();
418 }
419
420
421 /**
422 * Opens the previewed image with an external application.
423 */
424 private void openFile() {
425 mContainerActivity.getFileOperationsHelper().openFile(getFile());
426 finish();
427 }
428
429
430 private class LoadBitmapTask extends AsyncTask<OCFile, Void, LoadImage> {
431
432 /**
433 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
434 *
435 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
436 * memory before the load finishes.
437 */
438 private final WeakReference<ImageViewCustom> mImageViewRef;
439
440 /**
441 * Weak reference to the target {@link TextView} where error messages will be written.
442 *
443 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
444 * memory before the load finishes.
445 */
446 private final WeakReference<TextView> mMessageViewRef;
447
448
449 /**
450 * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
451 *
452 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
453 * memory before the load finishes.
454 */
455 private final WeakReference<ProgressBar> mProgressWheelRef;
456
457
458 /**
459 * Error message to show when a load fails
460 */
461 private int mErrorMessageId;
462
463
464 /**
465 * Constructor.
466 *
467 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
468 */
469 public LoadBitmapTask(ImageViewCustom imageView, TextView messageView,
470 ProgressBar progressWheel) {
471 mImageViewRef = new WeakReference<ImageViewCustom>(imageView);
472 mMessageViewRef = new WeakReference<TextView>(messageView);
473 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
474 }
475
476 @Override
477 protected LoadImage doInBackground(OCFile... params) {
478 Bitmap result = null;
479 if (params.length != 1) return null;
480 OCFile ocFile = params[0];
481 String storagePath = ocFile.getStoragePath();
482 try {
483
484 int maxDownScale = 3; // could be a parameter passed to doInBackground(...)
485 Point screenSize = DisplayUtils.getScreenSize(getActivity());
486 int minWidth = screenSize.x;
487 int minHeight = screenSize.y;
488 for (int i = 0; i < maxDownScale && result == null; i++) {
489 if (isCancelled()) return null;
490 try {
491 result = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth,
492 minHeight);
493
494 if (isCancelled()) return new LoadImage(result, ocFile);
495
496 if (result == null) {
497 mErrorMessageId = R.string.preview_image_error_unknown_format;
498 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
499 break;
500 } else {
501 // Rotate image, obeying exif tag.
502 result = BitmapUtils.rotateImage(result, storagePath);
503 }
504
505 } catch (OutOfMemoryError e) {
506 mErrorMessageId = R.string.common_error_out_memory;
507 if (i < maxDownScale - 1) {
508 Log_OC.w(TAG, "Out of memory rendering file " + storagePath +
509 " ; scaling down");
510 minWidth = minWidth / 2;
511 minHeight = minHeight / 2;
512
513 } else {
514 Log_OC.w(TAG, "Out of memory rendering file " + storagePath +
515 " ; failing");
516 }
517 if (result != null) {
518 result.recycle();
519 }
520 result = null;
521 }
522 }
523
524 } catch (NoSuchFieldError e) {
525 mErrorMessageId = R.string.common_error_unknown;
526 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file "
527 + storagePath, e);
528
529 } catch (Throwable t) {
530 mErrorMessageId = R.string.common_error_unknown;
531 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
532
533 }
534
535 return new LoadImage(result, ocFile);
536 }
537
538 @Override
539 protected void onCancelled(LoadImage result) {
540 if (result != null && result.bitmap != null) {
541 result.bitmap.recycle();
542 }
543 }
544
545 @Override
546 protected void onPostExecute(LoadImage result) {
547 hideProgressWheel();
548 if (result.bitmap != null) {
549 showLoadedImage(result);
550 }
551 else {
552 showErrorMessage();
553 }
554 if (result.bitmap != null && mBitmap != result.bitmap) {
555 // unused bitmap, release it! (just in case)
556 result.bitmap.recycle();
557 }
558 }
559
560 @SuppressLint("InlinedApi")
561 private void showLoadedImage(LoadImage result) {
562 final ImageViewCustom imageView = mImageViewRef.get();
563 Bitmap bitmap = result.bitmap;
564 if (imageView != null) {
565 Log_OC.d(TAG, "Showing image with resolution " + bitmap.getWidth() + "x" +
566 bitmap.getHeight());
567
568 if (result.ocFile.getMimetype().equalsIgnoreCase("image/png")){
569 Drawable backrepeat = getResources().getDrawable(R.drawable.backrepeat);
570 imageView.setBackground(backrepeat);
571 }
572
573 imageView.setImageBitmap(bitmap);
574 imageView.setVisibility(View.VISIBLE);
575 mBitmap = bitmap; // needs to be kept for recycling when not useful
576 }
577
578 final TextView messageView = mMessageViewRef.get();
579 if (messageView != null) {
580 messageView.setVisibility(View.GONE);
581 } // else , silently finish, the fragment was destroyed
582 }
583
584 private void showErrorMessage() {
585 final ImageView imageView = mImageViewRef.get();
586 if (imageView != null) {
587 // shows the default error icon
588 imageView.setVisibility(View.VISIBLE);
589 } // else , silently finish, the fragment was destroyed
590
591 final TextView messageView = mMessageViewRef.get();
592 if (messageView != null) {
593 messageView.setText(mErrorMessageId);
594 messageView.setVisibility(View.VISIBLE);
595 } // else , silently finish, the fragment was destroyed
596 }
597
598 private void hideProgressWheel() {
599 final ProgressBar progressWheel = mProgressWheelRef.get();
600 if (progressWheel != null) {
601 progressWheel.setVisibility(View.GONE);
602 }
603 }
604
605 }
606
607 /**
608 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment}
609 * to be previewed.
610 *
611 * @param file File to test if can be previewed.
612 * @return 'True' if the file can be handled by the fragment.
613 */
614 public static boolean canBePreviewed(OCFile file) {
615 return (file != null && file.isImage());
616 }
617
618
619 /**
620 * Finishes the preview
621 */
622 private void finish() {
623 Activity container = getActivity();
624 container.finish();
625 }
626
627 public TouchImageViewCustom getImageView() {
628 return mImageView;
629 }
630
631 private class LoadImage {
632 private Bitmap bitmap;
633 private OCFile ocFile;
634
635 public LoadImage(Bitmap bitmap, OCFile ocFile){
636 this.bitmap = bitmap;
637 this.ocFile = ocFile;
638 }
639
640 }
641
642 }