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