9e0474d52a60639480fc7efbf95c01404a358d78
[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.annotation.SuppressLint;
20 import android.content.BroadcastReceiver;
21 import android.content.ComponentName;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.IntentFilter;
25 import android.content.ServiceConnection;
26 import android.media.MediaScannerConnection;
27 import android.content.SharedPreferences;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.os.IBinder;
32 import android.os.Message;
33 import android.preference.PreferenceManager;
34 import android.support.v4.view.ViewPager;
35 import android.view.View;
36
37 import com.actionbarsherlock.app.ActionBar;
38 import com.actionbarsherlock.view.MenuItem;
39 import com.actionbarsherlock.view.Window;
40 import com.ortiz.touch.ExtendedViewPager;
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.FileDownloader.FileDownloaderBinder;
47 import com.owncloud.android.files.services.FileUploader;
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.lib.common.utils.Log_OC;
54 import com.owncloud.android.operations.CreateShareOperation;
55 import com.owncloud.android.operations.RemoveFileOperation;
56 import com.owncloud.android.operations.UnshareLinkOperation;
57 import com.owncloud.android.ui.activity.FileActivity;
58 import com.owncloud.android.ui.activity.FileDisplayActivity;
59 import com.owncloud.android.ui.activity.PinCodeActivity;
60 import com.owncloud.android.ui.fragment.FileFragment;
61 import com.owncloud.android.utils.DisplayUtils;
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
70 FileFragment.ContainerActivity,
71 ViewPager.OnPageChangeListener, OnRemoteOperationListener {
72
73 public static final int DIALOG_SHORT_WAIT = 0;
74
75 public static final String TAG = PreviewImageActivity.class.getSimpleName();
76
77 public static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
78 private static final String KEY_WAITING_FOR_BINDER = "WAITING_FOR_BINDER";
79
80 private static final int INITIAL_HIDE_DELAY = 0; // immediate hide
81
82 private ExtendedViewPager mViewPager;
83 private PreviewImagePagerAdapter mPreviewImagePagerAdapter;
84
85 private boolean mRequestWaitingForBinder;
86
87 private DownloadFinishReceiver mDownloadFinishReceiver;
88
89 private View mFullScreenAnchorView;
90
91
92 @Override
93 protected void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95
96 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
97 setContentView(R.layout.preview_image_activity);
98
99 ActionBar actionBar = getSupportActionBar();
100 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
101 actionBar.setDisplayHomeAsUpEnabled(true);
102 actionBar.hide();
103
104 // PIN CODE request
105 if (getIntent().getExtras() != null && savedInstanceState == null && fromNotification()) {
106 requestPinCode();
107 }
108
109 // Make sure we're running on Honeycomb or higher to use FullScreen and
110 // Immersive Mode
111 if (isHoneycombOrHigher()) {
112
113 mFullScreenAnchorView = getWindow().getDecorView();
114 // to keep our UI controls visibility in line with system bars
115 // visibility
116 mFullScreenAnchorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
117 @SuppressLint("InlinedApi")
118 @Override
119 public void onSystemUiVisibilityChange(int flags) {
120 boolean visible = (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
121 ActionBar actionBar = getSupportActionBar();
122 if (visible) {
123 actionBar.show();
124 } else {
125 actionBar.hide();
126 }
127 }
128 });
129
130 }
131
132 if (savedInstanceState != null) {
133 mRequestWaitingForBinder = savedInstanceState.getBoolean(KEY_WAITING_FOR_BINDER);
134 } else {
135 mRequestWaitingForBinder = false;
136 }
137
138 }
139
140 private void initViewPager() {
141 // get parent from path
142 String parentPath = getFile().getRemotePath().substring(0, getFile().getRemotePath().lastIndexOf(getFile().getFileName()));
143 OCFile parentFolder = getStorageManager().getFileByPath(parentPath);
144 if (parentFolder == null) {
145 // should not be necessary
146 parentFolder = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
147 }
148 mPreviewImagePagerAdapter = new PreviewImagePagerAdapter(getSupportFragmentManager(), parentFolder, getAccount(), getStorageManager());
149 mViewPager = (ExtendedViewPager) findViewById(R.id.fragmentPager);
150 int position = mPreviewImagePagerAdapter.getFilePosition(getFile());
151 position = (position >= 0) ? position : 0;
152 mViewPager.setAdapter(mPreviewImagePagerAdapter);
153 mViewPager.setOnPageChangeListener(this);
154 mViewPager.setCurrentItem(position);
155 if (position == 0 && !getFile().isDown()) {
156 // this is necessary because mViewPager.setCurrentItem(0) just after setting the adapter does not result in a call to #onPageSelected(0)
157 mRequestWaitingForBinder = true;
158 }
159 }
160
161
162 protected void onPostCreate(Bundle savedInstanceState) {
163 super.onPostCreate(savedInstanceState);
164
165 // Trigger the initial hide() shortly after the activity has been
166 // created, to briefly hint to the user that UI controls
167 // are available
168 delayedHide(INITIAL_HIDE_DELAY);
169
170 }
171
172 Handler mHideSystemUiHandler = new Handler() {
173 @Override
174 public void handleMessage(Message msg) {
175 if (isHoneycombOrHigher()) {
176 hideSystemUI(mFullScreenAnchorView);
177 }
178 getSupportActionBar().hide();
179 }
180 };
181
182 private void delayedHide(int delayMillis) {
183 mHideSystemUiHandler.removeMessages(0);
184 mHideSystemUiHandler.sendEmptyMessageDelayed(0, delayMillis);
185 }
186
187
188 /// handle Window Focus changes
189 @Override
190 public void onWindowFocusChanged(boolean hasFocus) {
191 super.onWindowFocusChanged(hasFocus);
192
193 // When the window loses focus (e.g. the action overflow is shown),
194 // cancel any pending hide action.
195 if (!hasFocus) {
196 mHideSystemUiHandler.removeMessages(0);
197 }
198 }
199
200
201
202 @Override
203 public void onStart() {
204 super.onStart();
205 }
206
207 @Override
208 protected void onSaveInstanceState(Bundle outState) {
209 super.onSaveInstanceState(outState);
210 outState.putBoolean(KEY_WAITING_FOR_BINDER, mRequestWaitingForBinder);
211 }
212
213 @Override
214 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
215 super.onRemoteOperationFinish(operation, result);
216
217 if (operation instanceof CreateShareOperation) {
218 onCreateShareOperationFinish((CreateShareOperation) operation, result);
219
220 } else if (operation instanceof UnshareLinkOperation) {
221 onUnshareLinkOperationFinish((UnshareLinkOperation) operation, result);
222
223 } else if (operation instanceof RemoveFileOperation) {
224 finish();
225 }
226 }
227
228
229 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
230 if (result.isSuccess()) {
231 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
232 if (file != null) {
233 setFile(file);
234 }
235 invalidateOptionsMenu();
236 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
237 backToDisplayActivity();
238 }
239
240 }
241
242 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
243 if (result.isSuccess()) {
244 OCFile file = getStorageManager().getFileByPath(getFile().getRemotePath());
245 if (file != null) {
246 setFile(file);
247 }
248 invalidateOptionsMenu();
249 }
250 }
251
252 @Override
253 protected ServiceConnection newTransferenceServiceConnection() {
254 return new PreviewImageServiceConnection();
255 }
256
257 /** Defines callbacks for service binding, passed to bindService() */
258 private class PreviewImageServiceConnection implements ServiceConnection {
259
260 @Override
261 public void onServiceConnected(ComponentName component, IBinder service) {
262
263 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
264 mDownloaderBinder = (FileDownloaderBinder) service;
265 if (mRequestWaitingForBinder) {
266 mRequestWaitingForBinder = false;
267 Log_OC.d(TAG, "Simulating reselection of current page after connection of download binder");
268 onPageSelected(mViewPager.getCurrentItem());
269 }
270
271 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
272 Log_OC.d(TAG, "Upload service connected");
273 mUploaderBinder = (FileUploaderBinder) service;
274 } else {
275 return;
276 }
277
278 }
279
280 @Override
281 public void onServiceDisconnected(ComponentName component) {
282 if (component.equals(new ComponentName(PreviewImageActivity.this, FileDownloader.class))) {
283 Log_OC.d(TAG, "Download service suddenly disconnected");
284 mDownloaderBinder = null;
285 } else if (component.equals(new ComponentName(PreviewImageActivity.this, FileUploader.class))) {
286 Log_OC.d(TAG, "Upload service suddenly disconnected");
287 mUploaderBinder = null;
288 }
289 }
290 };
291
292
293 @Override
294 public void onStop() {
295 super.onStop();
296 }
297
298
299 @Override
300 public void onDestroy() {
301 super.onDestroy();
302 }
303
304 @Override
305 public boolean onOptionsItemSelected(MenuItem item) {
306 boolean returnValue = false;
307
308 switch(item.getItemId()){
309 case android.R.id.home:
310 backToDisplayActivity();
311 returnValue = true;
312 break;
313 default:
314 returnValue = super.onOptionsItemSelected(item);
315 }
316
317 return returnValue;
318 }
319
320
321 @Override
322 protected void onResume() {
323 super.onResume();
324 //Log_OC.e(TAG, "ACTIVITY, ONRESUME");
325 mDownloadFinishReceiver = new DownloadFinishReceiver();
326
327 IntentFilter filter = new IntentFilter(FileDownloader.getDownloadFinishMessage());
328 filter.addAction(FileDownloader.getDownloadAddedMessage());
329 registerReceiver(mDownloadFinishReceiver, filter);
330 }
331
332 @Override
333 protected void onPostResume() {
334 //Log_OC.e(TAG, "ACTIVITY, ONPOSTRESUME");
335 super.onPostResume();
336 }
337
338 @Override
339 public void onPause() {
340 unregisterReceiver(mDownloadFinishReceiver);
341 mDownloadFinishReceiver = null;
342 super.onPause();
343 }
344
345
346 private void backToDisplayActivity() {
347 finish();
348 }
349
350 @Override
351 public void showDetails(OCFile file) {
352 Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
353 showDetailsIntent.setAction(FileDisplayActivity.ACTION_DETAILS);
354 showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, file);
355 showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
356 startActivity(showDetailsIntent);
357 int pos = mPreviewImagePagerAdapter.getFilePosition(file);
358 file = mPreviewImagePagerAdapter.getFileAt(pos);
359
360 }
361
362
363 private void requestForDownload(OCFile file) {
364 if (mDownloaderBinder == null) {
365 Log_OC.d(TAG, "requestForDownload called without binder to download service");
366
367 } else if (!mDownloaderBinder.isDownloading(getAccount(), file)) {
368 Intent i = new Intent(this, FileDownloader.class);
369 i.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());
370 i.putExtra(FileDownloader.EXTRA_FILE, file);
371 startService(i);
372 }
373 }
374
375 /**
376 * This method will be invoked when a new page becomes selected. Animation is not necessarily complete.
377 *
378 * @param Position Position index of the new selected page
379 */
380 @Override
381 public void onPageSelected(int position) {
382 if (mDownloaderBinder == null) {
383 mRequestWaitingForBinder = true;
384
385 } else {
386 OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);
387 getSupportActionBar().setTitle(currentFile.getFileName());
388 if (!currentFile.isDown()) {
389 if (!mPreviewImagePagerAdapter.pendingErrorAt(position)) {
390 requestForDownload(currentFile);
391 }
392 }
393
394 // Call to reset image zoom to initial state
395 ((PreviewImagePagerAdapter) mViewPager.getAdapter()).resetZoom();
396 }
397
398 }
399
400 /**
401 * Called when the scroll state changes. Useful for discovering when the user begins dragging,
402 * when the pager is automatically settling to the current page. when it is fully stopped/idle.
403 *
404 * @param State The new scroll state (SCROLL_STATE_IDLE, _DRAGGING, _SETTLING
405 */
406 @Override
407 public void onPageScrollStateChanged(int state) {
408 }
409
410 /**
411 * This method will be invoked when the current page is scrolled, either as part of a programmatically
412 * initiated smooth scroll or a user initiated touch scroll.
413 *
414 * @param position Position index of the first page currently being displayed.
415 * Page position+1 will be visible if positionOffset is nonzero.
416 *
417 * @param positionOffset Value from [0, 1) indicating the offset from the page at position.
418 * @param positionOffsetPixels Value in pixels indicating the offset from position.
419 */
420 @Override
421 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
422 }
423
424
425 /**
426 * Class waiting for broadcast events from the {@link FielDownloader} service.
427 *
428 * Updates the UI when a download is started or finished, provided that it is relevant for the
429 * folder displayed in the gallery.
430 */
431 private class DownloadFinishReceiver extends BroadcastReceiver {
432 @Override
433 public void onReceive(Context context, Intent intent) {
434 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
435 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
436 if (getAccount().name.equals(accountName) &&
437 downloadedRemotePath != null) {
438
439 OCFile file = getStorageManager().getFileByPath(downloadedRemotePath);
440 int position = mPreviewImagePagerAdapter.getFilePosition(file);
441 boolean downloadWasFine = intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false);
442 //boolean isOffscreen = Math.abs((mViewPager.getCurrentItem() - position)) <= mViewPager.getOffscreenPageLimit();
443
444 if (position >= 0 && intent.getAction().equals(FileDownloader.getDownloadFinishMessage())) {
445 if (downloadWasFine) {
446 mPreviewImagePagerAdapter.updateFile(position, file);
447
448 } else {
449 mPreviewImagePagerAdapter.updateWithDownloadError(position);
450 }
451 mPreviewImagePagerAdapter.notifyDataSetChanged(); // will trigger the creation of new fragments
452
453 } else {
454 Log_OC.d(TAG, "Download finished, but the fragment is offscreen");
455 }
456
457 }
458 removeStickyBroadcast(intent);
459 }
460
461 }
462
463 @SuppressLint("InlinedApi")
464 public void toggleFullScreen() {
465
466 if (isHoneycombOrHigher()) {
467
468 boolean visible = (mFullScreenAnchorView.getSystemUiVisibility()
469 & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
470
471 if (visible) {
472 hideSystemUI(mFullScreenAnchorView);
473 // actionBar.hide(); // propagated through
474 // OnSystemUiVisibilityChangeListener()
475 } else {
476 showSystemUI(mFullScreenAnchorView);
477 // actionBar.show(); // propagated through
478 // OnSystemUiVisibilityChangeListener()
479 }
480
481 } else {
482
483 ActionBar actionBar = getSupportActionBar();
484 if (!actionBar.isShowing()) {
485 actionBar.show();
486
487 } else {
488 actionBar.hide();
489
490 }
491
492 }
493 }
494
495 @Override
496 protected void onAccountSet(boolean stateWasRecovered) {
497 super.onAccountSet(stateWasRecovered);
498 if (getAccount() != null) {
499 OCFile file = getFile();
500 /// Validate handled file (first image to preview)
501 if (file == null) {
502 throw new IllegalStateException("Instanced with a NULL OCFile");
503 }
504 if (!file.isImage()) {
505 throw new IllegalArgumentException("Non-image file passed as argument");
506 }
507
508 // Update file according to DB file, if it is possible
509 if (file.getFileId() > FileDataStorageManager.ROOT_PARENT_ID)
510 file = getStorageManager().getFileById(file.getFileId());
511
512 if (file != null) {
513 /// Refresh the activity according to the Account and OCFile set
514 setFile(file); // reset after getting it fresh from storageManager
515 getSupportActionBar().setTitle(getFile().getFileName());
516 //if (!stateWasRecovered) {
517 initViewPager();
518 //}
519
520 } else {
521 // handled file not in the current Account
522 finish();
523 }
524 }
525 }
526
527
528 /**
529 * Launch an intent to request the PIN code to the user before letting him use the app
530 */
531 private void requestPinCode() {
532 boolean pinStart = false;
533 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
534 pinStart = appPrefs.getBoolean("set_pincode", false);
535 if (pinStart) {
536 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
537 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "PreviewImageActivity");
538 startActivity(i);
539 }
540 }
541
542 @Override
543 public void onBrowsedDownTo(OCFile folder) {
544 // TODO Auto-generated method stub
545
546 }
547
548 @Override
549 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
550 // TODO Auto-generated method stub
551
552 }
553
554
555 @SuppressLint("InlinedApi")
556 private void hideSystemUI(View anchorView) {
557 anchorView.setSystemUiVisibility(
558 View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hides NAVIGATION BAR; Android >= 4.0
559 | View.SYSTEM_UI_FLAG_FULLSCREEN // hides STATUS BAR; Android >= 4.1
560 | View.SYSTEM_UI_FLAG_IMMERSIVE // stays interactive; Android >= 4.4
561 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
562 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
563 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
564 );
565 }
566
567 @SuppressLint("InlinedApi")
568 private void showSystemUI(View anchorView) {
569 anchorView.setSystemUiVisibility(
570 View.SYSTEM_UI_FLAG_LAYOUT_STABLE // draw full window; Android >= 4.1
571 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // draw full window; Android >= 4.1
572 | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // draw full window; Android >= 4.1
573 );
574 }
575
576 /**
577 * Checks if OS version is Honeycomb one or higher
578 *
579 * @return boolean
580 */
581 private boolean isHoneycombOrHigher() {
582 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
583 return true;
584 }
585 return false;
586 }
587
588 }