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
.Point
;
34 import android
.os
.AsyncTask
;
35 import android
.os
.Bundle
;
36 import android
.support
.v4
.app
.FragmentStatePagerAdapter
;
37 import android
.view
.Display
;
38 import android
.view
.LayoutInflater
;
39 import android
.view
.View
;
40 import android
.view
.View
.OnClickListener
;
41 import android
.view
.ViewGroup
;
42 import android
.widget
.ImageView
;
43 import android
.widget
.ProgressBar
;
44 import android
.widget
.TextView
;
46 import com
.actionbarsherlock
.view
.Menu
;
47 import com
.actionbarsherlock
.view
.MenuInflater
;
48 import com
.actionbarsherlock
.view
.MenuItem
;
49 import com
.owncloud
.android
.R
;
50 import com
.owncloud
.android
.datamodel
.OCFile
;
51 import com
.owncloud
.android
.files
.FileMenuFilter
;
52 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
53 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
54 import com
.owncloud
.android
.ui
.dialog
.RemoveFileDialogFragment
;
55 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
56 import com
.owncloud
.android
.utils
.BitmapUtils
;
57 import com
.owncloud
.android
.utils
.TouchImageViewCustom
;
62 * This fragment shows a preview of a downloaded image.
64 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
66 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
68 * @author David A. Velasco
70 public class PreviewImageFragment
extends FileFragment
{
72 public static final String EXTRA_FILE
= "FILE";
73 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
76 private Account mAccount
;
77 private TouchImageViewCustom mImageView
;
78 private TextView mMessageView
;
79 private ProgressBar mProgressWheel
;
81 public Bitmap mBitmap
= null
;
83 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
85 private boolean mIgnoreFirstSavedState
;
87 private LoadBitmapTask mLoadBitmapTask
= null
;
91 * Creates a fragment to preview an image.
93 * When 'imageFile' or 'ocAccount' are null
95 * @param imageFile An {@link OCFile} to preview as an image in the fragment
96 * @param ocAccount An ownCloud account; needed to start downloads
97 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
99 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
101 mAccount
= ocAccount
;
102 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
107 * Creates an empty fragment for image previews.
109 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
111 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
113 public PreviewImageFragment() {
116 mIgnoreFirstSavedState
= false
;
124 public void onCreate(Bundle savedInstanceState
) {
125 super.onCreate(savedInstanceState
);
126 setHasOptionsMenu(true
);
134 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
135 Bundle savedInstanceState
) {
136 super.onCreateView(inflater
, container
, savedInstanceState
);
137 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
138 mImageView
= (TouchImageViewCustom
) mView
.findViewById(R
.id
.image
);
139 mImageView
.setVisibility(View
.GONE
);
140 mImageView
.setOnClickListener(new OnClickListener() {
142 public void onClick(View v
) {
143 ((PreviewImageActivity
) getActivity()).toggleFullScreen();
147 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
148 mMessageView
.setVisibility(View
.GONE
);
149 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
150 mProgressWheel
.setVisibility(View
.VISIBLE
);
158 public void onActivityCreated(Bundle savedInstanceState
) {
159 super.onActivityCreated(savedInstanceState
);
160 if (savedInstanceState
!= null
) {
161 if (!mIgnoreFirstSavedState
) {
162 OCFile file
= (OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
164 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
166 mIgnoreFirstSavedState
= false
;
169 if (getFile() == null
) {
170 throw new IllegalStateException("Instanced with a NULL OCFile");
172 if (mAccount
== null
) {
173 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
175 if (!getFile().isDown()) {
176 throw new IllegalStateException("There is no local file to preview");
185 public void onSaveInstanceState(Bundle outState
) {
186 super.onSaveInstanceState(outState
);
187 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
188 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
193 public void onStart() {
195 if (getFile() != null
) {
196 mLoadBitmapTask
= new LoadBitmapTask(mImageView
, mMessageView
, mProgressWheel
);
197 mLoadBitmapTask
.execute(new String
[]{getFile().getStoragePath()});
203 public void onStop() {
205 if (mLoadBitmapTask
!= null
) {
206 mLoadBitmapTask
.cancel(true
);
207 mLoadBitmapTask
= null
;
216 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
217 super.onCreateOptionsMenu(menu
, inflater
);
218 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
225 public void onPrepareOptionsMenu(Menu menu
) {
226 super.onPrepareOptionsMenu(menu
);
228 if (mContainerActivity
.getStorageManager() != null
) {
230 setFile(mContainerActivity
.getStorageManager().getFileById(getFile().getFileId()));
232 FileMenuFilter mf
= new FileMenuFilter(
234 mContainerActivity
.getStorageManager().getAccount(),
236 getSherlockActivity()
241 // additional restriction for this fragment
242 // TODO allow renaming in PreviewImageFragment
243 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
245 item
.setVisible(false
);
246 item
.setEnabled(false
);
249 // additional restriction for this fragment
250 // TODO allow refresh file in PreviewImageFragment
251 item
= menu
.findItem(R
.id
.action_sync_file
);
253 item
.setVisible(false
);
254 item
.setEnabled(false
);
257 // additional restriction for this fragment
258 item
= menu
.findItem(R
.id
.action_move
);
260 item
.setVisible(false
);
261 item
.setEnabled(false
);
272 public boolean onOptionsItemSelected(MenuItem item
) {
273 switch (item
.getItemId()) {
274 case R
.id
.action_share_file
: {
275 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
278 case R
.id
.action_unshare_file
: {
279 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
282 case R
.id
.action_open_file_with
: {
286 case R
.id
.action_remove_file
: {
287 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
288 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
291 case R
.id
.action_see_details
: {
295 case R
.id
.action_send_file
: {
296 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
299 case R
.id
.action_sync_file
: {
300 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
310 private void seeDetails() {
311 mContainerActivity
.showDetails(getFile());
316 public void onResume() {
322 public void onPause() {
327 public void onDestroy() {
328 if (mBitmap
!= null
) {
337 * Opens the previewed image with an external application.
339 private void openFile() {
340 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
345 private class LoadBitmapTask
extends AsyncTask
<String
, Void
, Bitmap
> {
348 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
350 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
352 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
355 * Weak reference to the target {@link TextView} where error messages will be written.
357 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
359 private final WeakReference
<TextView
> mMessageViewRef
;
363 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
365 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
367 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
371 * Error message to show when a load fails
373 private int mErrorMessageId
;
379 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
381 public LoadBitmapTask(ImageViewCustom imageView
, TextView messageView
, ProgressBar progressWheel
) {
382 mImageViewRef
= new WeakReference
<ImageViewCustom
>(imageView
);
383 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
384 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
389 protected Bitmap
doInBackground(String
... params
) {
390 Bitmap result
= null
;
391 if (params
.length
!= 1) return result
;
392 String storagePath
= params
[0];
395 if (isCancelled()) return result
;
397 File picture
= new File(storagePath
);
399 if (picture
!= null
) {
400 // Decode file into a bitmap in real size for being able to make zoom on
402 result
= BitmapFactory
.decodeStream(new FlushedInputStream
403 (new BufferedInputStream(new FileInputStream(picture
))));
406 if (isCancelled()) return result
;
408 if (result
== null
) {
409 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
410 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
412 // Rotate image, obeying exif tag.
413 result
= BitmapUtils
.rotateImage(result
, storagePath
);
416 } catch (OutOfMemoryError e
) {
417 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
419 if (isCancelled()) return result
;
421 // If out of memory error when loading or rotating image, try to load it scaled
422 result
= loadScaledImage(storagePath
);
424 if (result
== null
) {
425 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
426 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
428 // Rotate scaled image, obeying exif tag
429 result
= BitmapUtils
.rotateImage(result
, storagePath
);
432 } catch (NoSuchFieldError e
) {
433 mErrorMessageId
= R
.string
.common_error_unknown
;
434 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file "
437 } catch (Throwable t
) {
438 mErrorMessageId
= R
.string
.common_error_unknown
;
439 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
447 protected void onCancelled(Bitmap result
) {
448 if (result
!= null
) {
454 protected void onPostExecute(Bitmap result
) {
456 if (result
!= null
) {
457 showLoadedImage(result
);
463 @SuppressLint("InlinedApi")
464 private void showLoadedImage(Bitmap result
) {
465 if (mImageViewRef
!= null
) {
466 final ImageViewCustom imageView
= mImageViewRef
.get();
467 if (imageView
!= null
) {
468 imageView
.setBitmap(result
);
469 imageView
.setImageBitmap(result
);
470 imageView
.setVisibility(View
.VISIBLE
);
472 } // else , silently finish, the fragment was destroyed
474 if (mMessageViewRef
!= null
) {
475 final TextView messageView
= mMessageViewRef
.get();
476 if (messageView
!= null
) {
477 messageView
.setVisibility(View
.GONE
);
478 } // else , silently finish, the fragment was destroyed
482 private void showErrorMessage() {
483 if (mImageViewRef
!= null
) {
484 final ImageView imageView
= mImageViewRef
.get();
485 if (imageView
!= null
) {
486 // shows the default error icon
487 imageView
.setVisibility(View
.VISIBLE
);
488 } // else , silently finish, the fragment was destroyed
490 if (mMessageViewRef
!= null
) {
491 final TextView messageView
= mMessageViewRef
.get();
492 if (messageView
!= null
) {
493 messageView
.setText(mErrorMessageId
);
494 messageView
.setVisibility(View
.VISIBLE
);
495 } // else , silently finish, the fragment was destroyed
499 private void hideProgressWheel() {
500 if (mProgressWheelRef
!= null
) {
501 final ProgressBar progressWheel
= mProgressWheelRef
.get();
502 if (progressWheel
!= null
) {
503 progressWheel
.setVisibility(View
.GONE
);
511 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
513 * @param file File to test if can be previewed.
514 * @return 'True' if the file can be handled by the fragment.
516 public static boolean canBePreviewed(OCFile file
) {
517 return (file
!= null
&& file
.isImage());
522 * Finishes the preview
524 private void finish() {
525 Activity container
= getActivity();
529 public TouchImageViewCustom
getImageView() {
533 static class FlushedInputStream
extends FilterInputStream
{
534 public FlushedInputStream(InputStream inputStream
) {
539 public long skip(long n
) throws IOException
{
540 long totalBytesSkipped
= 0L;
541 while (totalBytesSkipped
< n
) {
542 long bytesSkipped
= in.skip(n
- totalBytesSkipped
);
543 if (bytesSkipped
== 0L) {
544 int byteValue
= read();
546 break; // we reached EOF
548 bytesSkipped
= 1; // we read one byte
551 totalBytesSkipped
+= bytesSkipped
;
553 return totalBytesSkipped
;
559 * @param storagePath: path of the image
562 @SuppressWarnings("deprecation")
563 private Bitmap
loadScaledImage(String storagePath
) {
565 Log_OC
.d(TAG
, "Loading image scaled");
567 // set desired options that will affect the size of the bitmap
568 BitmapFactory
.Options options
= new Options();
569 options
.inScaled
= true
;
570 options
.inPurgeable
= true
;
571 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
572 options
.inPreferQualityOverSpeed
= false
;
574 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
575 options
.inMutable
= false
;
577 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
578 options
.inJustDecodeBounds
= true
;
579 BitmapFactory
.decodeFile(storagePath
, options
);
581 int width
= options
.outWidth
;
582 int height
= options
.outHeight
;
585 Display display
= getActivity().getWindowManager().getDefaultDisplay();
586 Point size
= new Point();
589 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
590 display
.getSize(size
);
591 screenWidth
= size
.x
;
592 screenHeight
= size
.y
;
594 screenWidth
= display
.getWidth();
595 screenHeight
= display
.getHeight();
598 if (width
> screenWidth
) {
599 // second try to scale down the image , this time depending upon the screen size
600 scale
= (int) Math
.floor((float)width
/ screenWidth
);
602 if (height
> screenHeight
) {
603 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
605 options
.inSampleSize
= scale
;
607 // really load the bitmap
608 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
609 return BitmapFactory
.decodeFile(storagePath
, options
);