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
.ViewGroup
;
45 import android
.webkit
.MimeTypeMap
;
46 import android
.widget
.ImageView
;
47 import android
.widget
.Toast
;
49 import com
.actionbarsherlock
.app
.SherlockFragment
;
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
.network
.OwnCloudClientUtils
;
56 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
57 import com
.owncloud
.android
.operations
.RemoteOperation
;
58 import com
.owncloud
.android
.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
;
63 import com
.owncloud
.android
.R
;
64 import eu
.alefzero
.webdav
.WebdavClient
;
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 SherlockFragment
implements FileFragment
,
78 OnRemoteOperationListener
,
79 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
80 public static final String EXTRA_FILE
= "FILE";
81 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
85 private Account mAccount
;
86 private FileDataStorageManager mStorageManager
;
87 private ImageView mImageView
;
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
;
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
) {
107 mFile
= fileToDetail
;
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 Log
.e(TAG
, "PREVIEW_IMAGE_FRAGMENT ONCREATE " + ((mFile
== null
)?
"(NULL)" : mFile
.getFileName()));
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
);
158 public void onAttach(Activity activity
) {
159 super.onAttach(activity
);
160 if (!(activity
instanceof FileFragment
.ContainerActivity
))
161 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
169 public void onActivityCreated(Bundle savedInstanceState
) {
170 super.onActivityCreated(savedInstanceState
);
171 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
172 if (savedInstanceState
!= null
) {
173 if (!mIgnoreFirstSavedState
) {
174 mFile
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
175 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
177 mIgnoreFirstSavedState
= false
;
181 throw new IllegalStateException("Instanced with a NULL OCFile");
183 if (mAccount
== null
) {
184 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
186 if (!mFile
.isDown()) {
187 throw new IllegalStateException("There is no local file to preview");
196 public void onSaveInstanceState(Bundle outState
) {
197 super.onSaveInstanceState(outState
);
198 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, mFile
);
199 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
204 public void onStart() {
206 Log
.e(TAG
, "PREVIEW_IMAGE_FRAGMENT ONSTART " + mFile
.getFileName());
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() {
274 Log
.e(TAG
, "PREVIEW_IMAGE_FRAGMENT ONRESUME " + mFile
.getFileName());
276 mDownloadFinishReceiver = new DownloadFinishReceiver();
277 IntentFilter filter = new IntentFilter(
278 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
279 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
281 mUploadFinishReceiver = new UploadFinishReceiver();
282 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
283 getActivity().registerReceiver(mUploadFinishReceiver, filter);
290 public void onPause() {
291 Log
.e(TAG
, "PREVIEW_IMAGE_FRAGMENT ONPAUSE " + mFile
.getFileName());
294 if (mVideoPreview.getVisibility() == View.VISIBLE) {
295 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
298 getActivity().unregisterReceiver(mDownloadFinishReceiver);
299 mDownloadFinishReceiver = null;
301 getActivity().unregisterReceiver(mUploadFinishReceiver);
302 mUploadFinishReceiver = null;
308 public void onStop() {
310 Log
.e(TAG
, "PREVIEW_IMAGE_FRAGMENT ONSTOP " + mFile
.getFileName());
314 public void onDestroy() {
316 Log
.e(TAG
, "PREVIEW_IMAGE_FRAGMENT ONDESTROY " + mFile
.getFileName());
317 if (mBitmap
!= null
) {
324 * Opens the previewed image with an external application.
326 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
327 * we should get a list of available apps for MIME tpye in the server and join it with the list of
328 * available apps for the MIME type known from the file extension, to let the user choose
330 private void openFile() {
331 String storagePath
= mFile
.getStoragePath();
332 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
334 Intent i
= new Intent(Intent
.ACTION_VIEW
);
335 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
336 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
339 } catch (Throwable t
) {
340 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
341 boolean toastIt
= true
;
342 String mimeType
= "";
344 Intent i
= new Intent(Intent
.ACTION_VIEW
);
345 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
346 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
347 if (mimeType
!= null
) {
348 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
351 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
353 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
358 } catch (IndexOutOfBoundsException e
) {
359 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
361 } catch (ActivityNotFoundException e
) {
362 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
364 } catch (Throwable th
) {
365 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
369 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
379 * Starts a the removal of the previewed file.
381 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
382 * depending upon the user selection in the dialog.
384 private void removeFile() {
385 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
386 R
.string
.confirmation_remove_alert
,
387 new String
[]{mFile
.getFileName()},
388 R
.string
.confirmation_remove_remote_and_local
,
389 R
.string
.confirmation_remove_local
,
390 R
.string
.common_cancel
);
391 confDialog
.setOnConfirmationListener(this);
392 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
397 * Performs the removal of the previewed file, both locally and in the server.
400 public void onConfirmation(String callerTag
) {
401 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
402 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
405 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
406 mLastRemoteOperation
.execute(wc
, this, mHandler
);
408 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
414 * Removes the file from local storage
417 public void onNeutral(String callerTag
) {
418 // TODO this code should be made in a secondary thread,
419 if (mFile
.isDown()) { // checks it is still there
420 File f
= new File(mFile
.getStoragePath());
422 mFile
.setStoragePath(null
);
423 mStorageManager
.saveFile(mFile
);
429 * User cancelled the removal action.
432 public void onCancel(String callerTag
) {
433 // nothing to do here
440 public OCFile
getFile(){
446 * Use this method to signal this Activity that it shall update its view.
448 * @param file : An {@link OCFile}
450 public void updateFileDetails(OCFile file, Account ocAccount) {
452 if (ocAccount != null && (
453 mStorageManager == null ||
454 (mAccount != null && !mAccount.equals(ocAccount))
456 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
458 mAccount = ocAccount;
459 updateFileDetails(false);
464 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
467 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
469 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
471 private final WeakReference
<ImageView
> mImageViewRef
;
477 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
479 public BitmapLoader(ImageView imageView
) {
480 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
484 @SuppressWarnings("deprecation")
485 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
487 protected Bitmap
doInBackground(String
... params
) {
488 Bitmap result
= null
;
489 if (params
.length
!= 1) return result
;
490 String storagePath
= params
[0];
492 // set desired options that will affect the size of the bitmap
493 BitmapFactory
.Options options
= new Options();
494 options
.inScaled
= true
;
495 options
.inPurgeable
= true
;
496 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
497 options
.inPreferQualityOverSpeed
= false
;
499 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
500 options
.inMutable
= false
;
502 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
503 options
.inJustDecodeBounds
= true
;
504 BitmapFactory
.decodeFile(storagePath
, options
);
506 int width
= options
.outWidth
;
507 int height
= options
.outHeight
;
509 if (width
>= 2048 || height
>= 2048) {
510 // try to scale down the image to save memory
511 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
512 options
.inSampleSize
= scale
;
514 Display display
= getActivity().getWindowManager().getDefaultDisplay();
515 Point size
= new Point();
517 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
518 display
.getSize(size
);
519 screenwidth
= size
.x
;
521 screenwidth
= display
.getWidth();
524 Log
.d(TAG
, "image width: " + width
+ ", screen width: " + screenwidth
);
526 if (width
> screenwidth
) {
527 // second try to scale down the image , this time depending upon the screen size; WTF...
528 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
529 options
.inSampleSize
= scale
;
532 // really load the bitmap
533 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
534 result
= BitmapFactory
.decodeFile(storagePath
, options
);
535 Log
.e(TAG
, "loaded width: " + options
.outWidth
+ ", loaded height: " + options
.outHeight
);
537 } catch (OutOfMemoryError e
) {
539 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
541 } catch (NoSuchFieldError e
) {
543 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
545 } catch (Throwable t
) {
547 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
553 protected void onPostExecute(Bitmap result
) {
554 if (result
!= null
&& mImageViewRef
!= null
) {
555 final ImageView imageView
= mImageViewRef
.get();
556 imageView
.setImageBitmap(result
);
564 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
566 * @param file File to test if can be previewed.
567 * @return 'True' if the file can be handled by the fragment.
569 public static boolean canBePreviewed(OCFile file
) {
570 return (file
!= null
&& file
.isImage());
577 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
578 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
579 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
583 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
584 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
586 if (result
.isSuccess()) {
587 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
592 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
594 if (result
.isSslRecoverableException()) {
595 // TODO show the SSL warning dialog
601 * Finishes the preview
603 private void finish() {
604 Activity container
= getActivity();