Merge branch 'setAsWallpaper' into beta
[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 thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
212 String.valueOf("r" + getFile().getRemoteId())
213 );
214
215 if (thumbnail != null && !getFile().needsUpdateThumbnail()){
216 mProgressWheel.setVisibility(View.GONE);
217 mImageView.setImageBitmap(thumbnail);
218 mImageView.setVisibility(View.VISIBLE);
219 mBitmap = thumbnail;
220 } else {
221 // generate new Thumbnail
222 if (ThumbnailsCacheManager.cancelPotentialWork(getFile(), mImageView) &&
223 mContainerActivity.getStorageManager() != null) {
224 final ThumbnailsCacheManager.ThumbnailGenerationTask task =
225 new ThumbnailsCacheManager.ThumbnailGenerationTask(
226 mImageView, mContainerActivity.getStorageManager(),
227 mContainerActivity.getStorageManager().getAccount(),
228 mProgressWheel);
229 if (thumbnail == null) {
230 thumbnail = ThumbnailsCacheManager.mDefaultImg;
231 }
232 final ThumbnailsCacheManager.AsyncDrawable asyncDrawable =
233 new ThumbnailsCacheManager.AsyncDrawable(
234 MainApp.getAppContext().getResources(),
235 thumbnail,
236 task
237 );
238 mImageView.setImageDrawable(asyncDrawable);
239 task.execute(getFile(), false);
240 }
241 }
242 } else {
243 mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
244 mLoadBitmapTask.execute(getFile());
245 }
246 }
247 }
248
249
250 @Override
251 public void onStop() {
252 Log_OC.d(TAG, "onStop starts");
253 if (mLoadBitmapTask != null) {
254 mLoadBitmapTask.cancel(true);
255 mLoadBitmapTask = null;
256 }
257 super.onStop();
258 }
259
260 /**
261 * {@inheritDoc}
262 */
263 @Override
264 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
265 super.onCreateOptionsMenu(menu, inflater);
266 inflater.inflate(R.menu.file_actions_menu, menu);
267 }
268
269 /**
270 * {@inheritDoc}
271 */
272 @Override
273 public void onPrepareOptionsMenu(Menu menu) {
274 super.onPrepareOptionsMenu(menu);
275
276 if (mContainerActivity.getStorageManager() != null) {
277 // Update the file
278 setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
279
280 FileMenuFilter mf = new FileMenuFilter(
281 getFile(),
282 mContainerActivity.getStorageManager().getAccount(),
283 mContainerActivity,
284 getActivity()
285 );
286 mf.filter(menu);
287 }
288
289 // additional restriction for this fragment
290 // TODO allow renaming in PreviewImageFragment
291 MenuItem item = menu.findItem(R.id.action_rename_file);
292 if (item != null) {
293 item.setVisible(false);
294 item.setEnabled(false);
295 }
296
297 // additional restriction for this fragment
298 // TODO allow refresh file in PreviewImageFragment
299 item = menu.findItem(R.id.action_sync_file);
300 if (item != null) {
301 item.setVisible(false);
302 item.setEnabled(false);
303 }
304
305 // additional restriction for this fragment
306 item = menu.findItem(R.id.action_move);
307 if (item != null) {
308 item.setVisible(false);
309 item.setEnabled(false);
310 }
311
312 // additional restriction for this fragment
313 item = menu.findItem(R.id.action_copy);
314 if (item != null) {
315 item.setVisible(false);
316 item.setEnabled(false);
317 }
318
319 }
320
321
322 /**
323 * {@inheritDoc}
324 */
325 @Override
326 public boolean onOptionsItemSelected(MenuItem item) {
327 switch (item.getItemId()) {
328 case R.id.action_share_file: {
329 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
330 return true;
331 }
332 case R.id.action_unshare_file: {
333 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
334 return true;
335 }
336 case R.id.action_open_file_with: {
337 openFile();
338 return true;
339 }
340 case R.id.action_remove_file: {
341 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
342 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
343 return true;
344 }
345 case R.id.action_see_details: {
346 seeDetails();
347 return true;
348 }
349 case R.id.action_send_file: {
350 if (getFile().isImage() && !getFile().isDown()){
351 mContainerActivity.getFileOperationsHelper().sendCachedImage(getFile());
352 return true;
353 } else {
354 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
355 return true;
356 }
357 }
358 case R.id.action_sync_file: {
359 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
360 return true;
361 }
362 case R.id.action_favorite_file:{
363 mContainerActivity.getFileOperationsHelper().toggleFavorite(getFile(), true);
364 return true;
365 }
366 case R.id.action_unfavorite_file:{
367 mContainerActivity.getFileOperationsHelper().toggleFavorite(getFile(), false);
368 return true;
369 }
370 case R.id.action_set_as_wallpaper:{
371 mContainerActivity.getFileOperationsHelper().setPictureAs(getFile());
372 return true;
373 }
374 default:
375 return false;
376 }
377 }
378
379
380 private void seeDetails() {
381 mContainerActivity.showDetails(getFile());
382 }
383
384
385 @Override
386 public void onResume() {
387 super.onResume();
388 }
389
390
391 @Override
392 public void onPause() {
393 super.onPause();
394 }
395
396 @Override
397 public void onDestroy() {
398 if (mBitmap != null) {
399 mBitmap.recycle();
400 System.gc();
401 // putting this in onStop() is just the same; the fragment is always destroyed by
402 // {@link FragmentStatePagerAdapter} when the fragment in swiped further than the
403 // valid offscreen distance, and onStop() is never called before than that
404 }
405 super.onDestroy();
406 }
407
408
409 /**
410 * Opens the previewed image with an external application.
411 */
412 private void openFile() {
413 mContainerActivity.getFileOperationsHelper().openFile(getFile());
414 finish();
415 }
416
417
418 private class LoadBitmapTask extends AsyncTask<OCFile, Void, LoadImage> {
419
420 /**
421 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
422 *
423 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
424 * memory before the load finishes.
425 */
426 private final WeakReference<ImageViewCustom> mImageViewRef;
427
428 /**
429 * Weak reference to the target {@link TextView} where error messages will be written.
430 *
431 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
432 * memory before the load finishes.
433 */
434 private final WeakReference<TextView> mMessageViewRef;
435
436
437 /**
438 * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
439 *
440 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
441 * memory before the load finishes.
442 */
443 private final WeakReference<ProgressBar> mProgressWheelRef;
444
445
446 /**
447 * Error message to show when a load fails
448 */
449 private int mErrorMessageId;
450
451
452 /**
453 * Constructor.
454 *
455 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
456 */
457 public LoadBitmapTask(ImageViewCustom imageView, TextView messageView,
458 ProgressBar progressWheel) {
459 mImageViewRef = new WeakReference<ImageViewCustom>(imageView);
460 mMessageViewRef = new WeakReference<TextView>(messageView);
461 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
462 }
463
464 @Override
465 protected LoadImage doInBackground(OCFile... params) {
466 Bitmap result = null;
467 if (params.length != 1) return null;
468 OCFile ocFile = params[0];
469 String storagePath = ocFile.getStoragePath();
470 try {
471
472 int maxDownScale = 3; // could be a parameter passed to doInBackground(...)
473 Point screenSize = DisplayUtils.getScreenSize(getActivity());
474 int minWidth = screenSize.x;
475 int minHeight = screenSize.y;
476 for (int i = 0; i < maxDownScale && result == null; i++) {
477 if (isCancelled()) return null;
478 try {
479 result = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth,
480 minHeight);
481
482 if (isCancelled()) return new LoadImage(result, ocFile);
483
484 if (result == null) {
485 mErrorMessageId = R.string.preview_image_error_unknown_format;
486 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
487 break;
488 } else {
489 // Rotate image, obeying exif tag.
490 result = BitmapUtils.rotateImage(result, storagePath);
491 }
492
493 } catch (OutOfMemoryError e) {
494 mErrorMessageId = R.string.common_error_out_memory;
495 if (i < maxDownScale - 1) {
496 Log_OC.w(TAG, "Out of memory rendering file " + storagePath +
497 " ; scaling down");
498 minWidth = minWidth / 2;
499 minHeight = minHeight / 2;
500
501 } else {
502 Log_OC.w(TAG, "Out of memory rendering file " + storagePath +
503 " ; failing");
504 }
505 if (result != null) {
506 result.recycle();
507 }
508 result = null;
509 }
510 }
511
512 } catch (NoSuchFieldError e) {
513 mErrorMessageId = R.string.common_error_unknown;
514 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file "
515 + storagePath, e);
516
517 } catch (Throwable t) {
518 mErrorMessageId = R.string.common_error_unknown;
519 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
520
521 }
522
523 return new LoadImage(result, ocFile);
524 }
525
526 @Override
527 protected void onCancelled(LoadImage result) {
528 if (result != null && result.bitmap != null) {
529 result.bitmap.recycle();
530 }
531 }
532
533 @Override
534 protected void onPostExecute(LoadImage result) {
535 hideProgressWheel();
536 if (result.bitmap != null) {
537 showLoadedImage(result);
538 }
539 else {
540 showErrorMessage();
541 }
542 if (result.bitmap != null && mBitmap != result.bitmap) {
543 // unused bitmap, release it! (just in case)
544 result.bitmap.recycle();
545 }
546 }
547
548 @SuppressLint("InlinedApi")
549 private void showLoadedImage(LoadImage result) {
550 final ImageViewCustom imageView = mImageViewRef.get();
551 Bitmap bitmap = result.bitmap;
552 if (imageView != null) {
553 Log_OC.d(TAG, "Showing image with resolution " + bitmap.getWidth() + "x" +
554 bitmap.getHeight());
555
556 if (result.ocFile.getMimetype().equalsIgnoreCase("image/png")){
557 Drawable backrepeat = getResources().getDrawable(R.drawable.backrepeat);
558 imageView.setBackground(backrepeat);
559 }
560
561 if (result.ocFile.getMimetype().equalsIgnoreCase("image/gif")){
562 imageView.setGifImage(result.ocFile);
563 } else {
564 imageView.setImageBitmap(bitmap);
565 }
566
567 imageView.setVisibility(View.VISIBLE);
568 mBitmap = bitmap; // needs to be kept for recycling when not useful
569 }
570
571 final TextView messageView = mMessageViewRef.get();
572 if (messageView != null) {
573 messageView.setVisibility(View.GONE);
574 } // else , silently finish, the fragment was destroyed
575 }
576
577 private void showErrorMessage() {
578 final ImageView imageView = mImageViewRef.get();
579 if (imageView != null) {
580 // shows the default error icon
581 imageView.setVisibility(View.VISIBLE);
582 } // else , silently finish, the fragment was destroyed
583
584 final TextView messageView = mMessageViewRef.get();
585 if (messageView != null) {
586 messageView.setText(mErrorMessageId);
587 messageView.setVisibility(View.VISIBLE);
588 } // else , silently finish, the fragment was destroyed
589 }
590
591 private void hideProgressWheel() {
592 final ProgressBar progressWheel = mProgressWheelRef.get();
593 if (progressWheel != null) {
594 progressWheel.setVisibility(View.GONE);
595 }
596 }
597
598 }
599
600 /**
601 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment}
602 * to be previewed.
603 *
604 * @param file File to test if can be previewed.
605 * @return 'True' if the file can be handled by the fragment.
606 */
607 public static boolean canBePreviewed(OCFile file) {
608 return (file != null && file.isImage());
609 }
610
611
612 /**
613 * Finishes the preview
614 */
615 private void finish() {
616 Activity container = getActivity();
617 container.finish();
618 }
619
620 public TouchImageViewCustom getImageView() {
621 return mImageView;
622 }
623
624 private class LoadImage {
625 private Bitmap bitmap;
626 private OCFile ocFile;
627
628 public LoadImage(Bitmap bitmap, OCFile ocFile){
629 this.bitmap = bitmap;
630 this.ocFile = ocFile;
631 }
632
633 }
634
635 }