Fixed rename of files when folder for local files is not already created
[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 version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17 package com.owncloud.android.ui.preview;
18
19 import java.io.File;
20 import java.lang.ref.WeakReference;
21 import java.util.ArrayList;
22 import java.util.List;
23
24
25 import android.accounts.Account;
26 import android.annotation.SuppressLint;
27 import android.app.Activity;
28 import android.content.ActivityNotFoundException;
29 import android.content.Intent;
30 import android.graphics.Bitmap;
31 import android.graphics.BitmapFactory;
32 import android.graphics.BitmapFactory.Options;
33 import android.graphics.Point;
34 import android.net.Uri;
35 import android.os.AsyncTask;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.support.v4.app.FragmentStatePagerAdapter;
39 import android.util.Log;
40 import android.view.Display;
41 import android.view.LayoutInflater;
42 import android.view.View;
43 import android.view.View.OnTouchListener;
44 import android.view.ViewGroup;
45 import android.webkit.MimeTypeMap;
46 import android.widget.ImageView;
47 import android.widget.ProgressBar;
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 private ProgressBar mProgressWheel;
92
93 public Bitmap mBitmap = null;
94
95 private Handler mHandler;
96 private RemoteOperation mLastRemoteOperation;
97
98 private static final String TAG = PreviewImageFragment.class.getSimpleName();
99
100 private boolean mIgnoreFirstSavedState;
101
102
103 /**
104 * Creates a fragment to preview an image.
105 *
106 * When 'imageFile' or 'ocAccount' are null
107 *
108 * @param imageFile An {@link OCFile} to preview as an image in the fragment
109 * @param ocAccount An ownCloud account; needed to start downloads
110 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
111 */
112 public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
113 mFile = fileToDetail;
114 mAccount = ocAccount;
115 mStorageManager = null; // we need a context to init this; the container activity is not available yet at this moment
116 mIgnoreFirstSavedState = ignoreFirstSavedState;
117 }
118
119
120 /**
121 * Creates an empty fragment for image previews.
122 *
123 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
124 *
125 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
126 */
127 public PreviewImageFragment() {
128 mFile = null;
129 mAccount = null;
130 mStorageManager = null;
131 mIgnoreFirstSavedState = false;
132 }
133
134
135 /**
136 * {@inheritDoc}
137 */
138 @Override
139 public void onCreate(Bundle savedInstanceState) {
140 super.onCreate(savedInstanceState);
141 mHandler = new Handler();
142 setHasOptionsMenu(true);
143 }
144
145
146 /**
147 * {@inheritDoc}
148 */
149 @Override
150 public View onCreateView(LayoutInflater inflater, ViewGroup container,
151 Bundle savedInstanceState) {
152 super.onCreateView(inflater, container, savedInstanceState);
153 mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
154 mImageView = (ImageView)mView.findViewById(R.id.image);
155 mImageView.setVisibility(View.GONE);
156 mView.setOnTouchListener((OnTouchListener)getActivity()); // WATCH OUT THAT CAST
157 mMessageView = (TextView)mView.findViewById(R.id.message);
158 mMessageView.setVisibility(View.GONE);
159 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
160 mProgressWheel.setVisibility(View.VISIBLE);
161 return mView;
162 }
163
164
165 /**
166 * {@inheritDoc}
167 */
168 @Override
169 public void onAttach(Activity activity) {
170 super.onAttach(activity);
171 if (!(activity instanceof FileFragment.ContainerActivity))
172 throw new ClassCastException(activity.toString() + " must implement " + FileFragment.ContainerActivity.class.getSimpleName());
173 }
174
175
176 /**
177 * {@inheritDoc}
178 */
179 @Override
180 public void onActivityCreated(Bundle savedInstanceState) {
181 super.onActivityCreated(savedInstanceState);
182 mStorageManager = new FileDataStorageManager(mAccount, getActivity().getApplicationContext().getContentResolver());
183 if (savedInstanceState != null) {
184 if (!mIgnoreFirstSavedState) {
185 mFile = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
186 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
187 } else {
188 mIgnoreFirstSavedState = false;
189 }
190 }
191 if (mFile == null) {
192 throw new IllegalStateException("Instanced with a NULL OCFile");
193 }
194 if (mAccount == null) {
195 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
196 }
197 if (!mFile.isDown()) {
198 throw new IllegalStateException("There is no local file to preview");
199 }
200 }
201
202
203 /**
204 * {@inheritDoc}
205 */
206 @Override
207 public void onSaveInstanceState(Bundle outState) {
208 super.onSaveInstanceState(outState);
209 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, mFile);
210 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
211 }
212
213
214 @Override
215 public void onStart() {
216 super.onStart();
217 if (mFile != null) {
218 BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
219 bl.execute(new String[]{mFile.getStoragePath()});
220 }
221 }
222
223
224 /**
225 * {@inheritDoc}
226 */
227 @Override
228 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
229 super.onCreateOptionsMenu(menu, inflater);
230
231 inflater.inflate(R.menu.file_actions_menu, menu);
232 List<Integer> toHide = new ArrayList<Integer>();
233
234 MenuItem item = null;
235 toHide.add(R.id.action_cancel_download);
236 toHide.add(R.id.action_cancel_upload);
237 toHide.add(R.id.action_download_file);
238 toHide.add(R.id.action_rename_file); // by now
239
240 for (int i : toHide) {
241 item = menu.findItem(i);
242 if (item != null) {
243 item.setVisible(false);
244 item.setEnabled(false);
245 }
246 }
247
248 }
249
250
251 /**
252 * {@inheritDoc}
253 */
254 @Override
255 public boolean onOptionsItemSelected(MenuItem item) {
256 switch (item.getItemId()) {
257 case R.id.action_open_file_with: {
258 openFile();
259 return true;
260 }
261 case R.id.action_remove_file: {
262 removeFile();
263 return true;
264 }
265 case R.id.action_see_details: {
266 seeDetails();
267 return true;
268 }
269
270 default:
271 return false;
272 }
273 }
274
275
276 private void seeDetails() {
277 ((FileFragment.ContainerActivity)getActivity()).showFragmentWithDetails(mFile);
278 }
279
280
281 @Override
282 public void onResume() {
283 super.onResume();
284 //Log.e(TAG, "FRAGMENT, ONRESUME");
285 /*
286 mDownloadFinishReceiver = new DownloadFinishReceiver();
287 IntentFilter filter = new IntentFilter(
288 FileDownloader.DOWNLOAD_FINISH_MESSAGE);
289 getActivity().registerReceiver(mDownloadFinishReceiver, filter);
290
291 mUploadFinishReceiver = new UploadFinishReceiver();
292 filter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
293 getActivity().registerReceiver(mUploadFinishReceiver, filter);
294 */
295
296 }
297
298
299 @Override
300 public void onPause() {
301 super.onPause();
302 /*
303 if (mVideoPreview.getVisibility() == View.VISIBLE) {
304 mSavedPlaybackPosition = mVideoPreview.getCurrentPosition();
305 }*/
306 /*
307 getActivity().unregisterReceiver(mDownloadFinishReceiver);
308 mDownloadFinishReceiver = null;
309
310 getActivity().unregisterReceiver(mUploadFinishReceiver);
311 mUploadFinishReceiver = null;
312 */
313 }
314
315
316 @Override
317 public void onDestroy() {
318 super.onDestroy();
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 * Weak reference to the target {@link TextView} where error messages will be written.
477 *
478 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
479 */
480 private final WeakReference<TextView> mMessageViewRef;
481
482
483 /**
484 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
485 *
486 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
487 */
488 private final WeakReference<ProgressBar> mProgressWheelRef;
489
490
491 /**
492 * Error message to show when a load fails
493 */
494 private int mErrorMessageId;
495
496
497 /**
498 * Constructor.
499 *
500 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
501 */
502 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
503 mImageViewRef = new WeakReference<ImageView>(imageView);
504 mMessageViewRef = new WeakReference<TextView>(messageView);
505 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
506 }
507
508
509 @SuppressWarnings("deprecation")
510 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
511 @Override
512 protected Bitmap doInBackground(String... params) {
513 Bitmap result = null;
514 if (params.length != 1) return result;
515 String storagePath = params[0];
516 try {
517 // set desired options that will affect the size of the bitmap
518 BitmapFactory.Options options = new Options();
519 options.inScaled = true;
520 options.inPurgeable = true;
521 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
522 options.inPreferQualityOverSpeed = false;
523 }
524 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
525 options.inMutable = false;
526 }
527 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
528 options.inJustDecodeBounds = true;
529 BitmapFactory.decodeFile(storagePath, options);
530
531 int width = options.outWidth;
532 int height = options.outHeight;
533 int scale = 1;
534
535 Display display = getActivity().getWindowManager().getDefaultDisplay();
536 Point size = new Point();
537 int screenWidth;
538 int screenHeight;
539 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
540 display.getSize(size);
541 screenWidth = size.x;
542 screenHeight = size.y;
543 } else {
544 screenWidth = display.getWidth();
545 screenHeight = display.getHeight();
546 }
547
548 if (width > screenWidth) {
549 // second try to scale down the image , this time depending upon the screen size
550 scale = (int) Math.floor((float)width / screenWidth);
551 }
552 if (height > screenHeight) {
553 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
554 }
555 options.inSampleSize = scale;
556
557 // really load the bitmap
558 options.inJustDecodeBounds = false; // the next decodeFile call will be real
559 result = BitmapFactory.decodeFile(storagePath, options);
560 //Log.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
561
562 if (result == null) {
563 mErrorMessageId = R.string.preview_image_error_unknown_format;
564 Log.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
565 }
566
567 } catch (OutOfMemoryError e) {
568 mErrorMessageId = R.string.preview_image_error_unknown_format;
569 Log.e(TAG, "Out of memory occured for file " + storagePath, e);
570
571 } catch (NoSuchFieldError e) {
572 mErrorMessageId = R.string.common_error_unknown;
573 Log.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
574
575 } catch (Throwable t) {
576 mErrorMessageId = R.string.common_error_unknown;
577 Log.e(TAG, "Unexpected error loading " + mFile.getStoragePath(), t);
578
579 }
580 return result;
581 }
582
583 @Override
584 protected void onPostExecute(Bitmap result) {
585 hideProgressWheel();
586 if (result != null) {
587 showLoadedImage(result);
588 } else {
589 showErrorMessage();
590 }
591 }
592
593 private void showLoadedImage(Bitmap result) {
594 if (mImageViewRef != null) {
595 final ImageView imageView = mImageViewRef.get();
596 if (imageView != null) {
597 imageView.setImageBitmap(result);
598 imageView.setVisibility(View.VISIBLE);
599 mBitmap = result;
600 } // else , silently finish, the fragment was destroyed
601 }
602 if (mMessageViewRef != null) {
603 final TextView messageView = mMessageViewRef.get();
604 if (messageView != null) {
605 messageView.setVisibility(View.GONE);
606 } // else , silently finish, the fragment was destroyed
607 }
608 }
609
610 private void showErrorMessage() {
611 if (mImageViewRef != null) {
612 final ImageView imageView = mImageViewRef.get();
613 if (imageView != null) {
614 // shows the default error icon
615 imageView.setVisibility(View.VISIBLE);
616 } // else , silently finish, the fragment was destroyed
617 }
618 if (mMessageViewRef != null) {
619 final TextView messageView = mMessageViewRef.get();
620 if (messageView != null) {
621 messageView.setText(mErrorMessageId);
622 messageView.setVisibility(View.VISIBLE);
623 } // else , silently finish, the fragment was destroyed
624 }
625 }
626
627 private void hideProgressWheel() {
628 if (mProgressWheelRef != null) {
629 final ProgressBar progressWheel = mProgressWheelRef.get();
630 if (progressWheel != null) {
631 progressWheel.setVisibility(View.GONE);
632 }
633 }
634 }
635
636 }
637
638 /**
639 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
640 *
641 * @param file File to test if can be previewed.
642 * @return 'True' if the file can be handled by the fragment.
643 */
644 public static boolean canBePreviewed(OCFile file) {
645 return (file != null && file.isImage());
646 }
647
648
649 /**
650 * {@inheritDoc}
651 */
652 @Override
653 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
654 if (operation.equals(mLastRemoteOperation) && operation instanceof RemoveFileOperation) {
655 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
656 }
657 }
658
659 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
660 getActivity().dismissDialog(PreviewImageActivity.DIALOG_SHORT_WAIT);
661
662 if (result.isSuccess()) {
663 Toast msg = Toast.makeText(getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG);
664 msg.show();
665 finish();
666
667 } else {
668 Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
669 msg.show();
670 if (result.isSslRecoverableException()) {
671 // TODO show the SSL warning dialog
672 }
673 }
674 }
675
676 /**
677 * Finishes the preview
678 */
679 private void finish() {
680 Activity container = getActivity();
681 container.finish();
682 }
683
684
685 }