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

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