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