Fixed. App crash when setting a path without slash
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageFragment.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 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.lang.ref.WeakReference;
20
21 import android.accounts.Account;
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.graphics.Bitmap;
25 import android.graphics.BitmapFactory;
26 import android.graphics.BitmapFactory.Options;
27 import android.graphics.Point;
28 import android.os.AsyncTask;
29 import android.os.Bundle;
30 import android.support.v4.app.FragmentStatePagerAdapter;
31 import android.view.Display;
32 import android.view.LayoutInflater;
33 import android.view.View;
34 import android.view.View.OnClickListener;
35 import android.view.ViewGroup;
36 import android.widget.ImageView;
37 import android.widget.ProgressBar;
38 import android.widget.TextView;
39
40 import com.actionbarsherlock.view.Menu;
41 import com.actionbarsherlock.view.MenuInflater;
42 import com.actionbarsherlock.view.MenuItem;
43 import com.ortiz.touch.TouchImageView;
44 import com.owncloud.android.R;
45 import com.owncloud.android.datamodel.OCFile;
46 import com.owncloud.android.files.FileMenuFilter;
47 import com.owncloud.android.lib.common.utils.Log_OC;
48 import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
49 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
50 import com.owncloud.android.ui.fragment.FileFragment;
51
52
53 /**
54 * This fragment shows a preview of a downloaded image.
55 *
56 * Trying to get an instance with NULL {@link OCFile} or ownCloud {@link Account} values will produce an {@link IllegalStateException}.
57 *
58 * If the {@link OCFile} passed is not downloaded, an {@link IllegalStateException} is generated on instantiation too.
59 *
60 * @author David A. Velasco
61 */
62 public class PreviewImageFragment extends FileFragment {
63 public static final String EXTRA_FILE = "FILE";
64 public static final String EXTRA_ACCOUNT = "ACCOUNT";
65
66 private View mView;
67 private Account mAccount;
68 private TouchImageView mImageView;
69 private TextView mMessageView;
70 private ProgressBar mProgressWheel;
71
72 public Bitmap mBitmap = null;
73
74 private static final String TAG = PreviewImageFragment.class.getSimpleName();
75
76 private boolean mIgnoreFirstSavedState;
77
78
79 /**
80 * Creates a fragment to preview an image.
81 *
82 * When 'imageFile' or 'ocAccount' are null
83 *
84 * @param imageFile An {@link OCFile} to preview as an image in the fragment
85 * @param ocAccount An ownCloud account; needed to start downloads
86 * @param ignoreFirstSavedState Flag to work around an unexpected behaviour of {@link FragmentStatePagerAdapter}; TODO better solution
87 */
88 public PreviewImageFragment(OCFile fileToDetail, Account ocAccount, boolean ignoreFirstSavedState) {
89 super(fileToDetail);
90 mAccount = ocAccount;
91 mIgnoreFirstSavedState = ignoreFirstSavedState;
92 }
93
94
95 /**
96 * Creates an empty fragment for image previews.
97 *
98 * MUST BE KEPT: the system uses it when tries to reinstantiate a fragment automatically (for instance, when the device is turned a aside).
99 *
100 * DO NOT CALL IT: an {@link OCFile} and {@link Account} must be provided for a successful construction
101 */
102 public PreviewImageFragment() {
103 super();
104 mAccount = null;
105 mIgnoreFirstSavedState = false;
106 }
107
108
109 /**
110 * {@inheritDoc}
111 */
112 @Override
113 public void onCreate(Bundle savedInstanceState) {
114 super.onCreate(savedInstanceState);
115 setHasOptionsMenu(true);
116 }
117
118
119 /**
120 * {@inheritDoc}
121 */
122 @Override
123 public View onCreateView(LayoutInflater inflater, ViewGroup container,
124 Bundle savedInstanceState) {
125 super.onCreateView(inflater, container, savedInstanceState);
126 mView = inflater.inflate(R.layout.preview_image_fragment, container, false);
127 mImageView = (TouchImageView) mView.findViewById(R.id.image);
128 mImageView.setVisibility(View.GONE);
129 mImageView.setOnClickListener(new OnClickListener() {
130 @Override
131 public void onClick(View v) {
132 ((PreviewImageActivity) getActivity()).toggleFullScreen();
133 }
134
135 });
136 mMessageView = (TextView)mView.findViewById(R.id.message);
137 mMessageView.setVisibility(View.GONE);
138 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
139 mProgressWheel.setVisibility(View.VISIBLE);
140 return mView;
141 }
142
143 /**
144 * {@inheritDoc}
145 */
146 @Override
147 public void onActivityCreated(Bundle savedInstanceState) {
148 super.onActivityCreated(savedInstanceState);
149 if (savedInstanceState != null) {
150 if (!mIgnoreFirstSavedState) {
151 OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
152 setFile(file);
153 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
154 } else {
155 mIgnoreFirstSavedState = false;
156 }
157 }
158 if (getFile() == null) {
159 throw new IllegalStateException("Instanced with a NULL OCFile");
160 }
161 if (mAccount == null) {
162 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
163 }
164 if (!getFile().isDown()) {
165 throw new IllegalStateException("There is no local file to preview");
166 }
167 }
168
169
170 /**
171 * {@inheritDoc}
172 */
173 @Override
174 public void onSaveInstanceState(Bundle outState) {
175 super.onSaveInstanceState(outState);
176 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
177 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
178 }
179
180
181 @Override
182 public void onStart() {
183 super.onStart();
184 if (getFile() != null) {
185 BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
186 bl.execute(new String[]{getFile().getStoragePath()});
187 }
188 }
189
190
191 /**
192 * {@inheritDoc}
193 */
194 @Override
195 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
196 super.onCreateOptionsMenu(menu, inflater);
197 inflater.inflate(R.menu.file_actions_menu, menu);
198 }
199
200 /**
201 * {@inheritDoc}
202 */
203 @Override
204 public void onPrepareOptionsMenu(Menu menu) {
205 super.onPrepareOptionsMenu(menu);
206
207 if (mContainerActivity.getStorageManager() != null) {
208 // Update the file
209 setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
210
211 FileMenuFilter mf = new FileMenuFilter(
212 getFile(),
213 mContainerActivity.getStorageManager().getAccount(),
214 mContainerActivity,
215 getSherlockActivity()
216 );
217 mf.filter(menu);
218 }
219
220 // additional restriction for this fragment
221 // TODO allow renaming in PreviewImageFragment
222 MenuItem item = menu.findItem(R.id.action_rename_file);
223 if (item != null) {
224 item.setVisible(false);
225 item.setEnabled(false);
226 }
227
228 // additional restriction for this fragment
229 // TODO allow refresh file in PreviewImageFragment
230 item = menu.findItem(R.id.action_sync_file);
231 if (item != null) {
232 item.setVisible(false);
233 item.setEnabled(false);
234 }
235
236 // additional restriction for this fragment
237 item = menu.findItem(R.id.action_move);
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_share_file: {
254 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
255 return true;
256 }
257 case R.id.action_unshare_file: {
258 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
259 return true;
260 }
261 case R.id.action_open_file_with: {
262 openFile();
263 return true;
264 }
265 case R.id.action_remove_file: {
266 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
267 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
268 return true;
269 }
270 case R.id.action_see_details: {
271 seeDetails();
272 return true;
273 }
274 case R.id.action_send_file: {
275 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
276 return true;
277 }
278 case R.id.action_sync_file: {
279 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
280 return true;
281 }
282
283 default:
284 return false;
285 }
286 }
287
288
289 private void seeDetails() {
290 mContainerActivity.showDetails(getFile());
291 }
292
293
294 @Override
295 public void onResume() {
296 super.onResume();
297 }
298
299
300 @Override
301 public void onPause() {
302 super.onPause();
303 }
304
305 @Override
306 public void onDestroy() {
307 if (mBitmap != null) {
308 mBitmap.recycle();
309 }
310 super.onDestroy();
311 }
312
313
314 /**
315 * Opens the previewed image with an external application.
316 */
317 private void openFile() {
318 mContainerActivity.getFileOperationsHelper().openFile(getFile());
319 finish();
320 }
321
322
323 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
324
325 /**
326 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
327 *
328 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
329 */
330 private final WeakReference<ImageView> mImageViewRef;
331
332 /**
333 * Weak reference to the target {@link TextView} where error messages will be written.
334 *
335 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
336 */
337 private final WeakReference<TextView> mMessageViewRef;
338
339
340 /**
341 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
342 *
343 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
344 */
345 private final WeakReference<ProgressBar> mProgressWheelRef;
346
347
348 /**
349 * Error message to show when a load fails
350 */
351 private int mErrorMessageId;
352
353
354 /**
355 * Constructor.
356 *
357 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
358 */
359 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
360 mImageViewRef = new WeakReference<ImageView>(imageView);
361 mMessageViewRef = new WeakReference<TextView>(messageView);
362 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
363 }
364
365
366 @SuppressWarnings("deprecation")
367 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
368 @Override
369 protected Bitmap doInBackground(String... params) {
370 Bitmap result = null;
371 if (params.length != 1) return result;
372 String storagePath = params[0];
373 try {
374 // set desired options that will affect the size of the bitmap
375 BitmapFactory.Options options = new Options();
376 options.inScaled = true;
377 options.inPurgeable = true;
378 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
379 options.inPreferQualityOverSpeed = false;
380 }
381 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
382 options.inMutable = false;
383 }
384 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
385 options.inJustDecodeBounds = true;
386 BitmapFactory.decodeFile(storagePath, options);
387
388 int width = options.outWidth;
389 int height = options.outHeight;
390 int scale = 1;
391
392 Display display = getActivity().getWindowManager().getDefaultDisplay();
393 Point size = new Point();
394 int screenWidth;
395 int screenHeight;
396 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
397 display.getSize(size);
398 screenWidth = size.x;
399 screenHeight = size.y;
400 } else {
401 screenWidth = display.getWidth();
402 screenHeight = display.getHeight();
403 }
404
405 if (width > screenWidth) {
406 // second try to scale down the image , this time depending upon the screen size
407 scale = (int) Math.floor((float)width / screenWidth);
408 }
409 if (height > screenHeight) {
410 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
411 }
412 options.inSampleSize = scale;
413
414 // really load the bitmap
415 options.inJustDecodeBounds = false; // the next decodeFile call will be real
416 result = BitmapFactory.decodeFile(storagePath, options);
417 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
418
419 if (result == null) {
420 mErrorMessageId = R.string.preview_image_error_unknown_format;
421 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
422 }
423
424 } catch (OutOfMemoryError e) {
425 mErrorMessageId = R.string.preview_image_error_unknown_format;
426 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
427
428 } catch (NoSuchFieldError e) {
429 mErrorMessageId = R.string.common_error_unknown;
430 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
431
432 } catch (Throwable t) {
433 mErrorMessageId = R.string.common_error_unknown;
434 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
435
436 }
437 return result;
438 }
439
440 @Override
441 protected void onPostExecute(Bitmap result) {
442 hideProgressWheel();
443 if (result != null) {
444 showLoadedImage(result);
445 } else {
446 showErrorMessage();
447 }
448 }
449
450 private void showLoadedImage(Bitmap result) {
451 if (mImageViewRef != null) {
452 final ImageView imageView = mImageViewRef.get();
453 if (imageView != null) {
454 imageView.setImageBitmap(result);
455 imageView.setVisibility(View.VISIBLE);
456 mBitmap = result;
457 } // else , silently finish, the fragment was destroyed
458 }
459 if (mMessageViewRef != null) {
460 final TextView messageView = mMessageViewRef.get();
461 if (messageView != null) {
462 messageView.setVisibility(View.GONE);
463 } // else , silently finish, the fragment was destroyed
464 }
465 }
466
467 private void showErrorMessage() {
468 if (mImageViewRef != null) {
469 final ImageView imageView = mImageViewRef.get();
470 if (imageView != null) {
471 // shows the default error icon
472 imageView.setVisibility(View.VISIBLE);
473 } // else , silently finish, the fragment was destroyed
474 }
475 if (mMessageViewRef != null) {
476 final TextView messageView = mMessageViewRef.get();
477 if (messageView != null) {
478 messageView.setText(mErrorMessageId);
479 messageView.setVisibility(View.VISIBLE);
480 } // else , silently finish, the fragment was destroyed
481 }
482 }
483
484 private void hideProgressWheel() {
485 if (mProgressWheelRef != null) {
486 final ProgressBar progressWheel = mProgressWheelRef.get();
487 if (progressWheel != null) {
488 progressWheel.setVisibility(View.GONE);
489 }
490 }
491 }
492
493 }
494
495 /**
496 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
497 *
498 * @param file File to test if can be previewed.
499 * @return 'True' if the file can be handled by the fragment.
500 */
501 public static boolean canBePreviewed(OCFile file) {
502 return (file != null && file.isImage());
503 }
504
505
506 /**
507 * Finishes the preview
508 */
509 private void finish() {
510 Activity container = getActivity();
511 container.finish();
512 }
513
514 public TouchImageView getImageView() {
515 return mImageView;
516 }
517
518 }