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