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