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

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