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