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