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
.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
.TouchImageViewCustom
;
65 * This fragment shows a preview of a downloaded image.
67 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
69 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
71 * @author David A. Velasco
73 public class PreviewImageFragment
extends FileFragment
{
75 public static final String EXTRA_FILE
= "FILE";
76 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
79 private Account mAccount
;
80 private TouchImageViewCustom mImageView
;
81 private TextView mMessageView
;
82 private ProgressBar mProgressWheel
;
84 public Bitmap mBitmap
= null
;
86 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
88 private boolean mIgnoreFirstSavedState
;
92 * Creates a fragment to preview an image.
94 * When 'imageFile' or 'ocAccount' are null
96 * @param imageFile An {@link OCFile} to preview as an image in the fragment
97 * @param ocAccount An ownCloud account; needed to start downloads
98 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
100 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
102 mAccount
= ocAccount
;
103 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
108 * Creates an empty fragment for image previews.
110 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
112 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
114 public PreviewImageFragment() {
117 mIgnoreFirstSavedState
= false
;
125 public void onCreate(Bundle savedInstanceState
) {
126 super.onCreate(savedInstanceState
);
127 setHasOptionsMenu(true
);
135 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
136 Bundle savedInstanceState
) {
137 super.onCreateView(inflater
, container
, savedInstanceState
);
138 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
139 mImageView
= (TouchImageViewCustom
) mView
.findViewById(R
.id
.image
);
140 mImageView
.setVisibility(View
.GONE
);
141 mImageView
.setOnClickListener(new OnClickListener() {
143 public void onClick(View v
) {
144 ((PreviewImageActivity
) getActivity()).toggleFullScreen();
148 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
149 mMessageView
.setVisibility(View
.GONE
);
150 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
151 mProgressWheel
.setVisibility(View
.VISIBLE
);
159 public void onActivityCreated(Bundle savedInstanceState
) {
160 super.onActivityCreated(savedInstanceState
);
161 if (savedInstanceState
!= null
) {
162 if (!mIgnoreFirstSavedState
) {
163 OCFile file
= (OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
165 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
167 mIgnoreFirstSavedState
= false
;
170 if (getFile() == null
) {
171 throw new IllegalStateException("Instanced with a NULL OCFile");
173 if (mAccount
== null
) {
174 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
176 if (!getFile().isDown()) {
177 throw new IllegalStateException("There is no local file to preview");
186 public void onSaveInstanceState(Bundle outState
) {
187 super.onSaveInstanceState(outState
);
188 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
189 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
194 public void onStart() {
196 if (getFile() != null
) {
197 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
198 bl
.execute(new String
[]{getFile().getStoragePath()});
207 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
208 super.onCreateOptionsMenu(menu
, inflater
);
209 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
216 public void onPrepareOptionsMenu(Menu menu
) {
217 super.onPrepareOptionsMenu(menu
);
219 if (mContainerActivity
.getStorageManager() != null
) {
221 setFile(mContainerActivity
.getStorageManager().getFileById(getFile().getFileId()));
223 FileMenuFilter mf
= new FileMenuFilter(
225 mContainerActivity
.getStorageManager().getAccount(),
227 getSherlockActivity()
232 // additional restriction for this fragment
233 // TODO allow renaming in PreviewImageFragment
234 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
236 item
.setVisible(false
);
237 item
.setEnabled(false
);
240 // additional restriction for this fragment
241 // TODO allow refresh file in PreviewImageFragment
242 item
= menu
.findItem(R
.id
.action_sync_file
);
244 item
.setVisible(false
);
245 item
.setEnabled(false
);
248 // additional restriction for this fragment
249 item
= menu
.findItem(R
.id
.action_move
);
251 item
.setVisible(false
);
252 item
.setEnabled(false
);
263 public boolean onOptionsItemSelected(MenuItem item
) {
264 switch (item
.getItemId()) {
265 case R
.id
.action_share_file
: {
266 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
269 case R
.id
.action_unshare_file
: {
270 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
273 case R
.id
.action_open_file_with
: {
277 case R
.id
.action_remove_file
: {
278 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
279 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
282 case R
.id
.action_see_details
: {
286 case R
.id
.action_send_file
: {
287 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
290 case R
.id
.action_sync_file
: {
291 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
301 private void seeDetails() {
302 mContainerActivity
.showDetails(getFile());
307 public void onResume() {
313 public void onPause() {
318 public void onDestroy() {
319 if (mBitmap
!= null
) {
328 * Opens the previewed image with an external application.
330 private void openFile() {
331 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
336 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
339 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
341 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
343 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
346 * Weak reference to the target {@link TextView} where error messages will be written.
348 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
350 private final WeakReference
<TextView
> mMessageViewRef
;
354 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
356 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
358 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
362 * Error message to show when a load fails
364 private int mErrorMessageId
;
370 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
372 public BitmapLoader(ImageViewCustom imageView
, TextView messageView
, ProgressBar progressWheel
) {
373 mImageViewRef
= new WeakReference
<ImageViewCustom
>(imageView
);
374 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
375 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
380 protected Bitmap
doInBackground(String
... params
) {
381 Bitmap result
= null
;
382 if (params
.length
!= 1) return result
;
383 String storagePath
= params
[0];
386 File picture
= new File(storagePath
);
388 if (picture
!= null
) {
389 //Decode file into a bitmap in real size for being able to make zoom on the image
390 result
= BitmapFactory
.decodeStream(new FlushedInputStream
391 (new BufferedInputStream(new FileInputStream(picture
))));
394 if (result
== null
) {
395 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
396 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
399 } catch (OutOfMemoryError e
) {
400 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
402 // If out of memory error when loading image, try to load it scaled
403 result
= loadScaledImage(storagePath
);
405 if (result
== null
) {
406 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
407 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
410 } catch (NoSuchFieldError e
) {
411 mErrorMessageId
= R
.string
.common_error_unknown
;
412 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
414 } catch (Throwable t
) {
415 mErrorMessageId
= R
.string
.common_error_unknown
;
416 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
420 // Rotate image, obeying exif tag
421 result
= ThumbnailsCacheManager
.rotateImage(result
, storagePath
);
428 protected void onPostExecute(Bitmap result
) {
430 if (result
!= null
) {
431 showLoadedImage(result
);
437 @SuppressLint("InlinedApi")
438 private void showLoadedImage(Bitmap result
) {
439 if (mImageViewRef
!= null
) {
440 final ImageViewCustom imageView
= mImageViewRef
.get();
441 if (imageView
!= null
) {
442 imageView
.setBitmap(result
);
443 imageView
.setImageBitmap(result
);
444 imageView
.setVisibility(View
.VISIBLE
);
446 } // else , silently finish, the fragment was destroyed
448 if (mMessageViewRef
!= null
) {
449 final TextView messageView
= mMessageViewRef
.get();
450 if (messageView
!= null
) {
451 messageView
.setVisibility(View
.GONE
);
452 } // else , silently finish, the fragment was destroyed
456 private void showErrorMessage() {
457 if (mImageViewRef
!= null
) {
458 final ImageView imageView
= mImageViewRef
.get();
459 if (imageView
!= null
) {
460 // shows the default error icon
461 imageView
.setVisibility(View
.VISIBLE
);
462 } // else , silently finish, the fragment was destroyed
464 if (mMessageViewRef
!= null
) {
465 final TextView messageView
= mMessageViewRef
.get();
466 if (messageView
!= null
) {
467 messageView
.setText(mErrorMessageId
);
468 messageView
.setVisibility(View
.VISIBLE
);
469 } // else , silently finish, the fragment was destroyed
473 private void hideProgressWheel() {
474 if (mProgressWheelRef
!= null
) {
475 final ProgressBar progressWheel
= mProgressWheelRef
.get();
476 if (progressWheel
!= null
) {
477 progressWheel
.setVisibility(View
.GONE
);
485 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
487 * @param file File to test if can be previewed.
488 * @return 'True' if the file can be handled by the fragment.
490 public static boolean canBePreviewed(OCFile file
) {
491 return (file
!= null
&& file
.isImage());
496 * Finishes the preview
498 private void finish() {
499 Activity container
= getActivity();
503 public TouchImageViewCustom
getImageView() {
507 static class FlushedInputStream
extends FilterInputStream
{
508 public FlushedInputStream(InputStream inputStream
) {
513 public long skip(long n
) throws IOException
{
514 long totalBytesSkipped
= 0L;
515 while (totalBytesSkipped
< n
) {
516 long bytesSkipped
= in.skip(n
- totalBytesSkipped
);
517 if (bytesSkipped
== 0L) {
518 int byteValue
= read();
520 break; // we reached EOF
522 bytesSkipped
= 1; // we read one byte
525 totalBytesSkipped
+= bytesSkipped
;
527 return totalBytesSkipped
;
533 * @param storagePath: path of the image
536 @SuppressWarnings("deprecation")
537 private Bitmap
loadScaledImage(String storagePath
) {
539 Log_OC
.d(TAG
, "Loading image scaled");
541 // set desired options that will affect the size of the bitmap
542 BitmapFactory
.Options options
= new Options();
543 options
.inScaled
= true
;
544 options
.inPurgeable
= true
;
545 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
546 options
.inPreferQualityOverSpeed
= false
;
548 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
549 options
.inMutable
= false
;
551 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
552 options
.inJustDecodeBounds
= true
;
553 BitmapFactory
.decodeFile(storagePath
, options
);
555 int width
= options
.outWidth
;
556 int height
= options
.outHeight
;
559 Display display
= getActivity().getWindowManager().getDefaultDisplay();
560 Point size
= new Point();
563 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
564 display
.getSize(size
);
565 screenWidth
= size
.x
;
566 screenHeight
= size
.y
;
568 screenWidth
= display
.getWidth();
569 screenHeight
= display
.getHeight();
572 if (width
> screenWidth
) {
573 // second try to scale down the image , this time depending upon the screen size
574 scale
= (int) Math
.floor((float)width
/ screenWidth
);
576 if (height
> screenHeight
) {
577 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
579 options
.inSampleSize
= scale
;
581 // really load the bitmap
582 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
583 return BitmapFactory
.decodeFile(storagePath
, options
);