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