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