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 as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.ui
.preview
;
21 import java
.lang
.ref
.WeakReference
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
26 import android
.accounts
.Account
;
27 import android
.annotation
.SuppressLint
;
28 import android
.app
.Activity
;
29 import android
.content
.ActivityNotFoundException
;
30 import android
.content
.Intent
;
31 import android
.graphics
.Bitmap
;
32 import android
.graphics
.BitmapFactory
;
33 import android
.graphics
.BitmapFactory
.Options
;
34 import android
.graphics
.Point
;
35 import android
.net
.Uri
;
36 import android
.os
.AsyncTask
;
37 import android
.os
.Bundle
;
38 import android
.os
.Handler
;
39 import android
.support
.v4
.app
.FragmentStatePagerAdapter
;
40 import android
.util
.Log
;
41 import android
.view
.Display
;
42 import android
.view
.LayoutInflater
;
43 import android
.view
.View
;
44 import android
.view
.View
.OnTouchListener
;
45 import android
.view
.ViewGroup
;
46 import android
.webkit
.MimeTypeMap
;
47 import android
.widget
.ImageView
;
48 import android
.widget
.ProgressBar
;
49 import android
.widget
.TextView
;
50 import android
.widget
.Toast
;
52 import com
.actionbarsherlock
.app
.SherlockFragment
;
53 import com
.actionbarsherlock
.view
.Menu
;
54 import com
.actionbarsherlock
.view
.MenuInflater
;
55 import com
.actionbarsherlock
.view
.MenuItem
;
56 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
57 import com
.owncloud
.android
.datamodel
.OCFile
;
58 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
59 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
60 import com
.owncloud
.android
.operations
.RemoteOperation
;
61 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
62 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
63 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
64 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
66 import com
.owncloud
.android
.R
;
67 import eu
.alefzero
.webdav
.WebdavClient
;
68 import eu
.alefzero
.webdav
.WebdavUtils
;
72 * This fragment shows a preview of a downloaded image.
74 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
76 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
78 * @author David A. Velasco
80 public class PreviewImageFragment
extends SherlockFragment
implements FileFragment
,
81 OnRemoteOperationListener
,
82 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
83 public static final String EXTRA_FILE
= "FILE";
84 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
88 private Account mAccount
;
89 private FileDataStorageManager mStorageManager
;
90 private ImageView mImageView
;
91 private TextView mMessageView
;
92 private ProgressBar mProgressWheel
;
94 public Bitmap mBitmap
= null
;
96 private Handler mHandler
;
97 private RemoteOperation mLastRemoteOperation
;
99 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
101 private boolean mIgnoreFirstSavedState
;
105 * Creates a fragment to preview an image.
107 * When 'imageFile' or 'ocAccount' are null
109 * @param imageFile An {@link OCFile} to preview as an image in the fragment
110 * @param ocAccount An ownCloud account; needed to start downloads
111 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
113 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
114 mFile
= fileToDetail
;
115 mAccount
= ocAccount
;
116 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
117 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
122 * Creates an empty fragment for image previews.
124 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
126 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
128 public PreviewImageFragment() {
131 mStorageManager
= null
;
132 mIgnoreFirstSavedState
= false
;
140 public void onCreate(Bundle savedInstanceState
) {
141 super.onCreate(savedInstanceState
);
142 mHandler
= new Handler();
143 setHasOptionsMenu(true
);
151 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
152 Bundle savedInstanceState
) {
153 super.onCreateView(inflater
, container
, savedInstanceState
);
154 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
155 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
156 mImageView
.setVisibility(View
.GONE
);
157 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
158 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
159 mMessageView
.setVisibility(View
.GONE
);
160 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
161 mProgressWheel
.setVisibility(View
.VISIBLE
);
170 public void onAttach(Activity activity
) {
171 super.onAttach(activity
);
172 if (!(activity
instanceof FileFragment
.ContainerActivity
))
173 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
181 public void onActivityCreated(Bundle savedInstanceState
) {
182 super.onActivityCreated(savedInstanceState
);
183 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
184 if (savedInstanceState
!= null
) {
185 if (!mIgnoreFirstSavedState
) {
186 mFile
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
187 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
189 mIgnoreFirstSavedState
= false
;
193 throw new IllegalStateException("Instanced with a NULL OCFile");
195 if (mAccount
== null
) {
196 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
198 if (!mFile
.isDown()) {
199 throw new IllegalStateException("There is no local file to preview");
208 public void onSaveInstanceState(Bundle outState
) {
209 super.onSaveInstanceState(outState
);
210 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, mFile
);
211 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
216 public void onStart() {
219 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
220 bl
.execute(new String
[]{mFile
.getStoragePath()});
229 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
230 super.onCreateOptionsMenu(menu
, inflater
);
232 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
233 List
<Integer
> toHide
= new ArrayList
<Integer
>();
235 MenuItem item
= null
;
236 toHide
.add(R
.id
.action_cancel_download
);
237 toHide
.add(R
.id
.action_cancel_upload
);
238 toHide
.add(R
.id
.action_download_file
);
239 toHide
.add(R
.id
.action_rename_file
); // by now
241 for (int i
: toHide
) {
242 item
= menu
.findItem(i
);
244 item
.setVisible(false
);
245 item
.setEnabled(false
);
256 public boolean onOptionsItemSelected(MenuItem item
) {
257 switch (item
.getItemId()) {
258 case R
.id
.action_open_file_with
: {
262 case R
.id
.action_remove_file
: {
266 case R
.id
.action_see_details
: {
277 private void seeDetails() {
278 ((FileFragment
.ContainerActivity
)getActivity()).showFragmentWithDetails(mFile
);
283 public void onResume() {
285 //Log.e(TAG, "FRAGMENT, ONRESUME");
287 mDownloadFinishReceiver = new DownloadFinishReceiver();
288 IntentFilter filter = new IntentFilter(
289 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
290 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
292 mUploadFinishReceiver = new UploadFinishReceiver();
293 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
294 getActivity().registerReceiver(mUploadFinishReceiver, filter);
301 public void onPause() {
304 if (mVideoPreview.getVisibility() == View.VISIBLE) {
305 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
308 getActivity().unregisterReceiver(mDownloadFinishReceiver);
309 mDownloadFinishReceiver = null;
311 getActivity().unregisterReceiver(mUploadFinishReceiver);
312 mUploadFinishReceiver = null;
318 public void onDestroy() {
320 if (mBitmap
!= null
) {
327 * Opens the previewed image with an external application.
329 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
330 * we should get a list of available apps for MIME tpye in the server and join it with the list of
331 * available apps for the MIME type known from the file extension, to let the user choose
333 private void openFile() {
334 String storagePath
= mFile
.getStoragePath();
335 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
337 Intent i
= new Intent(Intent
.ACTION_VIEW
);
338 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
339 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
342 } catch (Throwable t
) {
343 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
344 boolean toastIt
= true
;
345 String mimeType
= "";
347 Intent i
= new Intent(Intent
.ACTION_VIEW
);
348 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
349 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
350 if (mimeType
!= null
) {
351 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
354 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
356 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
361 } catch (IndexOutOfBoundsException e
) {
362 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
364 } catch (ActivityNotFoundException e
) {
365 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
367 } catch (Throwable th
) {
368 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
372 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
382 * Starts a the removal of the previewed file.
384 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
385 * depending upon the user selection in the dialog.
387 private void removeFile() {
388 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
389 R
.string
.confirmation_remove_alert
,
390 new String
[]{mFile
.getFileName()},
391 R
.string
.confirmation_remove_remote_and_local
,
392 R
.string
.confirmation_remove_local
,
393 R
.string
.common_cancel
);
394 confDialog
.setOnConfirmationListener(this);
395 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
400 * Performs the removal of the previewed file, both locally and in the server.
403 public void onConfirmation(String callerTag
) {
404 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
405 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
408 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
409 mLastRemoteOperation
.execute(wc
, this, mHandler
);
411 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
417 * Removes the file from local storage
420 public void onNeutral(String callerTag
) {
421 // TODO this code should be made in a secondary thread,
422 if (mFile
.isDown()) { // checks it is still there
423 File f
= new File(mFile
.getStoragePath());
425 mFile
.setStoragePath(null
);
426 mStorageManager
.saveFile(mFile
);
432 * User cancelled the removal action.
435 public void onCancel(String callerTag
) {
436 // nothing to do here
443 public OCFile
getFile(){
449 * Use this method to signal this Activity that it shall update its view.
451 * @param file : An {@link OCFile}
453 public void updateFileDetails(OCFile file, Account ocAccount) {
455 if (ocAccount != null && (
456 mStorageManager == null ||
457 (mAccount != null && !mAccount.equals(ocAccount))
459 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
461 mAccount = ocAccount;
462 updateFileDetails(false);
467 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
470 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
472 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
474 private final WeakReference
<ImageView
> mImageViewRef
;
477 * Weak reference to the target {@link TextView} where error messages will be written.
479 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
481 private final WeakReference
<TextView
> mMessageViewRef
;
485 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
487 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
489 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
493 * Error message to show when a load fails
495 private int mErrorMessageId
;
501 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
503 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
504 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
505 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
506 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
510 @SuppressWarnings("deprecation")
511 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
513 protected Bitmap
doInBackground(String
... params
) {
514 Bitmap result
= null
;
515 if (params
.length
!= 1) return result
;
516 String storagePath
= params
[0];
518 // set desired options that will affect the size of the bitmap
519 BitmapFactory
.Options options
= new Options();
520 options
.inScaled
= true
;
521 options
.inPurgeable
= true
;
522 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
523 options
.inPreferQualityOverSpeed
= false
;
525 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
526 options
.inMutable
= false
;
528 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
529 options
.inJustDecodeBounds
= true
;
530 BitmapFactory
.decodeFile(storagePath
, options
);
532 int width
= options
.outWidth
;
533 int height
= options
.outHeight
;
536 Display display
= getActivity().getWindowManager().getDefaultDisplay();
537 Point size
= new Point();
540 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
541 display
.getSize(size
);
542 screenWidth
= size
.x
;
543 screenHeight
= size
.y
;
545 screenWidth
= display
.getWidth();
546 screenHeight
= display
.getHeight();
549 if (width
> screenWidth
) {
550 // second try to scale down the image , this time depending upon the screen size
551 scale
= (int) Math
.floor((float)width
/ screenWidth
);
553 if (height
> screenHeight
) {
554 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
556 options
.inSampleSize
= scale
;
558 // really load the bitmap
559 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
560 result
= BitmapFactory
.decodeFile(storagePath
, options
);
561 //Log.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
563 if (result
== null
) {
564 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
565 Log
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
568 } catch (OutOfMemoryError e
) {
569 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
570 Log
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
572 } catch (NoSuchFieldError e
) {
573 mErrorMessageId
= R
.string
.common_error_unknown
;
574 Log
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
576 } catch (Throwable t
) {
577 mErrorMessageId
= R
.string
.common_error_unknown
;
578 Log
.e(TAG
, "Unexpected error loading " + mFile
.getStoragePath(), t
);
585 protected void onPostExecute(Bitmap result
) {
587 if (result
!= null
) {
588 showLoadedImage(result
);
594 private void showLoadedImage(Bitmap result
) {
595 if (mImageViewRef
!= null
) {
596 final ImageView imageView
= mImageViewRef
.get();
597 if (imageView
!= null
) {
598 imageView
.setImageBitmap(result
);
599 imageView
.setVisibility(View
.VISIBLE
);
601 } // else , silently finish, the fragment was destroyed
603 if (mMessageViewRef
!= null
) {
604 final TextView messageView
= mMessageViewRef
.get();
605 if (messageView
!= null
) {
606 messageView
.setVisibility(View
.GONE
);
607 } // else , silently finish, the fragment was destroyed
611 private void showErrorMessage() {
612 if (mImageViewRef
!= null
) {
613 final ImageView imageView
= mImageViewRef
.get();
614 if (imageView
!= null
) {
615 // shows the default error icon
616 imageView
.setVisibility(View
.VISIBLE
);
617 } // else , silently finish, the fragment was destroyed
619 if (mMessageViewRef
!= null
) {
620 final TextView messageView
= mMessageViewRef
.get();
621 if (messageView
!= null
) {
622 messageView
.setText(mErrorMessageId
);
623 messageView
.setVisibility(View
.VISIBLE
);
624 } // else , silently finish, the fragment was destroyed
628 private void hideProgressWheel() {
629 if (mProgressWheelRef
!= null
) {
630 final ProgressBar progressWheel
= mProgressWheelRef
.get();
631 if (progressWheel
!= null
) {
632 progressWheel
.setVisibility(View
.GONE
);
640 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
642 * @param file File to test if can be previewed.
643 * @return 'True' if the file can be handled by the fragment.
645 public static boolean canBePreviewed(OCFile file
) {
646 return (file
!= null
&& file
.isImage());
654 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
655 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
656 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
660 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
661 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
663 if (result
.isSuccess()) {
664 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
669 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
671 if (result
.isSslRecoverableException()) {
672 // TODO show the SSL warning dialog
678 * Finishes the preview
680 private void finish() {
681 Activity container
= getActivity();