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