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