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