Merge branch 'develop' into check_account_existance_in_gallery
[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.app.Dialog;
20 import android.app.ProgressDialog;
21 import android.content.BroadcastReceiver;
22 import android.content.ComponentName;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.ServiceConnection;
27 import android.os.Bundle;
28 import android.os.IBinder;
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.authentication.AccountUtils;
38 import com.owncloud.android.datamodel.DataStorageManager;
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.fragment.FileFragment;
48
49 import com.owncloud.android.Log_OC;
50 import com.owncloud.android.R;
51
52 /**
53 * Holds a swiping galley where image files contained in an ownCloud directory are shown
54 *
55 * @author David A. Velasco
56 */
57 public class PreviewImageActivity extends FileActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
58
59 public static final int DIALOG_SHORT_WAIT = 0;
60
61 public static final String TAG = PreviewImageActivity.class.getSimpleName();
62
63 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
64 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
65
66 private DataStorageManager mStorageManager;
67
68 private ViewPager mViewPager;
69 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
70
71 private FileDownloaderBinder mDownloaderBinder = null;
72 private ServiceConnection mDownloadConnection, mUploadConnection = null;
73 private FileUploaderBinder mUploaderBinder = null;
74
75 private boolean mRequestWaitingForBinder;
76
77 private DownloadFinishReceiver mDownloadFinishReceiver;
78
79 private boolean mFullScreen;
80
81
82 @Override
83 protected void onCreate(Bundle savedInstanceState) {
84 super.onCreate(savedInstanceState);
85
86 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
87 setContentView(R.layout.preview_image_activity);
88
89 ActionBar actionBar = getSupportActionBar();
90 actionBar.setDisplayHomeAsUpEnabled(true);
91 actionBar.hide();
92
93 mFullScreen = true;
94 if (savedInstanceState != null) {
95 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
96 } else {
97 mRequestWaitingForBinder = false;
98 }
99 }
100
101 private void initViewPager() {
102 OCFile parentFolder = mStorageManager.getFileById(getFile().getParentId());
103 if (parentFolder == null) {
104 // should not be necessary
105 parentFolder = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
106 }
107 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), mStorageManager);
108 mViewPager = (ViewPager) findViewById(R.id.fragmentPager);
109 int position = mPreviewImagePagerAdapter.getFilePosition(getFile());
110 position = (position >= 0) ? position : 0;
111 mViewPager.setAdapter(mPreviewImagePagerAdapter);
112 mViewPager.setOnPageChangeListener(this);
113 mViewPager.setCurrentItem(position);
114 if (position == 0 && !getFile().isDown()) {
115 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
116 mRequestWaitingForBinder = true;
117 }
118 }
119
120
121 @Override
122 public void onStart() {
123 super.onStart();
124 mDownloadConnection = new PreviewImageServiceConnection();
125 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
126 mUploadConnection = new PreviewImageServiceConnection();
127 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
128 }
129
130 @Override
131 protected void onSaveInstanceState(Bundle outState) {
132 super.onSaveInstanceState(outState);
133 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
134 }
135
136
137 /** Defines callbacks for service binding, passed to bindService() */
138 private class PreviewImageServiceConnection implements ServiceConnection {
139
140 @Override
141 public void onServiceConnected(ComponentName component, IBinder service) {
142
143 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
144 mDownloaderBinder = (FileDownloaderBinder) service;
145 if (mRequestWaitingForBinder) {
146 mRequestWaitingForBinder = false;
147 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
148 onPageSelected(mViewPager.getCurrentItem());
149 }
150
151 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
152 Log_OC.d(TAG, "Upload service connected");
153 mUploaderBinder = (FileUploaderBinder) service;
154 } else {
155 return;
156 }
157
158 }
159
160 @Override
161 public void onServiceDisconnected(ComponentName component) {
162 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
163 Log_OC.d(TAG, "Download service suddenly disconnected");
164 mDownloaderBinder = null;
165 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
166 Log_OC.d(TAG, "Upload service suddenly disconnected");
167 mUploaderBinder = null;
168 }
169 }
170 };
171
172
173 @Override
174 public void onStop() {
175 super.onStop();
176 if (mDownloadConnection != null) {
177 unbindService(mDownloadConnection);
178 mDownloadConnection = null;
179 }
180 if (mUploadConnection != null) {
181 unbindService(mUploadConnection);
182 mUploadConnection = null;
183 }
184 }
185
186
187 @Override
188 public void onDestroy() {
189 super.onDestroy();
190 }
191
192
193 @Override
194 public boolean onOptionsItemSelected(MenuItem item) {
195 boolean returnValue = false;
196
197 switch(item.getItemId()){
198 case android.R.id.home:
199 backToDisplayActivity();
200 returnValue = true;
201 break;
202 default:
203 returnValue = super.onOptionsItemSelected(item);
204 }
205
206 return returnValue;
207 }
208
209
210 @Override
211 protected void onResume() {
212 super.onResume();
213 //Log.e(TAG, "ACTIVITY, ONRESUME");
214 mDownloadFinishReceiver = new DownloadFinishReceiver();
215 IntentFilter filter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
216 filter.addAction(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
217 registerReceiver(mDownloadFinishReceiver, filter);
218 }
219
220 @Override
221 protected void onPostResume() {
222 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
223 super.onPostResume();
224 }
225
226 @Override
227 public void onPause() {
228 super.onPause();
229 unregisterReceiver(mDownloadFinishReceiver);
230 mDownloadFinishReceiver = null;
231 }
232
233
234 private void backToDisplayActivity() {
235 finish();
236 }
237
238
239 @Override
240 protected Dialog onCreateDialog(int id) {
241 Dialog dialog = null;
242 switch (id) {
243 case DIALOG_SHORT_WAIT: {
244 ProgressDialog working_dialog = new ProgressDialog(this);
245 working_dialog.setMessage(getResources().getString(
246 R.string.wait_a_moment));
247 working_dialog.setIndeterminate(true);
248 working_dialog.setCancelable(false);
249 dialog = working_dialog;
250 break;
251 }
252 default:
253 dialog = null;
254 }
255 return dialog;
256 }
257
258
259 /**
260 * {@inheritDoc}
261 */
262 @Override
263 public void onFileStateChanged() {
264 // nothing to do here!
265 }
266
267
268 /**
269 * {@inheritDoc}
270 */
271 @Override
272 public FileDownloaderBinder getFileDownloaderBinder() {
273 return mDownloaderBinder;
274 }
275
276
277 @Override
278 public FileUploaderBinder getFileUploaderBinder() {
279 return mUploaderBinder;
280 }
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 = mStorageManager.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.DOWNLOAD_FINISH_MESSAGE)) {
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 if (getAccount() != null) {
417 OCFile file = getFile();
418 /// Validate handled file (first image to preview)
419 if (file == null) {
420 throw new IllegalStateException("Instanced with a NULL OCFile");
421 }
422 if (!file.isImage()) {
423 throw new IllegalArgumentException("Non-image file passed as argument");
424 }
425 mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver());
426 file = mStorageManager.getFileById(file.getFileId());
427 if (file != null) {
428 /// Refresh the activity according to the Account and OCFile set
429 setFile(file); // reset after getting it fresh from mStorageManager
430 getSupportActionBar().setTitle(getFile().getFileName());
431 //if (!stateWasRecovered) {
432 initViewPager();
433 //}
434
435 } else {
436 // handled file not in the current Account
437 finish();
438 }
439
440 } else {
441 Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!");
442 }
443 }
444
445
446 }