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