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