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
.R
;
54 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
55 import com
.owncloud
.android
.datamodel
.OCFile
;
56 import com
.owncloud
.android
.oc_framework
.network
.webdav
.WebdavUtils
;
57 import com
.owncloud
.android
.oc_framework
.operations
.OnRemoteOperationListener
;
58 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperation
;
59 import com
.owncloud
.android
.oc_framework
.operations
.RemoteOperationResult
;
60 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
61 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
62 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
63 import com
.owncloud
.android
.utils
.Log_OC
;
67 * This fragment shows a preview of a downloaded image.
69 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
71 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
73 * @author David A. Velasco
75 public class PreviewImageFragment
extends FileFragment
implements OnRemoteOperationListener
,
76 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
77 public static final String EXTRA_FILE
= "FILE";
78 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
81 private Account mAccount
;
82 private FileDataStorageManager mStorageManager
;
83 private ImageView mImageView
;
84 private TextView mMessageView
;
85 private ProgressBar mProgressWheel
;
87 public Bitmap mBitmap
= null
;
89 private Handler mHandler
;
90 private RemoteOperation mLastRemoteOperation
;
92 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
94 private boolean mIgnoreFirstSavedState
;
98 * Creates a fragment to preview an image.
100 * When 'imageFile' or 'ocAccount' are null
102 * @param imageFile An {@link OCFile} to preview as an image in the fragment
103 * @param ocAccount An ownCloud account; needed to start downloads
104 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
106 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
108 mAccount
= ocAccount
;
109 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
110 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
115 * Creates an empty fragment for image previews.
117 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
119 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
121 public PreviewImageFragment() {
124 mStorageManager
= null
;
125 mIgnoreFirstSavedState
= false
;
133 public void onCreate(Bundle savedInstanceState
) {
134 super.onCreate(savedInstanceState
);
135 mHandler
= new Handler();
136 setHasOptionsMenu(true
);
144 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
145 Bundle savedInstanceState
) {
146 super.onCreateView(inflater
, container
, savedInstanceState
);
147 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
148 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
149 mImageView
.setVisibility(View
.GONE
);
150 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
151 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
152 mMessageView
.setVisibility(View
.GONE
);
153 mProgressWheel
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
);
154 mProgressWheel
.setVisibility(View
.VISIBLE
);
163 public void onAttach(Activity activity
) {
164 super.onAttach(activity
);
165 if (!(activity
instanceof FileFragment
.ContainerActivity
))
166 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
174 public void onActivityCreated(Bundle savedInstanceState
) {
175 super.onActivityCreated(savedInstanceState
);
176 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
177 if (savedInstanceState
!= null
) {
178 if (!mIgnoreFirstSavedState
) {
179 setFile((OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
));
180 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
182 mIgnoreFirstSavedState
= false
;
185 if (getFile() == null
) {
186 throw new IllegalStateException("Instanced with a NULL OCFile");
188 if (mAccount
== null
) {
189 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
191 if (!getFile().isDown()) {
192 throw new IllegalStateException("There is no local file to preview");
201 public void onSaveInstanceState(Bundle outState
) {
202 super.onSaveInstanceState(outState
);
203 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile());
204 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
209 public void onStart() {
211 if (getFile() != null
) {
212 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
);
213 bl
.execute(new String
[]{getFile().getStoragePath()});
222 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
223 super.onCreateOptionsMenu(menu
, inflater
);
225 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
226 List
<Integer
> toHide
= new ArrayList
<Integer
>();
228 MenuItem item
= null
;
229 toHide
.add(R
.id
.action_cancel_download
);
230 toHide
.add(R
.id
.action_cancel_upload
);
231 toHide
.add(R
.id
.action_download_file
);
232 toHide
.add(R
.id
.action_rename_file
); // by now
234 for (int i
: toHide
) {
235 item
= menu
.findItem(i
);
237 item
.setVisible(false
);
238 item
.setEnabled(false
);
249 public boolean onOptionsItemSelected(MenuItem item
) {
250 switch (item
.getItemId()) {
251 case R
.id
.action_open_file_with
: {
255 case R
.id
.action_remove_file
: {
259 case R
.id
.action_see_details
: {
270 private void seeDetails() {
271 ((FileFragment
.ContainerActivity
)getActivity()).showDetails(getFile());
276 public void onResume() {
282 public void onPause() {
288 public void onDestroy() {
290 if (mBitmap
!= null
) {
297 * Opens the previewed image with an external application.
299 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
300 * we should get a list of available apps for MIME tpye in the server and join it with the list of
301 * available apps for the MIME type known from the file extension, to let the user choose
303 private void openFile() {
304 OCFile file
= getFile();
305 String storagePath
= file
.getStoragePath();
306 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
308 Intent i
= new Intent(Intent
.ACTION_VIEW
);
309 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), file
.getMimetype());
310 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
313 } catch (Throwable t
) {
314 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file
.getMimetype());
315 boolean toastIt
= true
;
316 String mimeType
= "";
318 Intent i
= new Intent(Intent
.ACTION_VIEW
);
319 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
320 if (mimeType
== null
|| !mimeType
.equals(file
.getMimetype())) {
321 if (mimeType
!= null
) {
322 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
325 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
327 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
332 } catch (IndexOutOfBoundsException e
) {
333 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
335 } catch (ActivityNotFoundException e
) {
336 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
338 } catch (Throwable th
) {
339 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
343 Toast
.makeText(getActivity(), "There is no application to handle file " + file
.getFileName(), Toast
.LENGTH_SHORT
).show();
353 * Starts a the removal of the previewed file.
355 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
356 * depending upon the user selection in the dialog.
358 private void removeFile() {
359 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
360 R
.string
.confirmation_remove_alert
,
361 new String
[]{getFile().getFileName()},
362 R
.string
.confirmation_remove_remote_and_local
,
363 R
.string
.confirmation_remove_local
,
364 R
.string
.common_cancel
);
365 confDialog
.setOnConfirmationListener(this);
366 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
371 * Performs the removal of the previewed file, both locally and in the server.
374 public void onConfirmation(String callerTag
) {
375 if (mStorageManager
.getFileById(getFile().getFileId()) != null
) { // check that the file is still there;
376 mLastRemoteOperation
= new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
379 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
381 ((PreviewImageActivity
) getActivity()).showLoadingDialog();
387 * Removes the file from local storage
390 public void onNeutral(String callerTag
) {
391 // TODO this code should be made in a secondary thread,
392 OCFile file
= getFile();
393 if (file
.isDown()) { // checks it is still there
394 File f
= new File(file
.getStoragePath());
396 file
.setStoragePath(null
);
397 mStorageManager
.saveFile(file
);
403 * User cancelled the removal action.
406 public void onCancel(String callerTag
) {
407 // nothing to do here
411 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
414 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
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
<ImageView
> mImageViewRef
;
421 * Weak reference to the target {@link TextView} where error messages will be written.
423 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
425 private final WeakReference
<TextView
> mMessageViewRef
;
429 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
431 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
433 private final WeakReference
<ProgressBar
> mProgressWheelRef
;
437 * Error message to show when a load fails
439 private int mErrorMessageId
;
445 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
447 public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) {
448 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
449 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
450 mProgressWheelRef
= new WeakReference
<ProgressBar
>(progressWheel
);
454 @SuppressWarnings("deprecation")
455 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
457 protected Bitmap
doInBackground(String
... params
) {
458 Bitmap result
= null
;
459 if (params
.length
!= 1) return result
;
460 String storagePath
= params
[0];
462 // set desired options that will affect the size of the bitmap
463 BitmapFactory
.Options options
= new Options();
464 options
.inScaled
= true
;
465 options
.inPurgeable
= true
;
466 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
467 options
.inPreferQualityOverSpeed
= false
;
469 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
470 options
.inMutable
= false
;
472 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
473 options
.inJustDecodeBounds
= true
;
474 BitmapFactory
.decodeFile(storagePath
, options
);
476 int width
= options
.outWidth
;
477 int height
= options
.outHeight
;
480 Display display
= getActivity().getWindowManager().getDefaultDisplay();
481 Point size
= new Point();
484 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
485 display
.getSize(size
);
486 screenWidth
= size
.x
;
487 screenHeight
= size
.y
;
489 screenWidth
= display
.getWidth();
490 screenHeight
= display
.getHeight();
493 if (width
> screenWidth
) {
494 // second try to scale down the image , this time depending upon the screen size
495 scale
= (int) Math
.floor((float)width
/ screenWidth
);
497 if (height
> screenHeight
) {
498 scale
= Math
.max(scale
, (int) Math
.floor((float)height
/ screenHeight
));
500 options
.inSampleSize
= scale
;
502 // really load the bitmap
503 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
504 result
= BitmapFactory
.decodeFile(storagePath
, options
);
505 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
507 if (result
== null
) {
508 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
509 Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
);
512 } catch (OutOfMemoryError e
) {
513 mErrorMessageId
= R
.string
.preview_image_error_unknown_format
;
514 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
);
516 } catch (NoSuchFieldError e
) {
517 mErrorMessageId
= R
.string
.common_error_unknown
;
518 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
);
520 } catch (Throwable t
) {
521 mErrorMessageId
= R
.string
.common_error_unknown
;
522 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
);
529 protected void onPostExecute(Bitmap result
) {
531 if (result
!= null
) {
532 showLoadedImage(result
);
538 private void showLoadedImage(Bitmap result
) {
539 if (mImageViewRef
!= null
) {
540 final ImageView imageView
= mImageViewRef
.get();
541 if (imageView
!= null
) {
542 imageView
.setImageBitmap(result
);
543 imageView
.setVisibility(View
.VISIBLE
);
545 } // else , silently finish, the fragment was destroyed
547 if (mMessageViewRef
!= null
) {
548 final TextView messageView
= mMessageViewRef
.get();
549 if (messageView
!= null
) {
550 messageView
.setVisibility(View
.GONE
);
551 } // else , silently finish, the fragment was destroyed
555 private void showErrorMessage() {
556 if (mImageViewRef
!= null
) {
557 final ImageView imageView
= mImageViewRef
.get();
558 if (imageView
!= null
) {
559 // shows the default error icon
560 imageView
.setVisibility(View
.VISIBLE
);
561 } // else , silently finish, the fragment was destroyed
563 if (mMessageViewRef
!= null
) {
564 final TextView messageView
= mMessageViewRef
.get();
565 if (messageView
!= null
) {
566 messageView
.setText(mErrorMessageId
);
567 messageView
.setVisibility(View
.VISIBLE
);
568 } // else , silently finish, the fragment was destroyed
572 private void hideProgressWheel() {
573 if (mProgressWheelRef
!= null
) {
574 final ProgressBar progressWheel
= mProgressWheelRef
.get();
575 if (progressWheel
!= null
) {
576 progressWheel
.setVisibility(View
.GONE
);
584 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
586 * @param file File to test if can be previewed.
587 * @return 'True' if the file can be handled by the fragment.
589 public static boolean canBePreviewed(OCFile file
) {
590 return (file
!= null
&& file
.isImage());
598 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
599 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
600 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
604 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
605 ((PreviewImageActivity
) getActivity()).dismissLoadingDialog();
607 if (result
.isSuccess()) {
608 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
613 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
615 if (result
.isSslRecoverableException()) {
616 // TODO show the SSL warning dialog
622 * Finishes the preview
624 private void finish() {
625 Activity container
= getActivity();