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