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