Use Extended view pager and set onTouchListener into image forshow/hide the action bar
[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.content.BroadcastReceiver;
20 import android.content.ComponentName;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.ServiceConnection;
25 import android.content.SharedPreferences;
26 import android.os.Bundle;
27 import android.os.IBinder;
28 import android.preference.PreferenceManager;
29 import android.support.v4.view.ViewPager;
30 import android.view.MotionEvent;
31 import android.view.View;
32 import android.view.View.OnTouchListener;
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.R;
39 import com.owncloud.android.authentication.AccountUtils;
40 import com.owncloud.android.datamodel.FileDataStorageManager;
41 import com.owncloud.android.datamodel.OCFile;
42 import com.owncloud.android.files.services.FileDownloader;
43 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
44 import com.owncloud.android.files.services.FileUploader;
45 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
46 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
47 import com.owncloud.android.lib.common.operations.RemoteOperation;
48 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
49 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
50 import com.owncloud.android.operations.CreateShareOperation;
51 import com.owncloud.android.operations.RemoveFileOperation;
52 import com.owncloud.android.operations.UnshareLinkOperation;
53 import com.owncloud.android.ui.activity.FileActivity;
54 import com.owncloud.android.ui.activity.FileDisplayActivity;
55 import com.owncloud.android.ui.activity.PinCodeActivity;
56 import com.owncloud.android.ui.fragment.FileFragment;
57 import com.owncloud.android.utils.DisplayUtils;
58 import com.owncloud.android.utils.Log_OC;
59
60
61 /**
62 * Holds a swiping galley where image files contained in an ownCloud directory are shown
63 *
64 * @author David A. Velasco
65 */
66 public class PreviewImageActivity extends FileActivity implements
67 FileFragment.ContainerActivity, OnTouchListener,
68 ViewPager.OnPageChangeListener, OnRemoteOperationListener {
69
70 public static final int DIALOG_SHORT_WAIT = 0;
71
72 public static final String TAG = PreviewImageActivity.class.getSimpleName();
73
74 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
75 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
76
77 private ExtendedViewPager mViewPager;
78 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
79
80 private boolean mRequestWaitingForBinder;
81
82 private DownloadFinishReceiver mDownloadFinishReceiver;
83
84 private boolean mFullScreen;
85
86
87 @Override
88 protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90
91 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
92 setContentView(R.layout.preview_image_activity);
93
94 ActionBar actionBar = getSupportActionBar();
95 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
96 actionBar.setDisplayHomeAsUpEnabled(true);
97 actionBar.hide();
98
99 // PIN CODE request
100 if (getIntent().getExtras() != null && savedInstanceState == null && fromNotification()) {
101 requestPinCode();
102 }
103
104 mFullScreen = true;
105 if (savedInstanceState != null) {
106 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
107 } else {
108 mRequestWaitingForBinder = false;
109 }
110
111 }
112
113 private void initViewPager() {
114 // get parent from path
115 String parentPath = getFile().getRemotePath().substring(0, getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
116 OCFile parentFolder = getStorageManager().getFileByPath(parentPath);
117 if (parentFolder == null) {
118 // should not be necessary
119 parentFolder = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
120 }
121 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), getStorageManager());
122 mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager);
123 int position = mPreviewImagePagerAdapter.getFilePosition(getFile());
124 position = (position >= 0) ? position : 0;
125 mViewPager.setAdapter(mPreviewImagePagerAdapter);
126 mViewPager.setOnPageChangeListener(this);
127 mViewPager.setCurrentItem(position);
128 if (position == 0 && !getFile().isDown()) {
129 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
130 mRequestWaitingForBinder = true;
131 }
132 }
133
134
135 @Override
136 public void onStart() {
137 super.onStart();
138 }
139
140 @Override
141 protected void onSaveInstanceState(Bundle outState) {
142 super.onSaveInstanceState(outState);
143 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
144 }
145
146 @Override
147 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
148 super.onRemoteOperationFinish(operation, result);
149
150 if (operation instanceof CreateShareOperation) {
151 onCreateShareOperationFinish((CreateShareOperation) operation, result);
152
153 } else if (operation instanceof UnshareLinkOperation) {
154 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
155
156 } else if (operation instanceof RemoveFileOperation) {
157 finish();
158 }
159 }
160
161
162 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
163 if (result.isSuccess()) {
164 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
165 if (file != null) {
166 setFile(file);
167 }
168 invalidateOptionsMenu();
169 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
170 backToDisplayActivity();
171 }
172
173 }
174
175 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
176 if (result.isSuccess()) {
177 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
178 if (file != null) {
179 setFile(file);
180 }
181 invalidateOptionsMenu();
182 }
183 }
184
185 @Override
186 protected ServiceConnection newTransferenceServiceConnection() {
187 return new PreviewImageServiceConnection();
188 }
189
190 /** Defines callbacks for service binding, passed to bindService() */
191 private class PreviewImageServiceConnection implements ServiceConnection {
192
193 @Override
194 public void onServiceConnected(ComponentName component, IBinder service) {
195
196 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
197 mDownloaderBinder = (FileDownloaderBinder) service;
198 if (mRequestWaitingForBinder) {
199 mRequestWaitingForBinder = false;
200 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
201 onPageSelected(mViewPager.getCurrentItem());
202 }
203
204 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
205 Log_OC.d(TAG, "Upload service connected");
206 mUploaderBinder = (FileUploaderBinder) service;
207 } else {
208 return;
209 }
210
211 }
212
213 @Override
214 public void onServiceDisconnected(ComponentName component) {
215 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
216 Log_OC.d(TAG, "Download service suddenly disconnected");
217 mDownloaderBinder = null;
218 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
219 Log_OC.d(TAG, "Upload service suddenly disconnected");
220 mUploaderBinder = null;
221 }
222 }
223 };
224
225
226 @Override
227 public void onStop() {
228 super.onStop();
229 }
230
231
232 @Override
233 public void onDestroy() {
234 super.onDestroy();
235 }
236
237 @Override
238 public boolean onOptionsItemSelected(MenuItem item) {
239 boolean returnValue = false;
240
241 switch(item.getItemId()){
242 case android.R.id.home:
243 backToDisplayActivity();
244 returnValue = true;
245 break;
246 default:
247 returnValue = super.onOptionsItemSelected(item);
248 }
249
250 return returnValue;
251 }
252
253
254 @Override
255 protected void onResume() {
256 super.onResume();
257 //Log.e(TAG, "ACTIVITY, ONRESUME");
258 mDownloadFinishReceiver = new DownloadFinishReceiver();
259
260 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
261 filter.addAction(FileDownloader.getDownloadAddedMessage());
262 registerReceiver(mDownloadFinishReceiver, filter);
263 }
264
265 @Override
266 protected void onPostResume() {
267 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
268 super.onPostResume();
269 }
270
271 @Override
272 public void onPause() {
273 unregisterReceiver(mDownloadFinishReceiver);
274 mDownloadFinishReceiver = null;
275 super.onPause();
276 }
277
278
279 private void backToDisplayActivity() {
280 finish();
281 }
282
283 @Override
284 public void showDetails(OCFile file) {
285 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
286 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
287 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
288 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
289 startActivity(showDetailsIntent);
290 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
291 file = mPreviewImagePagerAdapter.getFileAt(pos);
292
293 }
294
295
296 private void requestForDownload(OCFile file) {
297 if (mDownloaderBinder == null) {
298 Log_OC.d(TAG, "requestForDownload called without binder to download service");
299
300 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
301 Intent i = new Intent(this, FileDownloader.class);
302 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
303 i.putExtra(FileDownloader.EXTRA_FILE, file);
304 startService(i);
305 }
306 }
307
308 /**
309 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
310 *
311 * @param Position Position index of the new selected page
312 */
313 @Override
314 public void onPageSelected(int position) {
315 if (mDownloaderBinder == null) {
316 mRequestWaitingForBinder = true;
317
318 } else {
319 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
320 getSupportActionBar().setTitle(currentFile.getFileName());
321 if (!currentFile.isDown()) {
322 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
323 requestForDownload(currentFile);
324 }
325 }
326 }
327 }
328
329 /**
330 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
331 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
332 *
333 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
334 */
335 @Override
336 public void onPageScrollStateChanged(int state) {
337 }
338
339 /**
340 * This method will be invoked when the current page is scrolled, either as part of a programmatically
341 * initiated smooth scroll or a user initiated touch scroll.
342 *
343 * @param position Position index of the first page currently being displayed.
344 * Page position+1 will be visible if positionOffset is nonzero.
345 *
346 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
347 * @param positionOffsetPixels Value in pixels indicating the offset from position.
348 */
349 @Override
350 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
351 }
352
353
354 /**
355 * Class waiting for broadcast events from the {@link FielDownloader} service.
356 *
357 * Updates the UI when a download is started or finished, provided that it is relevant for the
358 * folder displayed in the gallery.
359 */
360 private class DownloadFinishReceiver extends BroadcastReceiver {
361 @Override
362 public void onReceive(Context context, Intent intent) {
363 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
364 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
365 if (getAccount().name.equals(accountName) &&
366 downloadedRemotePath != null) {
367
368 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
369 int position = mPreviewImagePagerAdapter.getFilePosition(file);
370 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
371 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
372
373 if (position >= 0 && intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
374 if (downloadWasFine) {
375 mPreviewImagePagerAdapter.updateFile(position, file);
376
377 } else {
378 mPreviewImagePagerAdapter.updateWithDownloadError(position);
379 }
380 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
381
382 } else {
383 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
384 }
385
386 }
387 removeStickyBroadcast(intent);
388 }
389
390 }
391
392
393 @Override
394 public boolean onTouch(View v, MotionEvent event) {
395 if (event.getAction() == MotionEvent.ACTION_UP) {
396 toggleFullScreen();
397 }
398 return true;
399 }
400
401
402 private void toggleFullScreen() {
403 ActionBar actionBar = getSupportActionBar();
404 if (mFullScreen) {
405 actionBar.show();
406
407 } else {
408 actionBar.hide();
409
410 }
411 mFullScreen = !mFullScreen;
412 }
413
414 @Override
415 protected void onAccountSet(boolean stateWasRecovered) {
416 super.onAccountSet(stateWasRecovered);
417 if (getAccount() != null) {
418 OCFile file = getFile();
419 /// Validate handled file (first image to preview)
420 if (file == null) {
421 throw new IllegalStateException("Instanced with a NULL OCFile");
422 }
423 if (!file.isImage()) {
424 throw new IllegalArgumentException("Non-image file passed as argument");
425 }
426
427 // Update file according to DB file, if it is possible
428 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
429 file = getStorageManager().getFileById(file.getFileId());
430
431 if (file != null) {
432 /// Refresh the activity according to the Account and OCFile set
433 setFile(file); // reset after getting it fresh from storageManager
434 getSupportActionBar().setTitle(getFile().getFileName());
435 //if (!stateWasRecovered) {
436 initViewPager();
437 //}
438
439 } else {
440 // handled file not in the current Account
441 finish();
442 }
443 }
444 }
445
446
447 /**
448 * Launch an intent to request the PIN code to the user before letting him use the app
449 */
450 private void requestPinCode() {
451 boolean pinStart = false;
452 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
453 pinStart = appPrefs.getBoolean("set_pincode", false);
454 if (pinStart) {
455 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
456 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "PreviewImageActivity");
457 startActivity(i);
458 }
459 }
460
461 @Override
462 public void onBrowsedDownTo(OCFile folder) {
463 // TODO Auto-generated method stub
464
465 }
466
467 @Override
468 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
469 // TODO Auto-generated method stub
470
471 }
472
473 }