modify code to be simpler
[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.lang.ref.WeakReference;
23
24 import android.accounts.Account;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.graphics.Bitmap;
28 import android.graphics.Point;
29 import android.os.AsyncTask;
30 import android.os.Bundle;
31 import android.support.v4.app.FragmentStatePagerAdapter;
32 import android.view.LayoutInflater;
33 import android.view.Menu;
34 import android.view.MenuInflater;
35 import android.view.MenuItem;
36 import android.view.View;
37 import android.view.View.OnClickListener;
38 import android.view.ViewGroup;
39 import android.widget.ImageView;
40 import android.widget.ProgressBar;
41 import android.widget.TextView;
42
43 import com.owncloud.android.R;
44 import com.owncloud.android.datamodel.OCFile;
45 import com.owncloud.android.files.FileMenuFilter;
46 import com.owncloud.android.lib.common.utils.Log_OC;
47 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
48 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
49 import com.owncloud.android.ui.fragment.FileFragment;
50 import com.owncloud.android.utils.BitmapUtils;
51 import com.owncloud.android.utils.DisplayUtils;
52
53 import third_parties.michaelOrtiz.TouchImageViewCustom;
54
55
56 /**
57 * This fragment shows a preview of a downloaded image.
58 *
59 * Trying to get an instance with a NULL {@link OCFile} will produce an
60 * {@link IllegalStateException}.
61 *
62 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on
63 * instantiation too.
64 */
65 public class PreviewImageFragment extends FileFragment {
66
67 public static final String EXTRA_FILE = "FILE";
68
69 private static final String ARG_FILE = "FILE";
70 private static final String ARG_IGNORE_FIRST = "IGNORE_FIRST";
71
72 private TouchImageViewCustom mImageView;
73 private TextView mMessageView;
74 private ProgressBar mProgressWheel;
75
76 public Bitmap mBitmap = null;
77
78 private static final String TAG = PreviewImageFragment.class.getSimpleName();
79
80 private boolean mIgnoreFirstSavedState;
81
82 private LoadBitmapTask mLoadBitmapTask = null;
83
84
85 /**
86 * Public factory method to create a new fragment that previews an image.
87 *
88 * Android strongly recommends keep the empty constructor of fragments as the only public
89 * constructor, and
90 * use {@link #setArguments(Bundle)} to set the needed arguments.
91 *
92 * This method hides to client objects the need of doing the construction in two steps.
93 *
94 * @param imageFile An {@link OCFile} to preview as an image in the fragment
95 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of
96 * {@link FragmentStatePagerAdapter}
97 * ; TODO better solution
98 */
99 public static PreviewImageFragment newInstance(OCFile imageFile, boolean ignoreFirstSavedState){
100 PreviewImageFragment frag = new PreviewImageFragment();
101 Bundle args = new Bundle();
102 args.putParcelable(ARG_FILE, imageFile);
103 args.putBoolean(ARG_IGNORE_FIRST, ignoreFirstSavedState);
104 frag.setArguments(args);
105 return frag;
106 }
107
108
109
110 /**
111 * Creates an empty fragment for image previews.
112 *
113 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically
114 * (for instance, when the device is turned a aside).
115 *
116 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful
117 * construction
118 */
119 public PreviewImageFragment() {
120 mIgnoreFirstSavedState = false;
121 }
122
123
124 /**
125 * {@inheritDoc}
126 */
127 @Override
128 public void onCreate(Bundle savedInstanceState) {
129 super.onCreate(savedInstanceState);
130 Bundle args = getArguments();
131 setFile((OCFile)args.getParcelable(ARG_FILE));
132 // TODO better in super, but needs to check ALL the class extending FileFragment;
133 // not right now
134
135 mIgnoreFirstSavedState = args.getBoolean(ARG_IGNORE_FIRST);
136 setHasOptionsMenu(true);
137 }
138
139
140 /**
141 * {@inheritDoc}
142 */
143 @Override
144 public View onCreateView(LayoutInflater inflater, ViewGroup container,
145 Bundle savedInstanceState) {
146 super.onCreateView(inflater, container, savedInstanceState);
147 View view = inflater.inflate(R.layout.preview_image_fragment, container, false);
148 mImageView = (TouchImageViewCustom) view.findViewById(R.id.image);
149 mImageView.setVisibility(View.GONE);
150 mImageView.setOnClickListener(new OnClickListener() {
151 @Override
152 public void onClick(View v) {
153 ((PreviewImageActivity) getActivity()).toggleFullScreen();
154 }
155
156 });
157 mMessageView = (TextView)view.findViewById(R.id.message);
158 mMessageView.setVisibility(View.GONE);
159 mProgressWheel = (ProgressBar)view.findViewById(R.id.progressWheel);
160 mProgressWheel.setVisibility(View.VISIBLE);
161 return view;
162 }
163
164 /**
165 * {@inheritDoc}
166 */
167 @Override
168 public void onActivityCreated(Bundle savedInstanceState) {
169 super.onActivityCreated(savedInstanceState);
170 if (savedInstanceState != null) {
171 if (!mIgnoreFirstSavedState) {
172 OCFile file = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
173 setFile(file);
174 } else {
175 mIgnoreFirstSavedState = false;
176 }
177 }
178 if (getFile() == null) {
179 throw new IllegalStateException("Instanced with a NULL OCFile");
180 }
181 if (!getFile().isDown()) {
182 throw new IllegalStateException("There is no local file to preview");
183 }
184 }
185
186
187 /**
188 * {@inheritDoc}
189 */
190 @Override
191 public void onSaveInstanceState(Bundle outState) {
192 super.onSaveInstanceState(outState);
193 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
194 }
195
196
197 @Override
198 public void onStart() {
199 super.onStart();
200 if (getFile() != null) {
201 mLoadBitmapTask = new LoadBitmapTask(mImageView, mMessageView, mProgressWheel);
202 //mLoadBitmapTask.execute(new String[]{getFile().getStoragePath()});
203 mLoadBitmapTask.execute(getFile().getStoragePath());
204 }
205 }
206
207
208 @Override
209 public void onStop() {
210 Log_OC.d(TAG, "onStop starts");
211 if (mLoadBitmapTask != null) {
212 mLoadBitmapTask.cancel(true);
213 mLoadBitmapTask = null;
214 }
215 super.onStop();
216 }
217
218 /**
219 * {@inheritDoc}
220 */
221 @Override
222 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
223 super.onCreateOptionsMenu(menu, inflater);
224 inflater.inflate(R.menu.file_actions_menu, menu);
225 }
226
227 /**
228 * {@inheritDoc}
229 */
230 @Override
231 public void onPrepareOptionsMenu(Menu menu) {
232 super.onPrepareOptionsMenu(menu);
233
234 if (mContainerActivity.getStorageManager() != null) {
235 // Update the file
236 setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
237
238 FileMenuFilter mf = new FileMenuFilter(
239 getFile(),
240 mContainerActivity.getStorageManager().getAccount(),
241 mContainerActivity,
242 getActivity()
243 );
244 mf.filter(menu);
245 }
246
247 // additional restriction for this fragment
248 // TODO allow renaming in PreviewImageFragment
249 MenuItem item = menu.findItem(R.id.action_rename_file);
250 if (item != null) {
251 item.setVisible(false);
252 item.setEnabled(false);
253 }
254
255 // additional restriction for this fragment
256 // TODO allow refresh file in PreviewImageFragment
257 item = menu.findItem(R.id.action_sync_file);
258 if (item != null) {
259 item.setVisible(false);
260 item.setEnabled(false);
261 }
262
263 // additional restriction for this fragment
264 item = menu.findItem(R.id.action_move);
265 if (item != null) {
266 item.setVisible(false);
267 item.setEnabled(false);
268 }
269
270 }
271
272
273
274 /**
275 * {@inheritDoc}
276 */
277 @Override
278 public boolean onOptionsItemSelected(MenuItem item) {
279 switch (item.getItemId()) {
280 case R.id.action_share_file: {
281 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
282 return true;
283 }
284 case R.id.action_unshare_file: {
285 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
286 return true;
287 }
288 case R.id.action_open_file_with: {
289 openFile();
290 return true;
291 }
292 case R.id.action_remove_file: {
293 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
294 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
295 return true;
296 }
297 case R.id.action_see_details: {
298 seeDetails();
299 return true;
300 }
301 case R.id.action_send_file: {
302 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
303 return true;
304 }
305 case R.id.action_sync_file: {
306 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
307 return true;
308 }
309
310 default:
311 return false;
312 }
313 }
314
315
316 private void seeDetails() {
317 mContainerActivity.showDetails(getFile());
318 }
319
320
321 @Override
322 public void onResume() {
323 super.onResume();
324 }
325
326
327 @Override
328 public void onPause() {
329 super.onPause();
330 }
331
332 @Override
333 public void onDestroy() {
334 if (mBitmap != null) {
335 mBitmap.recycle();
336 System.gc();
337 // putting this in onStop() is just the same; the fragment is always destroyed by
338 // {@link FragmentStatePagerAdapter} when the fragment in swiped further than the
339 // valid offscreen distance, and onStop() is never called before than that
340 }
341 super.onDestroy();
342 }
343
344
345 /**
346 * Opens the previewed image with an external application.
347 */
348 private void openFile() {
349 mContainerActivity.getFileOperationsHelper().openFile(getFile());
350 finish();
351 }
352
353
354 private class LoadBitmapTask extends AsyncTask<String, Void, Bitmap> {
355
356 /**
357 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
358 *
359 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
360 * memory before the load finishes.
361 */
362 private final WeakReference<ImageViewCustom> mImageViewRef;
363
364 /**
365 * Weak reference to the target {@link TextView} where error messages will be written.
366 *
367 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
368 * memory before the load finishes.
369 */
370 private final WeakReference<TextView> mMessageViewRef;
371
372
373 /**
374 * Weak reference to the target {@link ProgressBar} shown while the load is in progress.
375 *
376 * Using a weak reference will avoid memory leaks if the target ImageView is retired from
377 * memory before the load finishes.
378 */
379 private final WeakReference<ProgressBar> mProgressWheelRef;
380
381
382 /**
383 * Error message to show when a load fails
384 */
385 private int mErrorMessageId;
386
387
388 /**
389 * Constructor.
390 *
391 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
392 */
393 public LoadBitmapTask(ImageViewCustom imageView, TextView messageView,
394 ProgressBar progressWheel) {
395 mImageViewRef = new WeakReference<ImageViewCustom>(imageView);
396 mMessageViewRef = new WeakReference<TextView>(messageView);
397 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
398 }
399
400
401 @Override
402 protected Bitmap doInBackground(String... params) {
403 Bitmap result = null;
404 if (params.length != 1) return null;
405 String storagePath = params[0];
406 try {
407
408 int maxDownScale = 3; // could be a parameter passed to doInBackground(...)
409 Point screenSize = DisplayUtils.getScreenSize(getActivity());
410 int minWidth = screenSize.x;
411 int minHeight = screenSize.y;
412 for (int i = 0; i < maxDownScale && result == null; i++) {
413 if (isCancelled()) return null;
414 try {
415 result = BitmapUtils.decodeSampledBitmapFromFile(storagePath, minWidth,
416 minHeight);
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 break;
424 } else {
425 // Rotate image, obeying exif tag.
426 result = BitmapUtils.rotateImage(result, storagePath);
427 }
428
429 } catch (OutOfMemoryError e) {
430 mErrorMessageId = R.string.common_error_out_memory;
431 if (i < maxDownScale - 1) {
432 Log_OC.w(TAG, "Out of memory rendering file " + storagePath +
433 " ; scaling down");
434 minWidth = minWidth / 2;
435 minHeight = minHeight / 2;
436
437 } else {
438 Log_OC.w(TAG, "Out of memory rendering file " + storagePath +
439 " ; failing");
440 }
441 if (result != null) {
442 result.recycle();
443 }
444 result = null;
445 }
446 }
447
448 } catch (NoSuchFieldError e) {
449 mErrorMessageId = R.string.common_error_unknown;
450 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file "
451 + storagePath, e);
452
453 } catch (Throwable t) {
454 mErrorMessageId = R.string.common_error_unknown;
455 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
456
457 }
458
459 return result;
460 }
461
462 @Override
463 protected void onCancelled(Bitmap result) {
464 if (result != null) {
465 result.recycle();
466 }
467 }
468
469 @Override
470 protected void onPostExecute(Bitmap result) {
471 hideProgressWheel();
472 if (result != null) {
473 showLoadedImage(result);
474 } else {
475 showErrorMessage();
476 }
477 if (result != null && mBitmap != result) {
478 // unused bitmap, release it! (just in case)
479 result.recycle();
480 }
481 }
482
483 @SuppressLint("InlinedApi")
484 private void showLoadedImage(Bitmap result) {
485 final ImageViewCustom imageView = mImageViewRef.get();
486 if (imageView != null) {
487 Log_OC.d(TAG, "Showing image with resolution " + result.getWidth() + "x" +
488 result.getHeight());
489 imageView.setImageBitmap(result);
490 imageView.setVisibility(View.VISIBLE);
491 mBitmap = result; // needs to be kept for recycling when not useful
492 }
493
494 final TextView messageView = mMessageViewRef.get();
495 if (messageView != null) {
496 messageView.setVisibility(View.GONE);
497 } // else , silently finish, the fragment was destroyed
498 }
499
500 private void showErrorMessage() {
501 final ImageView imageView = mImageViewRef.get();
502 if (imageView != null) {
503 // shows the default error icon
504 imageView.setVisibility(View.VISIBLE);
505 } // else , silently finish, the fragment was destroyed
506
507 final TextView messageView = mMessageViewRef.get();
508 if (messageView != null) {
509 messageView.setText(mErrorMessageId);
510 messageView.setVisibility(View.VISIBLE);
511 } // else , silently finish, the fragment was destroyed
512 }
513
514 private void hideProgressWheel() {
515 final ProgressBar progressWheel = mProgressWheelRef.get();
516 if (progressWheel != null) {
517 progressWheel.setVisibility(View.GONE);
518 }
519 }
520
521 }
522
523 /**
524 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment}
525 * to be previewed.
526 *
527 * @param file File to test if can be previewed.
528 * @return 'True' if the file can be handled by the fragment.
529 */
530 public static boolean canBePreviewed(OCFile file) {
531 return (file != null && file.isImage());
532 }
533
534
535 /**
536 * Finishes the preview
537 */
538 private void finish() {
539 Activity container = getActivity();
540 container.finish();
541 }
542
543 public TouchImageViewCustom getImageView() {
544 return mImageView;
545 }
546
547 }