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
.Toast
;
50 import com
.actionbarsherlock
.app
.SherlockFragment
;
51 import com
.actionbarsherlock
.view
.Menu
;
52 import com
.actionbarsherlock
.view
.MenuInflater
;
53 import com
.actionbarsherlock
.view
.MenuItem
;
54 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
55 import com
.owncloud
.android
.datamodel
.OCFile
;
56 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
57 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
58 import com
.owncloud
.android
.operations
.RemoteOperation
;
59 import com
.owncloud
.android
.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
;
64 import com
.owncloud
.android
.R
;
65 import eu
.alefzero
.webdav
.WebdavClient
;
66 import eu
.alefzero
.webdav
.WebdavUtils
;
70 * This fragment shows a preview of a downloaded image.
72 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
74 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
76 * @author David A. Velasco
78 public class PreviewImageFragment
extends SherlockFragment
implements FileFragment
,
79 OnRemoteOperationListener
,
80 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
81 public static final String EXTRA_FILE
= "FILE";
82 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
86 private Account mAccount
;
87 private FileDataStorageManager mStorageManager
;
88 private ImageView mImageView
;
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
;
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
) {
108 mFile
= fileToDetail
;
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 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT
159 public void onAttach(Activity activity
) {
160 super.onAttach(activity
);
161 if (!(activity
instanceof FileFragment
.ContainerActivity
))
162 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
170 public void onActivityCreated(Bundle savedInstanceState
) {
171 super.onActivityCreated(savedInstanceState
);
172 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
173 if (savedInstanceState
!= null
) {
174 if (!mIgnoreFirstSavedState
) {
175 mFile
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
176 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
178 mIgnoreFirstSavedState
= false
;
182 throw new IllegalStateException("Instanced with a NULL OCFile");
184 if (mAccount
== null
) {
185 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
187 if (!mFile
.isDown()) {
188 throw new IllegalStateException("There is no local file to preview");
197 public void onSaveInstanceState(Bundle outState
) {
198 super.onSaveInstanceState(outState
);
199 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, mFile
);
200 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
205 public void onStart() {
208 BitmapLoader bl
= new BitmapLoader(mImageView
);
209 bl
.execute(new String
[]{mFile
.getStoragePath()});
218 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
219 super.onCreateOptionsMenu(menu
, inflater
);
221 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
222 List
<Integer
> toHide
= new ArrayList
<Integer
>();
224 MenuItem item
= null
;
225 toHide
.add(R
.id
.action_cancel_download
);
226 toHide
.add(R
.id
.action_cancel_upload
);
227 toHide
.add(R
.id
.action_download_file
);
228 toHide
.add(R
.id
.action_rename_file
); // by now
230 for (int i
: toHide
) {
231 item
= menu
.findItem(i
);
233 item
.setVisible(false
);
234 item
.setEnabled(false
);
245 public boolean onOptionsItemSelected(MenuItem item
) {
246 switch (item
.getItemId()) {
247 case R
.id
.action_open_file_with
: {
251 case R
.id
.action_remove_file
: {
255 case R
.id
.action_see_details
: {
266 private void seeDetails() {
267 ((FileFragment
.ContainerActivity
)getActivity()).showFragmentWithDetails(mFile
);
272 public void onResume() {
275 mDownloadFinishReceiver = new DownloadFinishReceiver();
276 IntentFilter filter = new IntentFilter(
277 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
278 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
280 mUploadFinishReceiver = new UploadFinishReceiver();
281 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
282 getActivity().registerReceiver(mUploadFinishReceiver, filter);
289 public void onPause() {
292 if (mVideoPreview.getVisibility() == View.VISIBLE) {
293 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
296 getActivity().unregisterReceiver(mDownloadFinishReceiver);
297 mDownloadFinishReceiver = null;
299 getActivity().unregisterReceiver(mUploadFinishReceiver);
300 mUploadFinishReceiver = null;
306 public void onDestroy() {
308 if (mBitmap
!= null
) {
315 * Opens the previewed image with an external application.
317 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
318 * we should get a list of available apps for MIME tpye in the server and join it with the list of
319 * available apps for the MIME type known from the file extension, to let the user choose
321 private void openFile() {
322 String storagePath
= mFile
.getStoragePath();
323 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
325 Intent i
= new Intent(Intent
.ACTION_VIEW
);
326 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
327 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
330 } catch (Throwable t
) {
331 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
332 boolean toastIt
= true
;
333 String mimeType
= "";
335 Intent i
= new Intent(Intent
.ACTION_VIEW
);
336 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
337 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
338 if (mimeType
!= null
) {
339 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
342 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
344 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
349 } catch (IndexOutOfBoundsException e
) {
350 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
352 } catch (ActivityNotFoundException e
) {
353 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
355 } catch (Throwable th
) {
356 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
360 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
370 * Starts a the removal of the previewed file.
372 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
373 * depending upon the user selection in the dialog.
375 private void removeFile() {
376 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
377 R
.string
.confirmation_remove_alert
,
378 new String
[]{mFile
.getFileName()},
379 R
.string
.confirmation_remove_remote_and_local
,
380 R
.string
.confirmation_remove_local
,
381 R
.string
.common_cancel
);
382 confDialog
.setOnConfirmationListener(this);
383 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
388 * Performs the removal of the previewed file, both locally and in the server.
391 public void onConfirmation(String callerTag
) {
392 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
393 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
396 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
397 mLastRemoteOperation
.execute(wc
, this, mHandler
);
399 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
405 * Removes the file from local storage
408 public void onNeutral(String callerTag
) {
409 // TODO this code should be made in a secondary thread,
410 if (mFile
.isDown()) { // checks it is still there
411 File f
= new File(mFile
.getStoragePath());
413 mFile
.setStoragePath(null
);
414 mStorageManager
.saveFile(mFile
);
420 * User cancelled the removal action.
423 public void onCancel(String callerTag
) {
424 // nothing to do here
431 public OCFile
getFile(){
437 * Use this method to signal this Activity that it shall update its view.
439 * @param file : An {@link OCFile}
441 public void updateFileDetails(OCFile file, Account ocAccount) {
443 if (ocAccount != null && (
444 mStorageManager == null ||
445 (mAccount != null && !mAccount.equals(ocAccount))
447 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
449 mAccount = ocAccount;
450 updateFileDetails(false);
455 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
458 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
460 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
462 private final WeakReference
<ImageView
> mImageViewRef
;
468 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
470 public BitmapLoader(ImageView imageView
) {
471 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
475 @SuppressWarnings("deprecation")
476 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
478 protected Bitmap
doInBackground(String
... params
) {
479 Bitmap result
= null
;
480 if (params
.length
!= 1) return result
;
481 String storagePath
= params
[0];
483 // set desired options that will affect the size of the bitmap
484 BitmapFactory
.Options options
= new Options();
485 options
.inScaled
= true
;
486 options
.inPurgeable
= true
;
487 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
488 options
.inPreferQualityOverSpeed
= false
;
490 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
491 options
.inMutable
= false
;
493 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
494 options
.inJustDecodeBounds
= true
;
495 BitmapFactory
.decodeFile(storagePath
, options
);
497 int width
= options
.outWidth
;
498 int height
= options
.outHeight
;
500 if (width
>= 2048 || height
>= 2048) {
501 // try to scale down the image to save memory
502 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
503 options
.inSampleSize
= scale
;
505 Display display
= getActivity().getWindowManager().getDefaultDisplay();
506 Point size
= new Point();
508 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
509 display
.getSize(size
);
510 screenwidth
= size
.x
;
512 screenwidth
= display
.getWidth();
515 Log
.d(TAG
, "image width: " + width
+ ", screen width: " + screenwidth
);
517 if (width
> screenwidth
) {
518 // second try to scale down the image , this time depending upon the screen size; WTF...
519 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
520 options
.inSampleSize
= scale
;
523 // really load the bitmap
524 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
525 result
= BitmapFactory
.decodeFile(storagePath
, options
);
526 Log
.e(TAG
, "loaded width: " + options
.outWidth
+ ", loaded height: " + options
.outHeight
);
528 } catch (OutOfMemoryError e
) {
530 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
532 } catch (NoSuchFieldError e
) {
534 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
536 } catch (Throwable t
) {
538 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
544 protected void onPostExecute(Bitmap result
) {
545 if (result
!= null
&& mImageViewRef
!= null
) {
546 final ImageView imageView
= mImageViewRef
.get();
547 imageView
.setImageBitmap(result
);
555 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
557 * @param file File to test if can be previewed.
558 * @return 'True' if the file can be handled by the fragment.
560 public static boolean canBePreviewed(OCFile file
) {
561 return (file
!= null
&& file
.isImage());
568 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
569 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
570 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
574 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
575 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
577 if (result
.isSuccess()) {
578 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
583 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
585 if (result
.isSslRecoverableException()) {
586 // TODO show the SSL warning dialog
592 * Finishes the preview
594 private void finish() {
595 Activity container
= getActivity();