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(),
235 getSherlockActivity()
240 // additional restriction for this fragment
241 // TODO allow renaming in PreviewImageFragment
242 MenuItem item
= menu
.findItem(R
.id
.action_rename_file
);
244 item
.setVisible(false
);
245 item
.setEnabled(false
);
248 // additional restriction for this fragment
249 // TODO allow refresh file in PreviewImageFragment
250 item
= menu
.findItem(R
.id
.action_sync_file
);
252 item
.setVisible(false
);
253 item
.setEnabled(false
);
256 // additional restriction for this fragment
257 item
= menu
.findItem(R
.id
.action_move
);
259 item
.setVisible(false
);
260 item
.setEnabled(false
);
271 public boolean onOptionsItemSelected(MenuItem item
) {
272 switch (item
.getItemId()) {
273 case R
.id
.action_share_file
: {
274 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
277 case R
.id
.action_unshare_file
: {
278 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
281 case R
.id
.action_open_file_with
: {
285 case R
.id
.action_remove_file
: {
286 RemoveFileDialogFragment dialog
= RemoveFileDialogFragment
.newInstance(getFile());
287 dialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
290 case R
.id
.action_see_details
: {
294 case R
.id
.action_send_file
: {
295 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
298 case R
.id
.action_sync_file
: {
299 mContainerActivity
.getFileOperationsHelper().syncFile(getFile());
309 private void seeDetails() {
310 mContainerActivity
.showDetails(getFile());
315 public void onResume() {
321 public void onPause() {
326 public void onDestroy() {
327 if (mBitmap
!= null
) {
336 * Opens the previewed image with an external application.
338 private void openFile() {
339 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
344 private class LoadBitmapTask
extends AsyncTask
<String
, Void
, Bitmap
> {
347 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
349 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
351 private final WeakReference
<ImageViewCustom
> mImageViewRef
;
354 * Weak reference to the target {@link TextView} where error messages will be written.
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
<TextView
> mMessageViewRef
;
362 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
364 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
366 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
370 * Error message to show when a load fails
372 private int mErrorMessageId
;
378 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
380 public LoadBitmapTask(ImageViewCustom imageView
, TextView messageView
, ProgressBar progressWheel
) {
381 mImageViewRef
= new WeakReference
<ImageViewCustom
>(imageView
);
382 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
383 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
388 protected Bitmap
doInBackground(String
... params
) {
389 Bitmap result
= null
;
390 if (params
.length
!= 1) return result
;
391 String storagePath
= params
[0];
394 if (isCancelled()) return result
;
396 File picture
= new File(storagePath
);
398 if (picture
!= null
) {
399 // Decode file into a bitmap in real size for being able to make zoom on
401 result
= BitmapFactory
.decodeStream(new FlushedInputStream
402 (new BufferedInputStream(new FileInputStream(picture
))));
405 if (isCancelled()) return result
;
407 if (result
== null
) {
408 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
409 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
411 // Rotate image, obeying exif tag.
412 result
= BitmapUtils
.rotateImage(result
, storagePath
);
415 } catch (OutOfMemoryError e
) {
416 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
418 if (isCancelled()) return result
;
420 // If out of memory error when loading or rotating image, try to load it scaled
421 result
= loadScaledImage(storagePath
);
423 if (result
== null
) {
424 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
425 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
427 // Rotate scaled image, obeying exif tag
428 result
= BitmapUtils
.rotateImage(result
, storagePath
);
431 } catch (NoSuchFieldError e
) {
432 mErrorMessageId
= R
.string
.common_error_unknown
;
433 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file "
436 } catch (Throwable t
) {
437 mErrorMessageId
= R
.string
.common_error_unknown
;
438 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
446 protected void onCancelled(Bitmap result
) {
447 if (result
!= null
) {
453 protected void onPostExecute(Bitmap result
) {
455 if (result
!= null
) {
456 showLoadedImage(result
);
462 @SuppressLint("InlinedApi")
463 private void showLoadedImage(Bitmap result
) {
464 if (mImageViewRef
!= null
) {
465 final ImageViewCustom imageView
= mImageViewRef
.get();
466 if (imageView
!= null
) {
467 imageView
.setBitmap(result
);
468 imageView
.setImageBitmap(result
);
469 imageView
.setVisibility(View
.VISIBLE
);
471 } // else , silently finish, the fragment was destroyed
473 if (mMessageViewRef
!= null
) {
474 final TextView messageView
= mMessageViewRef
.get();
475 if (messageView
!= null
) {
476 messageView
.setVisibility(View
.GONE
);
477 } // else , silently finish, the fragment was destroyed
481 private void showErrorMessage() {
482 if (mImageViewRef
!= null
) {
483 final ImageView imageView
= mImageViewRef
.get();
484 if (imageView
!= null
) {
485 // shows the default error icon
486 imageView
.setVisibility(View
.VISIBLE
);
487 } // else , silently finish, the fragment was destroyed
489 if (mMessageViewRef
!= null
) {
490 final TextView messageView
= mMessageViewRef
.get();
491 if (messageView
!= null
) {
492 messageView
.setText(mErrorMessageId
);
493 messageView
.setVisibility(View
.VISIBLE
);
494 } // else , silently finish, the fragment was destroyed
498 private void hideProgressWheel() {
499 if (mProgressWheelRef
!= null
) {
500 final ProgressBar progressWheel
= mProgressWheelRef
.get();
501 if (progressWheel
!= null
) {
502 progressWheel
.setVisibility(View
.GONE
);
510 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
512 * @param file File to test if can be previewed.
513 * @return 'True' if the file can be handled by the fragment.
515 public static boolean canBePreviewed(OCFile file
) {
516 return (file
!= null
&& file
.isImage());
521 * Finishes the preview
523 private void finish() {
524 Activity container
= getActivity();
528 public TouchImageViewCustom
getImageView() {
532 static class FlushedInputStream
extends FilterInputStream
{
533 public FlushedInputStream(InputStream inputStream
) {
538 public long skip(long n
) throws IOException
{
539 long totalBytesSkipped
= 0L;
540 while (totalBytesSkipped
< n
) {
541 long bytesSkipped
= in.skip(n
- totalBytesSkipped
);
542 if (bytesSkipped
== 0L) {
543 int byteValue
= read();
545 break; // we reached EOF
547 bytesSkipped
= 1; // we read one byte
550 totalBytesSkipped
+= bytesSkipped
;
552 return totalBytesSkipped
;
558 * @param storagePath: path of the image
561 @SuppressWarnings("deprecation")
562 private Bitmap
loadScaledImage(String storagePath
) {
564 Log_OC
.d(TAG
, "Loading image scaled");
566 // set desired options that will affect the size of the bitmap
567 BitmapFactory
.Options options
= new Options();
568 options
.inScaled
= true
;
569 options
.inPurgeable
= true
;
570 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
571 options
.inPreferQualityOverSpeed
= false
;
573 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
574 options
.inMutable
= false
;
576 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
577 options
.inJustDecodeBounds
= true
;
578 BitmapFactory
.decodeFile(storagePath
, options
);
580 int width
= options
.outWidth
;
581 int height
= options
.outHeight
;
584 Display display
= getActivity().getWindowManager().getDefaultDisplay();
585 Point size
= new Point();
588 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
589 display
.getSize(size
);
590 screenWidth
= size
.x
;
591 screenHeight
= size
.y
;
593 screenWidth
= display
.getWidth();
594 screenHeight
= display
.getHeight();
597 if (width
> screenWidth
) {
598 // second try to scale down the image , this time depending upon the screen size
599 scale
= (int) Math
.floor((float)width
/ screenWidth
);
601 if (height
> screenHeight
) {
602 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
604 options
.inSampleSize
= scale
;
606 // really load the bitmap
607 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
608 return BitmapFactory
.decodeFile(storagePath
, options
);