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