Merge branch 'feature_previews' into develop
[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 as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package com.owncloud.android.ui.preview;
19
20 import org.apache.commons.httpclient.methods.PostMethod;
21
22 import android.accounts.Account;
23 import android.app.Dialog;
24 import android.app.ProgressDialog;
25 import android.content.BroadcastReceiver;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.ServiceConnection;
31 import android.os.Bundle;
32 import android.os.IBinder;
33 import android.support.v4.app.Fragment;
34 import android.support.v4.view.ViewPager;
35 import android.util.Log;
36 import android.view.MotionEvent;
37 import android.view.View;
38 import android.view.View.OnTouchListener;
39
40 import com.actionbarsherlock.app.ActionBar;
41 import com.actionbarsherlock.app.SherlockFragmentActivity;
42 import com.actionbarsherlock.view.MenuItem;
43 import com.actionbarsherlock.view.Window;
44 import com.owncloud.android.datamodel.DataStorageManager;
45 import com.owncloud.android.datamodel.FileDataStorageManager;
46 import com.owncloud.android.datamodel.OCFile;
47 import com.owncloud.android.files.services.FileDownloader;
48 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
49 import com.owncloud.android.files.services.FileUploader;
50 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
51 import com.owncloud.android.ui.activity.FileDetailActivity;
52 import com.owncloud.android.ui.fragment.FileDetailFragment;
53 import com.owncloud.android.ui.fragment.FileFragment;
54
55 import com.owncloud.android.AccountUtils;
56 import com.owncloud.android.R;
57
58 /**
59 * Used as an utility to preview image files contained in an ownCloud account.
60 *
61 * @author David A. Velasco
62 */
63 public class PreviewImageActivity extends SherlockFragmentActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
64
65 public static final int DIALOG_SHORT_WAIT = 0;
66
67 public static final String TAG = PreviewImageActivity.class.getSimpleName();
68
69 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
70 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
71
72 private OCFile mFile;
73 private OCFile mParentFolder;
74 private Account mAccount;
75 private DataStorageManager mStorageManager;
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 mFile = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
96 mAccount = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
97 if (mFile == null) {
98 throw new IllegalStateException("Instanced with a NULL OCFile");
99 }
100 if (mAccount == null) {
101 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
102 }
103 if (!mFile.isImage()) {
104 throw new IllegalArgumentException("Non-image file passed as argument");
105 }
106 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
107 setContentView(R.layout.preview_image_activity);
108
109 ActionBar actionBar = getSupportActionBar();
110 actionBar.setDisplayHomeAsUpEnabled(true);
111 actionBar.setTitle(mFile.getFileName());
112 actionBar.hide();
113
114 mFullScreen = true;
115
116 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
117 mParentFolder = mStorageManager.getFileById(mFile.getParentId());
118 if (mParentFolder == null) {
119 // should not be necessary
120 mParentFolder = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
121 }
122
123 if (savedInstanceState != null) {
124 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
125 } else {
126 mRequestWaitingForBinder = false;
127 }
128
129 createViewPager();
130
131 }
132
133 private void createViewPager() {
134 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), mParentFolder, mAccount, mStorageManager);
135 mViewPager = (ViewPager) findViewById(R.id.fragmentPager);
136 int position = mPreviewImagePagerAdapter.getFilePosition(mFile);
137 position = (position >= 0) ? position : 0;
138 mViewPager.setAdapter(mPreviewImagePagerAdapter);
139 mViewPager.setOnPageChangeListener(this);
140 mViewPager.setCurrentItem(position);
141 if (position == 0 && !mFile.isDown()) {
142 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
143 mRequestWaitingForBinder = true;
144 }
145 }
146
147
148 @Override
149 public void onStart() {
150 super.onStart();
151 mDownloadConnection = new PreviewImageServiceConnection();
152 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
153 mUploadConnection = new PreviewImageServiceConnection();
154 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
155 }
156
157 @Override
158 protected void onSaveInstanceState(Bundle outState) {
159 super.onSaveInstanceState(outState);
160 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
161 }
162
163
164 /** Defines callbacks for service binding, passed to bindService() */
165 private class PreviewImageServiceConnection implements ServiceConnection {
166
167 @Override
168 public void onServiceConnected(ComponentName component, IBinder service) {
169
170 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
171 mDownloaderBinder = (FileDownloaderBinder) service;
172 if (mRequestWaitingForBinder) {
173 mRequestWaitingForBinder = false;
174 Log.d(TAG, "Simulating reselection of current page after connection of download binder");
175 onPageSelected(mViewPager.getCurrentItem());
176 }
177
178 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
179 Log.d(TAG, "Upload service connected");
180 mUploaderBinder = (FileUploaderBinder) service;
181 } else {
182 return;
183 }
184
185 }
186
187 @Override
188 public void onServiceDisconnected(ComponentName component) {
189 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
190 Log.d(TAG, "Download service suddenly disconnected");
191 mDownloaderBinder = null;
192 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
193 Log.d(TAG, "Upload service suddenly disconnected");
194 mUploaderBinder = null;
195 }
196 }
197 };
198
199
200 @Override
201 public void onStop() {
202 super.onStop();
203 if (mDownloadConnection != null) {
204 unbindService(mDownloadConnection);
205 mDownloadConnection = null;
206 }
207 if (mUploadConnection != null) {
208 unbindService(mUploadConnection);
209 mUploadConnection = null;
210 }
211 }
212
213
214 @Override
215 public void onDestroy() {
216 super.onDestroy();
217 }
218
219
220 @Override
221 public boolean onOptionsItemSelected(MenuItem item) {
222 boolean returnValue = false;
223
224 switch(item.getItemId()){
225 case android.R.id.home:
226 backToDisplayActivity();
227 returnValue = true;
228 break;
229 default:
230 returnValue = super.onOptionsItemSelected(item);
231 }
232
233 return returnValue;
234 }
235
236
237 @Override
238 protected void onResume() {
239 super.onResume();
240 //Log.e(TAG, "ACTIVITY, ONRESUME");
241 mDownloadFinishReceiver = new DownloadFinishReceiver();
242 IntentFilter filter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
243 filter.addAction(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
244 registerReceiver(mDownloadFinishReceiver, filter);
245 }
246
247 @Override
248 protected void onPostResume() {
249 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
250 super.onPostResume();
251 }
252
253 @Override
254 public void onPause() {
255 super.onPause();
256 unregisterReceiver(mDownloadFinishReceiver);
257 mDownloadFinishReceiver = null;
258 }
259
260
261 private void backToDisplayActivity() {
262 /*
263 Intent intent = new Intent(this, FileDisplayActivity.class);
264 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
265 intent.putExtra(FileDetailFragment.EXTRA_FILE, mFile);
266 intent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
267 startActivity(intent);
268 */
269 finish();
270 }
271
272
273 @Override
274 protected Dialog onCreateDialog(int id) {
275 Dialog dialog = null;
276 switch (id) {
277 case DIALOG_SHORT_WAIT: {
278 ProgressDialog working_dialog = new ProgressDialog(this);
279 working_dialog.setMessage(getResources().getString(
280 R.string.wait_a_moment));
281 working_dialog.setIndeterminate(true);
282 working_dialog.setCancelable(false);
283 dialog = working_dialog;
284 break;
285 }
286 default:
287 dialog = null;
288 }
289 return dialog;
290 }
291
292
293 /**
294 * {@inheritDoc}
295 */
296 @Override
297 public void onFileStateChanged() {
298 // nothing to do here!
299 }
300
301
302 /**
303 * {@inheritDoc}
304 */
305 @Override
306 public FileDownloaderBinder getFileDownloaderBinder() {
307 return mDownloaderBinder;
308 }
309
310
311 @Override
312 public FileUploaderBinder getFileUploaderBinder() {
313 return mUploaderBinder;
314 }
315
316
317 @Override
318 public void showFragmentWithDetails(OCFile file) {
319 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
320 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
321 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
322 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
323 startActivity(showDetailsIntent);
324 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
325 file = mPreviewImagePagerAdapter.getFileAt(pos);
326
327 }
328
329
330 private void requestForDownload(OCFile file) {
331 if (mDownloaderBinder == null) {
332 Log.d(TAG, "requestForDownload called without binder to download service");
333
334 } else if (!mDownloaderBinder.isDownloading(mAccount, file)) {
335 Intent i = new Intent(this, FileDownloader.class);
336 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
337 i.putExtra(FileDownloader.EXTRA_FILE, file);
338 startService(i);
339 }
340 }
341
342 /**
343 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
344 *
345 * @param Position Position index of the new selected page
346 */
347 @Override
348 public void onPageSelected(int position) {
349 if (mDownloaderBinder == null) {
350 mRequestWaitingForBinder = true;
351
352 } else {
353 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
354 getSupportActionBar().setTitle(currentFile.getFileName());
355 if (!currentFile.isDown()) {
356 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
357 requestForDownload(currentFile);
358 }
359 }
360 }
361 }
362
363 /**
364 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
365 * when the pager is automatically settling to the current page, or when it is fully stopped/idle.
366 *
367 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
368 */
369 @Override
370 public void onPageScrollStateChanged(int state) {
371 }
372
373 /**
374 * This method will be invoked when the current page is scrolled, either as part of a programmatically
375 * initiated smooth scroll or a user initiated touch scroll.
376 *
377 * @param position Position index of the first page currently being displayed.
378 * Page position+1 will be visible if positionOffset is nonzero.
379 *
380 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
381 * @param positionOffsetPixels Value in pixels indicating the offset from position.
382 */
383 @Override
384 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
385 }
386
387
388 /**
389 * Class waiting for broadcast events from the {@link FielDownloader} service.
390 *
391 * Updates the UI when a download is started or finished, provided that it is relevant for the
392 * folder displayed in the gallery.
393 */
394 private class DownloadFinishReceiver extends BroadcastReceiver {
395 @Override
396 public void onReceive(Context context, Intent intent) {
397 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
398 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
399 if (mAccount.name.equals(accountName) &&
400 downloadedRemotePath != null) {
401
402 OCFile file = mStorageManager.getFileByPath(downloadedRemotePath);
403 int position = mPreviewImagePagerAdapter.getFilePosition(file);
404 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
405 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
406
407 if (position >= 0 && intent.getAction().equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
408 if (downloadWasFine) {
409 mPreviewImagePagerAdapter.updateFile(position, file);
410
411 } else {
412 mPreviewImagePagerAdapter.updateWithDownloadError(position);
413 }
414 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
415
416 } else {
417 Log.d(TAG, "Download finished, but the fragment is offscreen");
418 }
419
420 }
421 removeStickyBroadcast(intent);
422 }
423
424 }
425
426
427 @Override
428 public boolean onTouch(View v, MotionEvent event) {
429 if (event.getAction() == MotionEvent.ACTION_UP) {
430 toggleFullScreen();
431 }
432 return true;
433 }
434
435
436 private void toggleFullScreen() {
437 ActionBar actionBar = getSupportActionBar();
438 if (mFullScreen) {
439 actionBar.show();
440
441 } else {
442 actionBar.hide();
443
444 }
445 mFullScreen = !mFullScreen;
446 }
447
448
449 }