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