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