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