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 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 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
;
88 private LoadBitmapTask mLoadBitmapTask
= null
;
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 mLoadBitmapTask
= new LoadBitmapTask(mImageView
, mMessageView
, mProgressWheel
);
198 mLoadBitmapTask
.execute(new String
[]{getFile().getStoragePath()});
204 public void onStop() {
205 Log_OC
.d(TAG
, "onStop starts");
206 if (mLoadBitmapTask
!= null
) {
207 mLoadBitmapTask
.cancel(true
);
208 mLoadBitmapTask
= null
;
217 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
218 super.onCreateOptionsMenu(menu
, inflater
);
219 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
226 public void onPrepareOptionsMenu(Menu menu
) {
227 super.onPrepareOptionsMenu(menu
);
229 if (mContainerActivity
.getStorageManager() != null
) {
231 setFile(mContainerActivity
.getStorageManager().getFileById(getFile().getFileId()));
233 FileMenuFilter mf
= new FileMenuFilter(
235 mContainerActivity
.getStorageManager().getAccount(),
237 getSherlockActivity()
242 // additional restriction for this fragment
243 // TODO allow renaming in PreviewImageFragment
244 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
246 item
.setVisible(false
);
247 item
.setEnabled(false
);
250 // additional restriction for this fragment
251 // TODO allow refresh file in PreviewImageFragment
252 item
= menu
.findItem(R
.id
.action_sync_file
);
254 item
.setVisible(false
);
255 item
.setEnabled(false
);
258 // additional restriction for this fragment
259 item
= menu
.findItem(R
.id
.action_move
);
261 item
.setVisible(false
);
262 item
.setEnabled(false
);
273 public boolean onOptionsItemSelected(MenuItem item
) {
274 switch (item
.getItemId()) {
275 case R
.id
.action_share_file
: {
276 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
279 case R
.id
.action_unshare_file
: {
280 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
283 case R
.id
.action_open_file_with
: {
287 case R
.id
.action_remove_file
: {
288 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
289 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
292 case R
.id
.action_see_details
: {
296 case R
.id
.action_send_file
: {
297 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
300 case R
.id
.action_sync_file
: {
301 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
311 private void seeDetails() {
312 mContainerActivity
.showDetails(getFile());
317 public void onResume() {
323 public void onPause() {
328 public void onDestroy() {
329 if (mBitmap
!= null
) {
332 // putting this in onStop() is just the same; the fragment is always destroyed by the ViewPager
333 // when swipes further than the valid offset, and onStop() is never called before than that
340 * Opens the previewed image with an external application.
342 private void openFile() {
343 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
348 private class LoadBitmapTask
extends AsyncTask
<String
, Void
, Bitmap
> {
351 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
353 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
355 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
358 * Weak reference to the target {@link TextView} where error messages will be written.
360 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
362 private final WeakReference
<TextView
> mMessageViewRef
;
366 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
368 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
370 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
374 * Error message to show when a load fails
376 private int mErrorMessageId
;
382 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
384 public LoadBitmapTask(ImageViewCustom imageView
, TextView messageView
, ProgressBar progressWheel
) {
385 mImageViewRef
= new WeakReference
<ImageViewCustom
>(imageView
);
386 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
387 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
392 protected Bitmap
doInBackground(String
... params
) {
393 Bitmap result
= null
;
394 if (params
.length
!= 1) return result
;
395 String storagePath
= params
[0];
398 if (isCancelled()) return result
;
400 File picture
= new File(storagePath
);
402 if (picture
!= null
) {
403 // Decode file into a bitmap in real size for being able to make zoom on
405 result
= BitmapFactory
.decodeStream(new FlushedInputStream
406 (new BufferedInputStream(new FileInputStream(picture
))));
409 if (isCancelled()) return result
;
411 if (result
== null
) {
412 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
413 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
415 // Rotate image, obeying exif tag.
416 result
= BitmapUtils
.rotateImage(result
, storagePath
);
419 } catch (OutOfMemoryError e
) {
420 Log_OC
.w(TAG
, "Out of memory rendering file " + storagePath
+ " in full size; scaling down");
422 if (isCancelled()) return result
;
424 // If out of memory error when loading or rotating image, try to load it scaled
425 result
= loadScaledImage(storagePath
);
427 if (result
== null
) {
428 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
429 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
431 // Rotate scaled image, obeying exif tag
432 result
= BitmapUtils
.rotateImage(result
, storagePath
);
435 } catch (NoSuchFieldError e
) {
436 mErrorMessageId
= R
.string
.common_error_unknown
;
437 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file "
440 } catch (Throwable t
) {
441 mErrorMessageId
= R
.string
.common_error_unknown
;
442 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
450 protected void onCancelled(Bitmap result
) {
451 if (result
!= null
) {
457 protected void onPostExecute(Bitmap result
) {
459 if (result
!= null
) {
460 showLoadedImage(result
);
464 if (mBitmap
!= result
) {
465 // unused bitmap, release it! (just in case)
470 @SuppressLint("InlinedApi")
471 private void showLoadedImage(Bitmap result
) {
472 if (mImageViewRef
!= null
) {
473 final ImageViewCustom imageView
= mImageViewRef
.get();
474 if (imageView
!= null
) {
475 imageView
.setImageBitmap(result
);
476 imageView
.setVisibility(View
.VISIBLE
);
477 mBitmap
= result
; // needs to be kept for recycling when not useful
480 if (mMessageViewRef
!= null
) {
481 final TextView messageView
= mMessageViewRef
.get();
482 if (messageView
!= null
) {
483 messageView
.setVisibility(View
.GONE
);
484 } // else , silently finish, the fragment was destroyed
488 private void showErrorMessage() {
489 if (mImageViewRef
!= null
) {
490 final ImageView imageView
= mImageViewRef
.get();
491 if (imageView
!= null
) {
492 // shows the default error icon
493 imageView
.setVisibility(View
.VISIBLE
);
494 } // else , silently finish, the fragment was destroyed
496 if (mMessageViewRef
!= null
) {
497 final TextView messageView
= mMessageViewRef
.get();
498 if (messageView
!= null
) {
499 messageView
.setText(mErrorMessageId
);
500 messageView
.setVisibility(View
.VISIBLE
);
501 } // else , silently finish, the fragment was destroyed
505 private void hideProgressWheel() {
506 if (mProgressWheelRef
!= null
) {
507 final ProgressBar progressWheel
= mProgressWheelRef
.get();
508 if (progressWheel
!= null
) {
509 progressWheel
.setVisibility(View
.GONE
);
517 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
519 * @param file File to test if can be previewed.
520 * @return 'True' if the file can be handled by the fragment.
522 public static boolean canBePreviewed(OCFile file
) {
523 return (file
!= null
&& file
.isImage());
528 * Finishes the preview
530 private void finish() {
531 Activity container
= getActivity();
535 public TouchImageViewCustom
getImageView() {
539 static class FlushedInputStream
extends FilterInputStream
{
540 public FlushedInputStream(InputStream inputStream
) {
545 public long skip(long n
) throws IOException
{
546 long totalBytesSkipped
= 0L;
547 while (totalBytesSkipped
< n
) {
548 long bytesSkipped
= in.skip(n
- totalBytesSkipped
);
549 if (bytesSkipped
== 0L) {
550 int byteValue
= read();
552 break; // we reached EOF
554 bytesSkipped
= 1; // we read one byte
557 totalBytesSkipped
+= bytesSkipped
;
559 return totalBytesSkipped
;
565 * @param storagePath: path of the image
568 @SuppressWarnings("deprecation")
569 private Bitmap
loadScaledImage(String storagePath
) {
571 Log_OC
.d(TAG
, "Loading image scaled");
573 // set desired options that will affect the size of the bitmap
574 BitmapFactory
.Options options
= new Options();
575 options
.inScaled
= true
;
576 options
.inPurgeable
= true
;
577 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
578 options
.inPreferQualityOverSpeed
= false
;
580 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
581 options
.inMutable
= false
;
583 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
584 options
.inJustDecodeBounds
= true
;
585 BitmapFactory
.decodeFile(storagePath
, options
);
587 int width
= options
.outWidth
;
588 int height
= options
.outHeight
;
591 Display display
= getActivity().getWindowManager().getDefaultDisplay();
592 Point size
= new Point();
595 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
596 display
.getSize(size
);
597 screenWidth
= size
.x
;
598 screenHeight
= size
.y
;
600 screenWidth
= display
.getWidth();
601 screenHeight
= display
.getHeight();
604 if (width
> screenWidth
) {
605 // second try to scale down the image , this time depending upon the screen size
606 scale
= (int) Math
.floor((float)width
/ screenWidth
);
608 if (height
> screenHeight
) {
609 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
611 options
.inSampleSize
= scale
;
613 // really load the bitmap
614 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
615 return BitmapFactory
.decodeFile(storagePath
, options
);