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 21KB

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