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