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
;
20 import java
.lang
.ref
.WeakReference
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
25 import android
.accounts
.Account
;
26 import android
.annotation
.SuppressLint
;
27 import android
.app
.Activity
;
28 import android
.content
.ActivityNotFoundException
;
29 import android
.content
.Intent
;
30 import android
.graphics
.Bitmap
;
31 import android
.graphics
.BitmapFactory
;
32 import android
.graphics
.BitmapFactory
.Options
;
33 import android
.graphics
.Point
;
34 import android
.net
.Uri
;
35 import android
.os
.AsyncTask
;
36 import android
.os
.Bundle
;
37 import android
.os
.Handler
;
38 import android
.support
.v4
.app
.FragmentStatePagerAdapter
;
39 import android
.util
.Log
;
40 import android
.view
.Display
;
41 import android
.view
.LayoutInflater
;
42 import android
.view
.View
;
43 import android
.view
.View
.OnTouchListener
;
44 import android
.view
.ViewGroup
;
45 import android
.webkit
.MimeTypeMap
;
46 import android
.widget
.ImageView
;
47 import android
.widget
.ProgressBar
;
48 import android
.widget
.TextView
;
49 import android
.widget
.Toast
;
51 import com
.actionbarsherlock
.app
.SherlockFragment
;
52 import com
.actionbarsherlock
.view
.Menu
;
53 import com
.actionbarsherlock
.view
.MenuInflater
;
54 import com
.actionbarsherlock
.view
.MenuItem
;
55 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
56 import com
.owncloud
.android
.datamodel
.OCFile
;
57 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
58 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
59 import com
.owncloud
.android
.operations
.RemoteOperation
;
60 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
61 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
62 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
63 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
65 import com
.owncloud
.android
.R
;
66 import eu
.alefzero
.webdav
.WebdavClient
;
67 import eu
.alefzero
.webdav
.WebdavUtils
;
71 * This fragment shows a preview of a downloaded image.
73 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
75 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
77 * @author David A. Velasco
79 public class PreviewImageFragment
extends SherlockFragment
implements FileFragment
,
80 OnRemoteOperationListener
,
81 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
82 public static final String EXTRA_FILE
= "FILE";
83 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
87 private Account mAccount
;
88 private FileDataStorageManager mStorageManager
;
89 private ImageView mImageView
;
90 private TextView mMessageView
;
91 private ProgressBar mProgressWheel
;
93 public Bitmap mBitmap
= null
;
95 private Handler mHandler
;
96 private RemoteOperation mLastRemoteOperation
;
98 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
100 private boolean mIgnoreFirstSavedState
;
104 * Creates a fragment to preview an image.
106 * When 'imageFile' or 'ocAccount' are null
108 * @param imageFile An {@link OCFile} to preview as an image in the fragment
109 * @param ocAccount An ownCloud account; needed to start downloads
110 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
112 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
113 mFile
= fileToDetail
;
114 mAccount
= ocAccount
;
115 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
116 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
121 * Creates an empty fragment for image previews.
123 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
125 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
127 public PreviewImageFragment() {
130 mStorageManager
= null
;
131 mIgnoreFirstSavedState
= false
;
139 public void onCreate(Bundle savedInstanceState
) {
140 super.onCreate(savedInstanceState
);
141 mHandler
= new Handler();
142 setHasOptionsMenu(true
);
150 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
151 Bundle savedInstanceState
) {
152 super.onCreateView(inflater
, container
, savedInstanceState
);
153 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
154 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
155 mImageView
.setVisibility(View
.GONE
);
156 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
157 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
158 mMessageView
.setVisibility(View
.GONE
);
159 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
160 mProgressWheel
.setVisibility(View
.VISIBLE
);
169 public void onAttach(Activity activity
) {
170 super.onAttach(activity
);
171 if (!(activity
instanceof FileFragment
.ContainerActivity
))
172 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
180 public void onActivityCreated(Bundle savedInstanceState
) {
181 super.onActivityCreated(savedInstanceState
);
182 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
183 if (savedInstanceState
!= null
) {
184 if (!mIgnoreFirstSavedState
) {
185 mFile
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
186 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
188 mIgnoreFirstSavedState
= false
;
192 throw new IllegalStateException("Instanced with a NULL OCFile");
194 if (mAccount
== null
) {
195 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
197 if (!mFile
.isDown()) {
198 throw new IllegalStateException("There is no local file to preview");
207 public void onSaveInstanceState(Bundle outState
) {
208 super.onSaveInstanceState(outState
);
209 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, mFile
);
210 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
215 public void onStart() {
218 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
219 bl
.execute(new String
[]{mFile
.getStoragePath()});
228 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
229 super.onCreateOptionsMenu(menu
, inflater
);
231 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
232 List
<Integer
> toHide
= new ArrayList
<Integer
>();
234 MenuItem item
= null
;
235 toHide
.add(R
.id
.action_cancel_download
);
236 toHide
.add(R
.id
.action_cancel_upload
);
237 toHide
.add(R
.id
.action_download_file
);
238 toHide
.add(R
.id
.action_rename_file
); // by now
240 for (int i
: toHide
) {
241 item
= menu
.findItem(i
);
243 item
.setVisible(false
);
244 item
.setEnabled(false
);
255 public boolean onOptionsItemSelected(MenuItem item
) {
256 switch (item
.getItemId()) {
257 case R
.id
.action_open_file_with
: {
261 case R
.id
.action_remove_file
: {
265 case R
.id
.action_see_details
: {
276 private void seeDetails() {
277 ((FileFragment
.ContainerActivity
)getActivity()).showFragmentWithDetails(mFile
);
282 public void onResume() {
284 //Log.e(TAG, "FRAGMENT, ONRESUME");
286 mDownloadFinishReceiver = new DownloadFinishReceiver();
287 IntentFilter filter = new IntentFilter(
288 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
289 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
291 mUploadFinishReceiver = new UploadFinishReceiver();
292 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
293 getActivity().registerReceiver(mUploadFinishReceiver, filter);
300 public void onPause() {
303 if (mVideoPreview.getVisibility() == View.VISIBLE) {
304 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
307 getActivity().unregisterReceiver(mDownloadFinishReceiver);
308 mDownloadFinishReceiver = null;
310 getActivity().unregisterReceiver(mUploadFinishReceiver);
311 mUploadFinishReceiver = null;
317 public void onDestroy() {
319 if (mBitmap
!= null
) {
326 * Opens the previewed image with an external application.
328 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
329 * we should get a list of available apps for MIME tpye in the server and join it with the list of
330 * available apps for the MIME type known from the file extension, to let the user choose
332 private void openFile() {
333 String storagePath
= mFile
.getStoragePath();
334 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
336 Intent i
= new Intent(Intent
.ACTION_VIEW
);
337 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
338 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
341 } catch (Throwable t
) {
342 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
343 boolean toastIt
= true
;
344 String mimeType
= "";
346 Intent i
= new Intent(Intent
.ACTION_VIEW
);
347 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
348 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
349 if (mimeType
!= null
) {
350 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
353 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
355 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
360 } catch (IndexOutOfBoundsException e
) {
361 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
363 } catch (ActivityNotFoundException e
) {
364 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
366 } catch (Throwable th
) {
367 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
371 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
381 * Starts a the removal of the previewed file.
383 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
384 * depending upon the user selection in the dialog.
386 private void removeFile() {
387 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
388 R
.string
.confirmation_remove_alert
,
389 new String
[]{mFile
.getFileName()},
390 R
.string
.confirmation_remove_remote_and_local
,
391 R
.string
.confirmation_remove_local
,
392 R
.string
.common_cancel
);
393 confDialog
.setOnConfirmationListener(this);
394 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
399 * Performs the removal of the previewed file, both locally and in the server.
402 public void onConfirmation(String callerTag
) {
403 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
404 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
407 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
408 mLastRemoteOperation
.execute(wc
, this, mHandler
);
410 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
416 * Removes the file from local storage
419 public void onNeutral(String callerTag
) {
420 // TODO this code should be made in a secondary thread,
421 if (mFile
.isDown()) { // checks it is still there
422 File f
= new File(mFile
.getStoragePath());
424 mFile
.setStoragePath(null
);
425 mStorageManager
.saveFile(mFile
);
431 * User cancelled the removal action.
434 public void onCancel(String callerTag
) {
435 // nothing to do here
442 public OCFile
getFile(){
448 * Use this method to signal this Activity that it shall update its view.
450 * @param file : An {@link OCFile}
452 public void updateFileDetails(OCFile file, Account ocAccount) {
454 if (ocAccount != null && (
455 mStorageManager == null ||
456 (mAccount != null && !mAccount.equals(ocAccount))
458 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
460 mAccount = ocAccount;
461 updateFileDetails(false);
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.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
.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
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
571 } catch (NoSuchFieldError e
) {
572 mErrorMessageId
= R
.string
.common_error_unknown
;
573 Log
.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
.e(TAG
, "Unexpected error loading " + mFile
.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 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
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();