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