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