Merge branch 'develop' into refactor_update_filelist_from_database
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
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.
7 *
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.
12 *
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/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import java.lang.ref.WeakReference;
20
21
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;
40
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.OCFile;
46 import com.owncloud.android.files.FileMenuFilter;
47 import com.owncloud.android.ui.activity.FileActivity;
48 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
49 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
50 import com.owncloud.android.ui.fragment.FileFragment;
51 import com.owncloud.android.utils.Log_OC;
52
53
54 /**
55 * This fragment shows a preview of a downloaded image.
56 *
57 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
58 *
59 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
60 *
61 * @author David A. Velasco
62 */
63 public class PreviewImageFragment extends FileFragment {
64 public static final String EXTRA_FILE = "FILE";
65 public static final String EXTRA_ACCOUNT = "ACCOUNT";
66
67 private View mView;
68 private Account mAccount;
69 private ImageView mImageView;
70 private TextView mMessageView;
71 private ProgressBar mProgressWheel;
72
73 public Bitmap mBitmap = null;
74
75 private static final String TAG = PreviewImageFragment.class.getSimpleName();
76
77 private boolean mIgnoreFirstSavedState;
78
79
80 /**
81 * Creates a fragment to preview an image.
82 *
83 * When 'imageFile' or 'ocAccount' are null
84 *
85 * @param imageFile An {@link OCFile} to preview as an image in the fragment
86 * @param ocAccount An ownCloud account; needed to start downloads
87 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
88 */
89 public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
90 super(fileToDetail);
91 mAccount = ocAccount;
92 mIgnoreFirstSavedState = ignoreFirstSavedState;
93 }
94
95
96 /**
97 * Creates an empty fragment for image previews.
98 *
99 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
100 *
101 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
102 */
103 public PreviewImageFragment() {
104 super();
105 mAccount = null;
106 mIgnoreFirstSavedState = false;
107 }
108
109
110 /**
111 * {@inheritDoc}
112 */
113 @Override
114 public void onCreate(Bundle savedInstanceState) {
115 super.onCreate(savedInstanceState);
116 setHasOptionsMenu(true);
117 }
118
119
120 /**
121 * {@inheritDoc}
122 */
123 @Override
124 public View onCreateView(LayoutInflater inflater, ViewGroup container,
125 Bundle savedInstanceState) {
126 super.onCreateView(inflater, container, savedInstanceState);
127 mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
128 mImageView = (ImageView)mView.findViewById(R.id.image);
129 mImageView.setVisibility(View.GONE);
130 mView.setOnTouchListener((OnTouchListener)getActivity());
131 mMessageView = (TextView)mView.findViewById(R.id.message);
132 mMessageView.setVisibility(View.GONE);
133 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
134 mProgressWheel.setVisibility(View.VISIBLE);
135 return mView;
136 }
137
138
139 /**
140 * {@inheritDoc}
141 */
142 @Override
143 public void onAttach(Activity activity) {
144 super.onAttach(activity);
145 if (!(activity instanceof OnTouchListener)) {
146 throw new ClassCastException(activity.toString() +
147 " must implement " + OnTouchListener.class.getSimpleName());
148 }
149 }
150
151
152 /**
153 * {@inheritDoc}
154 */
155 @Override
156 public void onActivityCreated(Bundle savedInstanceState) {
157 super.onActivityCreated(savedInstanceState);
158 if (savedInstanceState != null) {
159 if (!mIgnoreFirstSavedState) {
160 OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
161 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
162
163 // Update the file
164 if (mAccount!= null) {
165 OCFile updatedFile = ((FileActivity) getSherlockActivity()).
166 getStorageManager().getFileByPath(file.getRemotePath());
167 if (updatedFile != null) {
168 setFile(updatedFile);
169 } else {
170 setFile(file);
171 }
172 } else {
173 setFile(file);
174 }
175 } else {
176 mIgnoreFirstSavedState = false;
177 }
178 }
179 if (getFile() == null) {
180 throw new IllegalStateException("Instanced with a NULL OCFile");
181 }
182 if (mAccount == null) {
183 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
184 }
185 if (!getFile().isDown()) {
186 throw new IllegalStateException("There is no local file to preview");
187 }
188 }
189
190
191 /**
192 * {@inheritDoc}
193 */
194 @Override
195 public void onSaveInstanceState(Bundle outState) {
196 super.onSaveInstanceState(outState);
197 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
198 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
199 }
200
201
202 @Override
203 public void onStart() {
204 super.onStart();
205 if (getFile() != null) {
206 BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
207 bl.execute(new String[]{getFile().getStoragePath()});
208 }
209 }
210
211
212 /**
213 * {@inheritDoc}
214 */
215 @Override
216 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
217 super.onCreateOptionsMenu(menu, inflater);
218 inflater.inflate(R.menu.file_actions_menu, menu);
219 }
220
221 /**
222 * {@inheritDoc}
223 */
224 @Override
225 public void onPrepareOptionsMenu(Menu menu) {
226 super.onPrepareOptionsMenu(menu);
227
228 if (mContainerActivity.getStorageManager() != null) {
229 FileMenuFilter mf = new FileMenuFilter(
230 getFile(),
231 mContainerActivity.getStorageManager().getAccount(),
232 mContainerActivity,
233 getSherlockActivity()
234 );
235 mf.filter(menu);
236 }
237
238 // additional restriction for this fragment
239 // TODO allow renaming in PreviewImageFragment
240 MenuItem item = menu.findItem(R.id.action_rename_file);
241 if (item != null) {
242 item.setVisible(false);
243 item.setEnabled(false);
244 }
245 }
246
247
248
249 /**
250 * {@inheritDoc}
251 */
252 @Override
253 public boolean onOptionsItemSelected(MenuItem item) {
254 switch (item.getItemId()) {
255 case R.id.action_share_file: {
256 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
257 return true;
258 }
259 case R.id.action_unshare_file: {
260 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
261 return true;
262 }
263 case R.id.action_open_file_with: {
264 openFile();
265 return true;
266 }
267 case R.id.action_remove_file: {
268 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
269 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
270 return true;
271 }
272 case R.id.action_see_details: {
273 seeDetails();
274 return true;
275 }
276 case R.id.action_send_file: {
277 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
278 return true;
279 }
280 case R.id.action_sync_file: {
281 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
282 return true;
283 }
284
285 default:
286 return false;
287 }
288 }
289
290
291 private void seeDetails() {
292 mContainerActivity.showDetails(getFile());
293 }
294
295
296 @Override
297 public void onResume() {
298 super.onResume();
299 }
300
301
302 @Override
303 public void onPause() {
304 super.onPause();
305 }
306
307
308 @Override
309 public void onDestroy() {
310 super.onDestroy();
311 if (mBitmap != null) {
312 mBitmap.recycle();
313 }
314 }
315
316
317 /**
318 * Opens the previewed image with an external application.
319 */
320 private void openFile() {
321 mContainerActivity.getFileOperationsHelper().openFile(getFile());
322 finish();
323 }
324
325
326 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
327
328 /**
329 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
330 *
331 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
332 */
333 private final WeakReference<ImageView> mImageViewRef;
334
335 /**
336 * Weak reference to the target {@link TextView} where error messages will be written.
337 *
338 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
339 */
340 private final WeakReference<TextView> mMessageViewRef;
341
342
343 /**
344 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
345 *
346 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
347 */
348 private final WeakReference<ProgressBar> mProgressWheelRef;
349
350
351 /**
352 * Error message to show when a load fails
353 */
354 private int mErrorMessageId;
355
356
357 /**
358 * Constructor.
359 *
360 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
361 */
362 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
363 mImageViewRef = new WeakReference<ImageView>(imageView);
364 mMessageViewRef = new WeakReference<TextView>(messageView);
365 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
366 }
367
368
369 @SuppressWarnings("deprecation")
370 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
371 @Override
372 protected Bitmap doInBackground(String... params) {
373 Bitmap result = null;
374 if (params.length != 1) return result;
375 String storagePath = params[0];
376 try {
377 // set desired options that will affect the size of the bitmap
378 BitmapFactory.Options options = new Options();
379 options.inScaled = true;
380 options.inPurgeable = true;
381 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
382 options.inPreferQualityOverSpeed = false;
383 }
384 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
385 options.inMutable = false;
386 }
387 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
388 options.inJustDecodeBounds = true;
389 BitmapFactory.decodeFile(storagePath, options);
390
391 int width = options.outWidth;
392 int height = options.outHeight;
393 int scale = 1;
394
395 Display display = getActivity().getWindowManager().getDefaultDisplay();
396 Point size = new Point();
397 int screenWidth;
398 int screenHeight;
399 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
400 display.getSize(size);
401 screenWidth = size.x;
402 screenHeight = size.y;
403 } else {
404 screenWidth = display.getWidth();
405 screenHeight = display.getHeight();
406 }
407
408 if (width > screenWidth) {
409 // second try to scale down the image , this time depending upon the screen size
410 scale = (int) Math.floor((float)width / screenWidth);
411 }
412 if (height > screenHeight) {
413 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
414 }
415 options.inSampleSize = scale;
416
417 // really load the bitmap
418 options.inJustDecodeBounds = false; // the next decodeFile call will be real
419 result = BitmapFactory.decodeFile(storagePath, options);
420 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
421
422 if (result == null) {
423 mErrorMessageId = R.string.preview_image_error_unknown_format;
424 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
425 }
426
427 } catch (OutOfMemoryError e) {
428 mErrorMessageId = R.string.preview_image_error_unknown_format;
429 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
430
431 } catch (NoSuchFieldError e) {
432 mErrorMessageId = R.string.common_error_unknown;
433 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
434
435 } catch (Throwable t) {
436 mErrorMessageId = R.string.common_error_unknown;
437 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
438
439 }
440 return result;
441 }
442
443 @Override
444 protected void onPostExecute(Bitmap result) {
445 hideProgressWheel();
446 if (result != null) {
447 showLoadedImage(result);
448 } else {
449 showErrorMessage();
450 }
451 }
452
453 private void showLoadedImage(Bitmap result) {
454 if (mImageViewRef != null) {
455 final ImageView imageView = mImageViewRef.get();
456 if (imageView != null) {
457 imageView.setImageBitmap(result);
458 imageView.setVisibility(View.VISIBLE);
459 mBitmap = result;
460 } // else , silently finish, the fragment was destroyed
461 }
462 if (mMessageViewRef != null) {
463 final TextView messageView = mMessageViewRef.get();
464 if (messageView != null) {
465 messageView.setVisibility(View.GONE);
466 } // else , silently finish, the fragment was destroyed
467 }
468 }
469
470 private void showErrorMessage() {
471 if (mImageViewRef != null) {
472 final ImageView imageView = mImageViewRef.get();
473 if (imageView != null) {
474 // shows the default error icon
475 imageView.setVisibility(View.VISIBLE);
476 } // else , silently finish, the fragment was destroyed
477 }
478 if (mMessageViewRef != null) {
479 final TextView messageView = mMessageViewRef.get();
480 if (messageView != null) {
481 messageView.setText(mErrorMessageId);
482 messageView.setVisibility(View.VISIBLE);
483 } // else , silently finish, the fragment was destroyed
484 }
485 }
486
487 private void hideProgressWheel() {
488 if (mProgressWheelRef != null) {
489 final ProgressBar progressWheel = mProgressWheelRef.get();
490 if (progressWheel != null) {
491 progressWheel.setVisibility(View.GONE);
492 }
493 }
494 }
495
496 }
497
498 /**
499 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
500 *
501 * @param file File to test if can be previewed.
502 * @return 'True' if the file can be handled by the fragment.
503 */
504 public static boolean canBePreviewed(OCFile file) {
505 return (file != null && file.isImage());
506 }
507
508
509 /**
510 * Finishes the preview
511 */
512 private void finish() {
513 Activity container = getActivity();
514 container.finish();
515 }
516
517
518 }