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