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
.TextView
;
49 import android
.widget
.Toast
;
51 import com
.actionbarsherlock
.app
.SherlockFragment
;
52 import com
.actionbarsherlock
.view
.Menu
;
53 import com
.actionbarsherlock
.view
.MenuInflater
;
54 import com
.actionbarsherlock
.view
.MenuItem
;
55 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
56 import com
.owncloud
.android
.datamodel
.OCFile
;
57 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
58 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
59 import com
.owncloud
.android
.operations
.RemoteOperation
;
60 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
61 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
62 import com
.owncloud
.android
.ui
.fragment
.ConfirmationDialogFragment
;
63 import com
.owncloud
.android
.ui
.fragment
.FileFragment
;
65 import com
.owncloud
.android
.R
;
66 import eu
.alefzero
.webdav
.WebdavClient
;
67 import eu
.alefzero
.webdav
.WebdavUtils
;
71 * This fragment shows a preview of a downloaded image.
73 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
75 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
77 * @author David A. Velasco
79 public class PreviewImageFragment
extends SherlockFragment
implements FileFragment
,
80 OnRemoteOperationListener
,
81 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
82 public static final String EXTRA_FILE
= "FILE";
83 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
87 private Account mAccount
;
88 private FileDataStorageManager mStorageManager
;
89 private ImageView mImageView
;
90 private TextView mMessageView
;
92 public Bitmap mBitmap
= null
;
94 private Handler mHandler
;
95 private RemoteOperation mLastRemoteOperation
;
97 private static final String TAG
= PreviewImageFragment
.class.getSimpleName();
99 private boolean mIgnoreFirstSavedState
;
103 * Creates a fragment to preview an image.
105 * When 'imageFile' or 'ocAccount' are null
107 * @param imageFile An {@link OCFile} to preview as an image in the fragment
108 * @param ocAccount An ownCloud account; needed to start downloads
109 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
111 public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) {
112 mFile
= fileToDetail
;
113 mAccount
= ocAccount
;
114 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
115 mIgnoreFirstSavedState
= ignoreFirstSavedState
;
120 * Creates an empty fragment for image previews.
122 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
124 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
126 public PreviewImageFragment() {
129 mStorageManager
= null
;
130 mIgnoreFirstSavedState
= false
;
138 public void onCreate(Bundle savedInstanceState
) {
139 super.onCreate(savedInstanceState
);
140 mHandler
= new Handler();
141 setHasOptionsMenu(true
);
149 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
150 Bundle savedInstanceState
) {
151 super.onCreateView(inflater
, container
, savedInstanceState
);
152 mView
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
);
153 mImageView
= (ImageView
)mView
.findViewById(R
.id
.image
);
154 mView
.setOnTouchListener((OnTouchListener
)getActivity()); // WATCH OUT THAT CAST
155 mMessageView
= (TextView
)mView
.findViewById(R
.id
.message
);
156 mMessageView
.setVisibility(View
.GONE
);
165 public void onAttach(Activity activity
) {
166 super.onAttach(activity
);
167 if (!(activity
instanceof FileFragment
.ContainerActivity
))
168 throw new ClassCastException(activity
.toString() + " must implement " + FileFragment
.ContainerActivity
.class.getSimpleName());
176 public void onActivityCreated(Bundle savedInstanceState
) {
177 super.onActivityCreated(savedInstanceState
);
178 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
179 if (savedInstanceState
!= null
) {
180 if (!mIgnoreFirstSavedState
) {
181 mFile
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
);
182 mAccount
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
);
184 mIgnoreFirstSavedState
= false
;
188 throw new IllegalStateException("Instanced with a NULL OCFile");
190 if (mAccount
== null
) {
191 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
193 if (!mFile
.isDown()) {
194 throw new IllegalStateException("There is no local file to preview");
203 public void onSaveInstanceState(Bundle outState
) {
204 super.onSaveInstanceState(outState
);
205 outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, mFile
);
206 outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
);
211 public void onStart() {
214 BitmapLoader bl
= new BitmapLoader(mImageView
, mMessageView
);
215 bl
.execute(new String
[]{mFile
.getStoragePath()});
224 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
225 super.onCreateOptionsMenu(menu
, inflater
);
227 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
228 List
<Integer
> toHide
= new ArrayList
<Integer
>();
230 MenuItem item
= null
;
231 toHide
.add(R
.id
.action_cancel_download
);
232 toHide
.add(R
.id
.action_cancel_upload
);
233 toHide
.add(R
.id
.action_download_file
);
234 toHide
.add(R
.id
.action_rename_file
); // by now
236 for (int i
: toHide
) {
237 item
= menu
.findItem(i
);
239 item
.setVisible(false
);
240 item
.setEnabled(false
);
251 public boolean onOptionsItemSelected(MenuItem item
) {
252 switch (item
.getItemId()) {
253 case R
.id
.action_open_file_with
: {
257 case R
.id
.action_remove_file
: {
261 case R
.id
.action_see_details
: {
272 private void seeDetails() {
273 ((FileFragment
.ContainerActivity
)getActivity()).showFragmentWithDetails(mFile
);
278 public void onResume() {
280 Log
.e(TAG
, "FRAGMENT, ONRESUME");
282 mDownloadFinishReceiver = new DownloadFinishReceiver();
283 IntentFilter filter = new IntentFilter(
284 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
285 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
287 mUploadFinishReceiver = new UploadFinishReceiver();
288 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
289 getActivity().registerReceiver(mUploadFinishReceiver, filter);
296 public void onPause() {
299 if (mVideoPreview.getVisibility() == View.VISIBLE) {
300 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
303 getActivity().unregisterReceiver(mDownloadFinishReceiver);
304 mDownloadFinishReceiver = null;
306 getActivity().unregisterReceiver(mUploadFinishReceiver);
307 mUploadFinishReceiver = null;
313 public void onDestroy() {
315 if (mBitmap
!= null
) {
322 * Opens the previewed image with an external application.
324 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
325 * we should get a list of available apps for MIME tpye in the server and join it with the list of
326 * available apps for the MIME type known from the file extension, to let the user choose
328 private void openFile() {
329 String storagePath
= mFile
.getStoragePath();
330 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
332 Intent i
= new Intent(Intent
.ACTION_VIEW
);
333 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
334 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
337 } catch (Throwable t
) {
338 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
339 boolean toastIt
= true
;
340 String mimeType
= "";
342 Intent i
= new Intent(Intent
.ACTION_VIEW
);
343 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
344 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
345 if (mimeType
!= null
) {
346 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
349 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*-/*");
351 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
356 } catch (IndexOutOfBoundsException e
) {
357 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
359 } catch (ActivityNotFoundException e
) {
360 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
362 } catch (Throwable th
) {
363 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
367 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
377 * Starts a the removal of the previewed file.
379 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
380 * depending upon the user selection in the dialog.
382 private void removeFile() {
383 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
384 R
.string
.confirmation_remove_alert
,
385 new String
[]{mFile
.getFileName()},
386 R
.string
.confirmation_remove_remote_and_local
,
387 R
.string
.confirmation_remove_local
,
388 R
.string
.common_cancel
);
389 confDialog
.setOnConfirmationListener(this);
390 confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
);
395 * Performs the removal of the previewed file, both locally and in the server.
398 public void onConfirmation(String callerTag
) {
399 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) { // check that the file is still there;
400 mLastRemoteOperation
= new RemoveFileOperation( mFile
, // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
403 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
404 mLastRemoteOperation
.execute(wc
, this, mHandler
);
406 getActivity().showDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
412 * Removes the file from local storage
415 public void onNeutral(String callerTag
) {
416 // TODO this code should be made in a secondary thread,
417 if (mFile
.isDown()) { // checks it is still there
418 File f
= new File(mFile
.getStoragePath());
420 mFile
.setStoragePath(null
);
421 mStorageManager
.saveFile(mFile
);
427 * User cancelled the removal action.
430 public void onCancel(String callerTag
) {
431 // nothing to do here
438 public OCFile
getFile(){
444 * Use this method to signal this Activity that it shall update its view.
446 * @param file : An {@link OCFile}
448 public void updateFileDetails(OCFile file, Account ocAccount) {
450 if (ocAccount != null && (
451 mStorageManager == null ||
452 (mAccount != null && !mAccount.equals(ocAccount))
454 mStorageManager = new FileDataStorageManager(ocAccount, getActivity().getApplicationContext().getContentResolver());
456 mAccount = ocAccount;
457 updateFileDetails(false);
462 private class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
465 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
467 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
469 private final WeakReference
<ImageView
> mImageViewRef
;
472 * Weak reference to the target {@link TextView} where error messages will be written.
474 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
476 private final WeakReference
<TextView
> mMessageViewRef
;
479 private Throwable mThrowable
;
485 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
487 public BitmapLoader(ImageView imageView
, TextView messageView
) {
488 mImageViewRef
= new WeakReference
<ImageView
>(imageView
);
489 mMessageViewRef
= new WeakReference
<TextView
>(messageView
);
494 @SuppressWarnings("deprecation")
495 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
497 protected Bitmap
doInBackground(String
... params
) {
498 Bitmap result
= null
;
499 if (params
.length
!= 1) return result
;
500 String storagePath
= params
[0];
502 // set desired options that will affect the size of the bitmap
503 BitmapFactory
.Options options
= new Options();
504 options
.inScaled
= true
;
505 options
.inPurgeable
= true
;
506 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
507 options
.inPreferQualityOverSpeed
= false
;
509 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
510 options
.inMutable
= false
;
512 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
513 options
.inJustDecodeBounds
= true
;
514 BitmapFactory
.decodeFile(storagePath
, options
);
516 int width
= options
.outWidth
;
517 int height
= options
.outHeight
;
521 if (width >= 2048 || height >= 2048) {
522 // try to scale down the image to save memory
523 scale = (int) Math.ceil((Math.ceil(Math.max(height, width) / 2048.)));
524 options.inSampleSize = scale;
528 Display display
= getActivity().getWindowManager().getDefaultDisplay();
529 Point size
= new Point();
532 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
533 display
.getSize(size
);
534 screenWidth
= size
.x
;
535 screenHeight
= size
.y
;
537 screenWidth
= display
.getWidth();
538 screenHeight
= display
.getHeight();
541 if (width
> screenWidth
) {
542 // second try to scale down the image , this time depending upon the screen size; WTF...
543 scale
= (int) Math
.ceil((float)width
/ screenWidth
);
544 options
.inSampleSize
= scale
;
546 if (height
> screenHeight
) {
547 scale
= Math
.max(scale
, (int) Math
.ceil((float)height
/ screenHeight
));
551 // really load the bitmap
552 options
.inJustDecodeBounds
= false
; // the next decodeFile call will be real
553 result
= BitmapFactory
.decodeFile(storagePath
, options
);
554 //Log.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
556 } catch (Throwable t
) {
558 mThrowable
= t
; // error processing is delayed to #onPostExecute(Bitmap)
559 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
565 protected void onPostExecute(Bitmap result
) {
566 if (mImageViewRef
!= null
&& result
!= null
) {
567 final ImageView imageView
= mImageViewRef
.get();
568 if (imageView
!= null
) {
569 imageView
.setImageBitmap(result
);
571 if (mMessageViewRef
!= null
) {
572 final TextView messageView
= mMessageViewRef
.get();
573 if (messageView
!= null
) {
574 messageView
.setVisibility(View
.GONE
);
577 } // else , silently finish, the fragment was destroyed
579 } else if (mMessageViewRef
!= null
&& result
== null
) {
582 if (mThrowable
== null
) {
583 messageId
= R
.string
.preview_image_error_unknown_format
;
584 Log
.e(TAG
, "File could not be loaded as a bitmap: " + mFile
.getStoragePath());
586 } else if (mThrowable
instanceof OutOfMemoryError
) {
587 messageId
= R
.string
.preview_image_error_unknown_format
;
588 Log
.e(TAG
, "Out of memory occured for file " + mFile
.getStoragePath(), mThrowable
);
590 } else if (mThrowable
instanceof NoSuchFieldError
) {
591 messageId
= R
.string
.common_error_unknown
;
592 Log
.e(TAG
, "Error from access to unexisting field despite protection; file " + mFile
.getStoragePath(), mThrowable
);
595 messageId
= R
.string
.common_error_unknown
;
596 Log
.e(TAG
, "Unexpected error loading " + mFile
.getStoragePath(), mThrowable
);
598 final TextView messageView
= mMessageViewRef
.get();
599 if (messageView
!= null
) {
600 messageView
.setText(messageId
);
601 messageView
.setVisibility(View
.VISIBLE
);
602 } // else , silently finish, the fragment was destroyed
611 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
613 * @param file File to test if can be previewed.
614 * @return 'True' if the file can be handled by the fragment.
616 public static boolean canBePreviewed(OCFile file
) {
617 return (file
!= null
&& file
.isImage());
625 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
626 if (operation
.equals(mLastRemoteOperation
) && operation
instanceof RemoveFileOperation
) {
627 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
631 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
632 getActivity().dismissDialog(PreviewImageActivity
.DIALOG_SHORT_WAIT
);
634 if (result
.isSuccess()) {
635 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
640 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
642 if (result
.isSslRecoverableException()) {
643 // TODO show the SSL warning dialog
649 * Finishes the preview
651 private void finish() {
652 Activity container
= getActivity();