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