Merge remote-tracking branch 'upstream/develop' into resizedImages
[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.UnshareLinkOperation;
59 import com.owncloud.android.ui.activity.FileActivity;
60 import com.owncloud.android.ui.activity.FileDisplayActivity;
61 import com.owncloud.android.ui.fragment.FileFragment;
62 import com.owncloud.android.utils.DisplayUtils;
63
64
65 /**
66 * Holds a swiping galley where image files contained in an ownCloud directory are shown
67 */
68 public class PreviewImageActivity extends FileActivity implements
69 FileFragment.ContainerActivity,
70 ViewPager.OnPageChangeListener, OnRemoteOperationListener {
71
72 public static final int DIALOG_SHORT_WAIT = 0;
73
74 public static final String TAG = PreviewImageActivity.class.getSimpleName();
75
76 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
77 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
78
79 private static final int INITIAL_HIDE_DELAY = 0; // immediate hide
80
81 private ExtendedViewPager mViewPager;
82 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
83 private int mSavedPosition = 0;
84 private boolean mHasSavedPosition = false;
85
86 private boolean mRequestWaitingForBinder;
87
88 private DownloadFinishReceiver mDownloadFinishReceiver;
89
90 private View mFullScreenAnchorView;
91
92
93 @Override
94 protected void onCreate(Bundle savedInstanceState) {
95 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
96
97 super.onCreate(savedInstanceState);
98
99 setContentView(R.layout.preview_image_activity);
100
101 // Navigation Drawer
102 initDrawer();
103
104 // ActionBar
105 ActionBar actionBar = getSupportActionBar();
106 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
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 }
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 }
238 }
239
240
241 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation,
242 RemoteOperationResult result) {
243 if (result.isSuccess()) {
244 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
245 if (file != null) {
246 setFile(file);
247 }
248 invalidateOptionsMenu();
249 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
250 backToDisplayActivity();
251 }
252
253 }
254
255 private void onCreateShareOperationFinish(CreateShareOperation operation,
256 RemoteOperationResult result) {
257 if (result.isSuccess()) {
258 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
259 if (file != null) {
260 setFile(file);
261 }
262 invalidateOptionsMenu();
263 }
264 }
265
266 @Override
267 protected ServiceConnection newTransferenceServiceConnection() {
268 return new PreviewImageServiceConnection();
269 }
270
271 /** Defines callbacks for service binding, passed to bindService() */
272 private class PreviewImageServiceConnection implements ServiceConnection {
273
274 @Override
275 public void onServiceConnected(ComponentName component, IBinder service) {
276
277 if (component.equals(new ComponentName(PreviewImageActivity.this,
278 FileDownloader.class))) {
279 mDownloaderBinder = (FileDownloaderBinder) service;
280 if (mRequestWaitingForBinder) {
281 mRequestWaitingForBinder = false;
282 Log_OC.d(TAG, "Simulating reselection of current page after connection " +
283 "of download binder");
284 onPageSelected(mViewPager.getCurrentItem());
285 }
286
287 } else if (component.equals(new ComponentName(PreviewImageActivity.this,
288 FileUploader.class))) {
289 Log_OC.d(TAG, "Upload service connected");
290 mUploaderBinder = (FileUploaderBinder) service;
291 } else {
292 return;
293 }
294
295 }
296
297 @Override
298 public void onServiceDisconnected(ComponentName component) {
299 if (component.equals(new ComponentName(PreviewImageActivity.this,
300 FileDownloader.class))) {
301 Log_OC.d(TAG, "Download service suddenly disconnected");
302 mDownloaderBinder = null;
303 } else if (component.equals(new ComponentName(PreviewImageActivity.this,
304 FileUploader.class))) {
305 Log_OC.d(TAG, "Upload service suddenly disconnected");
306 mUploaderBinder = null;
307 }
308 }
309 };
310
311
312 @Override
313 public void onStop() {
314 super.onStop();
315 }
316
317
318 @Override
319 public void onDestroy() {
320 super.onDestroy();
321 }
322
323 @Override
324 public boolean onOptionsItemSelected(MenuItem item) {
325 boolean returnValue = false;
326
327 switch(item.getItemId()){
328 case android.R.id.home:
329 if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
330 mDrawerLayout.closeDrawer(GravityCompat.START);
331 } else {
332 backToDisplayActivity();
333 }
334 returnValue = true;
335 break;
336 default:
337 returnValue = super.onOptionsItemSelected(item);
338 }
339
340 return returnValue;
341 }
342
343
344 @Override
345 protected void onResume() {
346 super.onResume();
347
348 mDownloadFinishReceiver = new DownloadFinishReceiver();
349
350 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
351 filter.addAction(FileDownloader.getDownloadAddedMessage());
352 registerReceiver(mDownloadFinishReceiver, filter);
353 }
354
355 @Override
356 protected void onPostResume() {
357 super.onPostResume();
358 }
359
360 @Override
361 public void onPause() {
362 if (mDownloadFinishReceiver != null){
363 unregisterReceiver(mDownloadFinishReceiver);
364 mDownloadFinishReceiver = null;
365 }
366
367 super.onPause();
368 }
369
370
371 private void backToDisplayActivity() {
372 finish();
373 }
374
375 @Override
376 public void showDetails(OCFile file) {
377 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
378 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
379 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
380 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT,
381 AccountUtils.getCurrentOwnCloudAccount(this));
382 startActivity(showDetailsIntent);
383 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
384 file = mPreviewImagePagerAdapter.getFileAt(pos);
385
386 }
387
388
389 private void requestForDownload(OCFile file) {
390 if (mDownloaderBinder == null) {
391 Log_OC.d(TAG, "requestForDownload called without binder to download service");
392
393 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
394 Intent i = new Intent(this, FileDownloader.class);
395 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
396 i.putExtra(FileDownloader.EXTRA_FILE, file);
397 startService(i);
398 }
399 }
400
401 /**
402 * This method will be invoked when a new page becomes selected. Animation is not necessarily
403 * complete.
404 *
405 * @param position Position index of the new selected page
406 */
407 @Override
408 public void onPageSelected(int position) {
409 mSavedPosition = position;
410 mHasSavedPosition = true;
411 if (mDownloaderBinder == null) {
412 mRequestWaitingForBinder = true;
413
414 } else {
415 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
416 getSupportActionBar().setTitle(currentFile.getFileName());
417 mDrawerToggle.setDrawerIndicatorEnabled(false);
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 // actionBar.hide(); // propagated through
505 // OnSystemUiVisibilityChangeListener()
506 } else {
507 showSystemUI(mFullScreenAnchorView);
508 // actionBar.show(); // propagated through
509 // OnSystemUiVisibilityChangeListener()
510 }
511
512 } else {
513
514 ActionBar actionBar = getSupportActionBar();
515 if (!actionBar.isShowing()) {
516 actionBar.show();
517 mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
518
519 } else {
520 actionBar.hide();
521 mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
522
523 }
524
525 }
526 }
527
528 @Override
529 protected void onAccountSet(boolean stateWasRecovered) {
530 super.onAccountSet(stateWasRecovered);
531 if (getAccount() != null) {
532 OCFile file = getFile();
533 /// Validate handled file (first image to preview)
534 if (file == null) {
535 throw new IllegalStateException("Instanced with a NULL OCFile");
536 }
537 if (!file.isImage()) {
538 throw new IllegalArgumentException("Non-image file passed as argument");
539 }
540
541 // Update file according to DB file, if it is possible
542 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
543 file = getStorageManager().getFileById(file.getFileId());
544
545 if (file != null) {
546 /// Refresh the activity according to the Account and OCFile set
547 setFile(file); // reset after getting it fresh from storageManager
548 getSupportActionBar().setTitle(getFile().getFileName());
549 //if (!stateWasRecovered) {
550 initViewPager();
551 //}
552
553 } else {
554 // handled file not in the current Account
555 finish();
556 }
557 }
558 }
559
560 @Override
561 public void onBrowsedDownTo(OCFile folder) {
562 // TODO Auto-generated method stub
563
564 }
565
566 @Override
567 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
568 // TODO Auto-generated method stub
569
570 }
571
572
573 @SuppressLint("InlinedApi")
574 private void hideSystemUI(View anchorView) {
575 anchorView.setSystemUiVisibility(
576 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hides NAVIGATION BAR; Android >= 4.0
577 | View.SYSTEM_UI_FLAG_FULLSCREEN // hides STATUS BAR; Android >= 4.1
578 | View.SYSTEM_UI_FLAG_IMMERSIVE // stays interactive; Android >= 4.4
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 @SuppressLint("InlinedApi")
586 private void showSystemUI(View anchorView) {
587 anchorView.setSystemUiVisibility(
588 View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
589 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
590 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
591 );
592 }
593
594 /**
595 * Checks if OS version is Honeycomb one or higher
596 *
597 * @return boolean
598 */
599 private boolean isHoneycombOrHigher() {
600 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
601 return true;
602 }
603 return false;
604 }
605
606 @Override
607 public void allFilesOption(){
608 backToDisplayActivity();
609 super.allFilesOption();
610 }
611 }