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