1 /* ownCloud Android client application 
   2  *   Copyright (C) 2012-2014 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
; 
  20 import java
.util
.ArrayList
; 
  21 import java
.util
.List
; 
  24 import android
.accounts
.Account
; 
  25 import android
.annotation
.SuppressLint
; 
  26 import android
.app
.Activity
; 
  27 import android
.graphics
.Bitmap
; 
  28 import android
.graphics
.BitmapFactory
; 
  29 import android
.graphics
.BitmapFactory
.Options
; 
  30 import android
.graphics
.Point
; 
  31 import android
.os
.AsyncTask
; 
  32 import android
.os
.Bundle
; 
  33 import android
.support
.v4
.app
.FragmentStatePagerAdapter
; 
  34 import android
.view
.Display
; 
  35 import android
.view
.LayoutInflater
; 
  36 import android
.view
.View
; 
  37 import android
.view
.View
.OnTouchListener
; 
  38 import android
.view
.ViewGroup
; 
  39 import android
.widget
.ImageView
; 
  40 import android
.widget
.ProgressBar
; 
  41 import android
.widget
.TextView
; 
  43 import com
.actionbarsherlock
.view
.Menu
; 
  44 import com
.actionbarsherlock
.view
.MenuInflater
; 
  45 import com
.actionbarsherlock
.view
.MenuItem
; 
  46 import com
.owncloud
.android
.R
; 
  47 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
; 
  48 import com
.owncloud
.android
.datamodel
.OCFile
; 
  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
; 
  80     private FileFragment
.ContainerActivity mContainerActivity
; 
  84      * Creates a fragment to preview an image. 
  86      * When 'imageFile' or 'ocAccount' are null 
  88      * @param imageFile                 An {@link OCFile} to preview as an image in the fragment 
  89      * @param ocAccount                 An ownCloud account; needed to start downloads 
  90      * @param ignoreFirstSavedState     Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution  
  92     public PreviewImageFragment(OCFile fileToDetail
, Account ocAccount
, boolean ignoreFirstSavedState
) { 
  95         mIgnoreFirstSavedState 
= ignoreFirstSavedState
; 
 100      *  Creates an empty fragment for image previews. 
 102      *  MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside). 
 104      *  DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction  
 106     public PreviewImageFragment() { 
 109         mIgnoreFirstSavedState 
= false
; 
 117     public void onCreate(Bundle savedInstanceState
) { 
 118         super.onCreate(savedInstanceState
); 
 119         setHasOptionsMenu(true
); 
 127     public View 
onCreateView(LayoutInflater inflater
, ViewGroup container
, 
 128             Bundle savedInstanceState
) { 
 129         super.onCreateView(inflater
, container
, savedInstanceState
); 
 130         mView 
= inflater
.inflate(R
.layout
.preview_image_fragment
, container
, false
); 
 131         mImageView 
= (ImageView
)mView
.findViewById(R
.id
.image
); 
 132         mImageView
.setVisibility(View
.GONE
); 
 133         mView
.setOnTouchListener((OnTouchListener
)getActivity()); 
 134         mMessageView 
= (TextView
)mView
.findViewById(R
.id
.message
); 
 135         mMessageView
.setVisibility(View
.GONE
); 
 136         mProgressWheel 
= (ProgressBar
)mView
.findViewById(R
.id
.progressWheel
); 
 137         mProgressWheel
.setVisibility(View
.VISIBLE
); 
 146     public void onAttach(Activity activity
) { 
 147         super.onAttach(activity
); 
 148         if (!(activity 
instanceof OnTouchListener
)) { 
 149             throw new ClassCastException(activity
.toString() +  
 150                     " must implement " + OnTouchListener
.class.getSimpleName()); 
 159     public void onActivityCreated(Bundle savedInstanceState
) { 
 160         super.onActivityCreated(savedInstanceState
); 
 161         if (savedInstanceState 
!= null
) { 
 162             if (!mIgnoreFirstSavedState
) { 
 163                 OCFile file 
= (OCFile
)savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_FILE
); 
 165                 mAccount 
= savedInstanceState
.getParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
); 
 166 // TODO remove this code: update file no needed                
 167 //                // Update the file 
 168 ////                if (mAccount!= null) { 
 169 //                    OCFile updatedFile =  
 170 //                      mContainerActivity.getStorageManager().getFileByPath(file.getRemotePath()); 
 171 //                    if (updatedFile != null) { 
 172 //                        setFile(updatedFile); 
 181                 mIgnoreFirstSavedState 
= false
; 
 184         if (getFile() == null
) { 
 185             throw new IllegalStateException("Instanced with a NULL OCFile"); 
 187         if (mAccount 
== null
) { 
 188             throw new IllegalStateException("Instanced with a NULL ownCloud Account"); 
 190         if (!getFile().isDown()) { 
 191             throw new IllegalStateException("There is no local file to preview"); 
 200     public void onSaveInstanceState(Bundle outState
) { 
 201         super.onSaveInstanceState(outState
); 
 202         outState
.putParcelable(PreviewImageFragment
.EXTRA_FILE
, getFile()); 
 203         outState
.putParcelable(PreviewImageFragment
.EXTRA_ACCOUNT
, mAccount
); 
 208     public void onStart() { 
 210         if (getFile() != null
) { 
 211            BitmapLoader bl 
= new BitmapLoader(mImageView
, mMessageView
, mProgressWheel
); 
 212            bl
.execute(new String
[]{getFile().getStoragePath()}); 
 221     public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) { 
 222         super.onCreateOptionsMenu(menu
, inflater
); 
 224         inflater
.inflate(R
.menu
.file_actions_menu
, menu
); 
 225         List
<Integer
> toHide 
= new ArrayList
<Integer
>();     
 227         MenuItem item 
= null
; 
 228         toHide
.add(R
.id
.action_cancel_download
); 
 229         toHide
.add(R
.id
.action_cancel_upload
); 
 230         toHide
.add(R
.id
.action_download_file
); 
 231         toHide
.add(R
.id
.action_rename_file
);    // by now 
 234         if (!getFile().isShareByLink()) { 
 235             toHide
.add(R
.id
.action_unshare_file
); 
 239         boolean sendEnabled 
= getString(R
.string
.send_files_to_other_apps
).equalsIgnoreCase("on"); 
 241             toHide
.add(R
.id
.action_send_file
); 
 244         for (int i 
: toHide
) { 
 245             item 
= menu
.findItem(i
); 
 247                 item
.setVisible(false
); 
 248                 item
.setEnabled(false
); 
 258     public void onPrepareOptionsMenu(Menu menu
) { 
 259         super.onPrepareOptionsMenu(menu
); 
 261         MenuItem item 
= menu
.findItem(R
.id
.action_unshare_file
); 
 263         if (!getFile().isShareByLink()) { 
 264             item
.setVisible(false
); 
 265             item
.setEnabled(false
); 
 267             item
.setVisible(true
); 
 268             item
.setEnabled(true
); 
 279     public boolean onOptionsItemSelected(MenuItem item
) { 
 280         switch (item
.getItemId()) { 
 281             case R
.id
.action_share_file
: { 
 282                 mContainerActivity
.getFileOperationsHelper().shareFileWithLink(getFile()); 
 285             case R
.id
.action_unshare_file
: { 
 286                 mContainerActivity
.getFileOperationsHelper().unshareFileWithLink(getFile()); 
 289             case R
.id
.action_open_file_with
: { 
 293             case R
.id
.action_remove_file
: { 
 297             case R
.id
.action_see_details
: { 
 301             case R
.id
.action_send_file
: { 
 302                 mContainerActivity
.getFileOperationsHelper().sendDownloadedFile(getFile()); 
 312     private void seeDetails() { 
 313         mContainerActivity
.showDetails(getFile());         
 318     public void onResume() { 
 324     public void onPause() { 
 330     public void onDestroy() { 
 332         if (mBitmap 
!= null
) { 
 339      * Opens the previewed image with an external application. 
 341     private void openFile() { 
 342         mContainerActivity
.getFileOperationsHelper().openFile(getFile()); 
 348      * Starts a the removal of the previewed file. 
 350      * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)}, 
 351      * depending upon the user selection in the dialog.  
 353     private void removeFile() { 
 354         ConfirmationDialogFragment confDialog 
= ConfirmationDialogFragment
.newInstance( 
 355                 R
.string
.confirmation_remove_alert
, 
 356                 new String
[]{getFile().getFileName()}, 
 357                 R
.string
.confirmation_remove_remote_and_local
, 
 358                 R
.string
.confirmation_remove_local
, 
 359                 R
.string
.common_cancel
); 
 360         confDialog
.setOnConfirmationListener(this); 
 361         confDialog
.show(getFragmentManager(), ConfirmationDialogFragment
.FTAG_CONFIRMATION
); 
 366      * Performs the removal of the previewed file, both locally and in the server. 
 369     public void onConfirmation(String callerTag
) { 
 370         FileDataStorageManager storageManager 
= mContainerActivity
.getStorageManager(); 
 371         if (storageManager
.getFileById(getFile().getFileId()) != null
) {   // check that the file is still there; 
 372             mContainerActivity
.getFileOperationsHelper().removeFile(getFile(), true
); 
 378      * Removes the file from local storage 
 381     public void onNeutral(String callerTag
) { 
 382         OCFile file 
= getFile(); 
 383         mContainerActivity
.getStorageManager().removeFile(file
, false
, true
);    // TODO perform in background task / new thread 
 388      * User cancelled the removal action. 
 391     public void onCancel(String callerTag
) { 
 392         // nothing to do here 
 396     private class BitmapLoader 
extends AsyncTask
<String
, Void
, Bitmap
> { 
 399          * Weak reference to the target {@link ImageView} where the bitmap will be loaded into. 
 401          * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes. 
 403         private final WeakReference
<ImageView
> mImageViewRef
; 
 406          * Weak reference to the target {@link TextView} where error messages will be written. 
 408          * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes. 
 410         private final WeakReference
<TextView
> mMessageViewRef
; 
 414          * Weak reference to the target {@link Progressbar} shown while the load is in progress. 
 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
<ProgressBar
> mProgressWheelRef
; 
 422          * Error message to show when a load fails  
 424         private int mErrorMessageId
; 
 430          * @param imageView     Target {@link ImageView} where the bitmap will be loaded into. 
 432         public BitmapLoader(ImageView imageView
, TextView messageView
, ProgressBar progressWheel
) { 
 433             mImageViewRef 
= new WeakReference
<ImageView
>(imageView
); 
 434             mMessageViewRef 
= new WeakReference
<TextView
>(messageView
); 
 435             mProgressWheelRef 
= new WeakReference
<ProgressBar
>(progressWheel
); 
 439         @SuppressWarnings("deprecation") 
 440         @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20 
 442         protected Bitmap 
doInBackground(String
... params
) { 
 443             Bitmap result 
= null
; 
 444             if (params
.length 
!= 1) return result
; 
 445             String storagePath 
= params
[0]; 
 447                 // set desired options that will affect the size of the bitmap 
 448                 BitmapFactory
.Options options 
= new Options(); 
 449                 options
.inScaled 
= true
; 
 450                 options
.inPurgeable 
= true
; 
 451                 if (android
.os
.Build
.VERSION
.SDK_INT 
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) { 
 452                     options
.inPreferQualityOverSpeed 
= false
; 
 454                 if (android
.os
.Build
.VERSION
.SDK_INT 
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) { 
 455                     options
.inMutable 
= false
; 
 457                 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType 
 458                 options
.inJustDecodeBounds 
= true
; 
 459                 BitmapFactory
.decodeFile(storagePath
, options
);    
 461                 int width 
= options
.outWidth
; 
 462                 int height 
= options
.outHeight
; 
 465                 Display display 
= getActivity().getWindowManager().getDefaultDisplay(); 
 466                 Point size 
= new Point(); 
 469                 if (android
.os
.Build
.VERSION
.SDK_INT 
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) { 
 470                     display
.getSize(size
); 
 471                     screenWidth 
= size
.x
; 
 472                     screenHeight 
= size
.y
; 
 474                     screenWidth 
= display
.getWidth(); 
 475                     screenHeight 
= display
.getHeight(); 
 478                 if (width 
> screenWidth
) { 
 479                     // second try to scale down the image , this time depending upon the screen size  
 480                     scale 
= (int) Math
.floor((float)width 
/ screenWidth
); 
 482                 if (height 
> screenHeight
) { 
 483                     scale 
= Math
.max(scale
, (int) Math
.floor((float)height 
/ screenHeight
)); 
 485                 options
.inSampleSize 
= scale
; 
 487                 // really load the bitmap 
 488                 options
.inJustDecodeBounds 
= false
; // the next decodeFile call will be real 
 489                 result 
= BitmapFactory
.decodeFile(storagePath
, options
); 
 490                 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight); 
 492                 if (result 
== null
) { 
 493                     mErrorMessageId 
= R
.string
.preview_image_error_unknown_format
; 
 494                     Log_OC
.e(TAG
, "File could not be loaded as a bitmap: " + storagePath
); 
 497             } catch (OutOfMemoryError e
) { 
 498                 mErrorMessageId 
= R
.string
.preview_image_error_unknown_format
; 
 499                 Log_OC
.e(TAG
, "Out of memory occured for file " + storagePath
, e
); 
 501             } catch (NoSuchFieldError e
) { 
 502                 mErrorMessageId 
= R
.string
.common_error_unknown
; 
 503                 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection; file " + storagePath
, e
); 
 505             } catch (Throwable t
) { 
 506                 mErrorMessageId 
= R
.string
.common_error_unknown
; 
 507                 Log_OC
.e(TAG
, "Unexpected error loading " + getFile().getStoragePath(), t
); 
 514         protected void onPostExecute(Bitmap result
) { 
 516             if (result 
!= null
) { 
 517                 showLoadedImage(result
); 
 523         private void showLoadedImage(Bitmap result
) { 
 524             if (mImageViewRef 
!= null
) { 
 525                 final ImageView imageView 
= mImageViewRef
.get(); 
 526                 if (imageView 
!= null
) { 
 527                     imageView
.setImageBitmap(result
); 
 528                     imageView
.setVisibility(View
.VISIBLE
); 
 530                 } // else , silently finish, the fragment was destroyed 
 532             if (mMessageViewRef 
!= null
) { 
 533                 final TextView messageView 
= mMessageViewRef
.get(); 
 534                 if (messageView 
!= null
) { 
 535                     messageView
.setVisibility(View
.GONE
); 
 536                 } // else , silently finish, the fragment was destroyed 
 540         private void showErrorMessage() { 
 541             if (mImageViewRef 
!= null
) { 
 542                 final ImageView imageView 
= mImageViewRef
.get(); 
 543                 if (imageView 
!= null
) { 
 544                     // shows the default error icon 
 545                     imageView
.setVisibility(View
.VISIBLE
); 
 546                 } // else , silently finish, the fragment was destroyed 
 548             if (mMessageViewRef 
!= null
) { 
 549                 final TextView messageView 
= mMessageViewRef
.get(); 
 550                 if (messageView 
!= null
) { 
 551                     messageView
.setText(mErrorMessageId
); 
 552                     messageView
.setVisibility(View
.VISIBLE
); 
 553                 } // else , silently finish, the fragment was destroyed 
 557         private void hideProgressWheel() { 
 558             if (mProgressWheelRef 
!= null
) { 
 559                 final ProgressBar progressWheel 
= mProgressWheelRef
.get(); 
 560                 if (progressWheel 
!= null
) { 
 561                     progressWheel
.setVisibility(View
.GONE
); 
 569      * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed. 
 571      * @param file      File to test if can be previewed. 
 572      * @return          'True' if the file can be handled by the fragment. 
 574     public static boolean canBePreviewed(OCFile file
) { 
 575         return (file 
!= null 
&& file
.isImage()); 
 580      * Finishes the preview 
 582     private void finish() { 
 583         Activity container 
= getActivity();