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