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