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
.oc_framework
.network
.webdav
.WebdavUtils
;
56 import com
.owncloud
.android
.oc_framework
.operations
.OnRemoteOperationListener
;
57 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperation
;
58 import com
.owncloud
.android
.oc_framework
.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
;
62 import com
.owncloud
.android
.utils
.Log_OC
;
66 * This fragment shows a preview of a downloaded image.
68 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
70 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
72 * @author David A. Velasco
74 public class PreviewImageFragment
extends FileFragment
implements OnRemoteOperationListener
,
75 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
76 public static final String EXTRA_FILE
= "FILE";
77 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
80 private Account mAccount
;
81 private FileDataStorageManager mStorageManager
;
82 private ImageView mImageView
;
83 private TextView mMessageView
;
84 private ProgressBar mProgressWheel
;
86 public Bitmap mBitmap
= null
;
88 private Handler mHandler
;
89 private RemoteOperation mLastRemoteOperation
;
91 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
93 private boolean mIgnoreFirstSavedState
;
97 * Creates a fragment to preview an image.
99 * When 'imageFile' or 'ocAccount' are null
101 * @param imageFile An {@link OCFile} to preview as an image in the fragment
102 * @param ocAccount An ownCloud account; needed to start downloads
103 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
105 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
107 mAccount
= ocAccount
;
108 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
109 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
114 * Creates an empty fragment for image previews.
116 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
118 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
120 public PreviewImageFragment() {
123 mStorageManager
= null
;
124 mIgnoreFirstSavedState
= false
;
132 public void onCreate(Bundle savedInstanceState
) {
133 super.onCreate(savedInstanceState
);
134 mHandler
= new Handler();
135 setHasOptionsMenu(true
);
143 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
144 Bundle savedInstanceState
) {
145 super.onCreateView(inflater
, container
, savedInstanceState
);
146 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
147 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
148 mImageView
.setVisibility(View
.GONE
);
149 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
150 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
151 mMessageView
.setVisibility(View
.GONE
);
152 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
153 mProgressWheel
.setVisibility(View
.VISIBLE
);
162 public void onAttach(Activity activity
) {
163 super.onAttach(activity
);
164 if (!(activity
instanceof FileFragment
.ContainerActivity
))
165 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
173 public void onActivityCreated(Bundle savedInstanceState
) {
174 super.onActivityCreated(savedInstanceState
);
175 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
176 if (savedInstanceState
!= null
) {
177 if (!mIgnoreFirstSavedState
) {
178 setFile((OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
));
179 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
181 mIgnoreFirstSavedState
= false
;
184 if (getFile() == null
) {
185 throw new IllegalStateException("Instanced with a NULL OCFile");
187 if (mAccount
== null
) {
188 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
190 if (!getFile().isDown()) {
191 throw new IllegalStateException("There is no local file to preview");
200 public void onSaveInstanceState(Bundle outState
) {
201 super.onSaveInstanceState(outState
);
202 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
203 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
208 public void onStart() {
210 if (getFile() != null
) {
211 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
212 bl
.execute(new String
[]{getFile().getStoragePath()});
221 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
222 super.onCreateOptionsMenu(menu
, inflater
);
224 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
225 List
<Integer
> toHide
= new ArrayList
<Integer
>();
227 MenuItem item
= null
;
228 toHide
.add(R
.id
.action_cancel_download
);
229 toHide
.add(R
.id
.action_cancel_upload
);
230 toHide
.add(R
.id
.action_download_file
);
231 toHide
.add(R
.id
.action_rename_file
); // by now
233 for (int i
: toHide
) {
234 item
= menu
.findItem(i
);
236 item
.setVisible(false
);
237 item
.setEnabled(false
);
248 public boolean onOptionsItemSelected(MenuItem item
) {
249 switch (item
.getItemId()) {
250 case R
.id
.action_open_file_with
: {
254 case R
.id
.action_remove_file
: {
258 case R
.id
.action_see_details
: {
269 private void seeDetails() {
270 ((FileFragment
.ContainerActivity
)getActivity()).showDetails(getFile());
275 public void onResume() {
281 public void onPause() {
287 public void onDestroy() {
289 if (mBitmap
!= null
) {
296 * Opens the previewed image with an external application.
298 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
299 * we should get a list of available apps for MIME tpye in the server and join it with the list of
300 * available apps for the MIME type known from the file extension, to let the user choose
302 private void openFile() {
303 OCFile file
= getFile();
304 String storagePath
= file
.getStoragePath();
305 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
307 Intent i
= new Intent(Intent
.ACTION_VIEW
);
308 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), file
.getMimetype());
309 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
312 } catch (Throwable t
) {
313 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file
.getMimetype());
314 boolean toastIt
= true
;
315 String mimeType
= "";
317 Intent i
= new Intent(Intent
.ACTION_VIEW
);
318 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
319 if (mimeType
== null
|| !mimeType
.equals(file
.getMimetype())) {
320 if (mimeType
!= null
) {
321 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
324 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
326 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
331 } catch (IndexOutOfBoundsException e
) {
332 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
334 } catch (ActivityNotFoundException e
) {
335 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
337 } catch (Throwable th
) {
338 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
342 Toast
.makeText(getActivity(), "There is no application to handle file " + file
.getFileName(), Toast
.LENGTH_SHORT
).show();
352 * Starts a the removal of the previewed file.
354 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
355 * depending upon the user selection in the dialog.
357 private void removeFile() {
358 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
359 R
.string
.confirmation_remove_alert
,
360 new String
[]{getFile().getFileName()},
361 R
.string
.confirmation_remove_remote_and_local
,
362 R
.string
.confirmation_remove_local
,
363 R
.string
.common_cancel
);
364 confDialog
.setOnConfirmationListener(this);
365 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
370 * Performs the removal of the previewed file, both locally and in the server.
373 public void onConfirmation(String callerTag
) {
374 if (mStorageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
375 mLastRemoteOperation
= new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
378 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
380 ((PreviewImageActivity
) getActivity()).showLoadingDialog();
386 * Removes the file from local storage
389 public void onNeutral(String callerTag
) {
390 OCFile file
= getFile();
391 mStorageManager
.removeFile(file
, false
, true
); // TODO perform in background task / new thread
396 * User cancelled the removal action.
399 public void onCancel(String callerTag
) {
400 // nothing to do here
404 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
407 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
409 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
411 private final WeakReference
<ImageView
> mImageViewRef
;
414 * Weak reference to the target {@link TextView} where error messages will be written.
416 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
418 private final WeakReference
<TextView
> mMessageViewRef
;
422 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
424 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
426 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
430 * Error message to show when a load fails
432 private int mErrorMessageId
;
438 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
440 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
441 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
442 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
443 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
447 @SuppressWarnings("deprecation")
448 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
450 protected Bitmap
doInBackground(String
... params
) {
451 Bitmap result
= null
;
452 if (params
.length
!= 1) return result
;
453 String storagePath
= params
[0];
455 // set desired options that will affect the size of the bitmap
456 BitmapFactory
.Options options
= new Options();
457 options
.inScaled
= true
;
458 options
.inPurgeable
= true
;
459 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
460 options
.inPreferQualityOverSpeed
= false
;
462 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
463 options
.inMutable
= false
;
465 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
466 options
.inJustDecodeBounds
= true
;
467 BitmapFactory
.decodeFile(storagePath
, options
);
469 int width
= options
.outWidth
;
470 int height
= options
.outHeight
;
473 Display display
= getActivity().getWindowManager().getDefaultDisplay();
474 Point size
= new Point();
477 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
478 display
.getSize(size
);
479 screenWidth
= size
.x
;
480 screenHeight
= size
.y
;
482 screenWidth
= display
.getWidth();
483 screenHeight
= display
.getHeight();
486 if (width
> screenWidth
) {
487 // second try to scale down the image , this time depending upon the screen size
488 scale
= (int) Math
.floor((float)width
/ screenWidth
);
490 if (height
> screenHeight
) {
491 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
493 options
.inSampleSize
= scale
;
495 // really load the bitmap
496 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
497 result
= BitmapFactory
.decodeFile(storagePath
, options
);
498 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
500 if (result
== null
) {
501 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
502 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
505 } catch (OutOfMemoryError e
) {
506 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
507 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
509 } catch (NoSuchFieldError e
) {
510 mErrorMessageId
= R
.string
.common_error_unknown
;
511 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
513 } catch (Throwable t
) {
514 mErrorMessageId
= R
.string
.common_error_unknown
;
515 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
522 protected void onPostExecute(Bitmap result
) {
524 if (result
!= null
) {
525 showLoadedImage(result
);
531 private void showLoadedImage(Bitmap result
) {
532 if (mImageViewRef
!= null
) {
533 final ImageView imageView
= mImageViewRef
.get();
534 if (imageView
!= null
) {
535 imageView
.setImageBitmap(result
);
536 imageView
.setVisibility(View
.VISIBLE
);
538 } // else , silently finish, the fragment was destroyed
540 if (mMessageViewRef
!= null
) {
541 final TextView messageView
= mMessageViewRef
.get();
542 if (messageView
!= null
) {
543 messageView
.setVisibility(View
.GONE
);
544 } // else , silently finish, the fragment was destroyed
548 private void showErrorMessage() {
549 if (mImageViewRef
!= null
) {
550 final ImageView imageView
= mImageViewRef
.get();
551 if (imageView
!= null
) {
552 // shows the default error icon
553 imageView
.setVisibility(View
.VISIBLE
);
554 } // else , silently finish, the fragment was destroyed
556 if (mMessageViewRef
!= null
) {
557 final TextView messageView
= mMessageViewRef
.get();
558 if (messageView
!= null
) {
559 messageView
.setText(mErrorMessageId
);
560 messageView
.setVisibility(View
.VISIBLE
);
561 } // else , silently finish, the fragment was destroyed
565 private void hideProgressWheel() {
566 if (mProgressWheelRef
!= null
) {
567 final ProgressBar progressWheel
= mProgressWheelRef
.get();
568 if (progressWheel
!= null
) {
569 progressWheel
.setVisibility(View
.GONE
);
577 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
579 * @param file File to test if can be previewed.
580 * @return 'True' if the file can be handled by the fragment.
582 public static boolean canBePreviewed(OCFile file
) {
583 return (file
!= null
&& file
.isImage());
591 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
592 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
593 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
597 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
598 ((PreviewImageActivity
) getActivity()).dismissLoadingDialog();
600 if (result
.isSuccess()) {
601 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
606 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
608 if (result
.isSslRecoverableException()) {
609 // TODO show the SSL warning dialog
615 * Finishes the preview
617 private void finish() {
618 Activity container
= getActivity();