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