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
; 
  19 import java
.lang
.ref
.WeakReference
; 
  22 import android
.accounts
.Account
; 
  23 import android
.annotation
.SuppressLint
; 
  24 import android
.app
.Activity
; 
  25 import android
.graphics
.Bitmap
; 
  26 import android
.graphics
.BitmapFactory
; 
  27 import android
.graphics
.BitmapFactory
.Options
; 
  28 import android
.graphics
.Point
; 
  29 import android
.os
.AsyncTask
; 
  30 import android
.os
.Bundle
; 
  31 import android
.support
.v4
.app
.FragmentStatePagerAdapter
; 
  32 import android
.view
.Display
; 
  33 import android
.view
.LayoutInflater
; 
  34 import android
.view
.View
; 
  35 import android
.view
.View
.OnTouchListener
; 
  36 import android
.view
.ViewGroup
; 
  37 import android
.widget
.ImageView
; 
  38 import android
.widget
.ProgressBar
; 
  39 import android
.widget
.TextView
; 
  41 import com
.actionbarsherlock
.view
.Menu
; 
  42 import com
.actionbarsherlock
.view
.MenuInflater
; 
  43 import com
.actionbarsherlock
.view
.MenuItem
; 
  44 import com
.owncloud
.android
.R
; 
  45 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
; 
  46 import com
.owncloud
.android
.datamodel
.OCFile
; 
  47 import com
.owncloud
.android
.files
.FileMenuFilter
; 
  48 import com
.owncloud
.android
.ui
.activity
.FileActivity
; 
  49 import com
.owncloud
.android
.ui
.dialog
.ConfirmationDialogFragment
; 
  50 import com
.owncloud
.android
.ui
.fragment
.FileFragment
; 
  51 import com
.owncloud
.android
.utils
.Log_OC
; 
  55  * This fragment shows a preview of a downloaded image. 
  57  * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}. 
  59  * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too. 
  61  * @author David A. Velasco 
  63 public class PreviewImageFragment 
