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