Improvements in load of images: progress wheel while loading and better scaling
[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 as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package com.owncloud.android.ui.preview;
19
20 import org.apache.commons.httpclient.methods.PostMethod;
21
22 import android.accounts.Account;
23 import android.app.Dialog;
24 import android.app.ProgressDialog;
25 import android.content.BroadcastReceiver;
26 import android.content.ComponentName;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.IntentFilter;
30 import android.content.ServiceConnection;
31 import android.os.Bundle;
32 import android.os.IBinder;
33 import android.support.v4.app.Fragment;
34 import android.support.v4.view.ViewPager;
35 import android.util.Log;
36 import android.view.MotionEvent;
37 import android.view.View;
38 import android.view.View.OnTouchListener;
39
40 import com.actionbarsherlock.app.ActionBar;
41 import com.actionbarsherlock.app.SherlockFragmentActivity;
42 import com.actionbarsherlock.view.MenuItem;
43 import com.actionbarsherlock.view.Window;
44 import com.owncloud.android.datamodel.DataStorageManager;
45 import com.owncloud.android.datamodel.FileDataStorageManager;
46 import com.owncloud.android.datamodel.OCFile;
47 import com.owncloud.android.files.services.FileDownloader;
48 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
49 import com.owncloud.android.files.services.FileUploader;
50 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
51 import com.owncloud.android.ui.activity.FileDetailActivity;
52 import com.owncloud.android.ui.fragment.FileDetailFragment;
53 import com.owncloud.android.ui.fragment.FileFragment;
54
55 import com.owncloud.android.AccountUtils;
56 import com.owncloud.android.R;
57
58 /**
59 * Used as an utility to preview image files contained in an ownCloud account.
60 *
61 * @author David A. Velasco
62 */
63 public class PreviewImageActivity extends SherlockFragmentActivity implements FileFragment.ContainerActivity, ViewPager.OnPageChangeListener, OnTouchListener {
64
65 public static final int DIALOG_SHORT_WAIT = 0;
66
67 public static final String TAG = PreviewImageActivity.class.getSimpleName();
68
69 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
70 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
71
72 private OCFile mFile;
73 private OCFile mParentFolder;
74 private Account mAccount;
75 private DataStorageManager mStorageManager;
76
77 private ViewPager mViewPager;
78 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
79
80 private FileDownloaderBinder mDownloaderBinder = null;
81 private ServiceConnection mDownloadConnection, mUploadConnection = null;
82 private FileUploaderBinder mUploaderBinder = null;
83
84 private boolean mRequestWaitingForBinder;
85
86 private DownloadFinishReceiver mDownloadFinishReceiver;
87
88 private boolean mFullScreen;
89
90
91 @Override
92 protected void onCreate(Bundle savedInstanceState) {
93 super.onCreate(savedInstanceState);
94
95 mFile = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE);
96 mAccount = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
97 if (mFile == null) {
98 throw new IllegalStateException("Instanced with a NULL OCFile");
99 }
100 if (mAccount == null) {
101 throw new IllegalStateException("Instanced with a NULL ownCloud Account");
102 }
103 if (!mFile.isImage()) {
104 throw new IllegalArgumentException("Non-image file passed as argument");
105 }
106 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
107 setContentView(R.layout.preview_image_activity);
108
109 ActionBar actionBar = getSupportActionBar();
110 actionBar.setDisplayHomeAsUpEnabled(true);
111 actionBar.setTitle(mFile.getFileName());
112 actionBar.hide();
113
114 mFullScreen = true;
115
116 mStorageManager = new FileDataStorageManager(mAccount, getContentResolver());
117 mParentFolder = mStorageManager.getFileById(mFile.getParentId());
118 if (mParentFolder == null) {
119 // should not be necessary
120 mParentFolder = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
121 }
122
123 if (savedInstanceState != null) {
124 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
125 } else {
126 mRequestWaitingForBinder = false;
127 }
128
129 createViewPager();
130
131 }
132
133 private void createViewPager() {
134 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), mParentFolder, mAccount, mStorageManager);
135 mViewPager = (ViewPager) findViewById(R.id.fragmentPager);
136 int position = mPreviewImagePagerAdapter.getFilePosition(mFile);
137 position = (position >= 0) ? position : 0;
138 mViewPager.setAdapter(mPreviewImagePagerAdapter);
139 mViewPager.setOnPageChangeListener(this);
140 mViewPager.setCurrentItem(position);
141 if (position == 0 && !mFile.isDown()) {
142 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
143 mRequestWaitingForBinder = true;
144 }
145 }
146
147
148 @Override
149 public void onStart() {
150 super.onStart();
151 mDownloadConnection = new PreviewImageServiceConnection();
152 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
153 mUploadConnection = new PreviewImageServiceConnection();
154 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
155 }
156
157 @Override
158 protected void onSaveInstanceState(Bundle outState) {
159 super.onSaveInstanceState(outState);
160 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
161 }
162
163
164 /** Defines callbacks for service binding, passed to bindService() */
165 private class PreviewImageServiceConnection implements ServiceConnection {
166
167 @Override
168 public void onServiceConnected(ComponentName component, IBinder service) {
169
170 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
171 mDownloaderBinder = (FileDownloaderBinder) service;
172 if (mRequestWaitingForBinder) {
173 mRequestWaitingForBinder = false;
174 Log.d(TAG, "Simulating reselection of current page after connection of download binder");
175 onPageSelected(mViewPager.getCurrentItem());
176 }
177
178 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
179 Log.d(TAG, "Upload service connected");
180 mUploaderBinder = (FileUploaderBinder) service;
181 } else {
182 return;
183 }
184
185 }
186
187 @Override
188 public void onServiceDisconnected(ComponentName component) {
189 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
190 Log.d(TAG, "Download service suddenly disconnected");
191 mDownloaderBinder = null;
192 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
193 Log.d(TAG, "Upload service suddenly disconnected");
194 mUploaderBinder = null;
195 }
196 }
197 };
198
199
200 @Override
201 public void onStop() {
202 super.onStop();
203 if (mDownloadConnection != null) {
204 unbindService(mDownloadConnection);
205 mDownloadConnection = null;
206 }
207 if (mUploadConnection != null) {
208 unbindService(mUploadConnection);
209 mUploadConnection = null;
210 }
211 }
212
213
214 @Override
215 public void onDestroy() {
216 super.onDestroy();
217 }
218
219
220 @Override
221 public boolean onOptionsItemSelected(MenuItem item) {
222 boolean returnValue = false;
223
224 switch(item.getItemId()){
225 case android.R.id.home:
226 backToDisplayActivity();
227 returnValue = true;
228 break;
229 default:
230 returnValue = super.onOptionsItemSelected(item);
231 }
232
233 return returnValue;
234 }
235
236
237 @Override
238 protected void onResume() {
239 super.onResume();
240 //Log.e(TAG, "ACTIVITY, ONRESUME");
241 mDownloadFinishReceiver = new DownloadFinishReceiver();
242 IntentFilter filter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
243 registerReceiver(mDownloadFinishReceiver, filter);
244 }
245
246 @Override
247 protected void onPostResume() {
248 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
249 super.onPostResume();
250 }
251
252 @Override
253 public void onPause() {
254 super.onPause();
255 unregisterReceiver(mDownloadFinishReceiver);
256 mDownloadFinishReceiver = null;
257 }
258
259
260 private void backToDisplayActivity() {
261 /*
262 Intent intent = new Intent(this, FileDisplayActivity.class);
263 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
264 intent.putExtra(FileDetailFragment.EXTRA_FILE, mFile);
265 intent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, mAccount);
266 startActivity(intent);
267 */
268 finish();
269 }
270
271
272 @Override
273 protected Dialog onCreateDialog(int id) {
274 Dialog dialog = null;
275 switch (id) {
276 case DIALOG_SHORT_WAIT: {
277 ProgressDialog working_dialog = new ProgressDialog(this);
278 working_dialog.setMessage(getResources().getString(
279 R.string.wait_a_moment));
280 working_dialog.setIndeterminate(true);
281 working_dialog.setCancelable(false);
282 dialog = working_dialog;
283 break;
284 }
285 default:
286 dialog = null;
287 }
288 return dialog;
289 }
290
291
292 /**
293 * {@inheritDoc}
294 */
295 @Override
296 public void onFileStateChanged() {
297 // nothing to do here!
298 }
299
300
301 /**
302 * {@inheritDoc}
303 */
304 @Override
305 public FileDownloaderBinder getFileDownloaderBinder() {
306 return mDownloaderBinder;
307 }
308
309
310 @Override
311 public FileUploaderBinder getFileUploaderBinder() {
312 return mUploaderBinder;
313 }
314
315
316 @Override
317 public void showFragmentWithDetails(OCFile file) {
318 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
319 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
320 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
321 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
322 startActivity(showDetailsIntent);
323 }
324
325
326 private void requestForDownload(OCFile file) {
327 if (mDownloaderBinder == null) {
328 Log.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 requestForDownload(currentFile);
353 /*} else {
354 FileFragment fragment = mPreviewImagePagerAdapter.getFragmentAt(mViewPager.getCurrentItem());
355 if (fragment instanceof PreviewImageFragment) {
356 ((PreviewImageFragment)fragment).showError();
357 }*/
358 }
359 }
360 }
361
362 /**
363 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
364 * when the pager is automatically settling to the current page, or when it is fully stopped/idle.
365 *
366 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
367 */
368 @Override
369 public void onPageScrollStateChanged(int state) {
370 }
371
372 /**
373 * This method will be invoked when the current page is scrolled, either as part of a programmatically
374 * initiated smooth scroll or a user initiated touch scroll.
375 *
376 * @param position Position index of the first page currently being displayed.
377 * Page position+1 will be visible if positionOffset is nonzero.
378 *
379 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
380 * @param positionOffsetPixels Value in pixels indicating the offset from position.
381 */
382 @Override
383 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
384 }
385
386
387 private void updateCurrentDownloadFragment(boolean transferring) {
388 FileFragment fragment = mPreviewImagePagerAdapter.getFragmentAt(mViewPager.getCurrentItem());
389 if (fragment instanceof FileDownloadFragment) {
390 ((FileDownloadFragment) fragment).updateView(transferring);
391 //mViewPager.invalidate();
392 }
393 }
394
395
396 /**
397 * Class waiting for broadcast events from the {@link FielDownloader} service.
398 *
399 * Updates the UI when a download is started or finished, provided that it is relevant for the
400 * folder displayed in the gallery.
401 */
402 private class DownloadFinishReceiver extends BroadcastReceiver {
403 @Override
404 public void onReceive(Context context, Intent intent) {
405 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
406 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
407 if (mAccount.name.equals(accountName) &&
408 downloadedRemotePath != null) {
409
410 OCFile file = mStorageManager.getFileByPath(downloadedRemotePath);
411 int position = mPreviewImagePagerAdapter.getFilePosition(file);
412 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
413 boolean isCurrent = (mViewPager.getCurrentItem() == position);
414
415 if (position >= 0) {
416 /// ITS MY BUSSINESS
417 if (downloadWasFine) {
418 mPreviewImagePagerAdapter.updateFile(position, file);
419 mPreviewImagePagerAdapter.notifyDataSetChanged();
420
421 } else if (isCurrent) {
422 updateCurrentDownloadFragment(false);
423 }
424
425 } else {
426 Log.e(TAG, "DOWNLOADED FILE NOT FOUND IN ADAPTER ");
427 }
428
429 }
430 removeStickyBroadcast(intent);
431 }
432
433 }
434
435
436 @Override
437 public boolean onTouch(View v, MotionEvent event) {
438 if (event.getAction() == MotionEvent.ACTION_UP) {
439 toggleFullScreen();
440 }
441 return true;
442 }
443
444
445 private void toggleFullScreen() {
446 ActionBar actionBar = getSupportActionBar();
447 if (mFullScreen) {
448 actionBar.show();
449
450 } else {
451 actionBar.hide();
452
453 }
454 mFullScreen = !mFullScreen;
455 }
456
457
458 }