extends FileFragment 
implements  
  64 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener 
{ 
  65     public static final String EXTRA_FILE 
= "FILE"; 
  66     public static final String EXTRA_ACCOUNT 
= "ACCOUNT"; 
  69     private Account mAccount
; 
  70     private ImageView mImageView
; 
  71     private TextView mMessageView
; 
  72     private ProgressBar mProgressWheel
; 
  74     public Bitmap mBitmap 
= null
; 
  76     private static final String TAG 
= PreviewImageFragment
.class.getSimpleName(); 
  78     private boolean mIgnoreFirstSavedState
; 
  82      * Creates a fragment to preview an image. 
  84      * When 'imageFile' or 'ocAccount' are null 
  86      * @param imageFile                 An {@link OCFile} to preview as an image in the fragment 
  87      * @param ocAccount                 An ownCloud account; needed to start downloads 
  88      * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution  
  90     public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) { 
  93         mIgnoreFirstSavedState 
= ignoreFirstSavedState
; 
  98      *  Creates an empty fragment for image previews. 
 100      *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside). 
 102      *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction  
 104     public PreviewImageFragment() { 
 107         mIgnoreFirstSavedState 
= false
; 
 115     public void onCreate(Bundle savedInstanceState
) { 
 116         super.onCreate(savedInstanceState
); 
 117         setHasOptionsMenu(true
); 
 125     public View 
onCreateView(LayoutInflater inflater
, ViewGroup container
, 
 126             Bundle savedInstanceState
) { 
 127         super.onCreateView(inflater
, container
, savedInstanceState
); 
 128         mView 
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
); 
 129         mImageView 
= (ImageView
)mView
.findViewById(R
.id
.image
); 
 130         mImageView
.setVisibility(View
.GONE
); 
 131         mView
.setOnTouchListener((OnTouchListener
)getActivity()); 
 132         mMessageView 
= (TextView
)mView
.findViewById(R
.id
.message
); 
 133         mMessageView
.setVisibility(View
.GONE
); 
 134         mProgressWheel 
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
); 
 135         mProgressWheel
.setVisibility(View
.VISIBLE
); 
 144     public void onAttach(Activity activity
) { 
 145         super.onAttach(activity
); 
 146         if (!(activity 
instanceof OnTouchListener
)) { 
 147             throw new ClassCastException(activity
.toString() +  
 148                     " must implement " + OnTouchListener
.class.getSimpleName()); 
 157     public void onActivityCreated(Bundle savedInstanceState
) { 
 158         super.onActivityCreated(savedInstanceState
); 
 159         if (savedInstanceState 
!= null
) { 
 160             if (!mIgnoreFirstSavedState
) { 
 161                 OCFile file 
= (OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
); 
 162                 mAccount 
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
); 
 165                 if (mAccount
!= null
) { 
 166                     OCFile updatedFile 
= ((FileActivity
) getSherlockActivity()). 
 167                             getStorageManager().getFileByPath(file
.getRemotePath()); 
 168                     if (updatedFile 
!= null
) { 
 169                         setFile(updatedFile
); 
 177                 mIgnoreFirstSavedState 
= false
; 
 180         if (getFile() == null
) { 
 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 (!getFile().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
, getFile()); 
 199         outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
); 
 204     public void onStart() { 
 206         if (getFile() != null
) { 
 207            BitmapLoader bl 
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
); 
 208            bl
.execute(new String
[]{getFile().getStoragePath()}); 
 217     public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) { 
 218         super.onCreateOptionsMenu(menu
, inflater
); 
 219         inflater
.inflate(R
.menu
.file_actions_menu
, menu
); 
 226     public void onPrepareOptionsMenu(Menu menu
) { 
 227         super.onPrepareOptionsMenu(menu
); 
 229         FileMenuFilter mf 
= new FileMenuFilter( 
 231             mContainerActivity
.getStorageManager().getAccount(), 
 233             getSherlockActivity() 
 237         // additional restriction for this fragment  
 238         // TODO allow renaming in PreviewImageFragment 
 239         MenuItem item 
= menu
.findItem(R
.id
.action_rename_file
); 
 241             item
.setVisible(false
); 
 242             item
.setEnabled(false
); 
 252     public boolean onOptionsItemSelected(MenuItem item
) { 
 253         switch (item
.getItemId()) { 
 254             case R
.id
.action_share_file
: { 
 255                 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile()); 
 258             case R
.id
.action_unshare_file
: { 
 259                 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile()); 
 262             case R
.id
.action_open_file_with
: { 
 266             case R
.id
.action_remove_file
: { 
 270             case R
.id
.action_see_details
: { 
 274             case R
.id
.action_send_file
: { 
 275                 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile()); 
 278             case R
.id
.action_sync_file
: { 
 279                 mContainerActivity
.getFileOperationsHelper().syncFile(getFile()); 
 289     private void seeDetails() { 
 290         mContainerActivity
.showDetails(getFile());         
 295     public void onResume() { 
 301     public void onPause() { 
 307     public void onDestroy() { 
 309         if (mBitmap 
!= null
) { 
 316      * Opens the previewed image with an external application. 
 318     private void openFile() { 
 319         mContainerActivity
.getFileOperationsHelper().openFile(getFile()); 
 325      * Starts a the removal of the previewed file. 
 327      * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)}, 
 328      * depending upon the user selection in the dialog.  
 330     private void removeFile() { 
 331         ConfirmationDialogFragment confDialog 
= ConfirmationDialogFragment
.newInstance( 
 332                 R
.string
.confirmation_remove_alert
, 
 333                 new String
[]{getFile().getFileName()}, 
 334                 R
.string
.confirmation_remove_remote_and_local
, 
 335                 R
.string
.confirmation_remove_local
, 
 336                 R
.string
.common_cancel
); 
 337         confDialog
.setOnConfirmationListener(this); 
 338         confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
); 
 343      * Performs the removal of the previewed file, both locally and in the server. 
 346     public void onConfirmation(String callerTag
) { 
 347         FileDataStorageManager storageManager 
= mContainerActivity
.getStorageManager(); 
 348         if (storageManager
.getFileById(getFile().getFileId()) != null
) {   // check that the file is still there; 
 349             mContainerActivity
.getFileOperationsHelper().removeFile(getFile(), false
); 
 355      * Removes the file from local storage 
 358     public void onNeutral(String callerTag
) { 
 359         OCFile file 
= getFile(); 
 360         mContainerActivity
.getFileOperationsHelper().removeFile(file
, true
); 
 361         //mContainerActivity.getStorageManager().removeFile(file, false, true);    // TODO perform in background task / new thread 
 366      * User cancelled the removal action. 
 369     public void onCancel(String callerTag
) { 
 370         // nothing to do here 
 374     private class BitmapLoader 
extends AsyncTask
<String
, Void
, Bitmap
> { 
 377          * Weak reference to the target {@link ImageView} where the bitmap will be loaded into. 
 379          * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes. 
 381         private final WeakReference
<ImageView
> mImageViewRef
; 
 384          * Weak reference to the target {@link TextView} where error messages will be written. 
 386          * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes. 
 388         private final WeakReference
<TextView
> mMessageViewRef
; 
 392          * Weak reference to the target {@link Progressbar} shown while the load is in progress. 
 394          * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes. 
 396         private final WeakReference
<ProgressBar
> mProgressWheelRef
; 
 400          * Error message to show when a load fails  
 402         private int mErrorMessageId
; 
 408          * @param imageView     Target {@link ImageView} where the bitmap will be loaded into. 
 410         public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) { 
 411             mImageViewRef 
= new WeakReference
<ImageView
>(imageView
); 
 412             mMessageViewRef 
= new WeakReference
<TextView
>(messageView
); 
 413             mProgressWheelRef 
= new WeakReference
<ProgressBar
>(progressWheel
); 
 417         @SuppressWarnings("deprecation") 
 418         @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20 
 420         protected Bitmap 
doInBackground(String
... params
) { 
 421             Bitmap result 
= null
; 
 422             if (params
.length 
!= 1) return result
; 
 423             String storagePath 
= params
[0]; 
 425                 // set desired options that will affect the size of the bitmap 
 426                 BitmapFactory
.Options options 
= new Options(); 
 427                 options
.inScaled 
= true
; 
 428                 options
.inPurgeable 
= true
; 
 429                 if (android
.os
.Build
.VERSION
.SDK_INT 
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) { 
 430                     options
.inPreferQualityOverSpeed 
= false
; 
 432                 if (android
.os
.Build
.VERSION
.SDK_INT 
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) { 
 433                     options
.inMutable 
= false
; 
 435                 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType 
 436                 options
.inJustDecodeBounds 
= true
; 
 437                 BitmapFactory
.decodeFile(storagePath
, options
);    
 439                 int width 
= options
.outWidth
; 
 440                 int height 
= options
.outHeight
; 
 443                 Display display 
= getActivity().getWindowManager().getDefaultDisplay(); 
 444                 Point size 
= new Point(); 
 447                 if (android
.os
.Build
.VERSION
.SDK_INT 
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) { 
 448                     display
.getSize(size
); 
 449                     screenWidth 
= size
.x
; 
 450                     screenHeight 
= size
.y
; 
 452                     screenWidth 
= display
.getWidth(); 
 453                     screenHeight 
= display
.getHeight(); 
 456                 if (width 
> screenWidth
) { 
 457                     // second try to scale down the image , this time depending upon the screen size  
 458                     scale 
= (int) Math
.floor((float)width 
/ screenWidth
); 
 460                 if (height 
> screenHeight
) { 
 461                     scale 
= Math
.max(scale
, (int) Math
.floor((float)height 
/ screenHeight
)); 
 463                 options
.inSampleSize 
= scale
; 
 465                 // really load the bitmap 
 466                 options
.inJustDecodeBounds 
= false
; // the next decodeFile call will be real 
 467                 result 
= BitmapFactory
.decodeFile(storagePath
, options
); 
 468                 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight); 
 470                 if (result 
== null
) { 
 471                     mErrorMessageId 
= R
.string
.preview_image_error_unknown_format
; 
 472                     Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
); 
 475             } catch (OutOfMemoryError e
) { 
 476                 mErrorMessageId 
= R
.string
.preview_image_error_unknown_format
; 
 477                 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
); 
 479             } catch (NoSuchFieldError e
) { 
 480                 mErrorMessageId 
= R
.string
.common_error_unknown
; 
 481                 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
); 
 483             } catch (Throwable t
) { 
 484                 mErrorMessageId 
= R
.string
.common_error_unknown
; 
 485                 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
); 
 492         protected void onPostExecute(Bitmap result
) { 
 494             if (result 
!= null
) { 
 495                 showLoadedImage(result
); 
 501         private void showLoadedImage(Bitmap result
) { 
 502             if (mImageViewRef 
!= null
) { 
 503                 final ImageView imageView 
= mImageViewRef
.get(); 
 504                 if (imageView 
!= null
) { 
 505                     imageView
.setImageBitmap(result
); 
 506                     imageView
.setVisibility(View
.VISIBLE
); 
 508                 } // else , silently finish, the fragment was destroyed 
 510             if (mMessageViewRef 
!= null
) { 
 511                 final TextView messageView 
= mMessageViewRef
.get(); 
 512                 if (messageView 
!= null
) { 
 513                     messageView
.setVisibility(View
.GONE
); 
 514                 } // else , silently finish, the fragment was destroyed 
 518         private void showErrorMessage() { 
 519             if (mImageViewRef 
!= null
) { 
 520                 final ImageView imageView 
= mImageViewRef
.get(); 
 521                 if (imageView 
!= null
) { 
 522                     // shows the default error icon 
 523                     imageView
.setVisibility(View
.VISIBLE
); 
 524                 } // else , silently finish, the fragment was destroyed 
 526             if (mMessageViewRef 
!= null
) { 
 527                 final TextView messageView 
= mMessageViewRef
.get(); 
 528                 if (messageView 
!= null
) { 
 529                     messageView
.setText(mErrorMessageId
); 
 530                     messageView
.setVisibility(View
.VISIBLE
); 
 531                 } // else , silently finish, the fragment was destroyed 
 535         private void hideProgressWheel() { 
 536             if (mProgressWheelRef 
!= null
) { 
 537                 final ProgressBar progressWheel 
= mProgressWheelRef
.get(); 
 538                 if (progressWheel 
!= null
) { 
 539                     progressWheel
.setVisibility(View
.GONE
); 
 547      * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed. 
 549      * @param file      File to test if can be previewed. 
 550      * @return          'True' if the file can be handled by the fragment. 
 552     public static boolean canBePreviewed(OCFile file
) { 
 553         return (file 
!= null 
&& file
.isImage()); 
 558      * Finishes the preview 
 560     private void finish() { 
 561         Activity container 
= getActivity();