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