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