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