86a6aa77da7fa18e3b5cb790fa60bb0a2aead1b8
[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.OnTouchListener;
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.ui.dialog.ConfirmationDialogFragment;
48 import com.owncloud.android.ui.dialog.RemoveFileDialogFragment;
49 import com.owncloud.android.ui.fragment.FileFragment;
50 import com.owncloud.android.utils.Log_OC;
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.setOnTouchListener((OnTouchListener) getActivity());
130 mView.setOnTouchListener((OnTouchListener)getActivity());
131 mMessageView = (TextView)mView.findViewById(R.id.message);
132 mMessageView.setVisibility(View.GONE);
133 mProgressWheel = (ProgressBar)mView.findViewById(R.id.progressWheel);
134 mProgressWheel.setVisibility(View.VISIBLE);
135 return mView;
136 }
137
138
139 /**
140 * {@inheritDoc}
141 */
142 @Override
143 public void onAttach(Activity activity) {
144 super.onAttach(activity);
145 if (!(activity instanceof OnTouchListener)) {
146 throw new ClassCastException(activity.toString() +
147 " must implement " + OnTouchListener.class.getSimpleName());
148 }
149 }
150
151
152 /**
153 * {@inheritDoc}
154 */
155 @Override
156 public void onActivityCreated(Bundle savedInstanceState) {
157 super.onActivityCreated(savedInstanceState);
158 if (savedInstanceState != null) {
159 if (!mIgnoreFirstSavedState) {
160 OCFile file = (OCFile)savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_FILE);
161 setFile(file);
162 mAccount = savedInstanceState.getParcelable(PreviewImageFragment.EXTRA_ACCOUNT);
163 } else {
164 mIgnoreFirstSavedState = false;
165 }
166 }
167 if (getFile() == null) {
168 throw new IllegalStateException("Instanced with a NULL OCFile");
169 }
170 if (mAccount == null) {
171 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
172 }
173 if (!getFile().isDown()) {
174 throw new IllegalStateException("There is no local file to preview");
175 }
176 }
177
178
179 /**
180 * {@inheritDoc}
181 */
182 @Override
183 public void onSaveInstanceState(Bundle outState) {
184 super.onSaveInstanceState(outState);
185 outState.putParcelable(PreviewImageFragment.EXTRA_FILE, getFile());
186 outState.putParcelable(PreviewImageFragment.EXTRA_ACCOUNT, mAccount);
187 }
188
189
190 @Override
191 public void onStart() {
192 super.onStart();
193 if (getFile() != null) {
194 BitmapLoader bl = new BitmapLoader(mImageView, mMessageView, mProgressWheel);
195 bl.execute(new String[]{getFile().getStoragePath()});
196 }
197 }
198
199
200 /**
201 * {@inheritDoc}
202 */
203 @Override
204 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
205 super.onCreateOptionsMenu(menu, inflater);
206 inflater.inflate(R.menu.file_actions_menu, menu);
207 }
208
209 /**
210 * {@inheritDoc}
211 */
212 @Override
213 public void onPrepareOptionsMenu(Menu menu) {
214 super.onPrepareOptionsMenu(menu);
215
216 if (mContainerActivity.getStorageManager() != null) {
217 // Update the file
218 setFile(mContainerActivity.getStorageManager().getFileById(getFile().getFileId()));
219
220 FileMenuFilter mf = new FileMenuFilter(
221 getFile(),
222 mContainerActivity.getStorageManager().getAccount(),
223 mContainerActivity,
224 getSherlockActivity()
225 );
226 mf.filter(menu);
227 }
228
229 // additional restriction for this fragment
230 // TODO allow renaming in PreviewImageFragment
231 MenuItem item = menu.findItem(R.id.action_rename_file);
232 if (item != null) {
233 item.setVisible(false);
234 item.setEnabled(false);
235 }
236
237 // additional restriction for this fragment
238 // TODO allow refresh file in PreviewImageFragment
239 item = menu.findItem(R.id.action_sync_file);
240 if (item != null) {
241 item.setVisible(false);
242 item.setEnabled(false);
243 }
244
245 }
246
247
248
249 /**
250 * {@inheritDoc}
251 */
252 @Override
253 public boolean onOptionsItemSelected(MenuItem item) {
254 switch (item.getItemId()) {
255 case R.id.action_share_file: {
256 mContainerActivity.getFileOperationsHelper().shareFileWithLink(getFile());
257 return true;
258 }
259 case R.id.action_unshare_file: {
260 mContainerActivity.getFileOperationsHelper().unshareFileWithLink(getFile());
261 return true;
262 }
263 case R.id.action_open_file_with: {
264 openFile();
265 return true;
266 }
267 case R.id.action_remove_file: {
268 RemoveFileDialogFragment dialog = RemoveFileDialogFragment.newInstance(getFile());
269 dialog.show(getFragmentManager(), ConfirmationDialogFragment.FTAG_CONFIRMATION);
270 return true;
271 }
272 case R.id.action_see_details: {
273 seeDetails();
274 return true;
275 }
276 case R.id.action_send_file: {
277 mContainerActivity.getFileOperationsHelper().sendDownloadedFile(getFile());
278 return true;
279 }
280 case R.id.action_sync_file: {
281 mContainerActivity.getFileOperationsHelper().syncFile(getFile());
282 return true;
283 }
284
285 default:
286 return false;
287 }
288 }
289
290
291 private void seeDetails() {
292 mContainerActivity.showDetails(getFile());
293 }
294
295
296 @Override
297 public void onResume() {
298 super.onResume();
299 }
300
301
302 @Override
303 public void onPause() {
304 super.onPause();
305 }
306
307
308 @Override
309 public void onDestroy() {
310 if (mBitmap != null) {
311 mBitmap.recycle();
312 }
313 super.onDestroy();
314 }
315
316
317 /**
318 * Opens the previewed image with an external application.
319 */
320 private void openFile() {
321 mContainerActivity.getFileOperationsHelper().openFile(getFile());
322 finish();
323 }
324
325
326 private class BitmapLoader extends AsyncTask<String, Void, Bitmap> {
327
328 /**
329 * Weak reference to the target {@link ImageView} where the bitmap will be loaded into.
330 *
331 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
332 */
333 private final WeakReference<ImageView> mImageViewRef;
334
335 /**
336 * Weak reference to the target {@link TextView} where error messages will be written.
337 *
338 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
339 */
340 private final WeakReference<TextView> mMessageViewRef;
341
342
343 /**
344 * Weak reference to the target {@link Progressbar} shown while the load is in progress.
345 *
346 * Using a weak reference will avoid memory leaks if the target ImageView is retired from memory before the load finishes.
347 */
348 private final WeakReference<ProgressBar> mProgressWheelRef;
349
350
351 /**
352 * Error message to show when a load fails
353 */
354 private int mErrorMessageId;
355
356
357 /**
358 * Constructor.
359 *
360 * @param imageView Target {@link ImageView} where the bitmap will be loaded into.
361 */
362 public BitmapLoader(ImageView imageView, TextView messageView, ProgressBar progressWheel) {
363 mImageViewRef = new WeakReference<ImageView>(imageView);
364 mMessageViewRef = new WeakReference<TextView>(messageView);
365 mProgressWheelRef = new WeakReference<ProgressBar>(progressWheel);
366 }
367
368
369 @SuppressWarnings("deprecation")
370 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
371 @Override
372 protected Bitmap doInBackground(String... params) {
373 Bitmap result = null;
374 if (params.length != 1) return result;
375 String storagePath = params[0];
376 try {
377 // set desired options that will affect the size of the bitmap
378 BitmapFactory.Options options = new Options();
379 options.inScaled = true;
380 options.inPurgeable = true;
381 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
382 options.inPreferQualityOverSpeed = false;
383 }
384 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
385 options.inMutable = false;
386 }
387 // make a false load of the bitmap - just to be able to read outWidth, outHeight and outMimeType
388 options.inJustDecodeBounds = true;
389 BitmapFactory.decodeFile(storagePath, options);
390
391 int width = options.outWidth;
392 int height = options.outHeight;
393 int scale = 1;
394
395 Display display = getActivity().getWindowManager().getDefaultDisplay();
396 Point size = new Point();
397 int screenWidth;
398 int screenHeight;
399 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
400 display.getSize(size);
401 screenWidth = size.x;
402 screenHeight = size.y;
403 } else {
404 screenWidth = display.getWidth();
405 screenHeight = display.getHeight();
406 }
407
408 if (width > screenWidth) {
409 // second try to scale down the image , this time depending upon the screen size
410 scale = (int) Math.floor((float)width / screenWidth);
411 }
412 if (height > screenHeight) {
413 scale = Math.max(scale, (int) Math.floor((float)height / screenHeight));
414 }
415 options.inSampleSize = scale;
416
417 // really load the bitmap
418 options.inJustDecodeBounds = false; // the next decodeFile call will be real
419 result = BitmapFactory.decodeFile(storagePath, options);
420 //Log_OC.d(TAG, "Image loaded - width: " + options.outWidth + ", loaded height: " + options.outHeight);
421
422 if (result == null) {
423 mErrorMessageId = R.string.preview_image_error_unknown_format;
424 Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath);
425 }
426
427 } catch (OutOfMemoryError e) {
428 mErrorMessageId = R.string.preview_image_error_unknown_format;
429 Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e);
430
431 } catch (NoSuchFieldError e) {
432 mErrorMessageId = R.string.common_error_unknown;
433 Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e);
434
435 } catch (Throwable t) {
436 mErrorMessageId = R.string.common_error_unknown;
437 Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t);
438
439 }
440 return result;
441 }
442
443 @Override
444 protected void onPostExecute(Bitmap result) {
445 hideProgressWheel();
446 if (result != null) {
447 showLoadedImage(result);
448 } else {
449 showErrorMessage();
450 }
451 }
452
453 private void showLoadedImage(Bitmap result) {
454 if (mImageViewRef != null) {
455 final ImageView imageView = mImageViewRef.get();
456 if (imageView != null) {
457 imageView.setImageBitmap(result);
458 imageView.setVisibility(View.VISIBLE);
459 mBitmap = result;
460 } // else , silently finish, the fragment was destroyed
461 }
462 if (mMessageViewRef != null) {
463 final TextView messageView = mMessageViewRef.get();
464 if (messageView != null) {
465 messageView.setVisibility(View.GONE);
466 } // else , silently finish, the fragment was destroyed
467 }
468 }
469
470 private void showErrorMessage() {
471 if (mImageViewRef != null) {
472 final ImageView imageView = mImageViewRef.get();
473 if (imageView != null) {
474 // shows the default error icon
475 imageView.setVisibility(View.VISIBLE);
476 } // else , silently finish, the fragment was destroyed
477 }
478 if (mMessageViewRef != null) {
479 final TextView messageView = mMessageViewRef.get();
480 if (messageView != null) {
481 messageView.setText(mErrorMessageId);
482 messageView.setVisibility(View.VISIBLE);
483 } // else , silently finish, the fragment was destroyed
484 }
485 }
486
487 private void hideProgressWheel() {
488 if (mProgressWheelRef != null) {
489 final ProgressBar progressWheel = mProgressWheelRef.get();
490 if (progressWheel != null) {
491 progressWheel.setVisibility(View.GONE);
492 }
493 }
494 }
495
496 }
497
498 /**
499 * Helper method to test if an {@link OCFile} can be passed to a {@link PreviewImageFragment} to be previewed.
500 *
501 * @param file File to test if can be previewed.
502 * @return 'True' if the file can be handled by the fragment.
503 */
504 public static boolean canBePreviewed(OCFile file) {
505 return (file != null && file.isImage());
506 }
507
508
509 /**
510 * Finishes the preview
511 */
512 private void finish() {
513 Activity container = getActivity();
514 container.finish();
515 }
516
517
518 }