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