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
.view
.Display
;
40 import android
.view
.LayoutInflater
;
41 import android
.view
.View
;
42 import android
.view
.View
.OnTouchListener
;
43 import android
.view
.ViewGroup
;
44 import android
.webkit
.MimeTypeMap
;
45 import android
.widget
.ImageView
;
46 import android
.widget
.ProgressBar
;
47 import android
.widget
.TextView
;
48 import android
.widget
.Toast
;
50 import com
.actionbarsherlock
.app
.SherlockFragment
;
51 import com
.actionbarsherlock
.view
.Menu
;
52 import com
.actionbarsherlock
.view
.MenuInflater
;
53 import com
.actionbarsherlock
.view
.MenuItem
;
54 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
55 import com
.owncloud
.android
.datamodel
.OCFile
;
56 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
57 import com
.owncloud
.android
.operations
.RemoteOperation
;
58 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
59 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
60 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
61 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
63 import com
.owncloud
.android
.Log_OC
;
64 import com
.owncloud
.android
.R
;
65 import eu
.alefzero
.webdav
.WebdavUtils
;
69 * This fragment shows a preview of a downloaded image.
71 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
73 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
75 * @author David A. Velasco
77 public class PreviewImageFragment
extends SherlockFragment
implements FileFragment
,
78 OnRemoteOperationListener
,
79 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
80 public static final String EXTRA_FILE
= "FILE";
81 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
85 private Account mAccount
;
86 private FileDataStorageManager mStorageManager
;
87 private ImageView mImageView
;
88 private TextView mMessageView
;
89 private ProgressBar mProgressWheel
;
91 public Bitmap mBitmap
= null
;
93 private Handler mHandler
;
94 private RemoteOperation mLastRemoteOperation
;
96 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
98 private boolean mIgnoreFirstSavedState
;
102 * Creates a fragment to preview an image.
104 * When 'imageFile' or 'ocAccount' are null
106 * @param imageFile An {@link OCFile} to preview as an image in the fragment
107 * @param ocAccount An ownCloud account; needed to start downloads
108 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
110 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
111 mFile
= fileToDetail
;
112 mAccount
= ocAccount
;
113 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
114 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
119 * Creates an empty fragment for image previews.
121 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
123 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
125 public PreviewImageFragment() {
128 mStorageManager
= null
;
129 mIgnoreFirstSavedState
= false
;
137 public void onCreate(Bundle savedInstanceState
) {
138 super.onCreate(savedInstanceState
);
139 mHandler
= new Handler();
140 setHasOptionsMenu(true
);
148 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
149 Bundle savedInstanceState
) {
150 super.onCreateView(inflater
, container
, savedInstanceState
);
151 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
152 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
153 mImageView
.setVisibility(View
.GONE
);
154 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
155 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
156 mMessageView
.setVisibility(View
.GONE
);
157 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
158 mProgressWheel
.setVisibility(View
.VISIBLE
);
167 public void onAttach(Activity activity
) {
168 super.onAttach(activity
);
169 if (!(activity
instanceof FileFragment
.ContainerActivity
))
170 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
178 public void onActivityCreated(Bundle savedInstanceState
) {
179 super.onActivityCreated(savedInstanceState
);
180 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
181 if (savedInstanceState
!= null
) {
182 if (!mIgnoreFirstSavedState
) {
183 mFile
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
184 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
186 mIgnoreFirstSavedState
= false
;
190 throw new IllegalStateException("Instanced with a NULL OCFile");
192 if (mAccount
== null
) {
193 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
195 if (!mFile
.isDown()) {
196 throw new IllegalStateException("There is no local file to preview");
205 public void onSaveInstanceState(Bundle outState
) {
206 super.onSaveInstanceState(outState
);
207 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, mFile
);
208 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
213 public void onStart() {
216 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
217 bl
.execute(new String
[]{mFile
.getStoragePath()});
226 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
227 super.onCreateOptionsMenu(menu
, inflater
);
229 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
230 List
<Integer
> toHide
= new ArrayList
<Integer
>();
232 MenuItem item
= null
;
233 toHide
.add(R
.id
.action_cancel_download
);
234 toHide
.add(R
.id
.action_cancel_upload
);
235 toHide
.add(R
.id
.action_download_file
);
236 toHide
.add(R
.id
.action_rename_file
); // by now
238 for (int i
: toHide
) {
239 item
= menu
.findItem(i
);
241 item
.setVisible(false
);
242 item
.setEnabled(false
);
253 public boolean onOptionsItemSelected(MenuItem item
) {
254 switch (item
.getItemId()) {
255 case R
.id
.action_open_file_with
: {
259 case R
.id
.action_remove_file
: {
263 case R
.id
.action_see_details
: {
274 private void seeDetails() {
275 ((FileFragment
.ContainerActivity
)getActivity()).showFragmentWithDetails(mFile
);
280 public void onResume() {
282 //Log.e(TAG, "FRAGMENT, ONRESUME");
284 mDownloadFinishReceiver = new DownloadFinishReceiver();
285 IntentFilter filter = new IntentFilter(
286 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
287 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
289 mUploadFinishReceiver = new UploadFinishReceiver();
290 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
291 getActivity().registerReceiver(mUploadFinishReceiver, filter);
298 public void onPause() {
301 if (mVideoPreview.getVisibility() == View.VISIBLE) {
302 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
305 getActivity().unregisterReceiver(mDownloadFinishReceiver);
306 mDownloadFinishReceiver = null;
308 getActivity().unregisterReceiver(mUploadFinishReceiver);
309 mUploadFinishReceiver = null;
315 public void onDestroy() {
317 if (mBitmap
!= null
) {
324 * Opens the previewed image with an external application.
326 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
327 * we should get a list of available apps for MIME tpye in the server and join it with the list of
328 * available apps for the MIME type known from the file extension, to let the user choose
330 private void openFile() {
331 String storagePath
= mFile
.getStoragePath();
332 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
334 Intent i
= new Intent(Intent
.ACTION_VIEW
);
335 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
336 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
339 } catch (Throwable t
) {
340 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
341 boolean toastIt
= true
;
342 String mimeType
= "";
344 Intent i
= new Intent(Intent
.ACTION_VIEW
);
345 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
346 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
347 if (mimeType
!= null
) {
348 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
351 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
353 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
358 } catch (IndexOutOfBoundsException e
) {
359 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
361 } catch (ActivityNotFoundException e
) {
362 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
364 } catch (Throwable th
) {
365 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
369 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
379 * Starts a the removal of the previewed file.
381 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
382 * depending upon the user selection in the dialog.
384 private void removeFile() {
385 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
386 R
.string
.confirmation_remove_alert
,
387 new String
[]{mFile
.getFileName()},
388 R
.string
.confirmation_remove_remote_and_local
,
389 R
.string
.confirmation_remove_local
,
390 R
.string
.common_cancel
);
391 confDialog
.setOnConfirmationListener(this);
392 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
397 * Performs the removal of the previewed file, both locally and in the server.
400 public void onConfirmation(String callerTag
) {
401 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
402 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
405 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
407 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
413 * Removes the file from local storage
416 public void onNeutral(String callerTag
) {
417 // TODO this code should be made in a secondary thread,
418 if (mFile
.isDown()) { // checks it is still there
419 File f
= new File(mFile
.getStoragePath());
421 mFile
.setStoragePath(null
);
422 mStorageManager
.saveFile(mFile
);
428 * User cancelled the removal action.
431 public void onCancel(String callerTag
) {
432 // nothing to do here
439 public OCFile
getFile(){
445 * Use this method to signal this Activity that it shall update its view.
447 * @param file : An {@link OCFile}
449 public void updateFileDetails(OCFile file, Account ocAccount) {
451 if (ocAccount != null && (
452 mStorageManager == null ||
453 (mAccount != null && !mAccount.equals(ocAccount))
455 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
457 mAccount = ocAccount;
458 updateFileDetails(false);
463 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
466 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
468 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
470 private final WeakReference
<ImageView
> mImageViewRef
;
473 * Weak reference to the target {@link TextView} where error messages will be written.
475 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
477 private final WeakReference
<TextView
> mMessageViewRef
;
481 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
483 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
485 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
489 * Error message to show when a load fails
491 private int mErrorMessageId
;
497 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
499 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
500 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
501 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
502 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
506 @SuppressWarnings("deprecation")
507 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
509 protected Bitmap
doInBackground(String
... params
) {
510 Bitmap result
= null
;
511 if (params
.length
!= 1) return result
;
512 String storagePath
= params
[0];
514 // set desired options that will affect the size of the bitmap
515 BitmapFactory
.Options options
= new Options();
516 options
.inScaled
= true
;
517 options
.inPurgeable
= true
;
518 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
519 options
.inPreferQualityOverSpeed
= false
;
521 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
522 options
.inMutable
= false
;
524 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
525 options
.inJustDecodeBounds
= true
;
526 BitmapFactory
.decodeFile(storagePath
, options
);
528 int width
= options
.outWidth
;
529 int height
= options
.outHeight
;
532 Display display
= getActivity().getWindowManager().getDefaultDisplay();
533 Point size
= new Point();
536 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
537 display
.getSize(size
);
538 screenWidth
= size
.x
;
539 screenHeight
= size
.y
;
541 screenWidth
= display
.getWidth();
542 screenHeight
= display
.getHeight();
545 if (width
> screenWidth
) {
546 // second try to scale down the image , this time depending upon the screen size
547 scale
= (int) Math
.floor((float)width
/ screenWidth
);
549 if (height
> screenHeight
) {
550 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
552 options
.inSampleSize
= scale
;
554 // really load the bitmap
555 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
556 result
= BitmapFactory
.decodeFile(storagePath
, options
);
557 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
559 if (result
== null
) {
560 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
561 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
564 } catch (OutOfMemoryError e
) {
565 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
566 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
568 } catch (NoSuchFieldError e
) {
569 mErrorMessageId
= R
.string
.common_error_unknown
;
570 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
572 } catch (Throwable t
) {
573 mErrorMessageId
= R
.string
.common_error_unknown
;
574 Log_OC
.e(TAG
, "Unexpected error loading " + mFile
.getStoragePath(), t
);
581 protected void onPostExecute(Bitmap result
) {
583 if (result
!= null
) {
584 showLoadedImage(result
);
590 private void showLoadedImage(Bitmap result
) {
591 if (mImageViewRef
!= null
) {
592 final ImageView imageView
= mImageViewRef
.get();
593 if (imageView
!= null
) {
594 imageView
.setImageBitmap(result
);
595 imageView
.setVisibility(View
.VISIBLE
);
597 } // else , silently finish, the fragment was destroyed
599 if (mMessageViewRef
!= null
) {
600 final TextView messageView
= mMessageViewRef
.get();
601 if (messageView
!= null
) {
602 messageView
.setVisibility(View
.GONE
);
603 } // else , silently finish, the fragment was destroyed
607 private void showErrorMessage() {
608 if (mImageViewRef
!= null
) {
609 final ImageView imageView
= mImageViewRef
.get();
610 if (imageView
!= null
) {
611 // shows the default error icon
612 imageView
.setVisibility(View
.VISIBLE
);
613 } // else , silently finish, the fragment was destroyed
615 if (mMessageViewRef
!= null
) {
616 final TextView messageView
= mMessageViewRef
.get();
617 if (messageView
!= null
) {
618 messageView
.setText(mErrorMessageId
);
619 messageView
.setVisibility(View
.VISIBLE
);
620 } // else , silently finish, the fragment was destroyed
624 private void hideProgressWheel() {
625 if (mProgressWheelRef
!= null
) {
626 final ProgressBar progressWheel
= mProgressWheelRef
.get();
627 if (progressWheel
!= null
) {
628 progressWheel
.setVisibility(View
.GONE
);
636 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
638 * @param file File to test if can be previewed.
639 * @return 'True' if the file can be handled by the fragment.
641 public static boolean canBePreviewed(OCFile file
) {
642 return (file
!= null
&& file
.isImage());
650 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
651 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
652 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
656 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
657 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
659 if (result
.isSuccess()) {
660 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
665 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
667 if (result
.isSslRecoverableException()) {
668 // TODO show the SSL warning dialog
674 * Finishes the preview
676 private void finish() {
677 Activity container
= getActivity();