4326ce27f73c5106ed4010d573372d7223f4ddcb
[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.activity.ShareActivity;
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 Intent intent = new Intent(this, ShareActivity.class);
411 intent.putExtra(EXTRA_FILE, file);
412 intent.putExtra(EXTRA_ACCOUNT, getAccount());
413 startActivity(intent);
414 }
415 private void requestForDownload(OCFile file) {
416 if (mDownloaderBinder == null) {
417 Log_OC.d(TAG, "requestForDownload called without binder to download service");
418
419 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
420 Intent i = new Intent(this, FileDownloader.class);
421 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
422 i.putExtra(FileDownloader.EXTRA_FILE, file);
423 startService(i);
424 }
425 }
426
427 /**
428 * This method will be invoked when a new page becomes selected. Animation is not necessarily
429 * complete.
430 *
431 * @param position Position index of the new selected page
432 */
433 @Override
434 public void onPageSelected(int position) {
435 mSavedPosition = position;
436 mHasSavedPosition = true;
437 if (mDownloaderBinder == null) {
438 mRequestWaitingForBinder = true;
439
440 } else {
441 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
442 getSupportActionBar().setTitle(currentFile.getFileName());
443 mDrawerToggle.setDrawerIndicatorEnabled(false);
444 if (!currentFile.isDown()) {
445 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
446 requestForDownload(currentFile);
447 }
448 }
449
450 // Call to reset image zoom to initial state
451 ((PreviewImagePagerAdapter) mViewPager.getAdapter()).resetZoom();
452 }
453
454 }
455
456 /**
457 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
458 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
459 *
460 * @param state The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
461 */
462 @Override
463 public void onPageScrollStateChanged(int state) {
464 }
465
466 /**
467 * This method will be invoked when the current page is scrolled, either as part of a
468 * programmatically initiated smooth scroll or a user initiated touch scroll.
469 *
470 * @param position Position index of the first page currently being displayed.
471 * Page position+1 will be visible if positionOffset is
472 * nonzero.
473 *
474 * @param positionOffset Value from [0, 1) indicating the offset from the page
475 * at position.
476 * @param positionOffsetPixels Value in pixels indicating the offset from position.
477 */
478 @Override
479 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
480 }
481
482
483 /**
484 * Class waiting for broadcast events from the {@link FileDownloader} service.
485 *
486 * Updates the UI when a download is started or finished, provided that it is relevant for the
487 * folder displayed in the gallery.
488 */
489 private class DownloadFinishReceiver extends BroadcastReceiver {
490 @Override
491 public void onReceive(Context context, Intent intent) {
492 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
493 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
494 if (getAccount().name.equals(accountName) &&
495 downloadedRemotePath != null) {
496
497 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
498 int position = mPreviewImagePagerAdapter.getFilePosition(file);
499 boolean downloadWasFine = intent.getBooleanExtra(
500 FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
501 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position))
502 // <= mViewPager.getOffscreenPageLimit();
503
504 if (position >= 0 &&
505 intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
506 if (downloadWasFine) {
507 mPreviewImagePagerAdapter.updateFile(position, file);
508
509 } else {
510 mPreviewImagePagerAdapter.updateWithDownloadError(position);
511 }
512 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation
513 // of new fragments
514
515 } else {
516 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
517 }
518
519 }
520 removeStickyBroadcast(intent);
521 }
522
523 }
524
525 @SuppressLint("InlinedApi")
526 public void toggleFullScreen() {
527
528 if (isHoneycombOrHigher()) {
529
530 boolean visible = (mFullScreenAnchorView.getSystemUiVisibility()
531 & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
532
533 if (visible) {
534 hideSystemUI(mFullScreenAnchorView);
535 // actionBar.hide(); // propagated through
536 // OnSystemUiVisibilityChangeListener()
537 } else {
538 showSystemUI(mFullScreenAnchorView);
539 // actionBar.show(); // propagated through
540 // OnSystemUiVisibilityChangeListener()
541 }
542
543 } else {
544
545 ActionBar actionBar = getSupportActionBar();
546 if (!actionBar.isShowing()) {
547 actionBar.show();
548 mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
549
550 } else {
551 actionBar.hide();
552 mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
553
554 }
555
556 }
557 }
558
559 @Override
560 protected void onAccountSet(boolean stateWasRecovered) {
561 super.onAccountSet(stateWasRecovered);
562 if (getAccount() != null) {
563 OCFile file = getFile();
564 /// Validate handled file (first image to preview)
565 if (file == null) {
566 throw new IllegalStateException("Instanced with a NULL OCFile");
567 }
568 if (!file.isImage()) {
569 throw new IllegalArgumentException("Non-image file passed as argument");
570 }
571
572 // Update file according to DB file, if it is possible
573 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
574 file = getStorageManager().getFileById(file.getFileId());
575
576 if (file != null) {
577 /// Refresh the activity according to the Account and OCFile set
578 setFile(file); // reset after getting it fresh from storageManager
579 getSupportActionBar().setTitle(getFile().getFileName());
580 //if (!stateWasRecovered) {
581 initViewPager();
582 //}
583
584 } else {
585 // handled file not in the current Account
586 finish();
587 }
588 }
589 }
590
591 @Override
592 public void onBrowsedDownTo(OCFile folder) {
593 // TODO Auto-generated method stub
594
595 }
596
597 @Override
598 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
599 // TODO Auto-generated method stub
600
601 }
602
603
604 @SuppressLint("InlinedApi")
605 private void hideSystemUI(View anchorView) {
606 anchorView.setSystemUiVisibility(
607 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hides NAVIGATION BAR; Android >= 4.0
608 | View.SYSTEM_UI_FLAG_FULLSCREEN // hides STATUS BAR; Android >= 4.1
609 | View.SYSTEM_UI_FLAG_IMMERSIVE // stays interactive; Android >= 4.4
610 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
611 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
612 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
613 );
614 }
615
616 @SuppressLint("InlinedApi")
617 private void showSystemUI(View anchorView) {
618 anchorView.setSystemUiVisibility(
619 View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
620 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
621 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
622 );
623 }
624
625 /**
626 * Checks if OS version is Honeycomb one or higher
627 *
628 * @return boolean
629 */
630 private boolean isHoneycombOrHigher() {
631 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
632 return true;
633 }
634 return false;
635 }
636
637 @Override
638 public void allFilesOption(){
639 backToDisplayActivity();
640 super.allFilesOption();
641 }
642 }