1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 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
.lang
.ref
.WeakReference
;
20 import java
.util
.ArrayList
;
21 import java
.util
.List
;
24 import android
.accounts
.Account
;
25 import android
.annotation
.SuppressLint
;
26 import android
.app
.Activity
;
27 import android
.graphics
.Bitmap
;
28 import android
.graphics
.BitmapFactory
;
29 import android
.graphics
.BitmapFactory
.Options
;
30 import android
.graphics
.Point
;
31 import android
.os
.AsyncTask
;
32 import android
.os
.Bundle
;
33 import android
.support
.v4
.app
.FragmentStatePagerAdapter
;
34 import android
.view
.Display
;
35 import android
.view
.LayoutInflater
;
36 import android
.view
.View
;
37 import android
.view
.View
.OnTouchListener
;
38 import android
.view
.ViewGroup
;
39 import android
.widget
.ImageView
;
40 import android
.widget
.ProgressBar
;
41 import android
.widget
.TextView
;
43 import com
.actionbarsherlock
.view
.Menu
;
44 import com
.actionbarsherlock
.view
.MenuInflater
;
45 import com
.actionbarsherlock
.view
.MenuItem
;
46 import com
.owncloud
.android
.R
;
47 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
48 import com
.owncloud
.android
.datamodel
.OCFile
;
49 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
50 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
;
51 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
52 import com
.owncloud
.android
.utils
.Log_OC
;
56 * This fragment shows a preview of a downloaded image.
58 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
60 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
62 * @author David A. Velasco
64 public class PreviewImageFragment
extends FileFragment
implements
65 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
66 public static final String EXTRA_FILE
= "FILE";
67 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
70 private Account mAccount
;
71 private ImageView mImageView
;
72 private TextView mMessageView
;
73 private ProgressBar mProgressWheel
;
75 public Bitmap mBitmap
= null
;
77 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
79 private boolean mIgnoreFirstSavedState
;
83 * Creates a fragment to preview an image.
85 * When 'imageFile' or 'ocAccount' are null
87 * @param imageFile An {@link OCFile} to preview as an image in the fragment
88 * @param ocAccount An ownCloud account; needed to start downloads
89 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
91 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
94 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
99 * Creates an empty fragment for image previews.
101 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
103 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
105 public PreviewImageFragment() {
108 mIgnoreFirstSavedState
= false
;
116 public void onCreate(Bundle savedInstanceState
) {
117 super.onCreate(savedInstanceState
);
118 setHasOptionsMenu(true
);
126 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
127 Bundle savedInstanceState
) {
128 super.onCreateView(inflater
, container
, savedInstanceState
);
129 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
130 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
131 mImageView
.setVisibility(View
.GONE
);
132 mView
.setOnTouchListener((OnTouchListener
)getActivity());
133 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
134 mMessageView
.setVisibility(View
.GONE
);
135 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
136 mProgressWheel
.setVisibility(View
.VISIBLE
);
145 public void onAttach(Activity activity
) {
146 super.onAttach(activity
);
147 if (!(activity
instanceof OnTouchListener
)) {
148 throw new ClassCastException(activity
.toString() +
149 " must implement " + OnTouchListener
.class.getSimpleName());
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
);
163 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
166 if (mAccount
!= null
) {
167 OCFile updatedFile
= ((FileActivity
) getSherlockActivity()).
168 getStorageManager().getFileByPath(file
.getRemotePath());
169 if (updatedFile
!= null
) {
170 setFile(updatedFile
);
178 mIgnoreFirstSavedState
= false
;
181 if (getFile() == null
) {
182 throw new IllegalStateException("Instanced with a NULL OCFile");
184 if (mAccount
== null
) {
185 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
187 if (!getFile().isDown()) {
188 throw new IllegalStateException("There is no local file to preview");
197 public void onSaveInstanceState(Bundle outState
) {
198 super.onSaveInstanceState(outState
);
199 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
200 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
205 public void onStart() {
207 if (getFile() != null
) {
208 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
209 bl
.execute(new String
[]{getFile().getStoragePath()});
218 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
219 super.onCreateOptionsMenu(menu
, inflater
);
221 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
222 List
<Integer
> toHide
= new ArrayList
<Integer
>();
224 MenuItem item
= null
;
225 toHide
.add(R
.id
.action_cancel_download
);
226 toHide
.add(R
.id
.action_cancel_upload
);
227 toHide
.add(R
.id
.action_download_file
);
228 toHide
.add(R
.id
.action_rename_file
); // by now
231 if (!getFile().isShareByLink()) {
232 toHide
.add(R
.id
.action_unshare_file
);
236 boolean sendEnabled
= getString(R
.string
.send_files_to_other_apps
).equalsIgnoreCase("on");
238 toHide
.add(R
.id
.action_send_file
);
241 for (int i
: toHide
) {
242 item
= menu
.findItem(i
);
244 item
.setVisible(false
);
245 item
.setEnabled(false
);
255 public void onPrepareOptionsMenu(Menu menu
) {
256 super.onPrepareOptionsMenu(menu
);
258 MenuItem item
= menu
.findItem(R
.id
.action_unshare_file
);
260 if (!getFile().isShareByLink()) {
261 item
.setVisible(false
);
262 item
.setEnabled(false
);
264 item
.setVisible(true
);
265 item
.setEnabled(true
);
276 public boolean onOptionsItemSelected(MenuItem item
) {
277 switch (item
.getItemId()) {
278 case R
.id
.action_share_file
: {
279 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
282 case R
.id
.action_unshare_file
: {
283 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
286 case R
.id
.action_open_file_with
: {
290 case R
.id
.action_remove_file
: {
294 case R
.id
.action_see_details
: {
298 case R
.id
.action_send_file
: {
299 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
309 private void seeDetails() {
310 mContainerActivity
.showDetails(getFile());
315 public void onResume() {
321 public void onPause() {
327 public void onDestroy() {
329 if (mBitmap
!= null
) {
336 * Opens the previewed image with an external application.
338 private void openFile() {
339 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
345 * Starts a the removal of the previewed file.
347 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
348 * depending upon the user selection in the dialog.
350 private void removeFile() {
351 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
352 R
.string
.confirmation_remove_alert
,
353 new String
[]{getFile().getFileName()},
354 R
.string
.confirmation_remove_remote_and_local
,
355 R
.string
.confirmation_remove_local
,
356 R
.string
.common_cancel
);
357 confDialog
.setOnConfirmationListener(this);
358 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
363 * Performs the removal of the previewed file, both locally and in the server.
366 public void onConfirmation(String callerTag
) {
367 FileDataStorageManager storageManager
= mContainerActivity
.getStorageManager();
368 if (storageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
369 mContainerActivity
.getFileOperationsHelper().removeFile(getFile(), true
);
375 * Removes the file from local storage
378 public void onNeutral(String callerTag
) {
379 OCFile file
= getFile();
380 mContainerActivity
.getStorageManager().removeFile(file
, false
, true
); // TODO perform in background task / new thread
385 * User cancelled the removal action.
388 public void onCancel(String callerTag
) {
389 // nothing to do here
393 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
396 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
398 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
400 private final WeakReference
<ImageView
> mImageViewRef
;
403 * Weak reference to the target {@link TextView} where error messages will be written.
405 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
407 private final WeakReference
<TextView
> mMessageViewRef
;
411 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
413 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
415 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
419 * Error message to show when a load fails
421 private int mErrorMessageId
;
427 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
429 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
430 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
431 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
432 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
436 @SuppressWarnings("deprecation")
437 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
439 protected Bitmap
doInBackground(String
... params
) {
440 Bitmap result
= null
;
441 if (params
.length
!= 1) return result
;
442 String storagePath
= params
[0];
444 // set desired options that will affect the size of the bitmap
445 BitmapFactory
.Options options
= new Options();
446 options
.inScaled
= true
;
447 options
.inPurgeable
= true
;
448 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
449 options
.inPreferQualityOverSpeed
= false
;
451 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
452 options
.inMutable
= false
;
454 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
455 options
.inJustDecodeBounds
= true
;
456 BitmapFactory
.decodeFile(storagePath
, options
);
458 int width
= options
.outWidth
;
459 int height
= options
.outHeight
;
462 Display display
= getActivity().getWindowManager().getDefaultDisplay();
463 Point size
= new Point();
466 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
467 display
.getSize(size
);
468 screenWidth
= size
.x
;
469 screenHeight
= size
.y
;
471 screenWidth
= display
.getWidth();
472 screenHeight
= display
.getHeight();
475 if (width
> screenWidth
) {
476 // second try to scale down the image , this time depending upon the screen size
477 scale
= (int) Math
.floor((float)width
/ screenWidth
);
479 if (height
> screenHeight
) {
480 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
482 options
.inSampleSize
= scale
;
484 // really load the bitmap
485 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
486 result
= BitmapFactory
.decodeFile(storagePath
, options
);
487 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
489 if (result
== null
) {
490 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
491 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
494 } catch (OutOfMemoryError e
) {
495 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
496 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
498 } catch (NoSuchFieldError e
) {
499 mErrorMessageId
= R
.string
.common_error_unknown
;
500 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
502 } catch (Throwable t
) {
503 mErrorMessageId
= R
.string
.common_error_unknown
;
504 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
511 protected void onPostExecute(Bitmap result
) {
513 if (result
!= null
) {
514 showLoadedImage(result
);
520 private void showLoadedImage(Bitmap result
) {
521 if (mImageViewRef
!= null
) {
522 final ImageView imageView
= mImageViewRef
.get();
523 if (imageView
!= null
) {
524 imageView
.setImageBitmap(result
);
525 imageView
.setVisibility(View
.VISIBLE
);
527 } // else , silently finish, the fragment was destroyed
529 if (mMessageViewRef
!= null
) {
530 final TextView messageView
= mMessageViewRef
.get();
531 if (messageView
!= null
) {
532 messageView
.setVisibility(View
.GONE
);
533 } // else , silently finish, the fragment was destroyed
537 private void showErrorMessage() {
538 if (mImageViewRef
!= null
) {
539 final ImageView imageView
= mImageViewRef
.get();
540 if (imageView
!= null
) {
541 // shows the default error icon
542 imageView
.setVisibility(View
.VISIBLE
);
543 } // else , silently finish, the fragment was destroyed
545 if (mMessageViewRef
!= null
) {
546 final TextView messageView
= mMessageViewRef
.get();
547 if (messageView
!= null
) {
548 messageView
.setText(mErrorMessageId
);
549 messageView
.setVisibility(View
.VISIBLE
);
550 } // else , silently finish, the fragment was destroyed
554 private void hideProgressWheel() {
555 if (mProgressWheelRef
!= null
) {
556 final ProgressBar progressWheel
= mProgressWheelRef
.get();
557 if (progressWheel
!= null
) {
558 progressWheel
.setVisibility(View
.GONE
);
566 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
568 * @param file File to test if can be previewed.
569 * @return 'True' if the file can be handled by the fragment.
571 public static boolean canBePreviewed(OCFile file
) {
572 return (file
!= null
&& file
.isImage());
577 * Finishes the preview
579 private void finish() {
580 Activity container
= getActivity();