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