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