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