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