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
.view
.Menu
;
51 import com
.actionbarsherlock
.view
.MenuInflater
;
52 import com
.actionbarsherlock
.view
.MenuItem
;
53 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
54 import com
.owncloud
.android
.datamodel
.OCFile
;
55 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
56 import com
.owncloud
.android
.operations
.RemoteOperation
;
57 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
58 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
59 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
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 FileFragment
implements OnRemoteOperationListener
,
78 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
79 public static final String EXTRA_FILE
= "FILE";
80 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
83 private Account mAccount
;
84 private FileDataStorageManager mStorageManager
;
85 private ImageView mImageView
;
86 private TextView mMessageView
;
87 private ProgressBar mProgressWheel
;
89 public Bitmap mBitmap
= null
;
91 private Handler mHandler
;
92 private RemoteOperation mLastRemoteOperation
;
94 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
96 private boolean mIgnoreFirstSavedState
;
100 * Creates a fragment to preview an image.
102 * When 'imageFile' or 'ocAccount' are null
104 * @param imageFile An {@link OCFile} to preview as an image in the fragment
105 * @param ocAccount An ownCloud account; needed to start downloads
106 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
108 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
110 mAccount
= ocAccount
;
111 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
112 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
117 * Creates an empty fragment for image previews.
119 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
121 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
123 public PreviewImageFragment() {
126 mStorageManager
= null
;
127 mIgnoreFirstSavedState
= false
;
135 public void onCreate(Bundle savedInstanceState
) {
136 super.onCreate(savedInstanceState
);
137 mHandler
= new Handler();
138 setHasOptionsMenu(true
);
146 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
147 Bundle savedInstanceState
) {
148 super.onCreateView(inflater
, container
, savedInstanceState
);
149 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
150 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
151 mImageView
.setVisibility(View
.GONE
);
152 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
153 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
154 mMessageView
.setVisibility(View
.GONE
);
155 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
156 mProgressWheel
.setVisibility(View
.VISIBLE
);
165 public void onAttach(Activity activity
) {
166 super.onAttach(activity
);
167 if (!(activity
instanceof FileFragment
.ContainerActivity
))
168 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
176 public void onActivityCreated(Bundle savedInstanceState
) {
177 super.onActivityCreated(savedInstanceState
);
178 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
179 if (savedInstanceState
!= null
) {
180 if (!mIgnoreFirstSavedState
) {
181 setFile((OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
));
182 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
184 mIgnoreFirstSavedState
= false
;
187 if (getFile() == null
) {
188 throw new IllegalStateException("Instanced with a NULL OCFile");
190 if (mAccount
== null
) {
191 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
193 if (!getFile().isDown()) {
194 throw new IllegalStateException("There is no local file to preview");
203 public void onSaveInstanceState(Bundle outState
) {
204 super.onSaveInstanceState(outState
);
205 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
206 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
211 public void onStart() {
213 if (getFile() != null
) {
214 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
215 bl
.execute(new String
[]{getFile().getStoragePath()});
224 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
225 super.onCreateOptionsMenu(menu
, inflater
);
227 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
228 List
<Integer
> toHide
= new ArrayList
<Integer
>();
230 MenuItem item
= null
;
231 toHide
.add(R
.id
.action_cancel_download
);
232 toHide
.add(R
.id
.action_cancel_upload
);
233 toHide
.add(R
.id
.action_download_file
);
234 toHide
.add(R
.id
.action_rename_file
); // by now
236 for (int i
: toHide
) {
237 item
= menu
.findItem(i
);
239 item
.setVisible(false
);
240 item
.setEnabled(false
);
251 public boolean onOptionsItemSelected(MenuItem item
) {
252 switch (item
.getItemId()) {
253 case R
.id
.action_open_file_with
: {
257 case R
.id
.action_remove_file
: {
261 case R
.id
.action_see_details
: {
272 private void seeDetails() {
273 ((FileFragment
.ContainerActivity
)getActivity()).showDetails(getFile());
278 public void onResume() {
284 public void onPause() {
290 public void onDestroy() {
292 if (mBitmap
!= null
) {
299 * Opens the previewed image with an external application.
301 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
302 * we should get a list of available apps for MIME tpye in the server and join it with the list of
303 * available apps for the MIME type known from the file extension, to let the user choose
305 private void openFile() {
306 OCFile file
= getFile();
307 String storagePath
= file
.getStoragePath();
308 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
310 Intent i
= new Intent(Intent
.ACTION_VIEW
);
311 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), file
.getMimetype());
312 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
315 } catch (Throwable t
) {
316 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file
.getMimetype());
317 boolean toastIt
= true
;
318 String mimeType
= "";
320 Intent i
= new Intent(Intent
.ACTION_VIEW
);
321 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
322 if (mimeType
== null
|| !mimeType
.equals(file
.getMimetype())) {
323 if (mimeType
!= null
) {
324 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
327 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
329 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
334 } catch (IndexOutOfBoundsException e
) {
335 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
337 } catch (ActivityNotFoundException e
) {
338 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
340 } catch (Throwable th
) {
341 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
345 Toast
.makeText(getActivity(), "There is no application to handle file " + file
.getFileName(), Toast
.LENGTH_SHORT
).show();
355 * Starts a the removal of the previewed file.
357 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
358 * depending upon the user selection in the dialog.
360 private void removeFile() {
361 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
362 R
.string
.confirmation_remove_alert
,
363 new String
[]{getFile().getFileName()},
364 R
.string
.confirmation_remove_remote_and_local
,
365 R
.string
.confirmation_remove_local
,
366 R
.string
.common_cancel
);
367 confDialog
.setOnConfirmationListener(this);
368 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
373 * Performs the removal of the previewed file, both locally and in the server.
376 public void onConfirmation(String callerTag
) {
377 if (mStorageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
378 mLastRemoteOperation
= new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
381 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
383 ((PreviewImageActivity
) getActivity()).showLoadingDialog();
389 * Removes the file from local storage
392 public void onNeutral(String callerTag
) {
393 // TODO this code should be made in a secondary thread,
394 OCFile file
= getFile();
395 if (file
.isDown()) { // checks it is still there
396 File f
= new File(file
.getStoragePath());
398 file
.setStoragePath(null
);
399 mStorageManager
.saveFile(file
);
405 * User cancelled the removal action.
408 public void onCancel(String callerTag
) {
409 // nothing to do here
413 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
416 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
418 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
420 private final WeakReference
<ImageView
> mImageViewRef
;
423 * Weak reference to the target {@link TextView} where error messages will be written.
425 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
427 private final WeakReference
<TextView
> mMessageViewRef
;
431 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
433 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
435 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
439 * Error message to show when a load fails
441 private int mErrorMessageId
;
447 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
449 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
450 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
451 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
452 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
456 @SuppressWarnings("deprecation")
457 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
459 protected Bitmap
doInBackground(String
... params
) {
460 Bitmap result
= null
;
461 if (params
.length
!= 1) return result
;
462 String storagePath
= params
[0];
464 // set desired options that will affect the size of the bitmap
465 BitmapFactory
.Options options
= new Options();
466 options
.inScaled
= true
;
467 options
.inPurgeable
= true
;
468 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
469 options
.inPreferQualityOverSpeed
= false
;
471 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
472 options
.inMutable
= false
;
474 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
475 options
.inJustDecodeBounds
= true
;
476 BitmapFactory
.decodeFile(storagePath
, options
);
478 int width
= options
.outWidth
;
479 int height
= options
.outHeight
;
482 Display display
= getActivity().getWindowManager().getDefaultDisplay();
483 Point size
= new Point();
486 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
487 display
.getSize(size
);
488 screenWidth
= size
.x
;
489 screenHeight
= size
.y
;
491 screenWidth
= display
.getWidth();
492 screenHeight
= display
.getHeight();
495 if (width
> screenWidth
) {
496 // second try to scale down the image , this time depending upon the screen size
497 scale
= (int) Math
.floor((float)width
/ screenWidth
);
499 if (height
> screenHeight
) {
500 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
502 options
.inSampleSize
= scale
;
504 // really load the bitmap
505 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
506 result
= BitmapFactory
.decodeFile(storagePath
, options
);
507 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
509 if (result
== null
) {
510 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
511 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
514 } catch (OutOfMemoryError e
) {
515 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
516 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
518 } catch (NoSuchFieldError e
) {
519 mErrorMessageId
= R
.string
.common_error_unknown
;
520 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
522 } catch (Throwable t
) {
523 mErrorMessageId
= R
.string
.common_error_unknown
;
524 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
531 protected void onPostExecute(Bitmap result
) {
533 if (result
!= null
) {
534 showLoadedImage(result
);
540 private void showLoadedImage(Bitmap result
) {
541 if (mImageViewRef
!= null
) {
542 final ImageView imageView
= mImageViewRef
.get();
543 if (imageView
!= null
) {
544 imageView
.setImageBitmap(result
);
545 imageView
.setVisibility(View
.VISIBLE
);
547 } // else , silently finish, the fragment was destroyed
549 if (mMessageViewRef
!= null
) {
550 final TextView messageView
= mMessageViewRef
.get();
551 if (messageView
!= null
) {
552 messageView
.setVisibility(View
.GONE
);
553 } // else , silently finish, the fragment was destroyed
557 private void showErrorMessage() {
558 if (mImageViewRef
!= null
) {
559 final ImageView imageView
= mImageViewRef
.get();
560 if (imageView
!= null
) {
561 // shows the default error icon
562 imageView
.setVisibility(View
.VISIBLE
);
563 } // else , silently finish, the fragment was destroyed
565 if (mMessageViewRef
!= null
) {
566 final TextView messageView
= mMessageViewRef
.get();
567 if (messageView
!= null
) {
568 messageView
.setText(mErrorMessageId
);
569 messageView
.setVisibility(View
.VISIBLE
);
570 } // else , silently finish, the fragment was destroyed
574 private void hideProgressWheel() {
575 if (mProgressWheelRef
!= null
) {
576 final ProgressBar progressWheel
= mProgressWheelRef
.get();
577 if (progressWheel
!= null
) {
578 progressWheel
.setVisibility(View
.GONE
);
586 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
588 * @param file File to test if can be previewed.
589 * @return 'True' if the file can be handled by the fragment.
591 public static boolean canBePreviewed(OCFile file
) {
592 return (file
!= null
&& file
.isImage());
600 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
601 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
602 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
606 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
607 ((PreviewImageActivity
) getActivity()).dismissLoadingDialog();
609 if (result
.isSuccess()) {
610 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
615 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
617 if (result
.isSslRecoverableException()) {
618 // TODO show the SSL warning dialog
624 * Finishes the preview
626 private void finish() {
627 Activity container
= getActivity();