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
;
81 private FileFragment
.ContainerActivity mContainerActivity
;
85 * Creates a fragment to preview an image.
87 * When 'imageFile' or 'ocAccount' are null
89 * @param imageFile An {@link OCFile} to preview as an image in the fragment
90 * @param ocAccount An ownCloud account; needed to start downloads
91 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
93 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
96 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
101 * Creates an empty fragment for image previews.
103 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
105 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
107 public PreviewImageFragment() {
110 mIgnoreFirstSavedState
= false
;
118 public void onCreate(Bundle savedInstanceState
) {
119 super.onCreate(savedInstanceState
);
120 setHasOptionsMenu(true
);
128 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
129 Bundle savedInstanceState
) {
130 super.onCreateView(inflater
, container
, savedInstanceState
);
131 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
132 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
133 mImageView
.setVisibility(View
.GONE
);
134 mView
.setOnTouchListener((OnTouchListener
)getActivity());
135 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
136 mMessageView
.setVisibility(View
.GONE
);
137 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
138 mProgressWheel
.setVisibility(View
.VISIBLE
);
147 public void onAttach(Activity activity
) {
148 super.onAttach(activity
);
149 if (!(activity
instanceof OnTouchListener
)) {
150 throw new ClassCastException(activity
.toString() +
151 " must implement " + OnTouchListener
.class.getSimpleName());
160 public void onActivityCreated(Bundle savedInstanceState
) {
161 super.onActivityCreated(savedInstanceState
);
162 if (savedInstanceState
!= null
) {
163 if (!mIgnoreFirstSavedState
) {
164 OCFile file
= (OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
165 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
168 if (mAccount
!= null
) {
169 OCFile updatedFile
= ((FileActivity
) getSherlockActivity()).
170 getStorageManager().getFileByPath(file
.getRemotePath());
171 if (updatedFile
!= null
) {
172 setFile(updatedFile
);
180 mIgnoreFirstSavedState
= false
;
183 if (getFile() == null
) {
184 throw new IllegalStateException("Instanced with a NULL OCFile");
186 if (mAccount
== null
) {
187 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
189 if (!getFile().isDown()) {
190 throw new IllegalStateException("There is no local file to preview");
199 public void onSaveInstanceState(Bundle outState
) {
200 super.onSaveInstanceState(outState
);
201 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
202 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
207 public void onStart() {
209 if (getFile() != null
) {
210 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
211 bl
.execute(new String
[]{getFile().getStoragePath()});
220 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
221 super.onCreateOptionsMenu(menu
, inflater
);
223 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
224 List
<Integer
> toHide
= new ArrayList
<Integer
>();
226 MenuItem item
= null
;
227 toHide
.add(R
.id
.action_cancel_download
);
228 toHide
.add(R
.id
.action_cancel_upload
);
229 toHide
.add(R
.id
.action_download_file
);
230 toHide
.add(R
.id
.action_rename_file
); // by now
233 if (!getFile().isShareByLink()) {
234 toHide
.add(R
.id
.action_unshare_file
);
238 boolean sendEnabled
= getString(R
.string
.send_files_to_other_apps
).equalsIgnoreCase("on");
240 toHide
.add(R
.id
.action_send_file
);
243 for (int i
: toHide
) {
244 item
= menu
.findItem(i
);
246 item
.setVisible(false
);
247 item
.setEnabled(false
);
257 public void onPrepareOptionsMenu(Menu menu
) {
258 super.onPrepareOptionsMenu(menu
);
260 MenuItem item
= menu
.findItem(R
.id
.action_unshare_file
);
262 if (!getFile().isShareByLink()) {
263 item
.setVisible(false
);
264 item
.setEnabled(false
);
266 item
.setVisible(true
);
267 item
.setEnabled(true
);
278 public boolean onOptionsItemSelected(MenuItem item
) {
279 switch (item
.getItemId()) {
280 case R
.id
.action_share_file
: {
281 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile());
284 case R
.id
.action_unshare_file
: {
285 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile());
288 case R
.id
.action_open_file_with
: {
292 case R
.id
.action_remove_file
: {
296 case R
.id
.action_see_details
: {
300 case R
.id
.action_send_file
: {
301 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile());
311 private void seeDetails() {
312 mContainerActivity
.showDetails(getFile());
317 public void onResume() {
323 public void onPause() {
329 public void onDestroy() {
331 if (mBitmap
!= null
) {
338 * Opens the previewed image with an external application.
340 private void openFile() {
341 mContainerActivity
.getFileOperationsHelper().openFile(getFile());
347 * Starts a the removal of the previewed file.
349 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
350 * depending upon the user selection in the dialog.
352 private void removeFile() {
353 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
354 R
.string
.confirmation_remove_alert
,
355 new String
[]{getFile().getFileName()},
356 R
.string
.confirmation_remove_remote_and_local
,
357 R
.string
.confirmation_remove_local
,
358 R
.string
.common_cancel
);
359 confDialog
.setOnConfirmationListener(this);
360 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
365 * Performs the removal of the previewed file, both locally and in the server.
368 public void onConfirmation(String callerTag
) {
369 FileDataStorageManager storageManager
= mContainerActivity
.getStorageManager();
370 if (storageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
371 mContainerActivity
.getFileOperationsHelper().removeFile(getFile(), true
);
377 * Removes the file from local storage
380 public void onNeutral(String callerTag
) {
381 OCFile file
= getFile();
382 mContainerActivity
.getStorageManager().removeFile(file
, false
, true
); // TODO perform in background task / new thread
387 * User cancelled the removal action.
390 public void onCancel(String callerTag
) {
391 // nothing to do here
395 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
398 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
400 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
402 private final WeakReference
<ImageView
> mImageViewRef
;
405 * Weak reference to the target {@link TextView} where error messages will be written.
407 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
409 private final WeakReference
<TextView
> mMessageViewRef
;
413 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
415 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
417 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
421 * Error message to show when a load fails
423 private int mErrorMessageId
;
429 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
431 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
432 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
433 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
434 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
438 @SuppressWarnings("deprecation")
439 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
441 protected Bitmap
doInBackground(String
... params
) {
442 Bitmap result
= null
;
443 if (params
.length
!= 1) return result
;
444 String storagePath
= params
[0];
446 // set desired options that will affect the size of the bitmap
447 BitmapFactory
.Options options
= new Options();
448 options
.inScaled
= true
;
449 options
.inPurgeable
= true
;
450 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
451 options
.inPreferQualityOverSpeed
= false
;
453 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
454 options
.inMutable
= false
;
456 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
457 options
.inJustDecodeBounds
= true
;
458 BitmapFactory
.decodeFile(storagePath
, options
);
460 int width
= options
.outWidth
;
461 int height
= options
.outHeight
;
464 Display display
= getActivity().getWindowManager().getDefaultDisplay();
465 Point size
= new Point();
468 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
469 display
.getSize(size
);
470 screenWidth
= size
.x
;
471 screenHeight
= size
.y
;
473 screenWidth
= display
.getWidth();
474 screenHeight
= display
.getHeight();
477 if (width
> screenWidth
) {
478 // second try to scale down the image , this time depending upon the screen size
479 scale
= (int) Math
.floor((float)width
/ screenWidth
);
481 if (height
> screenHeight
) {
482 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
484 options
.inSampleSize
= scale
;
486 // really load the bitmap
487 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
488 result
= BitmapFactory
.decodeFile(storagePath
, options
);
489 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
491 if (result
== null
) {
492 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
493 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
496 } catch (OutOfMemoryError e
) {
497 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
498 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
500 } catch (NoSuchFieldError e
) {
501 mErrorMessageId
= R
.string
.common_error_unknown
;
502 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
504 } catch (Throwable t
) {
505 mErrorMessageId
= R
.string
.common_error_unknown
;
506 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
513 protected void onPostExecute(Bitmap result
) {
515 if (result
!= null
) {
516 showLoadedImage(result
);
522 private void showLoadedImage(Bitmap result
) {
523 if (mImageViewRef
!= null
) {
524 final ImageView imageView
= mImageViewRef
.get();
525 if (imageView
!= null
) {
526 imageView
.setImageBitmap(result
);
527 imageView
.setVisibility(View
.VISIBLE
);
529 } // else , silently finish, the fragment was destroyed
531 if (mMessageViewRef
!= null
) {
532 final TextView messageView
= mMessageViewRef
.get();
533 if (messageView
!= null
) {
534 messageView
.setVisibility(View
.GONE
);
535 } // else , silently finish, the fragment was destroyed
539 private void showErrorMessage() {
540 if (mImageViewRef
!= null
) {
541 final ImageView imageView
= mImageViewRef
.get();
542 if (imageView
!= null
) {
543 // shows the default error icon
544 imageView
.setVisibility(View
.VISIBLE
);
545 } // else , silently finish, the fragment was destroyed
547 if (mMessageViewRef
!= null
) {
548 final TextView messageView
= mMessageViewRef
.get();
549 if (messageView
!= null
) {
550 messageView
.setText(mErrorMessageId
);
551 messageView
.setVisibility(View
.VISIBLE
);
552 } // else , silently finish, the fragment was destroyed
556 private void hideProgressWheel() {
557 if (mProgressWheelRef
!= null
) {
558 final ProgressBar progressWheel
= mProgressWheelRef
.get();
559 if (progressWheel
!= null
) {
560 progressWheel
.setVisibility(View
.GONE
);
568 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
570 * @param file File to test if can be previewed.
571 * @return 'True' if the file can be handled by the fragment.
573 public static boolean canBePreviewed(OCFile file
) {
574 return (file
!= null
&& file
.isImage());
579 * Finishes the preview
581 private void finish() {
582 Activity container
= getActivity();