2 * ownCloud Android client application
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
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.
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.
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/>.
20 package com
.owncloud
.android
.ui
.preview
;
22 import java
.io
.BufferedInputStream
;
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
;
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
;
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
;
61 import third_parties
.michaelOrtiz
.TouchImageViewCustom
;
65 * This fragment shows a preview of a downloaded image.
67 * Trying to get an instance with a NULL {@link OCFile} will produce an {@link IllegalStateException}.
69 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
71 public class PreviewImageFragment
extends FileFragment
{
73 public static final String EXTRA_FILE
= "FILE";
75 private static final String ARG_FILE
= "FILE";
76 private static final String ARG_IGNORE_FIRST
= "IGNORE_FIRST";
79 private TouchImageViewCustom mImageView
;
80 private TextView mMessageView
;
81 private ProgressBar mProgressWheel
;
83 public Bitmap mBitmap
= null
;
85 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
87 private boolean mIgnoreFirstSavedState
;
89 private LoadBitmapTask mLoadBitmapTask
= null
;
93 * Public factory method to create a new fragment that previews an image.
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.
98 * This method hides to client objects the need of doing the construction in two steps.
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
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
);
116 * Creates an empty fragment for image previews.
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).
121 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
123 public PreviewImageFragment() {
124 mIgnoreFirstSavedState
= false
;
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
138 mIgnoreFirstSavedState
= args
.getBoolean(ARG_IGNORE_FIRST
);
139 setHasOptionsMenu(true
);
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() {
155 public void onClick(View v
) {
156 ((PreviewImageActivity
) getActivity()).toggleFullScreen();
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
);
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
);
178 mIgnoreFirstSavedState
= false
;
181 if (getFile() == null
) {
182 throw new IllegalStateException("Instanced with a NULL OCFile");
184 if (!getFile().isDown()) {
185 throw new IllegalStateException("There is no local file to preview");
194 public void onSaveInstanceState(Bundle outState
) {
195 super.onSaveInstanceState(outState
);
196 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
201 public void onStart() {
203 if (getFile() != null
) {
204 mLoadBitmapTask
= new LoadBitmapTask(mImageView
, mMessageView
, mProgressWheel
);
205 mLoadBitmapTask
.execute(new String
[]{getFile().getStoragePath()});
211 public void onStop() {
212 Log_OC
.d(TAG
, "onStop starts");
213 if (mLoadBitmapTask
!= null
) {
214 mLoadBitmapTask
.cancel(true
);
215 mLoadBitmapTask
= null
;
224 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
225 super.onCreateOptionsMenu(menu
, inflater
);
226 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
233 public void onPrepareOptionsMenu(Menu menu
) {
234 super.onPrepareOptionsMenu(menu
);
236 if (mContainerActivity
.getStorageManager() != null
) {
238 setFile(mContainerActivity
.getStorageManager().getFileById(getFile().getFileId()));
240 FileMenuFilter mf
= new FileMenuFilter(
242 mContainerActivity
.getStorageManager().getAccount(),
244 getSherlockActivity()
249 // additional restriction for this fragment
250 // TODO allow renaming in PreviewImageFragment
251 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
253 item
.setVisible(false
);
254 item
.setEnabled(false
);
257 // additional restriction for this fragment
258 // TODO allow refresh file in PreviewImageFragment
259 item
= menu
.findItem(R
.id
.action_sync_file
);
261 item
.setVisible(false
);
262 item
.setEnabled(false
);
265 // additional restriction for this fragment
266 item
= menu
.findItem(R
.id
.action_move
);
268 item
.setVisible(false
);
269 item
.setEnabled(false
);
280 public boolean onOptionsItemSelected(MenuItem item
) {
281 switch (item
.getItemId()) {
282 case R
.id
.action_share_file
: {
283 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
286 case R
.id
.action_unshare_file
: {
287 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
290 case R
.id
.action_open_file_with
: {
294 case R
.id
.action_remove_file
: {
295 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
296 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
299 case R
.id
.action_see_details
: {
303 case R
.id
.action_send_file
: {
304 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
307 case R
.id
.action_sync_file
: {
308 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
318 private void seeDetails() {
319 mContainerActivity
.showDetails(getFile());
324 public void onResume() {
330 public void onPause() {
335 public void onDestroy() {
336 if (mBitmap
!= null
) {
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
348 * Opens the previewed image with an external application.
350 private void openFile() {
351 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
356 private class LoadBitmapTask
extends AsyncTask
<String
, Void
, Bitmap
> {
359 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
361 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before
364 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
367 * Weak reference to the target {@link TextView} where error messages will be written.
369 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the
372 private final WeakReference
<TextView
> mMessageViewRef
;
376 * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
378 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
380 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
384 * Error message to show when a load fails
386 private int mErrorMessageId
;
392 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
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
);
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
;
409 if (isCancelled()) return result
;
411 File picture
= new File(storagePath
);
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
);
419 if (isCancelled()) return result
;
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
);
425 // Rotate image, obeying exif tag.
426 result
= BitmapUtils
.rotateImage(result
, storagePath
);
429 } catch (OutOfMemoryError e
) {
430 Log_OC
.w(TAG
, "Out of memory rendering file " + storagePath
+ " in full size; scaling down");
432 if (isCancelled()) return result
;
434 // If out of memory error when loading or rotating image, try to load it scaled
435 result
= loadScaledImage(storagePath
);
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
);
441 // Rotate scaled image, obeying exif tag
442 result
= BitmapUtils
.rotateImage(result
, storagePath
);
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 "
450 } catch (Throwable t
) {
451 mErrorMessageId
= R
.string
.common_error_unknown
;
452 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
458 } catch (IOException e
) {
459 Log_OC
.e(TAG
, "Unexpected exception closing stream; trying to continue ", e
);
468 protected void onCancelled(Bitmap result
) {
469 if (result
!= null
) {
475 protected void onPostExecute(Bitmap result
) {
477 if (result
!= null
) {
478 showLoadedImage(result
);
482 if (mBitmap
!= null
&& mBitmap
!= result
) {
483 // unused bitmap, release it! (just in case)
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
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
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
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
523 private void hideProgressWheel() {
524 if (mProgressWheelRef
!= null
) {
525 final ProgressBar progressWheel
= mProgressWheelRef
.get();
526 if (progressWheel
!= null
) {
527 progressWheel
.setVisibility(View
.GONE
);
535 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
537 * @param file File to test if can be previewed.
538 * @return 'True' if the file can be handled by the fragment.
540 public static boolean canBePreviewed(OCFile file
) {
541 return (file
!= null
&& file
.isImage());
546 * Finishes the preview
548 private void finish() {
549 Activity container
= getActivity();
553 public TouchImageViewCustom
getImageView() {
557 static class FlushedInputStream
extends FilterInputStream
{
558 public FlushedInputStream(InputStream inputStream
) {
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();
570 break; // we reached EOF
572 bytesSkipped
= 1; // we read one byte
575 totalBytesSkipped
+= bytesSkipped
;
577 return totalBytesSkipped
;
583 * @param storagePath: path of the image
586 @SuppressWarnings("deprecation")
587 private Bitmap
loadScaledImage(String storagePath
) {
589 Log_OC
.d(TAG
, "Loading image scaled");
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
;
598 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
599 options
.inMutable
= false
;
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
);
605 int width
= options
.outWidth
;
606 int height
= options
.outHeight
;
609 Display display
= getActivity().getWindowManager().getDefaultDisplay();
610 Point size
= new Point();
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
;
618 screenWidth
= display
.getWidth();
619 screenHeight
= display
.getHeight();
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
);
626 if (height
> screenHeight
) {
627 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
629 options
.inSampleSize
= scale
;
631 // really load the bitmap
632 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
633 return BitmapFactory
.decodeFile(storagePath
, options
);