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