b78ae5f1fc8644b95b2b86a4085150de50ff8a31
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 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.lang.ref.WeakReference;
20 import java.util.ArrayList;
21 import java.util.List;
22
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.BitmapFactory;
29 import android.graphics.BitmapFactory.Options;
30 import android.graphics.Point;
31 import android.os.AsyncTask;
32 import android.os.Bundle;
33 import android.support.v4.app.FragmentStatePagerAdapter;
34 import android.view.Display;
35 import android.view.LayoutInflater;
36 import android.view.View;
37 import android.view.View.OnTouchListener;
38 import android.view.ViewGroup;
39 import android.widget.ImageView;
40 import android.widget.ProgressBar;
41 import android.widget.TextView;
42
43 import com.actionbarsherlock.view.Menu;
44 import com.actionbarsherlock.view.MenuInflater;
45 import com.actionbarsherlock.view.MenuItem;
46 import com.owncloud.android.R;
47 import com.owncloud.android.datamodel.FileDataStorageManager;
48 import com.owncloud.android.datamodel.OCFile;
49 import com.owncloud.android.ui.activity.FileActivity;
50 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
51 import com.owncloud.android.ui.fragment.FileFragment;
52 import com.owncloud.android.utils.Log_OC;
53
54
55 /**
56 * This fragment shows a preview of a downloaded image.
57 *
58 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
59 *
60 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
61 *
62 * @author David A. Velasco
63 */
64 public class PreviewImageFragment extends FileFragment implements
65 ConfirmationDialogFragment.ConfirmationDialogFragmentListener {
66 public static final String EXTRA_FILE = "FILE";
67 public static final String EXTRA_ACCOUNT = "ACCOUNT";
68
69 private View mView;
70 private Account mAccount;
71 private ImageView mImageView;
72 private TextView mMessageView;
73 private ProgressBar mProgressWheel;
74
75 public Bitmap mBitmap = null;
76
77 private static final String TAG = PreviewImageFragment.class.getSimpleName();
78
79 private boolean mIgnoreFirstSavedState;
80
81
82 /**
83 * Creates a fragment to preview an image.
84 *
85 * When 'imageFile' or 'ocAccount' are null
86 *
87 * @param imageFile An {@link OCFile} to preview as an image in the fragment
88 * @param ocAccount An ownCloud account; needed to start downloads
89 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
90 */
91 public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
92 super(fileToDetail);
93 mAccount = ocAccount;
94 mIgnoreFirstSavedState = ignoreFirstSavedState;
95 }
96
97
98 /**
99 * Creates an empty fragment for image previews.
100 *
101 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
102 *
103 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
104 */
105 public PreviewImageFragment() {
106 super();
107 mAccount = null;
108 mIgnoreFirstSavedState = false;
109 }
110
111
112 /**
113 * {@inheritDoc}
114 */
115 @Override
116 public void onCreate(Bundle savedInstanceState) {
117 super.onCreate(savedInstanceState);
118 setHasOptionsMenu(true);
119 }
120
121
122 /**
123 * {@inheritDoc}
124 */
125 @Override
126 public View onCreateView(LayoutInflater inflater, ViewGroup container,
127 Bundle savedInstanceState) {
128 super.onCreateView(inflater, container, savedInstanceState);
129 mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
130 mImageView = (ImageView)mView.findViewById(R.id.image);
131 mImageView.setVisibility(View.GONE);
132 mView.setOnTouchListener((OnTouchListener)getActivity());
133 mMessageView = (TextView)mView.findViewById(R.id.message);
134 mMessageView.setVisibility(View.GONE);
135 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
136 mProgressWheel.setVisibility(View.VISIBLE);
137 return mView;
138 }
139
140
141 /**
142 * {@inheritDoc}
143 */
144 @Override
145 public void onAttach(Activity activity) {
146 super.onAttach(activity);
147 if (!(activity instanceof OnTouchListener)) {
148 throw new ClassCastException(activity.toString() +
149 " must implement " + OnTouchListener.class.getSimpleName());
150 }
151 }
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 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
164
165 // Update the file
166 if (mAccount!= null) {
167 OCFile updatedFile = ((FileActivity) getSherlockActivity()).
168 getStorageManager().getFileByPath(file.getRemotePath());
169 if (updatedFile != null) {
170 setFile(updatedFile);
171 } else {
172 setFile(file);
173 }
174 } else {
175 setFile(file);
176 }
177 } else {
178 mIgnoreFirstSavedState = false;
179 }
180 }
181 if (getFile() == null) {
182 throw new IllegalStateException("Instanced with a NULL OCFile");
183 }
184 if (mAccount == null) {
185 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
186 }
187 if (!getFile().isDown()) {
188 throw new IllegalStateException("There is no local file to preview");
189 }
190 }
191
192
193 /**
194 * {@inheritDoc}
195 */
196 @Override
197 public void onSaveInstanceState(Bundle outState) {
198 super.onSaveInstanceState(outState);
199 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
200 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
201 }
202
203
204 @Override
205 public void onStart() {
206 super.onStart();
207 if (getFile() != null) {
208 BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
209 bl.execute(new String[]{getFile().getStoragePath()});
210 }
211 }
212
213
214 /**
215 * {@inheritDoc}
216 */
217 @Override
218 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
219 super.onCreateOptionsMenu(menu, inflater);
220
221 inflater.inflate(R.menu.file_actions_menu, menu);
222 List<Integer> toHide = new ArrayList<Integer>();
223
224 MenuItem item = null;
225 toHide.add(R.id.action_cancel_download);
226 toHide.add(R.id.action_cancel_upload);
227 toHide.add(R.id.action_download_file);
228 toHide.add(R.id.action_rename_file); // by now
229
230 // Options shareLink
231 if (!getFile().isShareByLink()) {
232 toHide.add(R.id.action_unshare_file);
233 }
234
235 // Send file
236 boolean sendEnabled = getString(R.string.send_files_to_other_apps).equalsIgnoreCase("on");
237 if (!sendEnabled) {
238 toHide.add(R.id.action_send_file);
239 }
240
241 for (int i : toHide) {
242 item = menu.findItem(i);
243 if (item != null) {
244 item.setVisible(false);
245 item.setEnabled(false);
246 }
247 }
248
249 }
250
251 /**
252 * {@inheritDoc}
253 */
254 @Override
255 public void onPrepareOptionsMenu(Menu menu) {
256 super.onPrepareOptionsMenu(menu);
257
258 MenuItem item = menu.findItem(R.id.action_unshare_file);
259 // Options shareLink
260 if (!getFile().isShareByLink()) {
261 item.setVisible(false);
262 item.setEnabled(false);
263 } else {
264 item.setVisible(true);
265 item.setEnabled(true);
266 }
267
268 }
269
270
271
272 /**
273 * {@inheritDoc}
274 */
275 @Override
276 public boolean onOptionsItemSelected(MenuItem item) {
277 switch (item.getItemId()) {
278 case R.id.action_share_file: {
279 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
280 return true;
281 }
282 case R.id.action_unshare_file: {
283 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
284 return true;
285 }
286 case R.id.action_open_file_with: {
287 openFile();
288 return true;
289 }
290 case R.id.action_remove_file: {
291 removeFile();
292 return true;
293 }
294 case R.id.action_see_details: {
295 seeDetails();
296 return true;
297 }
298 case R.id.action_send_file: {
299 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(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
326 @Override
327 public void onDestroy() {
328 super.onDestroy();
329 if (mBitmap != null) {
330 mBitmap.recycle();
331 }
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 /**
345 * Starts a the removal of the previewed file.
346 *
347 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
348 * depending upon the user selection in the dialog.
349 */
350 private void removeFile() {
351 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
352 R.string.confirmation_remove_alert,
353 new String[]{getFile().getFileName()},
354 R.string.confirmation_remove_remote_and_local,
355 R.string.confirmation_remove_local,
356 R.string.common_cancel);
357 confDialog.setOnConfirmationListener(this);
358 confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
359 }
360
361
362 /**
363 * Performs the removal of the previewed file, both locally and in the server.
364 */
365 @Override
366 public void onConfirmation(String callerTag) {
367 FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
368 if (storageManager.getFileById(getFile().getFileId()) != null) { // check that the file is still there;
369 mContainerActivity.getFileOperationsHelper().removeFile(getFile(), true);
370 }
371 }
372
373
374 /**
375 * Removes the file from local storage
376 */
377 @Override
378 public void onNeutral(String callerTag) {
379 OCFile file = getFile();
380 mContainerActivity.getStorageManager().removeFile(file, false, true); // TODO perform in background task / new thread
381 finish();
382 }
383
384 /**
385 * User cancelled the removal action.
386 */
387 @Override
388 public void onCancel(String callerTag) {
389 // nothing to do here
390 }
391
392
393 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
394
395 /**
396 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
397 *
398 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
399 */
400 private final WeakReference<ImageView> mImageViewRef;
401
402 /**
403 * Weak reference to the target {@link TextView} where error messages will be written.
404 *
405 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
406 */
407 private final WeakReference<TextView> mMessageViewRef;
408
409
410 /**
411 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
412 *
413 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
414 */
415 private final WeakReference<ProgressBar> mProgressWheelRef;
416
417
418 /**
419 * Error message to show when a load fails
420 */
421 private int mErrorMessageId;
422
423
424 /**
425 * Constructor.
426 *
427 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
428 */
429 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
430 mImageViewRef = new WeakReference<ImageView>(imageView);
431 mMessageViewRef = new WeakReference<TextView>(messageView);
432 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
433 }
434
435
436 @SuppressWarnings("deprecation")
437 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
438 @Override
439 protected Bitmap doInBackground(String... params) {
440 Bitmap result = null;
441 if (params.length != 1) return result;
442 String storagePath = params[0];
443 try {
444 // set desired options that will affect the size of the bitmap
445 BitmapFactory.Options options = new Options();
446 options.inScaled = true;
447 options.inPurgeable = true;
448 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
449 options.inPreferQualityOverSpeed = false;
450 }
451 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
452 options.inMutable = false;
453 }
454 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
455 options.inJustDecodeBounds = true;
456 BitmapFactory.decodeFile(storagePath, options);
457
458 int width = options.outWidth;
459 int height = options.outHeight;
460 int scale = 1;
461
462 Display display = getActivity().getWindowManager().getDefaultDisplay();
463 Point size = new Point();
464 int screenWidth;
465 int screenHeight;
466 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
467 display.getSize(size);
468 screenWidth = size.x;
469 screenHeight = size.y;
470 } else {
471 screenWidth = display.getWidth();
472 screenHeight = display.getHeight();
473 }
474
475 if (width > screenWidth) {
476 // second try to scale down the image , this time depending upon the screen size
477 scale = (int) Math.floor((float)width / screenWidth);
478 }
479 if (height > screenHeight) {
480 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
481 }
482 options.inSampleSize = scale;
483
484 // really load the bitmap
485 options.inJustDecodeBounds = false; // the next decodeFile call will be real
486 result = BitmapFactory.decodeFile(storagePath, options);
487 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
488
489 if (result == null) {
490 mErrorMessageId = R.string.preview_image_error_unknown_format;
491 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
492 }
493
494 } catch (OutOfMemoryError e) {
495 mErrorMessageId = R.string.preview_image_error_unknown_format;
496 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
497
498 } catch (NoSuchFieldError e) {
499 mErrorMessageId = R.string.common_error_unknown;
500 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
501
502 } catch (Throwable t) {
503 mErrorMessageId = R.string.common_error_unknown;
504 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
505
506 }
507 return result;
508 }
509
510 @Override
511 protected void onPostExecute(Bitmap result) {
512 hideProgressWheel();
513 if (result != null) {
514 showLoadedImage(result);
515 } else {
516 showErrorMessage();
517 }
518 }
519
520 private void showLoadedImage(Bitmap result) {
521 if (mImageViewRef != null) {
522 final ImageView imageView = mImageViewRef.get();
523 if (imageView != null) {
524 imageView.setImageBitmap(result);
525 imageView.setVisibility(View.VISIBLE);
526 mBitmap = result;
527 } // else , silently finish, the fragment was destroyed
528 }
529 if (mMessageViewRef != null) {
530 final TextView messageView = mMessageViewRef.get();
531 if (messageView != null) {
532 messageView.setVisibility(View.GONE);
533 } // else , silently finish, the fragment was destroyed
534 }
535 }
536
537 private void showErrorMessage() {
538 if (mImageViewRef != null) {
539 final ImageView imageView = mImageViewRef.get();
540 if (imageView != null) {
541 // shows the default error icon
542 imageView.setVisibility(View.VISIBLE);
543 } // else , silently finish, the fragment was destroyed
544 }
545 if (mMessageViewRef != null) {
546 final TextView messageView = mMessageViewRef.get();
547 if (messageView != null) {
548 messageView.setText(mErrorMessageId);
549 messageView.setVisibility(View.VISIBLE);
550 } // else , silently finish, the fragment was destroyed
551 }
552 }
553
554 private void hideProgressWheel() {
555 if (mProgressWheelRef != null) {
556 final ProgressBar progressWheel = mProgressWheelRef.get();
557 if (progressWheel != null) {
558 progressWheel.setVisibility(View.GONE);
559 }
560 }
561 }
562
563 }
564
565 /**
566 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
567 *
568 * @param file File to test if can be previewed.
569 * @return 'True' if the file can be handled by the fragment.
570 */
571 public static boolean canBePreviewed(OCFile file) {
572 return (file != null && file.isImage());
573 }
574
575
576 /**
577 * Finishes the preview
578 */
579 private void finish() {
580 Activity container = getActivity();
581 container.finish();
582 }
583
584
585 }