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
.content
.ActivityNotFoundException
;
28 import android
.content
.Intent
;
29 import android
.graphics
.Bitmap
;
30 import android
.graphics
.BitmapFactory
;
31 import android
.graphics
.BitmapFactory
.Options
;
32 import android
.graphics
.Point
;
33 import android
.net
.Uri
;
34 import android
.os
.AsyncTask
;
35 import android
.os
.Bundle
;
36 import android
.os
.Handler
;
37 import android
.support
.v4
.app
.FragmentStatePagerAdapter
;
38 import android
.view
.Display
;
39 import android
.view
.LayoutInflater
;
40 import android
.view
.View
;
41 import android
.view
.View
.OnTouchListener
;
42 import android
.view
.ViewGroup
;
43 import android
.webkit
.MimeTypeMap
;
44 import android
.widget
.ImageView
;
45 import android
.widget
.ProgressBar
;
46 import android
.widget
.TextView
;
47 import android
.widget
.Toast
;
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
.FileDataStorageManager
;
54 import com
.owncloud
.android
.datamodel
.OCFile
;
55 import com
.owncloud
.android
.lib
.common
.network
.WebdavUtils
;
56 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
57 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
58 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
59 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
60 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
61 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
62 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
63 import com
.owncloud
.android
.utils
.Log_OC
;
67 * This fragment shows a preview of a downloaded image.
69 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
71 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
73 * @author David A. Velasco
75 public class PreviewImageFragment
extends FileFragment
implements OnRemoteOperationListener
,
76 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
77 public static final String EXTRA_FILE
= "FILE";
78 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
81 private Account mAccount
;
82 private FileDataStorageManager mStorageManager
;
83 private ImageView mImageView
;
84 private TextView mMessageView
;
85 private ProgressBar mProgressWheel
;
87 public Bitmap mBitmap
= null
;
89 private Handler mHandler
;
90 private RemoteOperation mLastRemoteOperation
;
92 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
94 private boolean mIgnoreFirstSavedState
;
98 * Creates a fragment to preview an image.
100 * When 'imageFile' or 'ocAccount' are null
102 * @param imageFile An {@link OCFile} to preview as an image in the fragment
103 * @param ocAccount An ownCloud account; needed to start downloads
104 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
106 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
108 mAccount
= ocAccount
;
109 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
110 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
115 * Creates an empty fragment for image previews.
117 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
119 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
121 public PreviewImageFragment() {
124 mStorageManager
= null
;
125 mIgnoreFirstSavedState
= false
;
133 public void onCreate(Bundle savedInstanceState
) {
134 super.onCreate(savedInstanceState
);
135 mHandler
= new Handler();
136 setHasOptionsMenu(true
);
144 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
145 Bundle savedInstanceState
) {
146 super.onCreateView(inflater
, container
, savedInstanceState
);
147 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
148 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
149 mImageView
.setVisibility(View
.GONE
);
150 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
151 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
152 mMessageView
.setVisibility(View
.GONE
);
153 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
154 mProgressWheel
.setVisibility(View
.VISIBLE
);
163 public void onAttach(Activity activity
) {
164 super.onAttach(activity
);
165 if (!(activity
instanceof FileFragment
.ContainerActivity
))
166 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
174 public void onActivityCreated(Bundle savedInstanceState
) {
175 super.onActivityCreated(savedInstanceState
);
176 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
177 if (savedInstanceState
!= null
) {
178 if (!mIgnoreFirstSavedState
) {
179 OCFile file
= (OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
180 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
183 if (mAccount
!= null
) {
184 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
185 OCFile updatedFile
= mStorageManager
.getFileByPath(file
.getRemotePath());
186 if (updatedFile
!= null
) {
187 setFile(updatedFile
);
196 mIgnoreFirstSavedState
= false
;
199 if (getFile() == null
) {
200 throw new IllegalStateException("Instanced with a NULL OCFile");
202 if (mAccount
== null
) {
203 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
205 if (!getFile().isDown()) {
206 throw new IllegalStateException("There is no local file to preview");
215 public void onSaveInstanceState(Bundle outState
) {
216 super.onSaveInstanceState(outState
);
217 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
218 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
223 public void onStart() {
225 if (getFile() != null
) {
226 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
227 bl
.execute(new String
[]{getFile().getStoragePath()});
236 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
237 super.onCreateOptionsMenu(menu
, inflater
);
239 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
240 List
<Integer
> toHide
= new ArrayList
<Integer
>();
242 MenuItem item
= null
;
243 toHide
.add(R
.id
.action_cancel_download
);
244 toHide
.add(R
.id
.action_cancel_upload
);
245 toHide
.add(R
.id
.action_download_file
);
246 toHide
.add(R
.id
.action_rename_file
); // by now
249 if (!getFile().isShareByLink()) {
250 toHide
.add(R
.id
.action_unshare_file
);
254 boolean sendEnabled
= getString(R
.string
.send_files_to_other_apps
).equalsIgnoreCase("on");
256 toHide
.add(R
.id
.action_send_file
);
259 for (int i
: toHide
) {
260 item
= menu
.findItem(i
);
262 item
.setVisible(false
);
263 item
.setEnabled(false
);
273 public void onPrepareOptionsMenu(Menu menu
) {
274 super.onPrepareOptionsMenu(menu
);
276 MenuItem item
= menu
.findItem(R
.id
.action_unshare_file
);
278 OCFile file
= ((FileActivity
) getSherlockActivity()).getFile();
279 if (!file
.isShareByLink()) {
280 item
.setVisible(false
);
281 item
.setEnabled(false
);
283 item
.setVisible(true
);
284 item
.setEnabled(true
);
295 public boolean onOptionsItemSelected(MenuItem item
) {
296 switch (item
.getItemId()) {
297 case R
.id
.action_share_file
: {
298 FileActivity act
= (FileActivity
)getSherlockActivity();
299 act
.getFileOperationsHelper().shareFileWithLink(getFile(), act
);
302 case R
.id
.action_unshare_file
: {
303 FileActivity act
= (FileActivity
)getSherlockActivity();
304 act
.getFileOperationsHelper().unshareFileWithLink(getFile(), act
);
307 case R
.id
.action_open_file_with
: {
311 case R
.id
.action_remove_file
: {
315 case R
.id
.action_see_details
: {
319 case R
.id
.action_send_file
: {
320 FileActivity act
= (FileActivity
)getSherlockActivity();
321 act
.getFileOperationsHelper().sendDownloadedFile(getFile(), act
);
331 private void seeDetails() {
332 ((FileFragment
.ContainerActivity
)getActivity()).showDetails(getFile());
337 public void onResume() {
343 public void onPause() {
349 public void onDestroy() {
351 if (mBitmap
!= null
) {
358 * Opens the previewed image with an external application.
360 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
361 * we should get a list of available apps for MIME tpye in the server and join it with the list of
362 * available apps for the MIME type known from the file extension, to let the user choose
364 private void openFile() {
365 OCFile file
= getFile();
366 String storagePath
= file
.getStoragePath();
367 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
369 Intent i
= new Intent(Intent
.ACTION_VIEW
);
370 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), file
.getMimetype());
371 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
374 } catch (Throwable t
) {
375 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file
.getMimetype());
376 boolean toastIt
= true
;
377 String mimeType
= "";
379 Intent i
= new Intent(Intent
.ACTION_VIEW
);
380 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
381 if (mimeType
== null
|| !mimeType
.equals(file
.getMimetype())) {
382 if (mimeType
!= null
) {
383 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
386 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
388 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
393 } catch (IndexOutOfBoundsException e
) {
394 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
396 } catch (ActivityNotFoundException e
) {
397 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
399 } catch (Throwable th
) {
400 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
404 Toast
.makeText(getActivity(), "There is no application to handle file " + file
.getFileName(), Toast
.LENGTH_SHORT
).show();
414 * Starts a the removal of the previewed file.
416 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
417 * depending upon the user selection in the dialog.
419 private void removeFile() {
420 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
421 R
.string
.confirmation_remove_alert
,
422 new String
[]{getFile().getFileName()},
423 R
.string
.confirmation_remove_remote_and_local
,
424 R
.string
.confirmation_remove_local
,
425 R
.string
.common_cancel
);
426 confDialog
.setOnConfirmationListener(this);
427 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
432 * Performs the removal of the previewed file, both locally and in the server.
435 public void onConfirmation(String callerTag
) {
436 if (mStorageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
437 mLastRemoteOperation
= new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
440 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
442 ((PreviewImageActivity
) getActivity()).showLoadingDialog();
448 * Removes the file from local storage
451 public void onNeutral(String callerTag
) {
452 OCFile file
= getFile();
453 mStorageManager
.removeFile(file
, false
, true
); // TODO perform in background task / new thread
458 * User cancelled the removal action.
461 public void onCancel(String callerTag
) {
462 // nothing to do here
466 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
469 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
471 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
473 private final WeakReference
<ImageView
> mImageViewRef
;
476 * Weak reference to the target {@link TextView} where error messages will be written.
478 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
480 private final WeakReference
<TextView
> mMessageViewRef
;
484 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
486 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
488 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
492 * Error message to show when a load fails
494 private int mErrorMessageId
;
500 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
502 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
503 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
504 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
505 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
509 @SuppressWarnings("deprecation")
510 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
512 protected Bitmap
doInBackground(String
... params
) {
513 Bitmap result
= null
;
514 if (params
.length
!= 1) return result
;
515 String storagePath
= params
[0];
517 // set desired options that will affect the size of the bitmap
518 BitmapFactory
.Options options
= new Options();
519 options
.inScaled
= true
;
520 options
.inPurgeable
= true
;
521 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
522 options
.inPreferQualityOverSpeed
= false
;
524 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
525 options
.inMutable
= false
;
527 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
528 options
.inJustDecodeBounds
= true
;
529 BitmapFactory
.decodeFile(storagePath
, options
);
531 int width
= options
.outWidth
;
532 int height
= options
.outHeight
;
535 Display display
= getActivity().getWindowManager().getDefaultDisplay();
536 Point size
= new Point();
539 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
540 display
.getSize(size
);
541 screenWidth
= size
.x
;
542 screenHeight
= size
.y
;
544 screenWidth
= display
.getWidth();
545 screenHeight
= display
.getHeight();
548 if (width
> screenWidth
) {
549 // second try to scale down the image , this time depending upon the screen size
550 scale
= (int) Math
.floor((float)width
/ screenWidth
);
552 if (height
> screenHeight
) {
553 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
555 options
.inSampleSize
= scale
;
557 // really load the bitmap
558 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
559 result
= BitmapFactory
.decodeFile(storagePath
, options
);
560 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
562 if (result
== null
) {
563 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
564 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
567 } catch (OutOfMemoryError e
) {
568 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
569 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
571 } catch (NoSuchFieldError e
) {
572 mErrorMessageId
= R
.string
.common_error_unknown
;
573 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
575 } catch (Throwable t
) {
576 mErrorMessageId
= R
.string
.common_error_unknown
;
577 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
584 protected void onPostExecute(Bitmap result
) {
586 if (result
!= null
) {
587 showLoadedImage(result
);
593 private void showLoadedImage(Bitmap result
) {
594 if (mImageViewRef
!= null
) {
595 final ImageView imageView
= mImageViewRef
.get();
596 if (imageView
!= null
) {
597 imageView
.setImageBitmap(result
);
598 imageView
.setVisibility(View
.VISIBLE
);
600 } // else , silently finish, the fragment was destroyed
602 if (mMessageViewRef
!= null
) {
603 final TextView messageView
= mMessageViewRef
.get();
604 if (messageView
!= null
) {
605 messageView
.setVisibility(View
.GONE
);
606 } // else , silently finish, the fragment was destroyed
610 private void showErrorMessage() {
611 if (mImageViewRef
!= null
) {
612 final ImageView imageView
= mImageViewRef
.get();
613 if (imageView
!= null
) {
614 // shows the default error icon
615 imageView
.setVisibility(View
.VISIBLE
);
616 } // else , silently finish, the fragment was destroyed
618 if (mMessageViewRef
!= null
) {
619 final TextView messageView
= mMessageViewRef
.get();
620 if (messageView
!= null
) {
621 messageView
.setText(mErrorMessageId
);
622 messageView
.setVisibility(View
.VISIBLE
);
623 } // else , silently finish, the fragment was destroyed
627 private void hideProgressWheel() {
628 if (mProgressWheelRef
!= null
) {
629 final ProgressBar progressWheel
= mProgressWheelRef
.get();
630 if (progressWheel
!= null
) {
631 progressWheel
.setVisibility(View
.GONE
);
639 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
641 * @param file File to test if can be previewed.
642 * @return 'True' if the file can be handled by the fragment.
644 public static boolean canBePreviewed(OCFile file
) {
645 return (file
!= null
&& file
.isImage());
653 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
654 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
655 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
659 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
660 ((PreviewImageActivity
) getActivity()).dismissLoadingDialog();
662 if (result
.isSuccess()) {
663 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
668 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
670 if (result
.isSslRecoverableException()) {
671 // TODO show the SSL warning dialog
677 * Finishes the preview
679 private void finish() {
680 Activity container
= getActivity();