1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
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.
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.
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/>.
17 package com
.owncloud
.android
.ui
.preview
;
19 import java
.io
.BufferedInputStream
;
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
;
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
;
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
;
63 * This fragment shows a preview of a downloaded image.
65 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
67 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
69 * @author David A. Velasco
71 public class PreviewImageFragment
extends FileFragment
{
73 public static final String EXTRA_FILE
= "FILE";
74 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
77 private Account mAccount
;
78 private TouchImageViewCustom mImageView
;
79 private TextView mMessageView
;
80 private ProgressBar mProgressWheel
;
82 public Bitmap mBitmap
= null
;
84 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
86 private boolean mIgnoreFirstSavedState
;
90 * Creates a fragment to preview an image.
92 * When 'imageFile' or 'ocAccount' are null
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
98 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
100 mAccount
= ocAccount
;
101 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
106 * Creates an empty fragment for image previews.
108 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
110 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
112 public PreviewImageFragment() {
115 mIgnoreFirstSavedState
= false
;
123 public void onCreate(Bundle savedInstanceState
) {
124 super.onCreate(savedInstanceState
);
125 setHasOptionsMenu(true
);
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() {
141 public void onClick(View v
) {
142 ((PreviewImageActivity
) getActivity()).toggleFullScreen();
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
);
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
);
163 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
165 mIgnoreFirstSavedState
= false
;
168 if (getFile() == null
) {
169 throw new IllegalStateException("Instanced with a NULL OCFile");
171 if (mAccount
== null
) {
172 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
174 if (!getFile().isDown()) {
175 throw new IllegalStateException("There is no local file to preview");
184 public void onSaveInstanceState(Bundle outState
) {
185 super.onSaveInstanceState(outState
);
186 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
187 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
192 public void onStart() {
194 if (getFile() != null
) {
195 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
196 bl
.execute(new String
[]{getFile().getStoragePath()});
205 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
206 super.onCreateOptionsMenu(menu
, inflater
);
207 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
214 public void onPrepareOptionsMenu(Menu menu
) {
215 super.onPrepareOptionsMenu(menu
);
217 if (mContainerActivity
.getStorageManager() != null
) {
219 setFile(mContainerActivity
.getStorageManager().getFileById(getFile().getFileId()));
221 FileMenuFilter mf
= new FileMenuFilter(
223 mContainerActivity
.getStorageManager().getAccount(),
225 getSherlockActivity()
230 // additional restriction for this fragment
231 // TODO allow renaming in PreviewImageFragment
232 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
234 item
.setVisible(false
);
235 item
.setEnabled(false
);
238 // additional restriction for this fragment
239 // TODO allow refresh file in PreviewImageFragment
240 item
= menu
.findItem(R
.id
.action_sync_file
);
242 item
.setVisible(false
);
243 item
.setEnabled(false
);
246 // additional restriction for this fragment
247 item
= menu
.findItem(R
.id
.action_move
);
249 item
.setVisible(false
);
250 item
.setEnabled(false
);
261 public boolean onOptionsItemSelected(MenuItem item
) {
262 switch (item
.getItemId()) {
263 case R
.id
.action_share_file
: {
264 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
267 case R
.id
.action_unshare_file
: {
268 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
271 case R
.id
.action_open_file_with
: {
275 case R
.id
.action_remove_file
: {
276 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
277 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
280 case R
.id
.action_see_details
: {
284 case R
.id
.action_send_file
: {
285 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
288 case R
.id
.action_sync_file
: {
289 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
299 private void seeDetails() {
300 mContainerActivity
.showDetails(getFile());
305 public void onResume() {
311 public void onPause() {
316 public void onDestroy() {
317 if (mBitmap
!= null
) {
326 * Opens the previewed image with an external application.
328 private void openFile() {
329 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
334 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
337 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
339 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
341 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
344 * Weak reference to the target {@link TextView} where error messages will be written.
346 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
348 private final WeakReference
<TextView
> mMessageViewRef
;
352 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
354 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
356 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
360 * Error message to show when a load fails
362 private int mErrorMessageId
;
368 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
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
);
378 protected Bitmap
doInBackground(String
... params
) {
379 Bitmap result
= null
;
380 if (params
.length
!= 1) return result
;
381 String storagePath
= params
[0];
384 File picture
= new File(storagePath
);
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
))));
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
);
397 } catch (OutOfMemoryError e
) {
398 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
400 // If out of memory error when loading image, try to load it scaled
401 result
= loadScaledImage(storagePath
);
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
);
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
);
412 } catch (Throwable t
) {
413 mErrorMessageId
= R
.string
.common_error_unknown
;
414 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
418 result
= rotateImage(result
, storagePath
);
424 private Bitmap
rotateImage(Bitmap bitmap
, String storagePath
){
425 Bitmap resultBitmap
= bitmap
;
429 ExifInterface exifInterface
= new ExifInterface(storagePath
);
430 int orientation
= exifInterface
.getAttributeInt(ExifInterface
.TAG_ORIENTATION
, 1);
432 Matrix matrix
= new Matrix();
437 if (orientation
== ExifInterface
.ORIENTATION_FLIP_HORIZONTAL
)
439 matrix
.postScale(-1.0f
, 1.0f
);
442 else if (orientation
== ExifInterface
.ORIENTATION_ROTATE_180
)
444 matrix
.postRotate(180);
447 else if (orientation
== ExifInterface
.ORIENTATION_FLIP_VERTICAL
)
449 matrix
.postScale(1.0f
, -1.0f
);
452 else if (orientation
== ExifInterface
.ORIENTATION_TRANSPOSE
)
454 matrix
.postRotate(-90);
455 matrix
.postScale(1.0f
, -1.0f
);
458 else if (orientation
== ExifInterface
.ORIENTATION_ROTATE_90
)
460 matrix
.postRotate(90);
463 else if (orientation
== ExifInterface
.ORIENTATION_TRANSVERSE
)
465 matrix
.postRotate(90);
466 matrix
.postScale(1.0f
, -1.0f
);
469 else if (orientation
== ExifInterface
.ORIENTATION_ROTATE_270
)
471 matrix
.postRotate(270);
475 resultBitmap
= Bitmap
.createBitmap(bitmap
, 0, 0, bitmap
.getWidth(), bitmap
.getHeight(), matrix
, true
);
477 catch (Exception exception
)
479 Log_OC
.e(TAG
, "Could not rotate the image: " + storagePath
);
485 protected void onPostExecute(Bitmap result
) {
487 if (result
!= null
) {
488 showLoadedImage(result
);
494 @SuppressLint("InlinedApi")
495 private void showLoadedImage(Bitmap result
) {
496 if (mImageViewRef
!= null
) {
497 final ImageViewCustom imageView
= mImageViewRef
.get();
498 if (imageView
!= null
) {
499 imageView
.setBitmap(result
);
500 imageView
.setImageBitmap(result
);
501 imageView
.setVisibility(View
.VISIBLE
);
503 } // else , silently finish, the fragment was destroyed
505 if (mMessageViewRef
!= null
) {
506 final TextView messageView
= mMessageViewRef
.get();
507 if (messageView
!= null
) {
508 messageView
.setVisibility(View
.GONE
);
509 } // else , silently finish, the fragment was destroyed
513 private void showErrorMessage() {
514 if (mImageViewRef
!= null
) {
515 final ImageView imageView
= mImageViewRef
.get();
516 if (imageView
!= null
) {
517 // shows the default error icon
518 imageView
.setVisibility(View
.VISIBLE
);
519 } // else , silently finish, the fragment was destroyed
521 if (mMessageViewRef
!= null
) {
522 final TextView messageView
= mMessageViewRef
.get();
523 if (messageView
!= null
) {
524 messageView
.setText(mErrorMessageId
);
525 messageView
.setVisibility(View
.VISIBLE
);
526 } // else , silently finish, the fragment was destroyed
530 private void hideProgressWheel() {
531 if (mProgressWheelRef
!= null
) {
532 final ProgressBar progressWheel
= mProgressWheelRef
.get();
533 if (progressWheel
!= null
) {
534 progressWheel
.setVisibility(View
.GONE
);
542 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
544 * @param file File to test if can be previewed.
545 * @return 'True' if the file can be handled by the fragment.
547 public static boolean canBePreviewed(OCFile file
) {
548 return (file
!= null
&& file
.isImage());
553 * Finishes the preview
555 private void finish() {
556 Activity container
= getActivity();
560 public TouchImageViewCustom
getImageView() {
564 static class FlushedInputStream
extends FilterInputStream
{
565 public FlushedInputStream(InputStream inputStream
) {
570 public long skip(long n
) throws IOException
{
571 long totalBytesSkipped
= 0L;
572 while (totalBytesSkipped
< n
) {
573 long bytesSkipped
= in.skip(n
- totalBytesSkipped
);
574 if (bytesSkipped
== 0L) {
575 int byteValue
= read();
577 break; // we reached EOF
579 bytesSkipped
= 1; // we read one byte
582 totalBytesSkipped
+= bytesSkipped
;
584 return totalBytesSkipped
;
590 * @param storagePath: path of the image
593 @SuppressWarnings("deprecation")
594 private Bitmap
loadScaledImage(String storagePath
) {
596 Log_OC
.d(TAG
, "Loading image scaled");
598 // set desired options that will affect the size of the bitmap
599 BitmapFactory
.Options options
= new Options();
600 options
.inScaled
= true
;
601 options
.inPurgeable
= true
;
602 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
603 options
.inPreferQualityOverSpeed
= false
;
605 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
606 options
.inMutable
= false
;
608 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
609 options
.inJustDecodeBounds
= true
;
610 BitmapFactory
.decodeFile(storagePath
, options
);
612 int width
= options
.outWidth
;
613 int height
= options
.outHeight
;
616 Display display
= getActivity().getWindowManager().getDefaultDisplay();
617 Point size
= new Point();
620 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
621 display
.getSize(size
);
622 screenWidth
= size
.x
;
623 screenHeight
= size
.y
;
625 screenWidth
= display
.getWidth();
626 screenHeight
= display
.getHeight();
629 if (width
> screenWidth
) {
630 // second try to scale down the image , this time depending upon the screen size
631 scale
= (int) Math
.floor((float)width
/ screenWidth
);
633 if (height
> screenHeight
) {
634 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
636 options
.inSampleSize
= scale
;
638 // really load the bitmap
639 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
640 return BitmapFactory
.decodeFile(storagePath
, options
);