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