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