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