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
.Menu
;
43 import android
.view
.MenuInflater
;
44 import android
.view
.MenuItem
;
45 import android
.view
.View
;
46 import android
.view
.View
.OnClickListener
;
47 import android
.view
.ViewGroup
;
48 import android
.widget
.ImageView
;
49 import android
.widget
.ProgressBar
;
50 import android
.widget
.TextView
;
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 NULL {@link OCFile} or ownCloud {@link Account} values will
68 * produce an {@link IllegalStateException}.
70 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on
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
;
90 private LoadBitmapTask mLoadBitmapTask
= null
;
94 * Creates a fragment to preview an image.
96 * When 'imageFile' or 'ocAccount' are null
98 * @param fileToDetail An {@link OCFile} to preview as an image in the fragment
99 * @param ocAccount An ownCloud account; needed to start downloads
100 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of
101 * {@link FragmentStatePagerAdapter}; TODO better solution
103 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
,
104 boolean ignoreFirstSavedState
) {
106 mAccount
= ocAccount
;
107 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
112 * Creates an empty fragment for image previews.
114 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
115 * (for instance, when the device is turned a aside).
117 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
120 public PreviewImageFragment() {
123 mIgnoreFirstSavedState
= false
;
131 public void onCreate(Bundle savedInstanceState
) {
132 super.onCreate(savedInstanceState
);
133 setHasOptionsMenu(true
);
141 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
142 Bundle savedInstanceState
) {
143 super.onCreateView(inflater
, container
, savedInstanceState
);
144 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
145 mImageView
= (TouchImageViewCustom
) mView
.findViewById(R
.id
.image
);
146 mImageView
.setVisibility(View
.GONE
);
147 mImageView
.setOnClickListener(new OnClickListener() {
149 public void onClick(View v
) {
150 ((PreviewImageActivity
) getActivity()).toggleFullScreen();
154 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
155 mMessageView
.setVisibility(View
.GONE
);
156 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
157 mProgressWheel
.setVisibility(View
.VISIBLE
);
165 public void onActivityCreated(Bundle savedInstanceState
) {
166 super.onActivityCreated(savedInstanceState
);
167 if (savedInstanceState
!= null
) {
168 if (!mIgnoreFirstSavedState
) {
169 OCFile file
= (OCFile
)savedInstanceState
.getParcelable(
170 PreviewImageFragment
.EXTRA_FILE
);
172 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
174 mIgnoreFirstSavedState
= false
;
177 if (getFile() == null
) {
178 throw new IllegalStateException("Instanced with a NULL OCFile");
180 if (mAccount
== null
) {
181 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
183 if (!getFile().isDown()) {
184 throw new IllegalStateException("There is no local file to preview");
193 public void onSaveInstanceState(Bundle outState
) {
194 super.onSaveInstanceState(outState
);
195 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
196 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
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() {
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(),
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
) {
345 * Opens the previewed image with an external application.
347 private void openFile() {
348 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
353 private class LoadBitmapTask
extends AsyncTask
<String
, Void
, Bitmap
> {
356 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
358 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
359 * memory before the load finishes.
361 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
364 * Weak reference to the target {@link TextView} where error messages will be written.
366 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
367 * memory before the load finishes.
369 private final WeakReference
<TextView
> mMessageViewRef
;
373 * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
375 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
376 * memory before the load finishes.
378 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
382 * Error message to show when a load fails
384 private int mErrorMessageId
;
390 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
392 public LoadBitmapTask(ImageViewCustom imageView
, TextView messageView
,
393 ProgressBar progressWheel
) {
394 mImageViewRef
= new WeakReference
<ImageViewCustom
>(imageView
);
395 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
396 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
401 protected Bitmap
doInBackground(String
... params
) {
402 Bitmap result
= null
;
403 if (params
.length
!= 1) return result
;
404 String storagePath
= params
[0];
407 if (isCancelled()) return result
;
409 File picture
= new File(storagePath
);
411 if (picture
!= null
) {
412 // Decode file into a bitmap in real size for being able to make zoom on
414 result
= BitmapFactory
.decodeStream(new FlushedInputStream
415 (new BufferedInputStream(new FileInputStream(picture
))));
418 if (isCancelled()) return result
;
420 if (result
== null
) {
421 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
422 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
424 // Rotate image, obeying exif tag.
425 result
= BitmapUtils
.rotateImage(result
, storagePath
);
428 } catch (OutOfMemoryError e
) {
429 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
431 if (isCancelled()) return result
;
433 // If out of memory error when loading or rotating image, try to load it scaled
434 result
= loadScaledImage(storagePath
);
436 if (result
== null
) {
437 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
438 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
440 // Rotate scaled image, obeying exif tag
441 result
= BitmapUtils
.rotateImage(result
, storagePath
);
444 } catch (NoSuchFieldError e
) {
445 mErrorMessageId
= R
.string
.common_error_unknown
;
446 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file "
449 } catch (Throwable t
) {
450 mErrorMessageId
= R
.string
.common_error_unknown
;
451 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
459 protected void onCancelled(Bitmap result
) {
460 if (result
!= null
) {
466 protected void onPostExecute(Bitmap result
) {
468 if (result
!= null
) {
469 showLoadedImage(result
);
475 @SuppressLint("InlinedApi")
476 private void showLoadedImage(Bitmap result
) {
477 if (mImageViewRef
!= null
) {
478 final ImageViewCustom imageView
= mImageViewRef
.get();
479 if (imageView
!= null
) {
480 imageView
.setBitmap(result
);
481 imageView
.setImageBitmap(result
);
482 imageView
.setVisibility(View
.VISIBLE
);
484 } // else , silently finish, the fragment was destroyed
486 if (mMessageViewRef
!= null
) {
487 final TextView messageView
= mMessageViewRef
.get();
488 if (messageView
!= null
) {
489 messageView
.setVisibility(View
.GONE
);
490 } // else , silently finish, the fragment was destroyed
494 private void showErrorMessage() {
495 if (mImageViewRef
!= null
) {
496 final ImageView imageView
= mImageViewRef
.get();
497 if (imageView
!= null
) {
498 // shows the default error icon
499 imageView
.setVisibility(View
.VISIBLE
);
500 } // else , silently finish, the fragment was destroyed
502 if (mMessageViewRef
!= null
) {
503 final TextView messageView
= mMessageViewRef
.get();
504 if (messageView
!= null
) {
505 messageView
.setText(mErrorMessageId
);
506 messageView
.setVisibility(View
.VISIBLE
);
507 } // else , silently finish, the fragment was destroyed
511 private void hideProgressWheel() {
512 if (mProgressWheelRef
!= null
) {
513 final ProgressBar progressWheel
= mProgressWheelRef
.get();
514 if (progressWheel
!= null
) {
515 progressWheel
.setVisibility(View
.GONE
);
523 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment}
526 * @param file File to test if can be previewed.
527 * @return 'True' if the file can be handled by the fragment.
529 public static boolean canBePreviewed(OCFile file
) {
530 return (file
!= null
&& file
.isImage());
535 * Finishes the preview
537 private void finish() {
538 Activity container
= getActivity();
542 public TouchImageViewCustom
getImageView() {
546 static class FlushedInputStream
extends FilterInputStream
{
547 public FlushedInputStream(InputStream inputStream
) {
552 public long skip(long n
) throws IOException
{
553 long totalBytesSkipped
= 0L;
554 while (totalBytesSkipped
< n
) {
555 long bytesSkipped
= in.skip(n
- totalBytesSkipped
);
556 if (bytesSkipped
== 0L) {
557 int byteValue
= read();
559 break; // we reached EOF
561 bytesSkipped
= 1; // we read one byte
564 totalBytesSkipped
+= bytesSkipped
;
566 return totalBytesSkipped
;
572 * @param storagePath: path of the image
575 @SuppressWarnings("deprecation")
576 private Bitmap
loadScaledImage(String storagePath
) {
578 Log_OC
.d(TAG
, "Loading image scaled");
580 // set desired options that will affect the size of the bitmap
581 BitmapFactory
.Options options
= new Options();
582 options
.inScaled
= true
;
583 options
.inPurgeable
= true
;
584 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
585 options
.inPreferQualityOverSpeed
= false
;
587 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
588 options
.inMutable
= false
;
590 // make a false load of the bitmap - just to be able to read outWidth, outHeight and
592 options
.inJustDecodeBounds
= true
;
593 BitmapFactory
.decodeFile(storagePath
, options
);
595 int width
= options
.outWidth
;
596 int height
= options
.outHeight
;
599 Display display
= getActivity().getWindowManager().getDefaultDisplay();
600 Point size
= new Point();
603 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
604 display
.getSize(size
);
605 screenWidth
= size
.x
;
606 screenHeight
= size
.y
;
608 screenWidth
= display
.getWidth();
609 screenHeight
= display
.getHeight();
612 if (width
> screenWidth
) {
613 // second try to scale down the image , this time depending upon the screen size
614 scale
= (int) Math
.floor((float)width
/ screenWidth
);
616 if (height
> screenHeight
) {
617 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
619 options
.inSampleSize
= scale
;
621 // really load the bitmap
622 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
623 return BitmapFactory
.decodeFile(storagePath
, options
);