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