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