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