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