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