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