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.

VSlider.java 22KB

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