Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

VSlider.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. * Copyright 2000-2018 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.ui;
  17. import com.google.gwt.core.client.Scheduler;
  18. import com.google.gwt.dom.client.Element;
  19. import com.google.gwt.dom.client.Style.Display;
  20. import com.google.gwt.dom.client.Style.Overflow;
  21. import com.google.gwt.dom.client.Style.Unit;
  22. import com.google.gwt.event.dom.client.KeyCodes;
  23. import com.google.gwt.event.logical.shared.ValueChangeEvent;
  24. import com.google.gwt.event.logical.shared.ValueChangeHandler;
  25. import com.google.gwt.event.shared.HandlerRegistration;
  26. import com.google.gwt.user.client.Command;
  27. import com.google.gwt.user.client.DOM;
  28. import com.google.gwt.user.client.Event;
  29. import com.google.gwt.user.client.Window;
  30. import com.google.gwt.user.client.ui.HTML;
  31. import com.google.gwt.user.client.ui.HasValue;
  32. import com.vaadin.client.ApplicationConnection;
  33. import com.vaadin.client.BrowserInfo;
  34. import com.vaadin.client.WidgetUtil;
  35. import com.vaadin.shared.ui.slider.SliderOrientation;
  36. public class VSlider extends SimpleFocusablePanel
  37. implements Field, HasValue<Double>, SubPartAware {
  38. public static final String CLASSNAME = "v-slider";
  39. /**
  40. * Minimum size (width or height, depending on orientation) of the slider
  41. * base.
  42. */
  43. private static final int MIN_SIZE = 50;
  44. protected ApplicationConnection client;
  45. protected String id;
  46. protected boolean disabled;
  47. protected boolean readonly;
  48. private int acceleration = 1;
  49. protected double min;
  50. protected double max;
  51. protected int resolution;
  52. protected Double value;
  53. protected SliderOrientation orientation = SliderOrientation.HORIZONTAL;
  54. private final HTML feedback = new HTML("", false);
  55. private final VOverlay feedbackPopup = new VOverlay(true, false) {
  56. {
  57. setOwner(VSlider.this);
  58. }
  59. @Override
  60. public void show() {
  61. super.show();
  62. updateFeedbackPosition();
  63. }
  64. };
  65. /* DOM element for slider's base */
  66. private final Element base;
  67. private static final int BASE_BORDER_WIDTH = 1;
  68. /* DOM element for slider's handle */
  69. private final Element handle;
  70. /* DOM element for decrement arrow */
  71. private final Element smaller;
  72. /* DOM element for increment arrow */
  73. private final Element bigger;
  74. /* Temporary dragging/animation variables */
  75. private boolean dragging = false;
  76. private VLazyExecutor delayedValueUpdater = new VLazyExecutor(100, () -> {
  77. fireValueChanged();
  78. acceleration = 1;
  79. });
  80. public VSlider() {
  81. super();
  82. base = DOM.createDiv();
  83. handle = DOM.createDiv();
  84. smaller = DOM.createDiv();
  85. bigger = DOM.createDiv();
  86. setStyleName(CLASSNAME);
  87. getElement().appendChild(bigger);
  88. getElement().appendChild(smaller);
  89. getElement().appendChild(base);
  90. base.appendChild(handle);
  91. // Hide initially
  92. smaller.getStyle().setDisplay(Display.NONE);
  93. bigger.getStyle().setDisplay(Display.NONE);
  94. sinkEvents(Event.MOUSEEVENTS | Event.ONMOUSEWHEEL | Event.KEYEVENTS
  95. | Event.FOCUSEVENTS | Event.TOUCHEVENTS);
  96. feedbackPopup.setWidget(feedback);
  97. }
  98. @Override
  99. public void setStyleName(String style) {
  100. updateStyleNames(style, false);
  101. }
  102. @Override
  103. public void setStylePrimaryName(String style) {
  104. updateStyleNames(style, true);
  105. }
  106. protected void updateStyleNames(String styleName,
  107. boolean isPrimaryStyleName) {
  108. feedbackPopup.removeStyleName(getStylePrimaryName() + "-feedback");
  109. removeStyleName(getStylePrimaryName() + "-vertical");
  110. if (isPrimaryStyleName) {
  111. super.setStylePrimaryName(styleName);
  112. } else {
  113. super.setStyleName(styleName);
  114. }
  115. feedbackPopup.addStyleName(getStylePrimaryName() + "-feedback");
  116. base.setClassName(getStylePrimaryName() + "-base");
  117. handle.setClassName(getStylePrimaryName() + "-handle");
  118. smaller.setClassName(getStylePrimaryName() + "-smaller");
  119. bigger.setClassName(getStylePrimaryName() + "-bigger");
  120. if (isVertical()) {
  121. addStyleName(getStylePrimaryName() + "-vertical");
  122. }
  123. }
  124. public void setFeedbackValue(double value) {
  125. feedback.setText(String.valueOf(value));
  126. }
  127. private void updateFeedbackPosition() {
  128. if (isVertical()) {
  129. feedbackPopup.setPopupPosition(
  130. handle.getAbsoluteLeft() + handle.getOffsetWidth(),
  131. handle.getAbsoluteTop() + handle.getOffsetHeight() / 2
  132. - feedbackPopup.getOffsetHeight() / 2);
  133. } else {
  134. feedbackPopup.setPopupPosition(
  135. handle.getAbsoluteLeft() + handle.getOffsetWidth() / 2
  136. - feedbackPopup.getOffsetWidth() / 2,
  137. handle.getAbsoluteTop() - feedbackPopup.getOffsetHeight());
  138. }
  139. }
  140. /** For internal use only. May be removed or replaced in the future. */
  141. public void buildBase() {
  142. final String styleAttribute = isVertical() ? "height" : "width";
  143. final String oppositeStyleAttribute = isVertical() ? "width" : "height";
  144. final String domProperty = isVertical() ? "offsetHeight"
  145. : "offsetWidth";
  146. // clear unnecessary opposite style attribute
  147. base.getStyle().clearProperty(oppositeStyleAttribute);
  148. /*
  149. * To resolve defect #13681 we should not return from method buildBase()
  150. * if slider has no parentElement, because such operations as
  151. * buildHandle() and setValues(), which are needed for Slider, are
  152. * called at the end of method buildBase(). And these methods will not
  153. * be called if there is no parentElement. So, instead of returning from
  154. * method buildBase() if there is no parentElement "if condition" is
  155. * applied to call code for parentElement only in case it exists.
  156. */
  157. if (getElement().hasParentElement()) {
  158. final Element p = getElement();
  159. if (p.getPropertyInt(domProperty) > MIN_SIZE) {
  160. if (isVertical()) {
  161. setHeight();
  162. } else {
  163. base.getStyle().clearProperty(styleAttribute);
  164. }
  165. } else {
  166. // Set minimum size and adjust after all components have
  167. // (supposedly) been drawn completely.
  168. base.getStyle().setPropertyPx(styleAttribute, MIN_SIZE);
  169. Scheduler.get().scheduleDeferred(new Command() {
  170. @Override
  171. public void execute() {
  172. final Element p = getElement();
  173. if (p.getPropertyInt(domProperty) > MIN_SIZE + 5
  174. || propertyNotNullOrEmpty(styleAttribute, p)) {
  175. if (isVertical()) {
  176. setHeight();
  177. } else {
  178. base.getStyle().clearProperty(styleAttribute);
  179. }
  180. // Ensure correct position
  181. setValue(value, false);
  182. }
  183. }
  184. // Style has non empty property
  185. private boolean propertyNotNullOrEmpty(
  186. final String styleAttribute, final Element p) {
  187. return p.getStyle().getProperty(styleAttribute) != null
  188. && !p.getStyle().getProperty(styleAttribute)
  189. .isEmpty();
  190. }
  191. });
  192. }
  193. }
  194. if (!isVertical()) {
  195. // Draw handle with a delay to allow base to gain maximum width
  196. Scheduler.get().scheduleDeferred(() -> {
  197. buildHandle();
  198. setValue(value, false);
  199. });
  200. } else {
  201. buildHandle();
  202. setValue(value, false);
  203. }
  204. // TODO attach listeners for focusing and arrow keys
  205. }
  206. void buildHandle() {
  207. final String handleAttribute = isVertical() ? "marginTop"
  208. : "marginLeft";
  209. final String oppositeHandleAttribute = isVertical() ? "marginLeft"
  210. : "marginTop";
  211. handle.getStyle().setProperty(handleAttribute, "0");
  212. // clear unnecessary opposite handle attribute
  213. handle.getStyle().clearProperty(oppositeHandleAttribute);
  214. }
  215. @Override
  216. public void onBrowserEvent(Event event) {
  217. if (disabled || readonly) {
  218. return;
  219. }
  220. final Element targ = DOM.eventGetTarget(event);
  221. if (DOM.eventGetType(event) == Event.ONMOUSEWHEEL) {
  222. processMouseWheelEvent(event);
  223. } else if (dragging || targ == handle) {
  224. processHandleEvent(event);
  225. } else if (targ == smaller) {
  226. decreaseValue(true);
  227. } else if (targ == bigger) {
  228. increaseValue(true);
  229. } else if (DOM.eventGetType(event) == Event.MOUSEEVENTS) {
  230. processBaseEvent(event);
  231. } else if (isNavigationEvent(event)) {
  232. if (handleNavigation(event.getKeyCode(), event.getCtrlKey(),
  233. event.getShiftKey())) {
  234. feedbackPopup.show();
  235. delayedValueUpdater.trigger();
  236. DOM.eventPreventDefault(event);
  237. DOM.eventCancelBubble(event, true);
  238. }
  239. } else if (targ.equals(getElement())
  240. && DOM.eventGetType(event) == Event.ONFOCUS) {
  241. feedbackPopup.show();
  242. } else if (targ.equals(getElement())
  243. && DOM.eventGetType(event) == Event.ONBLUR) {
  244. feedbackPopup.hide();
  245. } else if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
  246. feedbackPopup.show();
  247. }
  248. if (WidgetUtil.isTouchEvent(event)) {
  249. event.preventDefault(); // avoid simulated events
  250. event.stopPropagation();
  251. }
  252. }
  253. private boolean isNavigationEvent(Event event) {
  254. if (BrowserInfo.get().isGecko() && BrowserInfo.get().getGeckoVersion() < 65) {
  255. return DOM.eventGetType(event) == Event.ONKEYPRESS;
  256. } else {
  257. return DOM.eventGetType(event) == Event.ONKEYDOWN;
  258. }
  259. }
  260. private void processMouseWheelEvent(final Event event) {
  261. final int dir = DOM.eventGetMouseWheelVelocityY(event);
  262. if (dir < 0) {
  263. increaseValue(false);
  264. } else {
  265. decreaseValue(false);
  266. }
  267. delayedValueUpdater.trigger();
  268. DOM.eventPreventDefault(event);
  269. DOM.eventCancelBubble(event, true);
  270. }
  271. private void processHandleEvent(Event event) {
  272. switch (DOM.eventGetType(event)) {
  273. case Event.ONMOUSEDOWN:
  274. case Event.ONTOUCHSTART:
  275. if (!disabled && !readonly) {
  276. focus();
  277. feedbackPopup.show();
  278. dragging = true;
  279. handle.setClassName(getStylePrimaryName() + "-handle");
  280. handle.addClassName(getStylePrimaryName() + "-handle-active");
  281. DOM.setCapture(getElement());
  282. DOM.eventPreventDefault(event); // prevent selecting text
  283. DOM.eventCancelBubble(event, true);
  284. event.stopPropagation();
  285. }
  286. break;
  287. case Event.ONMOUSEMOVE:
  288. case Event.ONTOUCHMOVE:
  289. if (dragging) {
  290. setValueByEvent(event, false);
  291. updateFeedbackPosition();
  292. event.stopPropagation();
  293. }
  294. break;
  295. case Event.ONTOUCHEND:
  296. feedbackPopup.hide();
  297. case Event.ONMOUSEUP:
  298. // feedbackPopup.hide();
  299. dragging = false;
  300. handle.setClassName(getStylePrimaryName() + "-handle");
  301. DOM.releaseCapture(getElement());
  302. setValueByEvent(event, true);
  303. event.stopPropagation();
  304. break;
  305. default:
  306. break;
  307. }
  308. }
  309. private void processBaseEvent(Event event) {
  310. if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
  311. if (!disabled && !readonly && !dragging) {
  312. setValueByEvent(event, true);
  313. DOM.eventCancelBubble(event, true);
  314. }
  315. }
  316. }
  317. private void decreaseValue(boolean updateToServer) {
  318. setValue(new Double(value.doubleValue() - Math.pow(10, -resolution)),
  319. updateToServer);
  320. }
  321. private void increaseValue(boolean updateToServer) {
  322. setValue(new Double(value.doubleValue() + Math.pow(10, -resolution)),
  323. updateToServer);
  324. }
  325. private void setValueByEvent(Event event, boolean updateToServer) {
  326. double v = min; // Fallback to min
  327. final int coord = getEventPosition(event);
  328. final int handleSize, baseSize, baseOffset;
  329. if (isVertical()) {
  330. handleSize = handle.getOffsetHeight();
  331. baseSize = base.getOffsetHeight();
  332. baseOffset = base.getAbsoluteTop() - Window.getScrollTop()
  333. - handleSize / 2;
  334. } else {
  335. handleSize = handle.getOffsetWidth();
  336. baseSize = base.getOffsetWidth();
  337. baseOffset = base.getAbsoluteLeft() - Window.getScrollLeft()
  338. + handleSize / 2;
  339. }
  340. if (isVertical()) {
  341. v = (baseSize - (coord - baseOffset))
  342. / (double) (baseSize - handleSize) * (max - min) + min;
  343. } else {
  344. v = (coord - baseOffset) / (double) (baseSize - handleSize)
  345. * (max - min) + min;
  346. }
  347. if (v < min) {
  348. v = min;
  349. } else if (v > max) {
  350. v = max;
  351. }
  352. setValue(v, updateToServer);
  353. }
  354. /**
  355. * TODO consider extracting touches support to an impl class specific for
  356. * webkit (only browser that really supports touches).
  357. *
  358. * @param event
  359. * @return
  360. */
  361. protected int getEventPosition(Event event) {
  362. if (isVertical()) {
  363. return WidgetUtil.getTouchOrMouseClientY(event);
  364. } else {
  365. return WidgetUtil.getTouchOrMouseClientX(event);
  366. }
  367. }
  368. public void iLayout() {
  369. if (isVertical()) {
  370. setHeight();
  371. }
  372. // Update handle position
  373. setValue(value, false);
  374. }
  375. private void setHeight() {
  376. // Calculate decoration size
  377. base.getStyle().setHeight(0, Unit.PX);
  378. base.getStyle().setOverflow(Overflow.HIDDEN);
  379. int h = getElement().getOffsetHeight();
  380. if (h < MIN_SIZE) {
  381. h = MIN_SIZE;
  382. }
  383. base.getStyle().setHeight(h, Unit.PX);
  384. base.getStyle().clearOverflow();
  385. }
  386. private void fireValueChanged() {
  387. ValueChangeEvent.fire(VSlider.this, value);
  388. }
  389. /**
  390. * Handles the keyboard events handled by the Slider.
  391. *
  392. * @param keycode
  393. * The key code received
  394. * @param ctrl
  395. * Whether {@code CTRL} was pressed
  396. * @param shift
  397. * Whether {@code SHIFT} was pressed
  398. * @return true if the navigation event was handled
  399. */
  400. public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  401. // No support for ctrl moving
  402. if (ctrl) {
  403. return false;
  404. }
  405. if (keycode == getNavigationUpKey() && isVertical()
  406. || keycode == getNavigationRightKey() && !isVertical()) {
  407. if (shift) {
  408. for (int a = 0; a < acceleration; a++) {
  409. increaseValue(false);
  410. }
  411. acceleration++;
  412. } else {
  413. increaseValue(false);
  414. }
  415. return true;
  416. } else if (keycode == getNavigationDownKey() && isVertical()
  417. || keycode == getNavigationLeftKey() && !isVertical()) {
  418. if (shift) {
  419. for (int a = 0; a < acceleration; a++) {
  420. decreaseValue(false);
  421. }
  422. acceleration++;
  423. } else {
  424. decreaseValue(false);
  425. }
  426. return true;
  427. }
  428. return false;
  429. }
  430. /**
  431. * Get the key that increases the vertical slider. By default it is the up
  432. * arrow key but by overriding this you can change the key to whatever you
  433. * want.
  434. *
  435. * @return The keycode of the key
  436. */
  437. protected int getNavigationUpKey() {
  438. return KeyCodes.KEY_UP;
  439. }
  440. /**
  441. * Get the key that decreases the vertical slider. By default it is the down
  442. * arrow key but by overriding this you can change the key to whatever you
  443. * want.
  444. *
  445. * @return The keycode of the key
  446. */
  447. protected int getNavigationDownKey() {
  448. return KeyCodes.KEY_DOWN;
  449. }
  450. /**
  451. * Get the key that decreases the horizontal slider. By default it is the
  452. * left arrow key but by overriding this you can change the key to whatever
  453. * you want.
  454. *
  455. * @return The keycode of the key
  456. */
  457. protected int getNavigationLeftKey() {
  458. return KeyCodes.KEY_LEFT;
  459. }
  460. /**
  461. * Get the key that increases the horizontal slider. By default it is the
  462. * right arrow key but by overriding this you can change the key to whatever
  463. * you want.
  464. *
  465. * @return The keycode of the key
  466. */
  467. protected int getNavigationRightKey() {
  468. return KeyCodes.KEY_RIGHT;
  469. }
  470. public void setConnection(ApplicationConnection client) {
  471. this.client = client;
  472. }
  473. public void setId(String id) {
  474. this.id = id;
  475. }
  476. public void setDisabled(boolean disabled) {
  477. this.disabled = disabled;
  478. }
  479. public void setReadOnly(boolean readonly) {
  480. this.readonly = readonly;
  481. }
  482. private boolean isVertical() {
  483. return orientation == SliderOrientation.VERTICAL;
  484. }
  485. public void setOrientation(SliderOrientation orientation) {
  486. if (this.orientation != orientation) {
  487. this.orientation = orientation;
  488. updateStyleNames(getStylePrimaryName(), true);
  489. }
  490. }
  491. public void setMinValue(double value) {
  492. min = value;
  493. }
  494. public void setMaxValue(double value) {
  495. max = value;
  496. }
  497. public void setResolution(int resolution) {
  498. this.resolution = resolution;
  499. }
  500. @Override
  501. public HandlerRegistration addValueChangeHandler(
  502. ValueChangeHandler<Double> handler) {
  503. return addHandler(handler, ValueChangeEvent.getType());
  504. }
  505. @Override
  506. public Double getValue() {
  507. return value;
  508. }
  509. @Override
  510. public void setValue(Double value) {
  511. if (value < min) {
  512. value = min;
  513. } else if (value > max) {
  514. value = max;
  515. }
  516. // Update handle position
  517. final String styleAttribute = isVertical() ? "marginTop" : "marginLeft";
  518. final String domProperty = isVertical() ? "offsetHeight"
  519. : "offsetWidth";
  520. final int handleSize = handle.getPropertyInt(domProperty);
  521. final int baseSize = base.getPropertyInt(domProperty)
  522. - 2 * BASE_BORDER_WIDTH;
  523. final int range = baseSize - handleSize;
  524. double v = value.doubleValue();
  525. // Round value to resolution
  526. if (resolution > 0) {
  527. v = Math.round(v * Math.pow(10, resolution));
  528. v = v / Math.pow(10, resolution);
  529. } else {
  530. v = Math.round(v);
  531. }
  532. final double valueRange = max - min;
  533. double p = 0;
  534. if (valueRange > 0) {
  535. p = range * ((v - min) / valueRange);
  536. }
  537. if (p < 0) {
  538. p = 0;
  539. }
  540. if (isVertical()) {
  541. p = range - p;
  542. }
  543. final double pos = p;
  544. handle.getStyle().setPropertyPx(styleAttribute, (int) Math.round(pos));
  545. // Update value
  546. this.value = new Double(v);
  547. setFeedbackValue(v);
  548. }
  549. @Override
  550. public void setValue(Double value, boolean fireEvents) {
  551. if (value == null) {
  552. return;
  553. }
  554. setValue(value);
  555. if (fireEvents) {
  556. fireValueChanged();
  557. }
  558. }
  559. @Override
  560. public com.google.gwt.user.client.Element getSubPartElement(
  561. String subPart) {
  562. if (subPart.equals("popup")) {
  563. feedbackPopup.show();
  564. return feedbackPopup.getElement();
  565. }
  566. return null;
  567. }
  568. @Override
  569. public String getSubPartName(
  570. com.google.gwt.user.client.Element subElement) {
  571. if (feedbackPopup.getElement().isOrHasChild(subElement)) {
  572. return "popup";
  573. }
  574. return null;
  575. }
  576. }