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