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