Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ScrollbarBundle.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. /*
  2. * Copyright 2000-2021 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.Timer;
  33. import com.vaadin.client.BrowserInfo;
  34. import com.vaadin.client.DeferredWorker;
  35. import com.vaadin.client.WidgetUtil;
  36. import com.vaadin.client.widget.grid.events.ScrollEvent;
  37. import com.vaadin.client.widget.grid.events.ScrollHandler;
  38. /**
  39. * An element-like bundle representing a configurable and visual scrollbar in
  40. * one axis.
  41. *
  42. * @since 7.4
  43. * @author Vaadin Ltd
  44. * @see VerticalScrollbarBundle
  45. * @see HorizontalScrollbarBundle
  46. */
  47. public abstract class ScrollbarBundle implements DeferredWorker {
  48. private static final boolean SUPPORTS_REQUEST_ANIMATION_FRAME = new AnimationSupportDetector()
  49. .isNativelySupported();
  50. private class ScrollEventFirer {
  51. private final ScheduledCommand fireEventCommand = () -> {
  52. /*
  53. * Some kind of native-scroll-event related asynchronous problem
  54. * occurs here (at least on desktops) where the internal bookkeeping
  55. * isn't up to date with the real scroll position. The weird thing
  56. * is, that happens only once, and if you drag scrollbar fast
  57. * enough. After it has failed once, it never fails again.
  58. *
  59. * Theory: the user drags the scrollbar, and this command is
  60. * executed before the browser has a chance to fire a scroll event
  61. * (which normally would correct this situation). This would explain
  62. * why slow scrolling doesn't trigger the problem, while fast
  63. * scrolling does.
  64. *
  65. * To make absolutely sure that we have the latest scroll position,
  66. * let's update the internal value.
  67. *
  68. * This might lead to a slight performance hit (on my computer it
  69. * was never more than 3ms on either of Chrome 38 or Firefox 31). It
  70. * also _slightly_ counteracts the purpose of the internal
  71. * bookkeeping. But since getScrollPos is called 3 times (on one
  72. * direction) per scroll loop, it's still better to have take this
  73. * small penalty than removing it altogether.
  74. */
  75. updateScrollPosFromDom();
  76. getHandlerManager().fireEvent(new ScrollEvent());
  77. isBeingFired = false;
  78. };
  79. private boolean isBeingFired;
  80. public void scheduleEvent() {
  81. if (!isBeingFired) {
  82. /*
  83. * We'll gather all the scroll events, and only fire once, once
  84. * everything has calmed down.
  85. */
  86. if (SUPPORTS_REQUEST_ANIMATION_FRAME) {
  87. // Chrome MUST use this as deferred commands will sometimes
  88. // be run with a 300+ ms delay when scrolling.
  89. AnimationScheduler.get().requestAnimationFrame(
  90. timestamp -> fireEventCommand.execute());
  91. } else {
  92. // Does not support requestAnimationFrame and the fallback
  93. // uses a delay of 16ms, we stick to the old deferred
  94. // command which uses a delay of 0ms
  95. Scheduler.get().scheduleDeferred(fireEventCommand);
  96. }
  97. isBeingFired = true;
  98. }
  99. }
  100. }
  101. /**
  102. * The orientation of the scrollbar.
  103. */
  104. public enum Direction {
  105. /** Scrollbar orientation, indicated by the name. */
  106. VERTICAL, HORIZONTAL;
  107. }
  108. private class TemporaryResizer {
  109. private static final int TEMPORARY_RESIZE_DELAY = 1000;
  110. private final Timer timer = new Timer() {
  111. @Override
  112. public void run() {
  113. internalSetScrollbarThickness(1);
  114. root.getStyle().setVisibility(Visibility.HIDDEN);
  115. }
  116. };
  117. public void show() {
  118. internalSetScrollbarThickness(OSX_INVISIBLE_SCROLLBAR_FAKE_SIZE_PX);
  119. root.getStyle().setVisibility(Visibility.VISIBLE);
  120. timer.schedule(TEMPORARY_RESIZE_DELAY);
  121. }
  122. }
  123. /**
  124. * A means to listen to when the scrollbar handle in a
  125. * {@link ScrollbarBundle} either appears or is removed.
  126. */
  127. public interface VisibilityHandler extends EventHandler {
  128. /**
  129. * This method is called whenever the scrollbar handle's visibility is
  130. * changed in a {@link ScrollbarBundle}.
  131. *
  132. * @param event
  133. * the {@link VisibilityChangeEvent}
  134. */
  135. void visibilityChanged(VisibilityChangeEvent event);
  136. }
  137. /**
  138. * Event for scrollbar visibility changes.
  139. */
  140. public static class VisibilityChangeEvent
  141. extends GwtEvent<VisibilityHandler> {
  142. /** Event type. */
  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 static final 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 static final 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. /** Root element for the scrollbar-composition. */
  299. protected final Element root = DOM.createDiv();
  300. /**
  301. * Scroll size element. The size of this element determines the number of
  302. * pixels the scrollbar is able to scroll through
  303. */
  304. protected final Element scrollSizeElement = DOM.createDiv();
  305. /** Is the scrollbar "invisible" (thickness set to 0). */
  306. protected boolean isInvisibleScrollbar = false;
  307. private double scrollPos = 0;
  308. private double maxScrollPos = 0;
  309. private boolean scrollHandleIsVisible = false;
  310. private boolean isLocked = false;
  311. /** @deprecated access via {@link #getHandlerManager()} instead. */
  312. @Deprecated
  313. private HandlerManager handlerManager;
  314. private TemporaryResizer invisibleScrollbarTemporaryResizer = new TemporaryResizer();
  315. private final ScrollEventFirer scrollEventFirer = new ScrollEventFirer();
  316. private HandlerRegistration scrollInProgress;
  317. private ScrollbarBundle() {
  318. root.appendChild(scrollSizeElement);
  319. root.getStyle().setDisplay(Display.NONE);
  320. root.setTabIndex(-1);
  321. }
  322. /**
  323. * Returns the width (for horizontal) or height (for vertical) css property
  324. * for the scroll size element.
  325. *
  326. * @return the relevant size property based on orientation
  327. */
  328. protected abstract String internalGetScrollSize();
  329. /**
  330. * Sets the primary style name.
  331. *
  332. * @param primaryStyleName
  333. * The primary style name to use
  334. */
  335. public void setStylePrimaryName(String primaryStyleName) {
  336. root.setClassName(primaryStyleName + "-scroller");
  337. }
  338. /**
  339. * Gets the root element of this scrollbar-composition.
  340. *
  341. * @return the root element
  342. */
  343. public final Element getElement() {
  344. return root;
  345. }
  346. /**
  347. * Modifies the scroll position of this scrollbar by a number of pixels.
  348. * <p>
  349. * <em>Note:</em> Even though {@code double} values are used, they are
  350. * currently only used as integers as large {@code int} (or small but fast
  351. * {@code long}). This means, all values are truncated to zero decimal
  352. * places.
  353. *
  354. * @param delta
  355. * the delta in pixels to change the scroll position by
  356. */
  357. public final void setScrollPosByDelta(double delta) {
  358. if (delta != 0) {
  359. setScrollPos(getScrollPos() + delta);
  360. }
  361. }
  362. /**
  363. * Modifies {@link #root root's} dimensions in the axis the scrollbar is
  364. * representing.
  365. *
  366. * @param px
  367. * the new size of {@link #root} in the dimension this scrollbar
  368. * is representing
  369. */
  370. protected abstract void internalSetOffsetSize(double px);
  371. /**
  372. * Sets the length of the scrollbar.
  373. *
  374. * @param px
  375. * the length of the scrollbar in pixels
  376. * @see #setOffsetSizeAndScrollSize(double, double)
  377. */
  378. public final void setOffsetSize(final double px) {
  379. boolean newOffsetSizeIsGreaterThanScrollSize = px > getScrollSize();
  380. boolean offsetSizeBecomesGreaterThanScrollSize = showsScrollHandle()
  381. && newOffsetSizeIsGreaterThanScrollSize;
  382. if (offsetSizeBecomesGreaterThanScrollSize && getScrollPos() != 0) {
  383. setScrollPos(0);
  384. setOffsetSizeNow(px);
  385. } else if (px != getOffsetSize()) {
  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. }
  395. /**
  396. * Sets the length of the scrollbar and the amount of pixels the scrollbar
  397. * needs to be able to scroll through.
  398. *
  399. * @param offsetPx
  400. * the length of the scrollbar in pixels
  401. * @param scrollPx
  402. * the number of pixels the scrollbar should be able to scroll
  403. * through
  404. */
  405. public final void setOffsetSizeAndScrollSize(final double offsetPx,
  406. final double scrollPx) {
  407. boolean newOffsetSizeIsGreaterThanScrollSize = offsetPx > scrollPx;
  408. boolean offsetSizeBecomesGreaterThanScrollSize = showsScrollHandle()
  409. && newOffsetSizeIsGreaterThanScrollSize;
  410. boolean needsMoreHandling = false;
  411. if (offsetSizeBecomesGreaterThanScrollSize && getScrollPos() != 0) {
  412. setScrollPos(0);
  413. if (offsetPx != getOffsetSize()) {
  414. internalSetOffsetSize(Math.max(0, offsetPx));
  415. }
  416. if (scrollPx != getScrollSize()) {
  417. internalSetScrollSize(Math.max(0, scrollPx));
  418. }
  419. needsMoreHandling = true;
  420. } else {
  421. if (offsetPx != getOffsetSize()) {
  422. internalSetOffsetSize(Math.max(0, offsetPx));
  423. needsMoreHandling = true;
  424. }
  425. if (scrollPx != getScrollSize()) {
  426. internalSetScrollSize(Math.max(0, scrollPx));
  427. needsMoreHandling = true;
  428. }
  429. }
  430. if (needsMoreHandling) {
  431. recalculateMaxScrollPos();
  432. forceScrollbar(showsScrollHandle());
  433. fireVisibilityChangeIfNeeded();
  434. }
  435. }
  436. /**
  437. * Force the scrollbar to be visible with CSS. In practice, this means to
  438. * set either <code>overflow-x</code> or <code>overflow-y</code> to "
  439. * <code>scroll</code>" in the scrollbar's direction.
  440. * <p>
  441. * This method is an IE8 workaround, since it doesn't always show scrollbars
  442. * with <code>overflow: auto</code> enabled.
  443. * <p>
  444. * Firefox on the other hand loses pending scroll events when the scrollbar
  445. * is hidden, so the event must be fired manually.
  446. * <p>
  447. * When IE8 support is dropped, this should really be simplified.
  448. *
  449. * @param enable
  450. * {@code true} if the scrollbar should be forced to be visible,
  451. * {@code false} otherwise.
  452. */
  453. protected void forceScrollbar(boolean enable) {
  454. if (enable) {
  455. root.getStyle().clearDisplay();
  456. } else {
  457. if (BrowserInfo.get().isFirefox()) {
  458. /*
  459. * This is related to the Firefox workaround in setScrollSize
  460. * for setScrollPos(0)
  461. */
  462. scrollEventFirer.scheduleEvent();
  463. }
  464. root.getStyle().setDisplay(Display.NONE);
  465. }
  466. internalForceScrollbar(enable);
  467. }
  468. /**
  469. * Sets the overflow-x (for horizontal) or overflow-y (for vertical)
  470. * property to {@code "scroll"} if enabled, or clears the property if
  471. * disabled.
  472. *
  473. * @param enable
  474. * {@code true} if the overflow property should be set,
  475. * {@code false} otherwise.
  476. */
  477. protected abstract void internalForceScrollbar(boolean enable);
  478. /**
  479. * Gets the length of the scrollbar.
  480. *
  481. * @return the length of the scrollbar in pixels
  482. */
  483. public double getOffsetSize() {
  484. return parseCssDimensionToPixels(internalGetOffsetSize());
  485. }
  486. /**
  487. * Returns the width (for horizontal) or height (for vertical) css property
  488. * for the root element.
  489. *
  490. * @return the relevant size property based on orientation
  491. */
  492. public abstract String internalGetOffsetSize();
  493. /**
  494. * Sets the scroll position of the scrollbar in the axis the scrollbar is
  495. * representing.
  496. * <p>
  497. * <em>Note:</em> Even though {@code double} values are used, they are
  498. * currently only used as integers as large {@code int} (or small but fast
  499. * {@code long}). This means, all values are truncated to zero decimal
  500. * places.
  501. *
  502. * @param px
  503. * the new scroll position in pixels
  504. */
  505. public final void setScrollPos(double px) {
  506. if (isLocked()) {
  507. return;
  508. }
  509. double oldScrollPos = scrollPos;
  510. scrollPos = Math.max(0, Math.min(maxScrollPos, truncate(px)));
  511. if (!WidgetUtil.pixelValuesEqual(oldScrollPos, scrollPos)) {
  512. if (scrollInProgress == null) {
  513. // Only used for tracking that there is "workPending"
  514. scrollInProgress = addScrollHandler(event -> {
  515. scrollInProgress.removeHandler();
  516. scrollInProgress = null;
  517. });
  518. }
  519. if (isInvisibleScrollbar) {
  520. invisibleScrollbarTemporaryResizer.show();
  521. }
  522. /*
  523. * This is where the value needs to be converted into an integer no
  524. * matter how we flip it, since GWT expects an integer value.
  525. * There's no point making a JSNI method that accepts doubles as the
  526. * scroll position, since the browsers themselves don't support such
  527. * large numbers (as of today, 25.3.2014). This double-ranged is
  528. * only facilitating future virtual scrollbars.
  529. */
  530. internalSetScrollPos(toInt32(scrollPos));
  531. }
  532. }
  533. /**
  534. * Should be called whenever this bundle is attached to the DOM (typically,
  535. * from the onLoad of the containing widget). Used to ensure the DOM scroll
  536. * position is maintained when detaching and reattaching the bundle.
  537. *
  538. * @since 7.4.1
  539. */
  540. public void onLoad() {
  541. internalSetScrollPos(toInt32(scrollPos));
  542. }
  543. /**
  544. * Truncates a double such that no decimal places are retained.
  545. * <p>
  546. * E.g. {@code trunc(2.3d) == 2.0d} and {@code trunc(-2.3d) == -2.0d}.
  547. *
  548. * @param num
  549. * the double value to be truncated
  550. * @return the {@code num} value without any decimal digits
  551. */
  552. private static double truncate(double num) {
  553. if (num > 0) {
  554. return Math.floor(num);
  555. } else {
  556. return Math.ceil(num);
  557. }
  558. }
  559. /**
  560. * Modifies the element's scroll position (scrollTop or scrollLeft).
  561. * <p>
  562. * <em>Note:</em> The parameter here is a type of integer (instead of a
  563. * double) by design. The browsers internally convert all double values into
  564. * an integer value. To make this fact explicit, this API has chosen to
  565. * force integers already at this level.
  566. *
  567. * @param px
  568. * integer pixel value to scroll to
  569. */
  570. protected abstract void internalSetScrollPos(int px);
  571. /**
  572. * Gets the scroll position of the scrollbar in the axis the scrollbar is
  573. * representing.
  574. *
  575. * @return the new scroll position in pixels
  576. */
  577. public final double getScrollPos() {
  578. int internalScrollPos = internalGetScrollPos();
  579. assert Math.abs(internalScrollPos
  580. - toInt32(scrollPos)) <= 1 : "calculated scroll position ("
  581. + scrollPos
  582. + ") did not match the DOM element scroll position ("
  583. + internalScrollPos + ")";
  584. return scrollPos;
  585. }
  586. /**
  587. * Retrieves the element's scroll position (scrollTop or scrollLeft).
  588. * <p>
  589. * <em>Note:</em> The parameter here is a type of integer (instead of a
  590. * double) by design. The browsers internally convert all double values into
  591. * an integer value. To make this fact explicit, this API has chosen to
  592. * force integers already at this level.
  593. *
  594. * @return integer pixel value of the scroll position
  595. */
  596. protected abstract int internalGetScrollPos();
  597. /**
  598. * Modifies {@link #scrollSizeElement scrollSizeElement's} dimensions in
  599. * such a way that the scrollbar is able to scroll a certain number of
  600. * pixels in the axis it is representing.
  601. *
  602. * @param px
  603. * the new size of {@link #scrollSizeElement} in the dimension
  604. * this scrollbar is representing
  605. */
  606. protected abstract void internalSetScrollSize(double px);
  607. /**
  608. * Sets the amount of pixels the scrollbar needs to be able to scroll
  609. * through.
  610. *
  611. * @param px
  612. * the number of pixels the scrollbar should be able to scroll
  613. * through
  614. * @see #setOffsetSizeAndScrollSize(double, double)
  615. */
  616. public final void setScrollSize(final double px) {
  617. boolean newScrollSizeIsSmallerThanOffsetSize = px <= getOffsetSize();
  618. boolean scrollSizeBecomesSmallerThanOffsetSize = showsScrollHandle()
  619. && newScrollSizeIsSmallerThanOffsetSize;
  620. if (scrollSizeBecomesSmallerThanOffsetSize && getScrollPos() != 0) {
  621. setScrollPos(0);
  622. setScrollSizeNow(px);
  623. } else if (px != getScrollSize()) {
  624. setScrollSizeNow(px);
  625. }
  626. }
  627. private void setScrollSizeNow(double px) {
  628. internalSetScrollSize(Math.max(0, px));
  629. recalculateMaxScrollPos();
  630. forceScrollbar(showsScrollHandle());
  631. fireVisibilityChangeIfNeeded();
  632. }
  633. /**
  634. * Gets the amount of pixels the scrollbar needs to be able to scroll
  635. * through.
  636. *
  637. * @return the number of pixels the scrollbar should be able to scroll
  638. * through
  639. */
  640. public double getScrollSize() {
  641. return parseCssDimensionToPixels(internalGetScrollSize());
  642. }
  643. /**
  644. * Modifies {@link #scrollSizeElement scrollSizeElement's} dimensions in the
  645. * opposite axis to what the scrollbar is representing.
  646. *
  647. * @param px
  648. * the dimension that {@link #scrollSizeElement} should take in
  649. * the opposite axis to what the scrollbar is representing
  650. */
  651. protected abstract void internalSetScrollbarThickness(double px);
  652. /**
  653. * Sets the scrollbar's thickness.
  654. * <p>
  655. * If the thickness is set to 0, the scrollbar will be treated as an
  656. * "invisible" scrollbar. This means, the DOM structure will be given a
  657. * non-zero size, but {@link #getScrollbarThickness()} will still return the
  658. * value 0.
  659. *
  660. * @param px
  661. * the scrollbar's thickness in pixels
  662. */
  663. public final void setScrollbarThickness(double px) {
  664. isInvisibleScrollbar = (px == 0);
  665. if (isInvisibleScrollbar) {
  666. Event.sinkEvents(root, Event.ONSCROLL);
  667. Event.setEventListener(root,
  668. event -> invisibleScrollbarTemporaryResizer.show());
  669. root.getStyle().setVisibility(Visibility.HIDDEN);
  670. } else {
  671. Event.sinkEvents(root, 0);
  672. Event.setEventListener(root, null);
  673. root.getStyle().clearVisibility();
  674. }
  675. internalSetScrollbarThickness(Math.max(1d, px));
  676. }
  677. /**
  678. * Gets the scrollbar's thickness as defined in the DOM.
  679. *
  680. * @return the scrollbar's thickness as defined in the DOM, in pixels
  681. */
  682. protected abstract String internalGetScrollbarThickness();
  683. /**
  684. * Gets the scrollbar's thickness.
  685. * <p>
  686. * This value will differ from the value in the DOM, if the thickness was
  687. * set to 0 with {@link #setScrollbarThickness(double)}, as the scrollbar is
  688. * then treated as "invisible."
  689. *
  690. * @return the scrollbar's thickness in pixels
  691. */
  692. public final double getScrollbarThickness() {
  693. if (!isInvisibleScrollbar) {
  694. return parseCssDimensionToPixels(internalGetScrollbarThickness());
  695. } else {
  696. return 0;
  697. }
  698. }
  699. /**
  700. * Checks whether the scrollbar's handle is visible.
  701. * <p>
  702. * In other words, this method checks whether the contents is larger than
  703. * can visually fit in the element.
  704. *
  705. * @return <code>true</code> if the scrollbar's handle is visible
  706. */
  707. public boolean showsScrollHandle() {
  708. return getScrollSize() - getOffsetSize() > WidgetUtil.PIXEL_EPSILON;
  709. }
  710. /**
  711. * Calculates and sets maximum scroll position based on the current scroll
  712. * size and the scrollbar's length.
  713. */
  714. public void recalculateMaxScrollPos() {
  715. double scrollSize = getScrollSize();
  716. double offsetSize = getOffsetSize();
  717. maxScrollPos = Math.max(0, scrollSize - offsetSize);
  718. // make sure that the correct max scroll position is maintained.
  719. setScrollPos(scrollPos);
  720. }
  721. /**
  722. * This is a method that JSNI can call to synchronize the object state from
  723. * the DOM.
  724. */
  725. private final void updateScrollPosFromDom() {
  726. /*
  727. * TODO: this method probably shouldn't be called from Escalator's JSNI,
  728. * but probably could be handled internally by this listening to its own
  729. * element. Would clean up the code quite a bit. Needs further
  730. * investigation.
  731. */
  732. int newScrollPos = internalGetScrollPos();
  733. if (!isLocked()) {
  734. scrollPos = newScrollPos;
  735. scrollEventFirer.scheduleEvent();
  736. } else {
  737. if (scrollPos != newScrollPos) {
  738. // we need to actually undo the setting of the scroll.
  739. internalSetScrollPos(toInt32(scrollPos));
  740. }
  741. if (scrollInProgress != null) {
  742. // cancel the in-progress indicator
  743. scrollInProgress.removeHandler();
  744. scrollInProgress = null;
  745. }
  746. }
  747. }
  748. /**
  749. * Returns the handler manager for this scrollbar bundle.
  750. *
  751. * @return the handler manager
  752. */
  753. protected HandlerManager getHandlerManager() {
  754. if (handlerManager == null) {
  755. handlerManager = new HandlerManager(this);
  756. }
  757. return handlerManager;
  758. }
  759. /**
  760. * Adds handler for the scrollbar handle visibility.
  761. *
  762. * @param handler
  763. * the {@link VisibilityHandler} to add
  764. * @return {@link HandlerRegistration} used to remove the handler
  765. */
  766. public HandlerRegistration addVisibilityHandler(
  767. final VisibilityHandler handler) {
  768. return getHandlerManager().addHandler(VisibilityChangeEvent.TYPE,
  769. handler);
  770. }
  771. private void fireVisibilityChangeIfNeeded() {
  772. final boolean oldHandleIsVisible = scrollHandleIsVisible;
  773. scrollHandleIsVisible = showsScrollHandle();
  774. if (oldHandleIsVisible != scrollHandleIsVisible) {
  775. final VisibilityChangeEvent event = new VisibilityChangeEvent(
  776. scrollHandleIsVisible);
  777. getHandlerManager().fireEvent(event);
  778. }
  779. }
  780. /**
  781. * Converts a double into an integer by JavaScript's terms.
  782. * <p>
  783. * Implementation copied from {@link Element#toInt32(double)}.
  784. *
  785. * @param val
  786. * the double value to convert into an integer
  787. * @return the double value converted to an integer
  788. */
  789. private static native int toInt32(double val)
  790. /*-{
  791. return Math.round(val) | 0;
  792. }-*/;
  793. /**
  794. * Locks or unlocks the scrollbar bundle.
  795. * <p>
  796. * A locked scrollbar bundle will refuse to scroll, both programmatically
  797. * and via user-triggered events.
  798. *
  799. * @param isLocked
  800. * <code>true</code> to lock, <code>false</code> to unlock
  801. */
  802. public void setLocked(boolean isLocked) {
  803. this.isLocked = isLocked;
  804. }
  805. /**
  806. * Checks whether the scrollbar bundle is locked or not.
  807. *
  808. * @return <code>true</code> if the scrollbar bundle is locked
  809. */
  810. public boolean isLocked() {
  811. return isLocked;
  812. }
  813. /**
  814. * Returns the scroll direction of this scrollbar bundle.
  815. *
  816. * @return the scroll direction of this scrollbar bundle
  817. */
  818. public abstract Direction getDirection();
  819. /**
  820. * Adds a scroll handler to the scrollbar bundle.
  821. *
  822. * @param handler
  823. * the handler to add
  824. * @return the registration object for the handler registration
  825. */
  826. public HandlerRegistration addScrollHandler(final ScrollHandler handler) {
  827. return getHandlerManager().addHandler(ScrollEvent.TYPE, handler);
  828. }
  829. private static double parseCssDimensionToPixels(String size) {
  830. /*
  831. * Sizes of elements are calculated from CSS rather than
  832. * element.getOffset*() because those values are 0 whenever display:
  833. * none. Because we know that all elements have populated
  834. * CSS-dimensions, it's better to do it that way.
  835. *
  836. * Another solution would be to make the elements visible while
  837. * measuring and then re-hide them, but that would cause unnecessary
  838. * reflows that would probably kill the performance dead.
  839. */
  840. if (size.isEmpty()) {
  841. return 0;
  842. } else {
  843. assert size.endsWith("px") : "Can't parse CSS dimension \"" + size
  844. + "\"";
  845. return Double.parseDouble(size.substring(0, size.length() - 2));
  846. }
  847. }
  848. @Override
  849. public boolean isWorkPending() {
  850. // Need to include scrollEventFirer.isBeingFired as it might use
  851. // requestAnimationFrame - which is not automatically checked
  852. return scrollInProgress != null || scrollEventFirer.isBeingFired;
  853. }
  854. }