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