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