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