OC-2887: Fix bug, refresh share icon, share menu refresh
[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.operations.common.OnRemoteOperationListener;
49 import com.owncloud.android.lib.operations.common.RemoteOperation;
50 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
51 import com.owncloud.android.lib.operations.common.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
249 @Override
250 public boolean onOptionsItemSelected(MenuItem item) {
251 boolean returnValue = false;
252
253 switch(item.getItemId()){
254 case android.R.id.home:
255 backToDisplayActivity();
256 returnValue = true;
257 break;
258 default:
259 returnValue = super.onOptionsItemSelected(item);
260 }
261
262 return returnValue;
263 }
264
265
266 @Override
267 protected void onResume() {
268 super.onResume();
269 //Log.e(TAG, "ACTIVITY, ONRESUME");
270 mDownloadFinishReceiver = new DownloadFinishReceiver();
271
272 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
273 filter.addAction(FileDownloader.getDownloadAddedMessage());
274 registerReceiver(mDownloadFinishReceiver, filter);
275 }
276
277 @Override
278 protected void onPostResume() {
279 //Log.e(TAG, "ACTIVITY, ONPOSTRESUME");
280 super.onPostResume();
281 }
282
283 @Override
284 public void onPause() {
285 super.onPause();
286 unregisterReceiver(mDownloadFinishReceiver);
287 mDownloadFinishReceiver = null;
288 }
289
290
291 private void backToDisplayActivity() {
292 finish();
293 }
294
295 /**
296 * Show loading dialog
297 */
298 public void showLoadingDialog() {
299 // Construct dialog
300 LoadingDialog loading = new LoadingDialog(getResources().getString(R.string.wait_a_moment));
301 FragmentManager fm = getSupportFragmentManager();
302 FragmentTransaction ft = fm.beginTransaction();
303 loading.show(ft, DIALOG_WAIT_TAG);
304
305 }
306
307 /**
308 * Dismiss loading dialog
309 */
310 public void dismissLoadingDialog(){
311 Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG);
312 if (frag != null) {
313 LoadingDialog loading = (LoadingDialog) frag;
314 loading.dismiss();
315 }
316 }
317
318 /**
319 * {@inheritDoc}
320 */
321 @Override
322 public void onFileStateChanged() {
323 // nothing to do here!
324 }
325
326
327 /**
328 * {@inheritDoc}
329 */
330 @Override
331 public FileDownloaderBinder getFileDownloaderBinder() {
332 return mDownloaderBinder;
333 }
334
335
336 @Override
337 public FileUploaderBinder getFileUploaderBinder() {
338 return mUploaderBinder;
339 }
340
341
342 @Override
343 public void showDetails(OCFile file) {
344 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
345 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
346 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
347 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
348 startActivity(showDetailsIntent);
349 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
350 file = mPreviewImagePagerAdapter.getFileAt(pos);
351
352 }
353
354
355 private void requestForDownload(OCFile file) {
356 if (mDownloaderBinder == null) {
357 Log_OC.d(TAG, "requestForDownload called without binder to download service");
358
359 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
360 Intent i = new Intent(this, FileDownloader.class);
361 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
362 i.putExtra(FileDownloader.EXTRA_FILE, file);
363 startService(i);
364 }
365 }
366
367 /**
368 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
369 *
370 * @param Position Position index of the new selected page
371 */
372 @Override
373 public void onPageSelected(int position) {
374 if (mDownloaderBinder == null) {
375 mRequestWaitingForBinder = true;
376
377 } else {
378 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
379 getSupportActionBar().setTitle(currentFile.getFileName());
380 if (!currentFile.isDown()) {
381 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
382 requestForDownload(currentFile);
383 }
384 }
385 }
386 }
387
388 /**
389 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
390 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
391 *
392 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
393 */
394 @Override
395 public void onPageScrollStateChanged(int state) {
396 }
397
398 /**
399 * This method will be invoked when the current page is scrolled, either as part of a programmatically
400 * initiated smooth scroll or a user initiated touch scroll.
401 *
402 * @param position Position index of the first page currently being displayed.
403 * Page position+1 will be visible if positionOffset is nonzero.
404 *
405 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
406 * @param positionOffsetPixels Value in pixels indicating the offset from position.
407 */
408 @Override
409 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
410 }
411
412
413 /**
414 * Class waiting for broadcast events from the {@link FielDownloader} service.
415 *
416 * Updates the UI when a download is started or finished, provided that it is relevant for the
417 * folder displayed in the gallery.
418 */
419 private class DownloadFinishReceiver extends BroadcastReceiver {
420 @Override
421 public void onReceive(Context context, Intent intent) {
422 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
423 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
424 if (getAccount().name.equals(accountName) &&
425 downloadedRemotePath != null) {
426
427 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
428 int position = mPreviewImagePagerAdapter.getFilePosition(file);
429 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
430 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
431
432 if (position >= 0 && intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
433 if (downloadWasFine) {
434 mPreviewImagePagerAdapter.updateFile(position, file);
435
436 } else {
437 mPreviewImagePagerAdapter.updateWithDownloadError(position);
438 }
439 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
440
441 } else {
442 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
443 }
444
445 }
446 removeStickyBroadcast(intent);
447 }
448
449 }
450
451
452 @Override
453 public boolean onTouch(View v, MotionEvent event) {
454 if (event.getAction() == MotionEvent.ACTION_UP) {
455 toggleFullScreen();
456 }
457 return true;
458 }
459
460
461 private void toggleFullScreen() {
462 ActionBar actionBar = getSupportActionBar();
463 if (mFullScreen) {
464 actionBar.show();
465
466 } else {
467 actionBar.hide();
468
469 }
470 mFullScreen = !mFullScreen;
471 }
472
473 @Override
474 protected void onAccountSet(boolean stateWasRecovered) {
475 super.onAccountSet(stateWasRecovered);
476 if (getAccount() != null) {
477 OCFile file = getFile();
478 /// Validate handled file (first image to preview)
479 if (file == null) {
480 throw new IllegalStateException("Instanced with a NULL OCFile");
481 }
482 if (!file.isImage()) {
483 throw new IllegalArgumentException("Non-image file passed as argument");
484 }
485
486 // Update file according to DB file, if it is possible
487 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
488 file = getStorageManager().getFileById(file.getFileId());
489
490 if (file != null) {
491 /// Refresh the activity according to the Account and OCFile set
492 setFile(file); // reset after getting it fresh from storageManager
493 getSupportActionBar().setTitle(getFile().getFileName());
494 //if (!stateWasRecovered) {
495 initViewPager();
496 //}
497
498 } else {
499 // handled file not in the current Account
500 finish();
501 }
502 }
503 }
504
505
506 /**
507 * Launch an intent to request the PIN code to the user before letting him use the app
508 */
509 private void requestPinCode() {
510 boolean pinStart = false;
511 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
512 pinStart = appPrefs.getBoolean("set_pincode", false);
513 if (pinStart) {
514 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
515 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "PreviewImageActivity");
516 startActivity(i);
517 }
518 }
519
520 }