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