Fix, App crash after rotate the device previewing an image
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / preview / PreviewImageActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author David A. Velasco
5 * Copyright (C) 2015 ownCloud Inc.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2,
9 * as published by the Free Software Foundation.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 *
19 */
20 package com.owncloud.android.ui.preview;
21
22 import android.annotation.SuppressLint;
23 import android.content.BroadcastReceiver;
24 import android.content.ComponentName;
25 import android.content.Context;
26 import android.content.Intent;
27 import android.content.IntentFilter;
28 import android.content.ServiceConnection;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.os.Handler;
32 import android.os.IBinder;
33 import android.os.Message;
34 import android.support.v4.view.ViewPager;
35 import android.support.v7.app.ActionBar;
36 import android.view.MenuItem;
37 import android.view.View;
38 import android.view.Window;
39
40 import com.ortiz.touch.ExtendedViewPager;
41 import com.owncloud.android.R;
42 import com.owncloud.android.authentication.AccountUtils;
43 import com.owncloud.android.datamodel.FileDataStorageManager;
44 import com.owncloud.android.datamodel.OCFile;
45 import com.owncloud.android.files.services.FileDownloader;
46 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
47 import com.owncloud.android.files.services.FileUploader;
48 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
49 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
50 import com.owncloud.android.lib.common.operations.RemoteOperation;
51 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
52 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
53 import com.owncloud.android.lib.common.utils.Log_OC;
54 import com.owncloud.android.operations.CreateShareOperation;
55 import com.owncloud.android.operations.RemoveFileOperation;
56 import com.owncloud.android.operations.UnshareLinkOperation;
57 import com.owncloud.android.ui.activity.FileActivity;
58 import com.owncloud.android.ui.activity.FileDisplayActivity;
59 import com.owncloud.android.ui.fragment.FileFragment;
60 import com.owncloud.android.utils.DisplayUtils;
61
62
63 /**
64 * Holds a swiping galley where image files contained in an ownCloud directory are shown
65 */
66 public class PreviewImageActivity extends FileActivity implements
67 FileFragment.ContainerActivity,
68 ViewPager.OnPageChangeListener, OnRemoteOperationListener {
69
70 public static final int DIALOG_SHORT_WAIT = 0;
71
72 public static final String TAG = PreviewImageActivity.class.getSimpleName();
73
74 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
75 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
76
77 private static final int INITIAL_HIDE_DELAY = 0; // immediate hide
78
79 private ExtendedViewPager mViewPager;
80 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
81 private int mSavedPosition = 0;
82 private boolean mHasSavedPosition = false;
83
84 private boolean mRequestWaitingForBinder;
85
86 private DownloadFinishReceiver mDownloadFinishReceiver;
87
88 private View mFullScreenAnchorView;
89
90
91 @Override
92 protected void onCreate(Bundle savedInstanceState) {
93 super.onCreate(savedInstanceState);
94
95 //requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
96 setContentView(R.layout.preview_image_activity);
97
98 // Navigation Drawer
99 initDrawer();
100
101 // ActionBar
102 ActionBar actionBar = getSupportActionBar();
103 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
104 actionBar.setDisplayHomeAsUpEnabled(true);
105 actionBar.hide();
106
107 updateActionBarTitleAndHomeButton();
108
109 // Make sure we're running on Honeycomb or higher to use FullScreen and
110 // Immersive Mode
111 if (isHoneycombOrHigher()) {
112
113 mFullScreenAnchorView = getWindow().getDecorView();
114 // to keep our UI controls visibility in line with system bars
115 // visibility
116 mFullScreenAnchorView.setOnSystemUiVisibilityChangeListener
117 (new View.OnSystemUiVisibilityChangeListener() {
118 @SuppressLint("InlinedApi")
119 @Override
120 public void onSystemUiVisibilityChange(int flags) {
121 boolean visible = (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
122 ActionBar actionBar = getSupportActionBar();
123 if (visible) {
124 actionBar.show();
125 } else {
126 actionBar.hide();
127 }
128 }
129 });
130
131 }
132
133 if (savedInstanceState != null) {
134 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
135 } else {
136 mRequestWaitingForBinder = false;
137 }
138
139 }
140
141 private void initViewPager() {
142 // get parent from path
143 String parentPath = getFile().getRemotePath().substring(0,
144 getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
145 OCFile parentFolder = getStorageManager().getFileByPath(parentPath);
146 if (parentFolder == null) {
147 // should not be necessary
148 parentFolder = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
149 }
150
151 // TODO Enable when "On Device" is recovered ?
152 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(),
153 parentFolder, getAccount(), getStorageManager()/*, MainApp.getOnlyOnDevice()*/);
154
155 mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager);
156 int position = mHasSavedPosition ? mSavedPosition :
157 mPreviewImagePagerAdapter.getFilePosition(getFile());
158 position = (position >= 0) ? position : 0;
159 mViewPager.setAdapter(mPreviewImagePagerAdapter);
160 mViewPager.setOnPageChangeListener(this);
161 mViewPager.setCurrentItem(position);
162 if (position == 0 && !getFile().isDown()) {
163 // this is necessary because mViewPager.setCurrentItem(0) just after setting the
164 // adapter does not result in a call to #onPageSelected(0)
165 mRequestWaitingForBinder = true;
166 }
167 }
168
169
170 protected void onPostCreate(Bundle savedInstanceState) {
171 super.onPostCreate(savedInstanceState);
172
173 // Trigger the initial hide() shortly after the activity has been
174 // created, to briefly hint to the user that UI controls
175 // are available
176 delayedHide(INITIAL_HIDE_DELAY);
177
178 }
179
180 Handler mHideSystemUiHandler = new Handler() {
181 @Override
182 public void handleMessage(Message msg) {
183 if (isHoneycombOrHigher()) {
184 hideSystemUI(mFullScreenAnchorView);
185 }
186 getSupportActionBar().hide();
187 }
188 };
189
190 private void delayedHide(int delayMillis) {
191 mHideSystemUiHandler.removeMessages(0);
192 mHideSystemUiHandler.sendEmptyMessageDelayed(0, delayMillis);
193 }
194
195
196 /// handle Window Focus changes
197 @Override
198 public void onWindowFocusChanged(boolean hasFocus) {
199 super.onWindowFocusChanged(hasFocus);
200
201 // When the window loses focus (e.g. the action overflow is shown),
202 // cancel any pending hide action.
203 if (!hasFocus) {
204 mHideSystemUiHandler.removeMessages(0);
205 }
206 }
207
208
209
210 @Override
211 public void onStart() {
212 super.onStart();
213 }
214
215 @Override
216 protected void onSaveInstanceState(Bundle outState) {
217 super.onSaveInstanceState(outState);
218 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
219 }
220
221 @Override
222 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
223 super.onRemoteOperationFinish(operation, result);
224
225 if (operation instanceof CreateShareOperation) {
226 onCreateShareOperationFinish((CreateShareOperation) operation, result);
227
228 } else if (operation instanceof UnshareLinkOperation) {
229 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
230
231 } else if (operation instanceof RemoveFileOperation) {
232 finish();
233 }
234 }
235
236
237 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
238 RemoteOperationResult result) {
239 if (result.isSuccess()) {
240 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
241 if (file != null) {
242 setFile(file);
243 }
244 invalidateOptionsMenu();
245 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
246 backToDisplayActivity();
247 }
248
249 }
250
251 private void onCreateShareOperationFinish(CreateShareOperation operation,
252 RemoteOperationResult result) {
253 if (result.isSuccess()) {
254 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
255 if (file != null) {
256 setFile(file);
257 }
258 invalidateOptionsMenu();
259 }
260 }
261
262 @Override
263 protected ServiceConnection newTransferenceServiceConnection() {
264 return new PreviewImageServiceConnection();
265 }
266
267 /** Defines callbacks for service binding, passed to bindService() */
268 private class PreviewImageServiceConnection implements ServiceConnection {
269
270 @Override
271 public void onServiceConnected(ComponentName component, IBinder service) {
272
273 if (component.equals(new ComponentName(PreviewImageActivity.this,
274 FileDownloader.class))) {
275 mDownloaderBinder = (FileDownloaderBinder) service;
276 if (mRequestWaitingForBinder) {
277 mRequestWaitingForBinder = false;
278 Log_OC.d(TAG, "Simulating reselection of current page after connection " +
279 "of download binder");
280 onPageSelected(mViewPager.getCurrentItem());
281 }
282
283 } else if (component.equals(new ComponentName(PreviewImageActivity.this,
284 FileUploader.class))) {
285 Log_OC.d(TAG, "Upload service connected");
286 mUploaderBinder = (FileUploaderBinder) service;
287 } else {
288 return;
289 }
290
291 }
292
293 @Override
294 public void onServiceDisconnected(ComponentName component) {
295 if (component.equals(new ComponentName(PreviewImageActivity.this,
296 FileDownloader.class))) {
297 Log_OC.d(TAG, "Download service suddenly disconnected");
298 mDownloaderBinder = null;
299 } else if (component.equals(new ComponentName(PreviewImageActivity.this,
300 FileUploader.class))) {
301 Log_OC.d(TAG, "Upload service suddenly disconnected");
302 mUploaderBinder = null;
303 }
304 }
305 };
306
307
308 @Override
309 public void onStop() {
310 super.onStop();
311 }
312
313
314 @Override
315 public void onDestroy() {
316 super.onDestroy();
317 }
318
319 @Override
320 public boolean onOptionsItemSelected(MenuItem item) {
321 boolean returnValue = false;
322
323 switch(item.getItemId()){
324 case android.R.id.home:
325 backToDisplayActivity();
326 returnValue = true;
327 break;
328 default:
329 returnValue = super.onOptionsItemSelected(item);
330 }
331
332 return returnValue;
333 }
334
335
336 @Override
337 protected void onResume() {
338 super.onResume();
339
340 mDownloadFinishReceiver = new DownloadFinishReceiver();
341
342 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
343 filter.addAction(FileDownloader.getDownloadAddedMessage());
344 registerReceiver(mDownloadFinishReceiver, filter);
345 }
346
347 @Override
348 protected void onPostResume() {
349 super.onPostResume();
350 }
351
352 @Override
353 public void onPause() {
354 if (mDownloadFinishReceiver != null){
355 unregisterReceiver(mDownloadFinishReceiver);
356 mDownloadFinishReceiver = null;
357 }
358
359 super.onPause();
360 }
361
362
363 private void backToDisplayActivity() {
364 finish();
365 }
366
367 @Override
368 public void showDetails(OCFile file) {
369 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
370 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
371 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
372 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT,
373 AccountUtils.getCurrentOwnCloudAccount(this));
374 startActivity(showDetailsIntent);
375 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
376 file = mPreviewImagePagerAdapter.getFileAt(pos);
377
378 }
379
380
381 private void requestForDownload(OCFile file) {
382 if (mDownloaderBinder == null) {
383 Log_OC.d(TAG, "requestForDownload called without binder to download service");
384
385 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
386 Intent i = new Intent(this, FileDownloader.class);
387 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
388 i.putExtra(FileDownloader.EXTRA_FILE, file);
389 startService(i);
390 }
391 }
392
393 /**
394 * This method will be invoked when a new page becomes selected. Animation is not necessarily
395 * complete.
396 *
397 * @param position Position index of the new selected page
398 */
399 @Override
400 public void onPageSelected(int position) {
401 mSavedPosition = position;
402 mHasSavedPosition = true;
403 if (mDownloaderBinder == null) {
404 mRequestWaitingForBinder = true;
405
406 } else {
407 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
408 getSupportActionBar().setTitle(currentFile.getFileName());
409 mDrawerToggle.setDrawerIndicatorEnabled(false);
410 if (!currentFile.isDown()) {
411 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
412 requestForDownload(currentFile);
413 }
414 }
415
416 // Call to reset image zoom to initial state
417 ((PreviewImagePagerAdapter) mViewPager.getAdapter()).resetZoom();
418 }
419
420 }
421
422 /**
423 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
424 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
425 *
426 * @param state The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
427 */
428 @Override
429 public void onPageScrollStateChanged(int state) {
430 }
431
432 /**
433 * This method will be invoked when the current page is scrolled, either as part of a
434 * programmatically initiated smooth scroll or a user initiated touch scroll.
435 *
436 * @param position Position index of the first page currently being displayed.
437 * Page position+1 will be visible if positionOffset is
438 * nonzero.
439 *
440 * @param positionOffset Value from [0, 1) indicating the offset from the page
441 * at position.
442 * @param positionOffsetPixels Value in pixels indicating the offset from position.
443 */
444 @Override
445 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
446 }
447
448
449 /**
450 * Class waiting for broadcast events from the {@link FileDownloader} service.
451 *
452 * Updates the UI when a download is started or finished, provided that it is relevant for the
453 * folder displayed in the gallery.
454 */
455 private class DownloadFinishReceiver extends BroadcastReceiver {
456 @Override
457 public void onReceive(Context context, Intent intent) {
458 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
459 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
460 if (getAccount().name.equals(accountName) &&
461 downloadedRemotePath != null) {
462
463 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
464 int position = mPreviewImagePagerAdapter.getFilePosition(file);
465 boolean downloadWasFine = intent.getBooleanExtra(
466 FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
467 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position))
468 // <= mViewPager.getOffscreenPageLimit();
469
470 if (position >= 0 &&
471 intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
472 if (downloadWasFine) {
473 mPreviewImagePagerAdapter.updateFile(position, file);
474
475 } else {
476 mPreviewImagePagerAdapter.updateWithDownloadError(position);
477 }
478 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation
479 // of new fragments
480
481 } else {
482 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
483 }
484
485 }
486 removeStickyBroadcast(intent);
487 }
488
489 }
490
491 @SuppressLint("InlinedApi")
492 public void toggleFullScreen() {
493
494 if (isHoneycombOrHigher()) {
495
496 boolean visible = (mFullScreenAnchorView.getSystemUiVisibility()
497 & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
498
499 if (visible) {
500 hideSystemUI(mFullScreenAnchorView);
501 // actionBar.hide(); // propagated through
502 // OnSystemUiVisibilityChangeListener()
503 } else {
504 showSystemUI(mFullScreenAnchorView);
505 // actionBar.show(); // propagated through
506 // OnSystemUiVisibilityChangeListener()
507 }
508
509 } else {
510
511 ActionBar actionBar = getSupportActionBar();
512 if (!actionBar.isShowing()) {
513 actionBar.show();
514
515 } else {
516 actionBar.hide();
517
518 }
519
520 }
521 }
522
523 @Override
524 protected void onAccountSet(boolean stateWasRecovered) {
525 super.onAccountSet(stateWasRecovered);
526 if (getAccount() != null) {
527 OCFile file = getFile();
528 /// Validate handled file (first image to preview)
529 if (file == null) {
530 throw new IllegalStateException("Instanced with a NULL OCFile");
531 }
532 if (!file.isImage()) {
533 throw new IllegalArgumentException("Non-image file passed as argument");
534 }
535
536 // Update file according to DB file, if it is possible
537 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
538 file = getStorageManager().getFileById(file.getFileId());
539
540 if (file != null) {
541 /// Refresh the activity according to the Account and OCFile set
542 setFile(file); // reset after getting it fresh from storageManager
543 getSupportActionBar().setTitle(getFile().getFileName());
544 //if (!stateWasRecovered) {
545 initViewPager();
546 //}
547
548 } else {
549 // handled file not in the current Account
550 finish();
551 }
552 }
553 }
554
555 @Override
556 public void onBrowsedDownTo(OCFile folder) {
557 // TODO Auto-generated method stub
558
559 }
560
561 @Override
562 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
563 // TODO Auto-generated method stub
564
565 }
566
567
568 @SuppressLint("InlinedApi")
569 private void hideSystemUI(View anchorView) {
570 anchorView.setSystemUiVisibility(
571 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hides NAVIGATION BAR; Android >= 4.0
572 | View.SYSTEM_UI_FLAG_FULLSCREEN // hides STATUS BAR; Android >= 4.1
573 | View.SYSTEM_UI_FLAG_IMMERSIVE // stays interactive; Android >= 4.4
574 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
575 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
576 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
577 );
578 }
579
580 @SuppressLint("InlinedApi")
581 private void showSystemUI(View anchorView) {
582 anchorView.setSystemUiVisibility(
583 View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
584 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
585 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
586 );
587 }
588
589 /**
590 * Checks if OS version is Honeycomb one or higher
591 *
592 * @return boolean
593 */
594 private boolean isHoneycombOrHigher() {
595 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
596 return true;
597 }
598 return false;
599 }
600
601 @Override
602 public void allFilesOption(){
603 backToDisplayActivity();
604 super.allFilesOption();
605 }
606 }