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