Removed call to methods to check transfer state of files through binders and replaced...
[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 getSherlockActivity()
236 );
237 mf.filter(menu);
238 }
239
240 // additional restriction for this fragment
241 // TODO allow renaming in PreviewImageFragment
242 MenuItem item = menu.findItem(R.id.action_rename_file);
243 if (item != null) {
244 item.setVisible(false);
245 item.setEnabled(false);
246 }
247
248 // additional restriction for this fragment
249 // TODO allow refresh file in PreviewImageFragment
250 item = menu.findItem(R.id.action_sync_file);
251 if (item != null) {
252 item.setVisible(false);
253 item.setEnabled(false);
254 }
255
256 // additional restriction for this fragment
257 item = menu.findItem(R.id.action_move);
258 if (item != null) {
259 item.setVisible(false);
260 item.setEnabled(false);
261 }
262
263 }
264
265
266
267 /**
268 * {@inheritDoc}
269 */
270 @Override
271 public boolean onOptionsItemSelected(MenuItem item) {
272 switch (item.getItemId()) {
273 case R.id.action_share_file: {
274 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
275 return true;
276 }
277 case R.id.action_unshare_file: {
278 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
279 return true;
280 }
281 case R.id.action_open_file_with: {
282 openFile();
283 return true;
284 }
285 case R.id.action_remove_file: {
286 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
287 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
288 return true;
289 }
290 case R.id.action_see_details: {
291 seeDetails();
292 return true;
293 }
294 case R.id.action_send_file: {
295 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
296 return true;
297 }
298 case R.id.action_sync_file: {
299 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
300 return true;
301 }
302
303 default:
304 return false;
305 }
306 }
307
308
309 private void seeDetails() {
310 mContainerActivity.showDetails(getFile());
311 }
312
313
314 @Override
315 public void onResume() {
316 super.onResume();
317 }
318
319
320 @Override
321 public void onPause() {
322 super.onPause();
323 }
324
325 @Override
326 public void onDestroy() {
327 if (mBitmap != null) {
328 mBitmap.recycle();
329 System.gc();
330 }
331 super.onDestroy();
332 }
333
334
335 /**
336 * Opens the previewed image with an external application.
337 */
338 private void openFile() {
339 mContainerActivity.getFileOperationsHelper().openFile(getFile());
340 finish();
341 }
342
343
344 private class LoadBitmapTask extends AsyncTask<String, Void, Bitmap> {
345
346 /**
347 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
348 *
349 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
350 */
351 private final WeakReference<ImageViewCustom> mImageViewRef;
352
353 /**
354 * Weak reference to the target {@link TextView} where error messages will be written.
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<TextView> mMessageViewRef;
359
360
361 /**
362 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
363 *
364 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
365 */
366 private final WeakReference<ProgressBar> mProgressWheelRef;
367
368
369 /**
370 * Error message to show when a load fails
371 */
372 private int mErrorMessageId;
373
374
375 /**
376 * Constructor.
377 *
378 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
379 */
380 public LoadBitmapTask(ImageViewCustom imageView, TextView messageView, ProgressBar progressWheel) {
381 mImageViewRef = new WeakReference<ImageViewCustom>(imageView);
382 mMessageViewRef = new WeakReference<TextView>(messageView);
383 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
384 }
385
386
387 @Override
388 protected Bitmap doInBackground(String... params) {
389 Bitmap result = null;
390 if (params.length != 1) return result;
391 String storagePath = params[0];
392 try {
393
394 if (isCancelled()) return result;
395
396 File picture = new File(storagePath);
397
398 if (picture != null) {
399 // Decode file into a bitmap in real size for being able to make zoom on
400 // the image
401 result = BitmapFactory.decodeStream(new FlushedInputStream
402 (new BufferedInputStream(new FileInputStream(picture))));
403 }
404
405 if (isCancelled()) return result;
406
407 if (result == null) {
408 mErrorMessageId = R.string.preview_image_error_unknown_format;
409 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
410 } else {
411 // Rotate image, obeying exif tag.
412 result = BitmapUtils.rotateImage(result, storagePath);
413 }
414
415 } catch (OutOfMemoryError e) {
416 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
417
418 if (isCancelled()) return result;
419
420 // If out of memory error when loading or rotating image, try to load it scaled
421 result = loadScaledImage(storagePath);
422
423 if (result == null) {
424 mErrorMessageId = R.string.preview_image_error_unknown_format;
425 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
426 } else {
427 // Rotate scaled image, obeying exif tag
428 result = BitmapUtils.rotateImage(result, storagePath);
429 }
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 "
434 + storagePath, e);
435
436 } catch (Throwable t) {
437 mErrorMessageId = R.string.common_error_unknown;
438 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
439
440 }
441
442 return result;
443 }
444
445 @Override
446 protected void onCancelled(Bitmap result) {
447 if (result != null) {
448 result.recycle();
449 }
450 }
451
452 @Override
453 protected void onPostExecute(Bitmap result) {
454 hideProgressWheel();
455 if (result != null) {
456 showLoadedImage(result);
457 } else {
458 showErrorMessage();
459 }
460 }
461
462 @SuppressLint("InlinedApi")
463 private void showLoadedImage(Bitmap result) {
464 if (mImageViewRef != null) {
465 final ImageViewCustom imageView = mImageViewRef.get();
466 if (imageView != null) {
467 imageView.setBitmap(result);
468 imageView.setImageBitmap(result);
469 imageView.setVisibility(View.VISIBLE);
470 mBitmap = result;
471 } // else , silently finish, the fragment was destroyed
472 }
473 if (mMessageViewRef != null) {
474 final TextView messageView = mMessageViewRef.get();
475 if (messageView != null) {
476 messageView.setVisibility(View.GONE);
477 } // else , silently finish, the fragment was destroyed
478 }
479 }
480
481 private void showErrorMessage() {
482 if (mImageViewRef != null) {
483 final ImageView imageView = mImageViewRef.get();
484 if (imageView != null) {
485 // shows the default error icon
486 imageView.setVisibility(View.VISIBLE);
487 } // else , silently finish, the fragment was destroyed
488 }
489 if (mMessageViewRef != null) {
490 final TextView messageView = mMessageViewRef.get();
491 if (messageView != null) {
492 messageView.setText(mErrorMessageId);
493 messageView.setVisibility(View.VISIBLE);
494 } // else , silently finish, the fragment was destroyed
495 }
496 }
497
498 private void hideProgressWheel() {
499 if (mProgressWheelRef != null) {
500 final ProgressBar progressWheel = mProgressWheelRef.get();
501 if (progressWheel != null) {
502 progressWheel.setVisibility(View.GONE);
503 }
504 }
505 }
506
507 }
508
509 /**
510 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
511 *
512 * @param file File to test if can be previewed.
513 * @return 'True' if the file can be handled by the fragment.
514 */
515 public static boolean canBePreviewed(OCFile file) {
516 return (file != null && file.isImage());
517 }
518
519
520 /**
521 * Finishes the preview
522 */
523 private void finish() {
524 Activity container = getActivity();
525 container.finish();
526 }
527
528 public TouchImageViewCustom getImageView() {
529 return mImageView;
530 }
531
532 static class FlushedInputStream extends FilterInputStream {
533 public FlushedInputStream(InputStream inputStream) {
534 super(inputStream);
535 }
536
537 @Override
538 public long skip(long n) throws IOException {
539 long totalBytesSkipped = 0L;
540 while (totalBytesSkipped < n) {
541 long bytesSkipped = in.skip(n - totalBytesSkipped);
542 if (bytesSkipped == 0L) {
543 int byteValue = read();
544 if (byteValue < 0) {
545 break; // we reached EOF
546 } else {
547 bytesSkipped = 1; // we read one byte
548 }
549 }
550 totalBytesSkipped += bytesSkipped;
551 }
552 return totalBytesSkipped;
553 }
554 }
555
556 /**
557 * Load image scaled
558 * @param storagePath: path of the image
559 * @return Bitmap
560 */
561 @SuppressWarnings("deprecation")
562 private Bitmap loadScaledImage(String storagePath) {
563
564 Log_OC.d(TAG, "Loading image scaled");
565
566 // set desired options that will affect the size of the bitmap
567 BitmapFactory.Options options = new Options();
568 options.inScaled = true;
569 options.inPurgeable = true;
570 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
571 options.inPreferQualityOverSpeed = false;
572 }
573 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
574 options.inMutable = false;
575 }
576 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
577 options.inJustDecodeBounds = true;
578 BitmapFactory.decodeFile(storagePath, options);
579
580 int width = options.outWidth;
581 int height = options.outHeight;
582 int scale = 1;
583
584 Display display = getActivity().getWindowManager().getDefaultDisplay();
585 Point size = new Point();
586 int screenWidth;
587 int screenHeight;
588 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
589 display.getSize(size);
590 screenWidth = size.x;
591 screenHeight = size.y;
592 } else {
593 screenWidth = display.getWidth();
594 screenHeight = display.getHeight();
595 }
596
597 if (width > screenWidth) {
598 // second try to scale down the image , this time depending upon the screen size
599 scale = (int) Math.floor((float)width / screenWidth);
600 }
601 if (height > screenHeight) {
602 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
603 }
604 options.inSampleSize = scale;
605
606 // really load the bitmap
607 options.inJustDecodeBounds = false; // the next decodeFile call will be real
608 return BitmapFactory.decodeFile(storagePath, options);
609
610 }
611 }