Merge branch 'develop' into refactor_update_filelist_from_database
[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.content.ActivityNotFoundException;
28 import android.content.Intent;
29 import android.graphics.Bitmap;
30 import android.graphics.BitmapFactory;
31 import android.graphics.BitmapFactory.Options;
32 import android.graphics.Point;
33 import android.net.Uri;
34 import android.os.AsyncTask;
35 import android.os.Bundle;
36 import android.os.Handler;
37 import android.support.v4.app.FragmentStatePagerAdapter;
38 import android.view.Display;
39 import android.view.LayoutInflater;
40 import android.view.View;
41 import android.view.View.OnTouchListener;
42 import android.view.ViewGroup;
43 import android.webkit.MimeTypeMap;
44 import android.widget.ImageView;
45 import android.widget.ProgressBar;
46 import android.widget.TextView;
47 import android.widget.Toast;
48
49 import com.actionbarsherlock.view.Menu;
50 import com.actionbarsherlock.view.MenuInflater;
51 import com.actionbarsherlock.view.MenuItem;
52 import com.owncloud.android.R;
53 import com.owncloud.android.datamodel.FileDataStorageManager;
54 import com.owncloud.android.datamodel.OCFile;
55 import com.owncloud.android.lib.common.network.WebdavUtils;
56 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
57 import com.owncloud.android.lib.common.operations.RemoteOperation;
58 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
59 import com.owncloud.android.operations.RemoveFileOperation;
60 import com.owncloud.android.ui.activity.FileActivity;
61 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
62 import com.owncloud.android.ui.fragment.FileFragment;
63 import com.owncloud.android.utils.Log_OC;
64
65
66 /**
67 * This fragment shows a preview of a downloaded image.
68 *
69 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
70 *
71 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
72 *
73 * @author David A. Velasco
74 */
75 public class PreviewImageFragment extends FileFragment implements OnRemoteOperationListener,
76 ConfirmationDialogFragment.ConfirmationDialogFragmentListener {
77 public static final String EXTRA_FILE = "FILE";
78 public static final String EXTRA_ACCOUNT = "ACCOUNT";
79
80 private View mView;
81 private Account mAccount;
82 private ImageView mImageView;
83 private TextView mMessageView;
84 private ProgressBar mProgressWheel;
85
86 public Bitmap mBitmap = null;
87
88 private Handler mHandler;
89 private RemoteOperation mLastRemoteOperation;
90
91 private static final String TAG = PreviewImageFragment.class.getSimpleName();
92
93 private boolean mIgnoreFirstSavedState;
94
95
96 /**
97 * Creates a fragment to preview an image.
98 *
99 * When 'imageFile' or 'ocAccount' are null
100 *
101 * @param imageFile An {@link OCFile} to preview as an image in the fragment
102 * @param ocAccount An ownCloud account; needed to start downloads
103 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
104 */
105 public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
106 super(fileToDetail);
107 mAccount = ocAccount;
108 mIgnoreFirstSavedState = ignoreFirstSavedState;
109 }
110
111
112 /**
113 * Creates an empty fragment for image previews.
114 *
115 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
116 *
117 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
118 */
119 public PreviewImageFragment() {
120 super();
121 mAccount = null;
122 mIgnoreFirstSavedState = false;
123 }
124
125
126 /**
127 * {@inheritDoc}
128 */
129 @Override
130 public void onCreate(Bundle savedInstanceState) {
131 super.onCreate(savedInstanceState);
132 mHandler = new Handler();
133 setHasOptionsMenu(true);
134 }
135
136
137 /**
138 * {@inheritDoc}
139 */
140 @Override
141 public View onCreateView(LayoutInflater inflater, ViewGroup container,
142 Bundle savedInstanceState) {
143 super.onCreateView(inflater, container, savedInstanceState);
144 mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
145 mImageView = (ImageView)mView.findViewById(R.id.image);
146 mImageView.setVisibility(View.GONE);
147 mView.setOnTouchListener((OnTouchListener)getActivity()); // WATCH OUT THAT CAST
148 mMessageView = (TextView)mView.findViewById(R.id.message);
149 mMessageView.setVisibility(View.GONE);
150 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
151 mProgressWheel.setVisibility(View.VISIBLE);
152 return mView;
153 }
154
155
156 /**
157 * {@inheritDoc}
158 */
159 @Override
160 public void onAttach(Activity activity) {
161 super.onAttach(activity);
162 if (!(activity instanceof FileFragment.ContainerActivity))
163 throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
164 }
165
166
167 /**
168 * {@inheritDoc}
169 */
170 @Override
171 public void onActivityCreated(Bundle savedInstanceState) {
172 super.onActivityCreated(savedInstanceState);
173 if (savedInstanceState != null) {
174 if (!mIgnoreFirstSavedState) {
175 OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
176 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
177
178 // Update the file
179 if (mAccount!= null) {
180 OCFile updatedFile = ((FileActivity)getSherlockActivity()).
181 getStorageManager().getFileByPath(file.getRemotePath());
182 if (updatedFile != null) {
183 setFile(updatedFile);
184 } else {
185 setFile(file);
186 }
187 } else {
188 setFile(file);
189 }
190
191 } else {
192 mIgnoreFirstSavedState = false;
193 }
194 }
195 if (getFile() == null) {
196 throw new IllegalStateException("Instanced with a NULL OCFile");
197 }
198 if (mAccount == null) {
199 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
200 }
201 if (!getFile().isDown()) {
202 throw new IllegalStateException("There is no local file to preview");
203 }
204 }
205
206
207 /**
208 * {@inheritDoc}
209 */
210 @Override
211 public void onSaveInstanceState(Bundle outState) {
212 super.onSaveInstanceState(outState);
213 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
214 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
215 }
216
217
218 @Override
219 public void onStart() {
220 super.onStart();
221 if (getFile() != null) {
222 BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
223 bl.execute(new String[]{getFile().getStoragePath()});
224 }
225 }
226
227
228 /**
229 * {@inheritDoc}
230 */
231 @Override
232 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
233 super.onCreateOptionsMenu(menu, inflater);
234
235 inflater.inflate(R.menu.file_actions_menu, menu);
236 List<Integer> toHide = new ArrayList<Integer>();
237
238 MenuItem item = null;
239 toHide.add(R.id.action_cancel_download);
240 toHide.add(R.id.action_cancel_upload);
241 toHide.add(R.id.action_download_file);
242 toHide.add(R.id.action_rename_file); // by now
243
244 // Options shareLink
245 if (!getFile().isShareByLink()) {
246 toHide.add(R.id.action_unshare_file);
247 }
248
249 // Send file
250 boolean sendEnabled = getString(R.string.send_files_to_other_apps).equalsIgnoreCase("on");
251 if (!sendEnabled) {
252 toHide.add(R.id.action_send_file);
253 }
254
255 for (int i : toHide) {
256 item = menu.findItem(i);
257 if (item != null) {
258 item.setVisible(false);
259 item.setEnabled(false);
260 }
261 }
262
263 }
264
265 /**
266 * {@inheritDoc}
267 */
268 @Override
269 public void onPrepareOptionsMenu(Menu menu) {
270 super.onPrepareOptionsMenu(menu);
271
272 MenuItem item = menu.findItem(R.id.action_unshare_file);
273 // Options shareLink
274 OCFile file = ((FileActivity) getSherlockActivity()).getFile();
275 if (!file.isShareByLink()) {
276 item.setVisible(false);
277 item.setEnabled(false);
278 } else {
279 item.setVisible(true);
280 item.setEnabled(true);
281 }
282
283 }
284
285
286
287 /**
288 * {@inheritDoc}
289 */
290 @Override
291 public boolean onOptionsItemSelected(MenuItem item) {
292 switch (item.getItemId()) {
293 case R.id.action_share_file: {
294 FileActivity act = (FileActivity)getSherlockActivity();
295 act.getFileOperationsHelper().shareFileWithLink(getFile(), act);
296 return true;
297 }
298 case R.id.action_unshare_file: {
299 FileActivity act = (FileActivity)getSherlockActivity();
300 act.getFileOperationsHelper().unshareFileWithLink(getFile(), act);
301 return true;
302 }
303 case R.id.action_open_file_with: {
304 openFile();
305 return true;
306 }
307 case R.id.action_remove_file: {
308 removeFile();
309 return true;
310 }
311 case R.id.action_see_details: {
312 seeDetails();
313 return true;
314 }
315 case R.id.action_send_file: {
316 FileActivity act = (FileActivity)getSherlockActivity();
317 act.getFileOperationsHelper().sendDownloadedFile(getFile(), act);
318 return true;
319 }
320
321 default:
322 return false;
323 }
324 }
325
326
327 private void seeDetails() {
328 ((FileFragment.ContainerActivity)getActivity()).showDetails(getFile());
329 }
330
331
332 @Override
333 public void onResume() {
334 super.onResume();
335 }
336
337
338 @Override
339 public void onPause() {
340 super.onPause();
341 }
342
343
344 @Override
345 public void onDestroy() {
346 super.onDestroy();
347 if (mBitmap != null) {
348 mBitmap.recycle();
349 }
350 }
351
352
353 /**
354 * Opens the previewed image with an external application.
355 *
356 * TODO - improve this; instead of prioritize the actions available for the MIME type in the server,
357 * we should get a list of available apps for MIME tpye in the server and join it with the list of
358 * available apps for the MIME type known from the file extension, to let the user choose
359 */
360 private void openFile() {
361 OCFile file = getFile();
362 String storagePath = file.getStoragePath();
363 String encodedStoragePath = WebdavUtils.encodePath(storagePath);
364 try {
365 Intent i = new Intent(Intent.ACTION_VIEW);
366 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), file.getMimetype());
367 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
368 startActivity(i);
369
370 } catch (Throwable t) {
371 Log_OC.e(TAG, "Fail when trying to open with the mimeType provided from the ownCloud server: " + file.getMimetype());
372 boolean toastIt = true;
373 String mimeType = "";
374 try {
375 Intent i = new Intent(Intent.ACTION_VIEW);
376 mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
377 if (mimeType == null || !mimeType.equals(file.getMimetype())) {
378 if (mimeType != null) {
379 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), mimeType);
380 } else {
381 // desperate try
382 i.setDataAndType(Uri.parse("file://"+ encodedStoragePath), "*-/*");
383 }
384 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
385 startActivity(i);
386 toastIt = false;
387 }
388
389 } catch (IndexOutOfBoundsException e) {
390 Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);
391
392 } catch (ActivityNotFoundException e) {
393 Log_OC.e(TAG, "No activity found to handle: " + storagePath + " with MIME type " + mimeType + " obtained from extension");
394
395 } catch (Throwable th) {
396 Log_OC.e(TAG, "Unexpected problem when opening: " + storagePath, th);
397
398 } finally {
399 if (toastIt) {
400 Toast.makeText(getActivity(), "There is no application to handle file " + file.getFileName(), Toast.LENGTH_SHORT).show();
401 }
402 }
403
404 }
405 finish();
406 }
407
408
409 /**
410 * Starts a the removal of the previewed file.
411 *
412 * Shows a confirmation dialog. The action continues in {@link #onConfirmation(String)} , {@link #onNeutral(String)} or {@link #onCancel(String)},
413 * depending upon the user selection in the dialog.
414 */
415 private void removeFile() {
416 ConfirmationDialogFragment confDialog = ConfirmationDialogFragment.newInstance(
417 R.string.confirmation_remove_alert,
418 new String[]{getFile().getFileName()},
419 R.string.confirmation_remove_remote_and_local,
420 R.string.confirmation_remove_local,
421 R.string.common_cancel);
422 confDialog.setOnConfirmationListener(this);
423 confDialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
424 }
425
426
427 /**
428 * Performs the removal of the previewed file, both locally and in the server.
429 */
430 @Override
431 public void onConfirmation(String callerTag) {
432 FileDataStorageManager storageManager =
433 ((FileActivity)getSherlockActivity()).getStorageManager();
434 if (storageManager.getFileById(getFile().getFileId()) != null) { // check that the file is still there;
435 mLastRemoteOperation = new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
436 true,
437 storageManager);
438 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
439
440 ((FileActivity) getActivity()).showLoadingDialog();
441 }
442 }
443
444
445 /**
446 * Removes the file from local storage
447 */
448 @Override
449 public void onNeutral(String callerTag) {
450 OCFile file = getFile();
451 ((FileActivity)getSherlockActivity()).getStorageManager().removeFile(file, false, true); // TODO perform in background task / new thread
452 finish();
453 }
454
455 /**
456 * User cancelled the removal action.
457 */
458 @Override
459 public void onCancel(String callerTag) {
460 // nothing to do here
461 }
462
463
464 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
465
466 /**
467 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
468 *
469 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
470 */
471 private final WeakReference<ImageView> mImageViewRef;
472
473 /**
474 * Weak reference to the target {@link TextView} where error messages will be written.
475 *
476 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
477 */
478 private final WeakReference<TextView> mMessageViewRef;
479
480
481 /**
482 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
483 *
484 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
485 */
486 private final WeakReference<ProgressBar> mProgressWheelRef;
487
488
489 /**
490 * Error message to show when a load fails
491 */
492 private int mErrorMessageId;
493
494
495 /**
496 * Constructor.
497 *
498 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
499 */
500 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
501 mImageViewRef = new WeakReference<ImageView>(imageView);
502 mMessageViewRef = new WeakReference<TextView>(messageView);
503 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
504 }
505
506
507 @SuppressWarnings("deprecation")
508 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
509 @Override
510 protected Bitmap doInBackground(String... params) {
511 Bitmap result = null;
512 if (params.length != 1) return result;
513 String storagePath = params[0];
514 try {
515 // set desired options that will affect the size of the bitmap
516 BitmapFactory.Options options = new Options();
517 options.inScaled = true;
518 options.inPurgeable = true;
519 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
520 options.inPreferQualityOverSpeed = false;
521 }
522 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
523 options.inMutable = false;
524 }
525 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
526 options.inJustDecodeBounds = true;
527 BitmapFactory.decodeFile(storagePath, options);
528
529 int width = options.outWidth;
530 int height = options.outHeight;
531 int scale = 1;
532
533 Display display = getActivity().getWindowManager().getDefaultDisplay();
534 Point size = new Point();
535 int screenWidth;
536 int screenHeight;
537 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
538 display.getSize(size);
539 screenWidth = size.x;
540 screenHeight = size.y;
541 } else {
542 screenWidth = display.getWidth();
543 screenHeight = display.getHeight();
544 }
545
546 if (width > screenWidth) {
547 // second try to scale down the image , this time depending upon the screen size
548 scale = (int) Math.floor((float)width / screenWidth);
549 }
550 if (height > screenHeight) {
551 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
552 }
553 options.inSampleSize = scale;
554
555 // really load the bitmap
556 options.inJustDecodeBounds = false; // the next decodeFile call will be real
557 result = BitmapFactory.decodeFile(storagePath, options);
558 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
559
560 if (result == null) {
561 mErrorMessageId = R.string.preview_image_error_unknown_format;
562 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
563 }
564
565 } catch (OutOfMemoryError e) {
566 mErrorMessageId = R.string.preview_image_error_unknown_format;
567 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
568
569 } catch (NoSuchFieldError e) {
570 mErrorMessageId = R.string.common_error_unknown;
571 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
572
573 } catch (Throwable t) {
574 mErrorMessageId = R.string.common_error_unknown;
575 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
576
577 }
578 return result;
579 }
580
581 @Override
582 protected void onPostExecute(Bitmap result) {
583 hideProgressWheel();
584 if (result != null) {
585 showLoadedImage(result);
586 } else {
587 showErrorMessage();
588 }
589 }
590
591 private void showLoadedImage(Bitmap result) {
592 if (mImageViewRef != null) {
593 final ImageView imageView = mImageViewRef.get();
594 if (imageView != null) {
595 imageView.setImageBitmap(result);
596 imageView.setVisibility(View.VISIBLE);
597 mBitmap = result;
598 } // else , silently finish, the fragment was destroyed
599 }
600 if (mMessageViewRef != null) {
601 final TextView messageView = mMessageViewRef.get();
602 if (messageView != null) {
603 messageView.setVisibility(View.GONE);
604 } // else , silently finish, the fragment was destroyed
605 }
606 }
607
608 private void showErrorMessage() {
609 if (mImageViewRef != null) {
610 final ImageView imageView = mImageViewRef.get();
611 if (imageView != null) {
612 // shows the default error icon
613 imageView.setVisibility(View.VISIBLE);
614 } // else , silently finish, the fragment was destroyed
615 }
616 if (mMessageViewRef != null) {
617 final TextView messageView = mMessageViewRef.get();
618 if (messageView != null) {
619 messageView.setText(mErrorMessageId);
620 messageView.setVisibility(View.VISIBLE);
621 } // else , silently finish, the fragment was destroyed
622 }
623 }
624
625 private void hideProgressWheel() {
626 if (mProgressWheelRef != null) {
627 final ProgressBar progressWheel = mProgressWheelRef.get();
628 if (progressWheel != null) {
629 progressWheel.setVisibility(View.GONE);
630 }
631 }
632 }
633
634 }
635
636 /**
637 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
638 *
639 * @param file File to test if can be previewed.
640 * @return 'True' if the file can be handled by the fragment.
641 */
642 public static boolean canBePreviewed(OCFile file) {
643 return (file != null && file.isImage());
644 }
645
646
647 /**
648 * {@inheritDoc}
649 */
650 @Override
651 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
652 if (operation.equals(mLastRemoteOperation) && operation instanceof RemoveFileOperation) {
653 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
654 }
655 }
656
657 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
658 ((FileActivity) getActivity()).dismissLoadingDialog();
659
660 if (result.isSuccess()) {
661 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
662 msg.show();
663 finish();
664
665 } else {
666 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
667 msg.show();
668 if (result.isSslRecoverableException()) {
669 // TODO show the SSL warning dialog
670 }
671 }
672 }
673
674 /**
675 * Finishes the preview
676 */
677 private void finish() {
678 Activity container = getActivity();
679 container.finish();
680 }
681
682
683 }