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