trigger Media Scan on:
[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 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.media.MediaScannerConnection;
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.Log_OC;
54 import com.owncloud.android.R;
55 import com.owncloud.android.datamodel.FileDataStorageManager;
56 import com.owncloud.android.datamodel.OCFile;
57 import com.owncloud.android.operations.OnRemoteOperationListener;
58 import com.owncloud.android.operations.RemoteOperation;
59 import com.owncloud.android.operations.RemoteOperationResult;
60 import com.owncloud.android.operations.RemoveFileOperation;
61 import com.owncloud.android.ui.fragment.ConfirmationDialogFragment;
62 import com.owncloud.android.ui.fragment.FileFragment;
63
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 String path = new File(getFile().getStoragePath()).getParent();
378 mLastRemoteOperation = new RemoveFileOperation( getFile(), // TODO we need to review the interface with RemoteOperations, and use OCFile IDs instead of OCFile objects as parameters
379 true,
380 mStorageManager);
381 mLastRemoteOperation.execute(mAccount, getSherlockActivity(), this, mHandler, getSherlockActivity());
382
383 ((PreviewImageActivity) getActivity()).showLoadingDialog();
384
385 triggerMediaScan(path);
386 }
387 }
388
389
390 /**
391 * Removes the file from local storage
392 */
393 @Override
394 public void onNeutral(String callerTag) {
395 // TODO this code should be made in a secondary thread,
396 OCFile file = getFile();
397 if (file.isDown()) { // checks it is still there
398 File f = new File(file.getStoragePath());
399 String path = f.getParent();
400 f.delete();
401
402 triggerMediaScan(path);
403
404 file.setStoragePath(null);
405 mStorageManager.saveFile(file);
406 finish();
407 }
408 }
409
410 /**
411 * User cancelled the removal action.
412 */
413 @Override
414 public void onCancel(String callerTag) {
415 // nothing to do here
416 }
417
418 private void triggerMediaScan(String path){
419 MediaScannerConnection.scanFile(
420 getActivity().getApplicationContext(),
421 new String[]{path},
422 null,null);
423 }
424
425
426 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
427
428 /**
429 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
430 *
431 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
432 */
433 private final WeakReference<ImageView> mImageViewRef;
434
435 /**
436 * Weak reference to the target {@link TextView} where error messages will be written.
437 *
438 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
439 */
440 private final WeakReference<TextView> mMessageViewRef;
441
442
443 /**
444 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
445 *
446 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
447 */
448 private final WeakReference<ProgressBar> mProgressWheelRef;
449
450
451 /**
452 * Error message to show when a load fails
453 */
454 private int mErrorMessageId;
455
456
457 /**
458 * Constructor.
459 *
460 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
461 */
462 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
463 mImageViewRef = new WeakReference<ImageView>(imageView);
464 mMessageViewRef = new WeakReference<TextView>(messageView);
465 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
466 }
467
468
469 @SuppressWarnings("deprecation")
470 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
471 @Override
472 protected Bitmap doInBackground(String... params) {
473 Bitmap result = null;
474 if (params.length != 1) return result;
475 String storagePath = params[0];
476 try {
477 // set desired options that will affect the size of the bitmap
478 BitmapFactory.Options options = new Options();
479 options.inScaled = true;
480 options.inPurgeable = true;
481 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
482 options.inPreferQualityOverSpeed = false;
483 }
484 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
485 options.inMutable = false;
486 }
487 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
488 options.inJustDecodeBounds = true;
489 BitmapFactory.decodeFile(storagePath, options);
490
491 int width = options.outWidth;
492 int height = options.outHeight;
493 int scale = 1;
494
495 Display display = getActivity().getWindowManager().getDefaultDisplay();
496 Point size = new Point();
497 int screenWidth;
498 int screenHeight;
499 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
500 display.getSize(size);
501 screenWidth = size.x;
502 screenHeight = size.y;
503 } else {
504 screenWidth = display.getWidth();
505 screenHeight = display.getHeight();
506 }
507
508 if (width > screenWidth) {
509 // second try to scale down the image , this time depending upon the screen size
510 scale = (int) Math.floor((float)width / screenWidth);
511 }
512 if (height > screenHeight) {
513 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
514 }
515 options.inSampleSize = scale;
516
517 // really load the bitmap
518 options.inJustDecodeBounds = false; // the next decodeFile call will be real
519 result = BitmapFactory.decodeFile(storagePath, options);
520 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
521
522 if (result == null) {
523 mErrorMessageId = R.string.preview_image_error_unknown_format;
524 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
525 }
526
527 } catch (OutOfMemoryError e) {
528 mErrorMessageId = R.string.preview_image_error_unknown_format;
529 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
530
531 } catch (NoSuchFieldError e) {
532 mErrorMessageId = R.string.common_error_unknown;
533 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
534
535 } catch (Throwable t) {
536 mErrorMessageId = R.string.common_error_unknown;
537 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
538
539 }
540 return result;
541 }
542
543 @Override
544 protected void onPostExecute(Bitmap result) {
545 hideProgressWheel();
546 if (result != null) {
547 showLoadedImage(result);
548 } else {
549 showErrorMessage();
550 }
551 }
552
553 private void showLoadedImage(Bitmap result) {
554 if (mImageViewRef != null) {
555 final ImageView imageView = mImageViewRef.get();
556 if (imageView != null) {
557 imageView.setImageBitmap(result);
558 imageView.setVisibility(View.VISIBLE);
559 mBitmap = result;
560 } // else , silently finish, the fragment was destroyed
561 }
562 if (mMessageViewRef != null) {
563 final TextView messageView = mMessageViewRef.get();
564 if (messageView != null) {
565 messageView.setVisibility(View.GONE);
566 } // else , silently finish, the fragment was destroyed
567 }
568 }
569
570 private void showErrorMessage() {
571 if (mImageViewRef != null) {
572 final ImageView imageView = mImageViewRef.get();
573 if (imageView != null) {
574 // shows the default error icon
575 imageView.setVisibility(View.VISIBLE);
576 } // else , silently finish, the fragment was destroyed
577 }
578 if (mMessageViewRef != null) {
579 final TextView messageView = mMessageViewRef.get();
580 if (messageView != null) {
581 messageView.setText(mErrorMessageId);
582 messageView.setVisibility(View.VISIBLE);
583 } // else , silently finish, the fragment was destroyed
584 }
585 }
586
587 private void hideProgressWheel() {
588 if (mProgressWheelRef != null) {
589 final ProgressBar progressWheel = mProgressWheelRef.get();
590 if (progressWheel != null) {
591 progressWheel.setVisibility(View.GONE);
592 }
593 }
594 }
595
596 }
597
598 /**
599 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
600 *
601 * @param file File to test if can be previewed.
602 * @return 'True' if the file can be handled by the fragment.
603 */
604 public static boolean canBePreviewed(OCFile file) {
605 return (file != null && file.isImage());
606 }
607
608
609 /**
610 * {@inheritDoc}
611 */
612 @Override
613 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
614 if (operation.equals(mLastRemoteOperation) && operation instanceof RemoveFileOperation) {
615 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
616 }
617 }
618
619 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
620 ((PreviewImageActivity) getActivity()).dismissLoadingDialog();
621
622 if (result.isSuccess()) {
623 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
624 msg.show();
625 finish();
626
627 } else {
628 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
629 msg.show();
630 if (result.isSslRecoverableException()) {
631 // TODO show the SSL warning dialog
632 }
633 }
634 }
635
636 /**
637 * Finishes the preview
638 */
639 private void finish() {
640 Activity container = getActivity();
641 container.finish();
642 }
643
644
645 }