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