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