You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ScrollbarBundle.java 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.widget.escalator;
  17. import com.google.gwt.animation.client.AnimationScheduler;
  18. import com.google.gwt.animation.client.AnimationScheduler.AnimationSupportDetector;
  19. import com.google.gwt.core.client.Scheduler;
  20. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  21. import com.google.gwt.dom.client.Element;
  22. import com.google.gwt.dom.client.Style.Display;
  23. import com.google.gwt.dom.client.Style.Overflow;
  24. import com.google.gwt.dom.client.Style.Unit;
  25. import com.google.gwt.dom.client.Style.Visibility;
  26. import com.google.gwt.event.shared.EventHandler;
  27. import com.google.gwt.event.shared.GwtEvent;
  28. import com.google.gwt.event.shared.HandlerManager;
  29. import com.google.gwt.event.shared.HandlerRegistration;
  30. import com.google.gwt.user.client.DOM;
  31. import com.google.gwt.user.client.Event;
  32. import com.google.gwt.user.client.EventListener;
  33. import com.google.gwt.user.client.Timer;
  34. import com.vaadin.client.BrowserInfo;
  35. import com.vaadin.client.DeferredWorker;
  36. import com.vaadin.client.WidgetUtil;
  37. import com.vaadin.client.widget.grid.events.ScrollEvent;
  38. import com.vaadin.client.widget.grid.events.ScrollHandler;
  39. /**
  40. * An element-like bundle representing a configurable and visual scrollbar in
  41. * one axis.
  42. *
  43. * @since 7.4
  44. * @author Vaadin Ltd
  45. * @see VerticalScrollbarBundle
  46. * @see HorizontalScrollbarBundle
  47. */
  48. public abstract class ScrollbarBundle implements DeferredWorker {
  49. private static final boolean supportsRequestAnimationFrame = new AnimationSupportDetector()
  50. .isNativelySupported();
  51. private class ScrollEventFirer {
  52. private final ScheduledCommand fireEventCommand = new ScheduledCommand() {
  53. @Override
  54. public void execute() {
  55. /*
  56. * Some kind of native-scroll-event related asynchronous problem
  57. * occurs here (at least on desktops) where the internal
  58. * bookkeeping isn't up to date with the real scroll position.
  59. * The weird thing is, that happens only once, and if you drag
  60. * scrollbar fast enough. After it has failed once, it never
  61. * fails again.
  62. *
  63. * Theory: the user drags the scrollbar, and this command is
  64. * executed before the browser has a chance to fire a scroll
  65. * event (which normally would correct this situation). This
  66. * would explain why slow scrolling doesn't trigger the problem,
  67. * while fast scrolling does.
  68. *
  69. * To make absolutely sure that we have the latest scroll
  70. * position, let's update the internal value.
  71. *
  72. * This might lead to a slight performance hit (on my computer
  73. * it was never more than 3ms on either of Chrome 38 or Firefox
  74. * 31). It also _slightly_ counteracts the purpose of the
  75. * internal bookkeeping. But since getScrollPos is called 3
  76. * times (on one direction) per scroll loop, it's still better
  77. * to have take this small penalty than removing it altogether.
  78. */
  79. updateScrollPosFromDom();
  80. getHandlerManager().fireEvent(new ScrollEvent());
  81. isBeingFired = false;
  82. }
  83. };
  84. private boolean isBeingFired;
  85. public void scheduleEvent() {
  86. if (!isBeingFired) {
  87. /*
  88. * We'll gather all the scroll events, and only fire once, once
  89. * everything has calmed down.
  90. */
  91. if (supportsRequestAnimationFrame) {
  92. // Chrome MUST use this as deferred commands will sometimes
  93. // be run with a 300+ ms delay when scrolling.
  94. AnimationScheduler.get().requestAnimationFrame(
  95. timestamp -> fireEventCommand.execute());
  96. } else {
  97. // Does not support requestAnimationFrame and the fallback
  98. // uses a delay of 16ms, we stick to the old deferred
  99. // command which uses a delay of 0ms
  100. Scheduler.get().scheduleDeferred(fireEventCommand);
  101. }
  102. isBeingFired = true;
  103. }
  104. }
  105. }
  106. /**
  107. * The orientation of the scrollbar.
  108. */
  109. public enum Direction {
  110. VERTICAL, HORIZONTAL;
  111. }
  112. private class TemporaryResizer {
  113. private static final int TEMPORARY_RESIZE_DELAY = 1000;
  114. private final Timer timer = new Timer() {
  115. @Override
  116. public void run() {
  117. internalSetScrollbarThickness(1);
  118. root.getStyle().setVisibility(Visibility.HIDDEN);
  119. }
  120. };
  121. public void show() {
  122. internalSetScrollbarThickness(OSX_INVISIBLE_SCROLLBAR_FAKE_SIZE_PX);
  123. root.getStyle().setVisibility(Visibility.VISIBLE);
  124. timer.schedule(TEMPORARY_RESIZE_DELAY);
  125. }
  126. }
  127. /**
  128. * A means to listen to when the scrollbar handle in a
  129. * {@link ScrollbarBundle} either appears or is removed.
  130. */
  131. public interface VisibilityHandler extends EventHandler {
  132. /**
  133. * This method is called whenever the scrollbar handle's visibility is
  134. * changed in a {@link ScrollbarBundle}.
  135. *
  136. * @param event
  137. * the {@link VisibilityChangeEvent}
  138. */
  139. void visibilityChanged(VisibilityChangeEvent event);
  140. }
  141. public static class VisibilityChangeEvent
  142. extends GwtEvent<VisibilityHandler> {
  143. public static final Type<VisibilityHandler> TYPE = new Type<ScrollbarBundle.VisibilityHandler>() {
  144. @Override
  145. public String toString() {
  146. return "VisibilityChangeEvent";
  147. }
  148. };
  149. private final boolean isScrollerVisible;
  150. private VisibilityChangeEvent(boolean isScrollerVisible) {
  151. this.isScrollerVisible = isScrollerVisible;
  152. }
  153. /**
  154. * Checks whether the scroll handle is currently visible or not
  155. *
  156. * @return <code>true</code> if the scroll handle is currently visible.
  157. * <code>false</code> if not.
  158. */
  159. public boolean isScrollerVisible() {
  160. return isScrollerVisible;
  161. }
  162. @Override
  163. public Type<VisibilityHandler> getAssociatedType() {
  164. return TYPE;
  165. }
  166. @Override
  167. protected void dispatch(VisibilityHandler handler) {
  168. handler.visibilityChanged(this);
  169. }
  170. }
  171. /**
  172. * The pixel size for OSX's invisible scrollbars.
  173. * <p>
  174. * Touch devices don't show a scrollbar at all, so the scrollbar size is
  175. * irrelevant in their case. There doesn't seem to be any other popular
  176. * platforms that has scrollbars similar to OSX. Thus, this behavior is
  177. * tailored for OSX only, until additional platforms start behaving this
  178. * way.
  179. */
  180. private static final int OSX_INVISIBLE_SCROLLBAR_FAKE_SIZE_PX = 13;
  181. /**
  182. * A representation of a single vertical scrollbar.
  183. *
  184. * @see VerticalScrollbarBundle#getElement()
  185. */
  186. public final static class VerticalScrollbarBundle extends ScrollbarBundle {
  187. @Override
  188. public void setStylePrimaryName(String primaryStyleName) {
  189. super.setStylePrimaryName(primaryStyleName);
  190. root.addClassName(primaryStyleName + "-scroller-vertical");
  191. }
  192. @Override
  193. protected void internalSetScrollPos(int px) {
  194. root.setScrollTop(px);
  195. }
  196. @Override
  197. protected int internalGetScrollPos() {
  198. return root.getScrollTop();
  199. }
  200. @Override
  201. protected void internalSetScrollSize(double px) {
  202. scrollSizeElement.getStyle().setHeight(px, Unit.PX);
  203. }
  204. @Override
  205. protected String internalGetScrollSize() {
  206. return scrollSizeElement.getStyle().getHeight();
  207. }
  208. @Override
  209. protected void internalSetOffsetSize(double px) {
  210. root.getStyle().setHeight(px, Unit.PX);
  211. }
  212. @Override
  213. public String internalGetOffsetSize() {
  214. return root.getStyle().getHeight();
  215. }
  216. @Override
  217. protected void internalSetScrollbarThickness(double px) {
  218. root.getStyle().setPaddingRight(px, Unit.PX);
  219. root.getStyle().setWidth(0, Unit.PX);
  220. scrollSizeElement.getStyle().setWidth(px, Unit.PX);
  221. }
  222. @Override
  223. protected String internalGetScrollbarThickness() {
  224. return scrollSizeElement.getStyle().getWidth();
  225. }
  226. @Override
  227. protected void internalForceScrollbar(boolean enable) {
  228. if (enable) {
  229. root.getStyle().setOverflowY(Overflow.SCROLL);
  230. } else {
  231. root.getStyle().clearOverflowY();
  232. }
  233. }
  234. @Override
  235. public Direction getDirection() {
  236. return Direction.VERTICAL;
  237. }
  238. }
  239. /**
  240. * A representation of a single horizontal scrollbar.
  241. *
  242. * @see HorizontalScrollbarBundle#getElement()
  243. */
  244. public final static class HorizontalScrollbarBundle
  245. extends ScrollbarBundle {
  246. @Override
  247. public void setStylePrimaryName(String primaryStyleName) {
  248. super.setStylePrimaryName(primaryStyleName);
  249. root.addClassName(primaryStyleName + "-scroller-horizontal");
  250. }
  251. @Override
  252. protected void internalSetScrollPos(int px) {
  253. root.setScrollLeft(px);
  254. }
  255. @Override
  256. protected int internalGetScrollPos() {
  257. return root.getScrollLeft();
  258. }
  259. @Override
  260. protected void internalSetScrollSize(double px) {
  261. scrollSizeElement.getStyle().setWidth(px, Unit.PX);
  262. }
  263. @Override
  264. protected String internalGetScrollSize() {
  265. return scrollSizeElement.getStyle().getWidth();
  266. }
  267. @Override
  268. protected void internalSetOffsetSize(double px) {
  269. root.getStyle().setWidth(px, Unit.PX);
  270. }
  271. @Override
  272. public String internalGetOffsetSize() {
  273. return root.getStyle().getWidth();
  274. }
  275. @Override
  276. protected void internalSetScrollbarThickness(double px) {
  277. root.getStyle().setPaddingBottom(px, Unit.PX);
  278. root.getStyle().setHeight(0, Unit.PX);
  279. scrollSizeElement.getStyle().setHeight(px, Unit.PX);
  280. }
  281. @Override
  282. protected String internalGetScrollbarThickness() {
  283. return scrollSizeElement.getStyle().getHeight();
  284. }
  285. @Override
  286. protected void internalForceScrollbar(boolean enable) {
  287. if (enable) {
  288. root.getStyle().setOverflowX(Overflow.SCROLL);
  289. } else {
  290. root.getStyle().clearOverflowX();
  291. }
  292. }
  293. @Override
  294. public Direction getDirection() {
  295. return Direction.HORIZONTAL;
  296. }
  297. }
  298. protected final Element root = DOM.createDiv();
  299. protected final Element scrollSizeElement = DOM.createDiv();
  300. protected boolean isInvisibleScrollbar = false;
  301. private double scrollPos = 0;
  302. private double maxScrollPos = 0;
  303. private boolean scrollHandleIsVisible = false;
  304. private boolean isLocked = false;
  305. /** @deprecated access via {@link #getHandlerManager()} instead. */
  306. @Deprecated
  307. private HandlerManager handlerManager;
  308. private TemporaryResizer invisibleScrollbarTemporaryResizer = new TemporaryResizer();
  309. private final ScrollEventFirer scrollEventFirer = new ScrollEventFirer();
  310. private HandlerRegistration scrollSizeTemporaryScrollHandler;
  311. private HandlerRegistration offsetSizeTemporaryScrollHandler;
  312. private ScrollbarBundle() {
  313. root.appendChild(scrollSizeElement);
  314. root.getStyle().setDisplay(Display.NONE);
  315. root.setTabIndex(-1);
  316. }
  317. protected abstract String internalGetScrollSize();
  318. /**
  319. * Sets the primary style name
  320. *
  321. * @param primaryStyleName
  322. * The primary style name to use
  323. */
  324. public void setStylePrimaryName(String primaryStyleName) {
  325. root.setClassName(primaryStyleName + "-scroller");
  326. }
  327. /**
  328. * Gets the root element of this scrollbar-composition.
  329. *
  330. * @return the root element
  331. */
  332. public final Element getElement() {
  333. return root;
  334. }
  335. /**
  336. * Modifies the scroll position of this scrollbar by a number of pixels.
  337. * <p>
  338. * <em>Note:</em> Even though {@code double} values are used, they are
  339. * currently only used as integers as large {@code int} (or small but fast
  340. * {@code long}). This means, all values are truncated to zero decimal
  341. * places.
  342. *
  343. * @param delta
  344. * the delta in pixels to change the scroll position by
  345. */
  346. public final void setScrollPosByDelta(double delta) {
  347. if (delta != 0) {
  348. setScrollPos(getScrollPos() + delta);
  349. }
  350. }
  351. /**
  352. * Modifies {@link #root root's} dimensions in the axis the scrollbar is
  353. * representing.
  354. *
  355. * @param px
  356. * the new size of {@link #root} in the dimension this scrollbar
  357. * is representing
  358. */
  359. protected abstract void internalSetOffsetSize(double px);
  360. /**
  361. * Sets the length of the scrollbar.
  362. *
  363. * @param px
  364. * the length of the scrollbar in pixels
  365. */
  366. public final void setOffsetSize(final double px) {
  367. /*
  368. * This needs to be made step-by-step because IE8 flat-out refuses to
  369. * fire a scroll event when the scroll size becomes smaller than the
  370. * offset size. All other browser need to suffer alongside.
  371. */
  372. boolean newOffsetSizeIsGreaterThanScrollSize = px > getScrollSize();
  373. boolean offsetSizeBecomesGreaterThanScrollSize = showsScrollHandle()
  374. && newOffsetSizeIsGreaterThanScrollSize;
  375. if (offsetSizeBecomesGreaterThanScrollSize && getScrollPos() != 0) {
  376. // must be a field because Java insists.
  377. offsetSizeTemporaryScrollHandler = addScrollHandler(
  378. new ScrollHandler() {
  379. @Override
  380. public void onScroll(ScrollEvent event) {
  381. setOffsetSizeNow(px);
  382. }
  383. });
  384. setScrollPos(0);
  385. } else {
  386. setOffsetSizeNow(px);
  387. }
  388. }
  389. private void setOffsetSizeNow(double px) {
  390. internalSetOffsetSize(Math.max(0, px));
  391. recalculateMaxScrollPos();
  392. forceScrollbar(showsScrollHandle());
  393. fireVisibilityChangeIfNeeded();
  394. if (offsetSizeTemporaryScrollHandler != null) {
  395. offsetSizeTemporaryScrollHandler.removeHandler();
  396. offsetSizeTemporaryScrollHandler = null;
  397. }
  398. }
  399. /**
  400. * Force the scrollbar to be visible with CSS. In practice, this means to
  401. * set either <code>overflow-x</code> or <code>overflow-y</code> to "
  402. * <code>scroll</code>" in the scrollbar's direction.
  403. * <p>
  404. * This method is an IE8 workaround, since it doesn't always show scrollbars
  405. * with <code>overflow: auto</code> enabled.
  406. * <p>
  407. * Firefox on the other hand loses pending scroll events when the scrollbar
  408. * is hidden, so the event must be fired manually.
  409. * <p>
  410. * When IE8 support is dropped, this should really be simplified.
  411. */
  412. protected void forceScrollbar(boolean enable) {
  413. if (enable) {
  414. root.getStyle().clearDisplay();
  415. } else {
  416. if (BrowserInfo.get().isFirefox()) {
  417. /*
  418. * This is related to the Firefox workaround in setScrollSize
  419. * for setScrollPos(0)
  420. */
  421. scrollEventFirer.scheduleEvent();
  422. }
  423. root.getStyle().setDisplay(Display.NONE);
  424. }
  425. internalForceScrollbar(enable);
  426. }
  427. protected abstract void internalForceScrollbar(boolean enable);
  428. /**
  429. * Gets the length of the scrollbar
  430. *
  431. * @return the length of the scrollbar in pixels
  432. */
  433. public double getOffsetSize() {
  434. return parseCssDimensionToPixels(internalGetOffsetSize());
  435. }
  436. public abstract String internalGetOffsetSize();
  437. /**
  438. * Sets the scroll position of the scrollbar in the axis the scrollbar is
  439. * representing.
  440. * <p>
  441. * <em>Note:</em> Even though {@code double} values are used, they are
  442. * currently only used as integers as large {@code int} (or small but fast
  443. * {@code long}). This means, all values are truncated to zero decimal
  444. * places.
  445. *
  446. * @param px
  447. * the new scroll position in pixels
  448. */
  449. public final void setScrollPos(double px) {
  450. if (isLocked()) {
  451. return;
  452. }
  453. double oldScrollPos = scrollPos;
  454. scrollPos = Math.max(0, Math.min(maxScrollPos, truncate(px)));
  455. if (!WidgetUtil.pixelValuesEqual(oldScrollPos, scrollPos)) {
  456. if (isInvisibleScrollbar) {
  457. invisibleScrollbarTemporaryResizer.show();
  458. }
  459. /*
  460. * This is where the value needs to be converted into an integer no
  461. * matter how we flip it, since GWT expects an integer value.
  462. * There's no point making a JSNI method that accepts doubles as the
  463. * scroll position, since the browsers themselves don't support such
  464. * large numbers (as of today, 25.3.2014). This double-ranged is
  465. * only facilitating future virtual scrollbars.
  466. */
  467. internalSetScrollPos(toInt32(scrollPos));
  468. }
  469. }
  470. /**
  471. * Should be called whenever this bundle is attached to the DOM (typically,
  472. * from the onLoad of the containing widget). Used to ensure the DOM scroll
  473. * position is maintained when detaching and reattaching the bundle.
  474. *
  475. * @since 7.4.1
  476. */
  477. public void onLoad() {
  478. internalSetScrollPos(toInt32(scrollPos));
  479. }
  480. /**
  481. * Truncates a double such that no decimal places are retained.
  482. * <p>
  483. * E.g. {@code trunc(2.3d) == 2.0d} and {@code trunc(-2.3d) == -2.0d}.
  484. *
  485. * @param num
  486. * the double value to be truncated
  487. * @return the {@code num} value without any decimal digits
  488. */
  489. private static double truncate(double num) {
  490. if (num > 0) {
  491. return Math.floor(num);
  492. } else {
  493. return Math.ceil(num);
  494. }
  495. }
  496. /**
  497. * Modifies the element's scroll position (scrollTop or scrollLeft).
  498. * <p>
  499. * <em>Note:</em> The parameter here is a type of integer (instead of a
  500. * double) by design. The browsers internally convert all double values into
  501. * an integer value. To make this fact explicit, this API has chosen to
  502. * force integers already at this level.
  503. *
  504. * @param px
  505. * integer pixel value to scroll to
  506. */
  507. protected abstract void internalSetScrollPos(int px);
  508. /**
  509. * Gets the scroll position of the scrollbar in the axis the scrollbar is
  510. * representing.
  511. *
  512. * @return the new scroll position in pixels
  513. */
  514. public final double getScrollPos() {
  515. assert internalGetScrollPos() == toInt32(
  516. scrollPos) : "calculated scroll position (" + scrollPos
  517. + ") did not match the DOM element scroll position ("
  518. + internalGetScrollPos() + ")";
  519. return scrollPos;
  520. }
  521. /**
  522. * Retrieves the element's scroll position (scrollTop or scrollLeft).
  523. * <p>
  524. * <em>Note:</em> The parameter here is a type of integer (instead of a
  525. * double) by design. The browsers internally convert all double values into
  526. * an integer value. To make this fact explicit, this API has chosen to
  527. * force integers already at this level.
  528. *
  529. * @return integer pixel value of the scroll position
  530. */
  531. protected abstract int internalGetScrollPos();
  532. /**
  533. * Modifies {@link #scrollSizeElement scrollSizeElement's} dimensions in
  534. * such a way that the scrollbar is able to scroll a certain number of
  535. * pixels in the axis it is representing.
  536. *
  537. * @param px
  538. * the new size of {@link #scrollSizeElement} in the dimension
  539. * this scrollbar is representing
  540. */
  541. protected abstract void internalSetScrollSize(double px);
  542. /**
  543. * Sets the amount of pixels the scrollbar needs to be able to scroll
  544. * through.
  545. *
  546. * @param px
  547. * the number of pixels the scrollbar should be able to scroll
  548. * through
  549. */
  550. public final void setScrollSize(final double px) {
  551. /*
  552. * This needs to be made step-by-step because IE8 flat-out refuses to
  553. * fire a scroll event when the scroll size becomes smaller than the
  554. * offset size. All other browser need to suffer alongside.
  555. *
  556. * This really should be changed to not use any temporary scroll
  557. * handlers at all once IE8 support is dropped, like now done only for
  558. * Firefox.
  559. */
  560. boolean newScrollSizeIsSmallerThanOffsetSize = px <= getOffsetSize();
  561. boolean scrollSizeBecomesSmallerThanOffsetSize = showsScrollHandle()
  562. && newScrollSizeIsSmallerThanOffsetSize;
  563. if (scrollSizeBecomesSmallerThanOffsetSize && getScrollPos() != 0) {
  564. /*
  565. * For whatever reason, Firefox loses the scroll event in this case
  566. * and the onscroll handler is never called (happens when reducing
  567. * size from 1000 items to 1 while being scrolled a bit down, see
  568. * #19802). Based on the comment above, only IE8 should really use
  569. * 'delayedSizeSet'
  570. */
  571. boolean delayedSizeSet = !BrowserInfo.get().isFirefox();
  572. if (delayedSizeSet) {
  573. scrollSizeTemporaryScrollHandler = addScrollHandler(
  574. new ScrollHandler() {
  575. @Override
  576. public void onScroll(ScrollEvent event) {
  577. setScrollSizeNow(px);
  578. }
  579. });
  580. }
  581. setScrollPos(0);
  582. if (!delayedSizeSet) {
  583. setScrollSizeNow(px);
  584. }
  585. } else {
  586. setScrollSizeNow(px);
  587. }
  588. }
  589. private void setScrollSizeNow(double px) {
  590. internalSetScrollSize(Math.max(0, px));
  591. recalculateMaxScrollPos();
  592. forceScrollbar(showsScrollHandle());
  593. fireVisibilityChangeIfNeeded();
  594. if (scrollSizeTemporaryScrollHandler != null) {
  595. scrollSizeTemporaryScrollHandler.removeHandler();
  596. scrollSizeTemporaryScrollHandler = null;
  597. }
  598. }
  599. /**
  600. * Gets the amount of pixels the scrollbar needs to be able to scroll
  601. * through.
  602. *
  603. * @return the number of pixels the scrollbar should be able to scroll
  604. * through
  605. */
  606. public double getScrollSize() {
  607. return parseCssDimensionToPixels(internalGetScrollSize());
  608. }
  609. /**
  610. * Modifies {@link #scrollSizeElement scrollSizeElement's} dimensions in the
  611. * opposite axis to what the scrollbar is representing.
  612. *
  613. * @param px
  614. * the dimension that {@link #scrollSizeElement} should take in
  615. * the opposite axis to what the scrollbar is representing
  616. */
  617. protected abstract void internalSetScrollbarThickness(double px);
  618. /**
  619. * Sets the scrollbar's thickness.
  620. * <p>
  621. * If the thickness is set to 0, the scrollbar will be treated as an
  622. * "invisible" scrollbar. This means, the DOM structure will be given a
  623. * non-zero size, but {@link #getScrollbarThickness()} will still return the
  624. * value 0.
  625. *
  626. * @param px
  627. * the scrollbar's thickness in pixels
  628. */
  629. public final void setScrollbarThickness(double px) {
  630. isInvisibleScrollbar = (px == 0);
  631. if (isInvisibleScrollbar) {
  632. Event.sinkEvents(root, Event.ONSCROLL);
  633. Event.setEventListener(root, new EventListener() {
  634. @Override
  635. public void onBrowserEvent(Event event) {
  636. invisibleScrollbarTemporaryResizer.show();
  637. }
  638. });
  639. root.getStyle().setVisibility(Visibility.HIDDEN);
  640. } else {
  641. Event.sinkEvents(root, 0);
  642. Event.setEventListener(root, null);
  643. root.getStyle().clearVisibility();
  644. }
  645. internalSetScrollbarThickness(Math.max(1d, px));
  646. }
  647. /**
  648. * Gets the scrollbar's thickness as defined in the DOM.
  649. *
  650. * @return the scrollbar's thickness as defined in the DOM, in pixels
  651. */
  652. protected abstract String internalGetScrollbarThickness();
  653. /**
  654. * Gets the scrollbar's thickness.
  655. * <p>
  656. * This value will differ from the value in the DOM, if the thickness was
  657. * set to 0 with {@link #setScrollbarThickness(double)}, as the scrollbar is
  658. * then treated as "invisible."
  659. *
  660. * @return the scrollbar's thickness in pixels
  661. */
  662. public final double getScrollbarThickness() {
  663. if (!isInvisibleScrollbar) {
  664. return parseCssDimensionToPixels(internalGetScrollbarThickness());
  665. } else {
  666. return 0;
  667. }
  668. }
  669. /**
  670. * Checks whether the scrollbar's handle is visible.
  671. * <p>
  672. * In other words, this method checks whether the contents is larger than
  673. * can visually fit in the element.
  674. *
  675. * @return <code>true</code> iff the scrollbar's handle is visible
  676. */
  677. public boolean showsScrollHandle() {
  678. return getScrollSize() - getOffsetSize() > WidgetUtil.PIXEL_EPSILON;
  679. }
  680. public void recalculateMaxScrollPos() {
  681. double scrollSize = getScrollSize();
  682. double offsetSize = getOffsetSize();
  683. maxScrollPos = Math.max(0, scrollSize - offsetSize);
  684. // make sure that the correct max scroll position is maintained.
  685. setScrollPos(scrollPos);
  686. }
  687. /**
  688. * This is a method that JSNI can call to synchronize the object state from
  689. * the DOM.
  690. */
  691. private final void updateScrollPosFromDom() {
  692. /*
  693. * TODO: this method probably shouldn't be called from Escalator's JSNI,
  694. * but probably could be handled internally by this listening to its own
  695. * element. Would clean up the code quite a bit. Needs further
  696. * investigation.
  697. */
  698. int newScrollPos = internalGetScrollPos();
  699. if (!isLocked()) {
  700. scrollPos = newScrollPos;
  701. scrollEventFirer.scheduleEvent();
  702. } else if (scrollPos != newScrollPos) {
  703. // we need to actually undo the setting of the scroll.
  704. internalSetScrollPos(toInt32(scrollPos));
  705. }
  706. }
  707. protected HandlerManager getHandlerManager() {
  708. if (handlerManager == null) {
  709. handlerManager = new HandlerManager(this);
  710. }
  711. return handlerManager;
  712. }
  713. /**
  714. * Adds handler for the scrollbar handle visibility.
  715. *
  716. * @param handler
  717. * the {@link VisibilityHandler} to add
  718. * @return {@link HandlerRegistration} used to remove the handler
  719. */
  720. public HandlerRegistration addVisibilityHandler(
  721. final VisibilityHandler handler) {
  722. return getHandlerManager().addHandler(VisibilityChangeEvent.TYPE,
  723. handler);
  724. }
  725. private void fireVisibilityChangeIfNeeded() {
  726. final boolean oldHandleIsVisible = scrollHandleIsVisible;
  727. scrollHandleIsVisible = showsScrollHandle();
  728. if (oldHandleIsVisible != scrollHandleIsVisible) {
  729. final VisibilityChangeEvent event = new VisibilityChangeEvent(
  730. scrollHandleIsVisible);
  731. getHandlerManager().fireEvent(event);
  732. }
  733. }
  734. /**
  735. * Converts a double into an integer by JavaScript's terms.
  736. * <p>
  737. * Implementation copied from {@link Element#toInt32(double)}.
  738. *
  739. * @param val
  740. * the double value to convert into an integer
  741. * @return the double value converted to an integer
  742. */
  743. private static native int toInt32(double val)
  744. /*-{
  745. return Math.round(val) | 0;
  746. }-*/;
  747. /**
  748. * Locks or unlocks the scrollbar bundle.
  749. * <p>
  750. * A locked scrollbar bundle will refuse to scroll, both programmatically
  751. * and via user-triggered events.
  752. *
  753. * @param isLocked
  754. * <code>true</code> to lock, <code>false</code> to unlock
  755. */
  756. public void setLocked(boolean isLocked) {
  757. this.isLocked = isLocked;
  758. }
  759. /**
  760. * Checks whether the scrollbar bundle is locked or not.
  761. *
  762. * @return <code>true</code> iff the scrollbar bundle is locked
  763. */
  764. public boolean isLocked() {
  765. return isLocked;
  766. }
  767. /**
  768. * Returns the scroll direction of this scrollbar bundle.
  769. *
  770. * @return the scroll direction of this scrollbar bundle
  771. */
  772. public abstract Direction getDirection();
  773. /**
  774. * Adds a scroll handler to the scrollbar bundle.
  775. *
  776. * @param handler
  777. * the handler to add
  778. * @return the registration object for the handler registration
  779. */
  780. public HandlerRegistration addScrollHandler(final ScrollHandler handler) {
  781. return getHandlerManager().addHandler(ScrollEvent.TYPE, handler);
  782. }
  783. private static double parseCssDimensionToPixels(String size) {
  784. /*
  785. * Sizes of elements are calculated from CSS rather than
  786. * element.getOffset*() because those values are 0 whenever display:
  787. * none. Because we know that all elements have populated
  788. * CSS-dimensions, it's better to do it that way.
  789. *
  790. * Another solution would be to make the elements visible while
  791. * measuring and then re-hide them, but that would cause unnecessary
  792. * reflows that would probably kill the performance dead.
  793. */
  794. if (size.isEmpty()) {
  795. return 0;
  796. } else {
  797. assert size.endsWith("px") : "Can't parse CSS dimension \"" + size
  798. + "\"";
  799. return Double.parseDouble(size.substring(0, size.length() - 2));
  800. }
  801. }
  802. @Override
  803. public boolean isWorkPending() {
  804. // Need to include scrollEventFirer.isBeingFired as it might use
  805. // requestAnimationFrame - which is not automatically checked
  806. return scrollSizeTemporaryScrollHandler != null
  807. || offsetSizeTemporaryScrollHandler != null
  808. || scrollEventFirer.isBeingFired;
  809. }
  810. }