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