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
.fragment
.ConfirmationDialogFragment
;
60 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
62 import com
.owncloud
.android
.Log_OC
;
63 import com
.owncloud
.android
.R
;
64 import eu
.alefzero
.webdav
.WebdavUtils
;
68 * This fragment shows a preview of a downloaded image.
70 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
72 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
74 * @author David A. Velasco
76 public class PreviewImageFragment
extends FileFragment
implements OnRemoteOperationListener
,
77 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
78 public static final String EXTRA_FILE
= "FILE";
79 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
82 private Account mAccount
;
83 private FileDataStorageManager mStorageManager
;
84 private ImageView mImageView
;
85 private TextView mMessageView
;
86 private ProgressBar mProgressWheel
;
88 public Bitmap mBitmap
= null
;
90 private Handler mHandler
;
91 private RemoteOperation mLastRemoteOperation
;
93 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
95 private boolean mIgnoreFirstSavedState
;
99 * Creates a fragment to preview an image.
101 * When 'imageFile' or 'ocAccount' are null
103 * @param imageFile An {@link OCFile} to preview as an image in the fragment
104 * @param ocAccount An ownCloud account; needed to start downloads
105 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
107 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
109 mAccount
= ocAccount
;
110 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
111 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
116 * Creates an empty fragment for image previews.
118 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
120 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
122 public PreviewImageFragment() {
125 mStorageManager
= null
;
126 mIgnoreFirstSavedState
= false
;
134 public void onCreate(Bundle savedInstanceState
) {
135 super.onCreate(savedInstanceState
);
136 mHandler
= new Handler();
137 setHasOptionsMenu(true
);
145 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
146 Bundle savedInstanceState
) {
147 super.onCreateView(inflater
, container
, savedInstanceState
);
148 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
149 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
150 mImageView
.setVisibility(View
.GONE
);
151 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
152 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
153 mMessageView
.setVisibility(View
.GONE
);
154 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
155 mProgressWheel
.setVisibility(View
.VISIBLE
);
164 public void onAttach(Activity activity
) {
165 super.onAttach(activity
);
166 if (!(activity
instanceof FileFragment
.ContainerActivity
))
167 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
175 public void onActivityCreated(Bundle savedInstanceState
) {
176 super.onActivityCreated(savedInstanceState
);
177 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
178 if (savedInstanceState
!= null
) {
179 if (!mIgnoreFirstSavedState
) {
180 setFile((OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
));
181 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
183 mIgnoreFirstSavedState
= false
;
186 if (getFile() == null
) {
187 throw new IllegalStateException("Instanced with a NULL OCFile");
189 if (mAccount
== null
) {
190 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
192 if (!getFile().isDown()) {
193 throw new IllegalStateException("There is no local file to preview");
202 public void onSaveInstanceState(Bundle outState
) {
203 super.onSaveInstanceState(outState
);
204 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
205 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
210 public void onStart() {
212 if (getFile() != null
) {
213 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
214 bl
.execute(new String
[]{getFile().getStoragePath()});
223 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
224 super.onCreateOptionsMenu(menu
, inflater
);
226 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
227 List
<Integer
> toHide
= new ArrayList
<Integer
>();
229 MenuItem item
= null
;
230 toHide
.add(R
.id
.action_cancel_download
);
231 toHide
.add(R
.id
.action_cancel_upload
);
232 toHide
.add(R
.id
.action_download_file
);
233 toHide
.add(R
.id
.action_rename_file
); // by now
235 for (int i
: toHide
) {
236 item
= menu
.findItem(i
);
238 item
.setVisible(false
);
239 item
.setEnabled(false
);
250 public boolean onOptionsItemSelected(MenuItem item
) {
251 switch (item
.getItemId()) {
252 case R
.id
.action_open_file_with
: {
256 case R
.id
.action_remove_file
: {
260 case R
.id
.action_see_details
: {
271 private void seeDetails() {
272 ((FileFragment
.ContainerActivity
)getActivity()).showDetails(getFile());
277 public void onResume() {
283 public void onPause() {
289 public void onDestroy() {
291 if (mBitmap
!= null
) {
298 * Opens the previewed image with an external application.
300 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
301 * we should get a list of available apps for MIME tpye in the server and join it with the list of
302 * available apps for the MIME type known from the file extension, to let the user choose
304 private void openFile() {
305 OCFile file
= getFile();
306 String storagePath
= file
.getStoragePath();
307 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
309 Intent i
= new Intent(Intent
.ACTION_VIEW
);
310 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), file
.getMimetype());
311 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
314 } catch (Throwable t
) {
315 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file
.getMimetype());
316 boolean toastIt
= true
;
317 String mimeType
= "";
319 Intent i
= new Intent(Intent
.ACTION_VIEW
);
320 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
321 if (mimeType
== null
|| !mimeType
.equals(file
.getMimetype())) {
322 if (mimeType
!= null
) {
323 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
326 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
328 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
333 } catch (IndexOutOfBoundsException e
) {
334 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
336 } catch (ActivityNotFoundException e
) {
337 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
339 } catch (Throwable th
) {
340 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
344 Toast
.makeText(getActivity(), "There is no application to handle file " + file
.getFileName(), Toast
.LENGTH_SHORT
).show();
354 * Starts a the removal of the previewed file.
356 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
357 * depending upon the user selection in the dialog.
359 private void removeFile() {
360 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
361 R
.string
.confirmation_remove_alert
,
362 new String
[]{getFile().getFileName()},
363 R
.string
.confirmation_remove_remote_and_local
,
364 R
.string
.confirmation_remove_local
,
365 R
.string
.common_cancel
);
366 confDialog
.setOnConfirmationListener(this);
367 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
372 * Performs the removal of the previewed file, both locally and in the server.
375 public void onConfirmation(String callerTag
) {
376 if (mStorageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
377 mLastRemoteOperation
= new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
380 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
382 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
388 * Removes the file from local storage
391 public void onNeutral(String callerTag
) {
392 // TODO this code should be made in a secondary thread,
393 OCFile file
= getFile();
394 if (file
.isDown()) { // checks it is still there
395 File f
= new File(file
.getStoragePath());
397 file
.setStoragePath(null
);
398 mStorageManager
.saveFile(file
);
404 * User cancelled the removal action.
407 public void onCancel(String callerTag
) {
408 // nothing to do here
412 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
415 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
417 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
419 private final WeakReference
<ImageView
> mImageViewRef
;
422 * Weak reference to the target {@link TextView} where error messages will be written.
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
<TextView
> mMessageViewRef
;
430 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
432 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
434 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
438 * Error message to show when a load fails
440 private int mErrorMessageId
;
446 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
448 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
449 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
450 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
451 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
455 @SuppressWarnings("deprecation")
456 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
458 protected Bitmap
doInBackground(String
... params
) {
459 Bitmap result
= null
;
460 if (params
.length
!= 1) return result
;
461 String storagePath
= params
[0];
463 // set desired options that will affect the size of the bitmap
464 BitmapFactory
.Options options
= new Options();
465 options
.inScaled
= true
;
466 options
.inPurgeable
= true
;
467 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
468 options
.inPreferQualityOverSpeed
= false
;
470 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
471 options
.inMutable
= false
;
473 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
474 options
.inJustDecodeBounds
= true
;
475 BitmapFactory
.decodeFile(storagePath
, options
);
477 int width
= options
.outWidth
;
478 int height
= options
.outHeight
;
481 Display display
= getActivity().getWindowManager().getDefaultDisplay();
482 Point size
= new Point();
485 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
486 display
.getSize(size
);
487 screenWidth
= size
.x
;
488 screenHeight
= size
.y
;
490 screenWidth
= display
.getWidth();
491 screenHeight
= display
.getHeight();
494 if (width
> screenWidth
) {
495 // second try to scale down the image , this time depending upon the screen size
496 scale
= (int) Math
.floor((float)width
/ screenWidth
);
498 if (height
> screenHeight
) {
499 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
501 options
.inSampleSize
= scale
;
503 // really load the bitmap
504 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
505 result
= BitmapFactory
.decodeFile(storagePath
, options
);
506 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
508 if (result
== null
) {
509 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
510 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
513 } catch (OutOfMemoryError e
) {
514 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
515 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
517 } catch (NoSuchFieldError e
) {
518 mErrorMessageId
= R
.string
.common_error_unknown
;
519 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
521 } catch (Throwable t
) {
522 mErrorMessageId
= R
.string
.common_error_unknown
;
523 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
530 protected void onPostExecute(Bitmap result
) {
532 if (result
!= null
) {
533 showLoadedImage(result
);
539 private void showLoadedImage(Bitmap result
) {
540 if (mImageViewRef
!= null
) {
541 final ImageView imageView
= mImageViewRef
.get();
542 if (imageView
!= null
) {
543 imageView
.setImageBitmap(result
);
544 imageView
.setVisibility(View
.VISIBLE
);
546 } // else , silently finish, the fragment was destroyed
548 if (mMessageViewRef
!= null
) {
549 final TextView messageView
= mMessageViewRef
.get();
550 if (messageView
!= null
) {
551 messageView
.setVisibility(View
.GONE
);
552 } // else , silently finish, the fragment was destroyed
556 private void showErrorMessage() {
557 if (mImageViewRef
!= null
) {
558 final ImageView imageView
= mImageViewRef
.get();
559 if (imageView
!= null
) {
560 // shows the default error icon
561 imageView
.setVisibility(View
.VISIBLE
);
562 } // else , silently finish, the fragment was destroyed
564 if (mMessageViewRef
!= null
) {
565 final TextView messageView
= mMessageViewRef
.get();
566 if (messageView
!= null
) {
567 messageView
.setText(mErrorMessageId
);
568 messageView
.setVisibility(View
.VISIBLE
);
569 } // else , silently finish, the fragment was destroyed
573 private void hideProgressWheel() {
574 if (mProgressWheelRef
!= null
) {
575 final ProgressBar progressWheel
= mProgressWheelRef
.get();
576 if (progressWheel
!= null
) {
577 progressWheel
.setVisibility(View
.GONE
);
585 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
587 * @param file File to test if can be previewed.
588 * @return 'True' if the file can be handled by the fragment.
590 public static boolean canBePreviewed(OCFile file
) {
591 return (file
!= null
&& file
.isImage());
599 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
600 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
601 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
605 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
606 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
608 if (result
.isSuccess()) {
609 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
614 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
616 if (result
.isSslRecoverableException()) {
617 // TODO show the SSL warning dialog
623 * Finishes the preview
625 private void finish() {
626 Activity container
= getActivity();