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