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