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