Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

VSlider.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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.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.dom.client.Style.Visibility;
  25. import com.google.gwt.event.dom.client.KeyCodes;
  26. import com.google.gwt.event.logical.shared.ValueChangeEvent;
  27. import com.google.gwt.event.logical.shared.ValueChangeHandler;
  28. import com.google.gwt.event.shared.HandlerRegistration;
  29. import com.google.gwt.user.client.Command;
  30. import com.google.gwt.user.client.DOM;
  31. import com.google.gwt.user.client.Event;
  32. import com.google.gwt.user.client.Window;
  33. import com.google.gwt.user.client.ui.HTML;
  34. import com.google.gwt.user.client.ui.HasValue;
  35. import com.vaadin.client.ApplicationConnection;
  36. import com.vaadin.client.BrowserInfo;
  37. import com.vaadin.client.ContainerResizedListener;
  38. import com.vaadin.client.Util;
  39. import com.vaadin.client.VConsole;
  40. import com.vaadin.shared.ui.slider.SliderOrientation;
  41. public class VSlider extends SimpleFocusablePanel implements Field,
  42. ContainerResizedListener, HasValue<Double> {
  43. public static final String CLASSNAME = "v-slider";
  44. /**
  45. * Minimum size (width or height, depending on orientation) of the slider
  46. * base.
  47. */
  48. private static final int MIN_SIZE = 50;
  49. protected ApplicationConnection client;
  50. protected String id;
  51. protected boolean immediate;
  52. protected boolean disabled;
  53. protected boolean readonly;
  54. private int acceleration = 1;
  55. protected double min;
  56. protected double max;
  57. protected int resolution;
  58. protected Double value;
  59. protected SliderOrientation orientation = SliderOrientation.HORIZONTAL;
  60. private final HTML feedback = new HTML("", false);
  61. private final VOverlay feedbackPopup = new VOverlay(true, false, true) {
  62. {
  63. setOwner(VSlider.this);
  64. }
  65. @Override
  66. public void show() {
  67. super.show();
  68. updateFeedbackPosition();
  69. }
  70. };
  71. /* DOM element for slider's base */
  72. private final Element base;
  73. private final int BASE_BORDER_WIDTH = 1;
  74. /* DOM element for slider's handle */
  75. private final Element handle;
  76. /* DOM element for decrement arrow */
  77. private final Element smaller;
  78. /* DOM element for increment arrow */
  79. private final Element bigger;
  80. /* Temporary dragging/animation variables */
  81. private boolean dragging = false;
  82. private VLazyExecutor delayedValueUpdater = new VLazyExecutor(100,
  83. new ScheduledCommand() {
  84. @Override
  85. public void execute() {
  86. fireValueChanged();
  87. acceleration = 1;
  88. }
  89. });
  90. public VSlider() {
  91. super();
  92. base = DOM.createDiv();
  93. handle = DOM.createDiv();
  94. smaller = DOM.createDiv();
  95. bigger = DOM.createDiv();
  96. setStyleName(CLASSNAME);
  97. getElement().appendChild(bigger);
  98. getElement().appendChild(smaller);
  99. getElement().appendChild(base);
  100. base.appendChild(handle);
  101. // Hide initially
  102. smaller.getStyle().setDisplay(Display.NONE);
  103. bigger.getStyle().setDisplay(Display.NONE);
  104. handle.getStyle().setVisibility(Visibility.HIDDEN);
  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, boolean isPrimaryStyleName) {
  118. feedbackPopup.removeStyleName(getStylePrimaryName() + "-feedback");
  119. removeStyleName(getStylePrimaryName() + "-vertical");
  120. if (isPrimaryStyleName) {
  121. super.setStylePrimaryName(styleName);
  122. } else {
  123. super.setStyleName(styleName);
  124. }
  125. feedbackPopup.addStyleName(getStylePrimaryName() + "-feedback");
  126. base.setClassName(getStylePrimaryName() + "-base");
  127. handle.setClassName(getStylePrimaryName() + "-handle");
  128. smaller.setClassName(getStylePrimaryName() + "-smaller");
  129. bigger.setClassName(getStylePrimaryName() + "-bigger");
  130. if (isVertical()) {
  131. addStyleName(getStylePrimaryName() + "-vertical");
  132. }
  133. }
  134. public void setFeedbackValue(double value) {
  135. String currentValue = "" + value;
  136. if (resolution == 0) {
  137. currentValue = "" + new Double(value).intValue();
  138. }
  139. feedback.setText(currentValue);
  140. }
  141. private void updateFeedbackPosition() {
  142. if (isVertical()) {
  143. feedbackPopup.setPopupPosition(
  144. handle.getAbsoluteLeft() + handle.getOffsetWidth(),
  145. handle.getAbsoluteTop() + handle.getOffsetHeight() / 2
  146. - feedbackPopup.getOffsetHeight() / 2);
  147. } else {
  148. feedbackPopup.setPopupPosition(
  149. handle.getAbsoluteLeft() + handle.getOffsetWidth() / 2
  150. - feedbackPopup.getOffsetWidth() / 2,
  151. handle.getAbsoluteTop() - feedbackPopup.getOffsetHeight());
  152. }
  153. }
  154. /** For internal use only. May be removed or replaced in the future. */
  155. public void buildBase() {
  156. final String styleAttribute = isVertical() ? "height" : "width";
  157. final String oppositeStyleAttribute = isVertical() ? "width" : "height";
  158. final String domProperty = isVertical() ? "offsetHeight"
  159. : "offsetWidth";
  160. // clear unnecessary opposite style attribute
  161. base.getStyle().clearProperty(oppositeStyleAttribute);
  162. if (!getElement().hasParentElement()) {
  163. return;
  164. }
  165. final Element p = getElement().getParentElement();
  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 Element p = getElement().getParentElement();
  180. if (p.getPropertyInt(domProperty) > (MIN_SIZE + 5)) {
  181. if (isVertical()) {
  182. setHeight();
  183. } else {
  184. base.getStyle().clearProperty(styleAttribute);
  185. }
  186. // Ensure correct position
  187. setValue(value, false);
  188. }
  189. }
  190. });
  191. }
  192. if (!isVertical()) {
  193. // Draw handle with a delay to allow base to gain maximum width
  194. Scheduler.get().scheduleDeferred(new Command() {
  195. @Override
  196. public void execute() {
  197. buildHandle();
  198. setValue(value, false);
  199. }
  200. });
  201. } else {
  202. buildHandle();
  203. setValue(value, false);
  204. }
  205. // TODO attach listeners for focusing and arrow keys
  206. }
  207. void buildHandle() {
  208. final String handleAttribute = isVertical() ? "marginTop"
  209. : "marginLeft";
  210. final String oppositeHandleAttribute = isVertical() ? "marginLeft"
  211. : "marginTop";
  212. handle.getStyle().setProperty(handleAttribute, "0");
  213. // clear unnecessary opposite handle attribute
  214. handle.getStyle().clearProperty(oppositeHandleAttribute);
  215. // Restore visibility
  216. handle.getStyle().setVisibility(Visibility.VISIBLE);
  217. }
  218. @Override
  219. public void onBrowserEvent(Event event) {
  220. if (disabled || readonly) {
  221. return;
  222. }
  223. final Element targ = DOM.eventGetTarget(event);
  224. if (DOM.eventGetType(event) == Event.ONMOUSEWHEEL) {
  225. processMouseWheelEvent(event);
  226. } else if (dragging || targ == handle) {
  227. processHandleEvent(event);
  228. } else if (targ == smaller) {
  229. decreaseValue(true);
  230. } else if (targ == bigger) {
  231. increaseValue(true);
  232. } else if (DOM.eventGetType(event) == Event.MOUSEEVENTS) {
  233. processBaseEvent(event);
  234. } else if ((BrowserInfo.get().isGecko() && DOM.eventGetType(event) == Event.ONKEYPRESS)
  235. || (!BrowserInfo.get().isGecko() && DOM.eventGetType(event) == Event.ONKEYDOWN)) {
  236. if (handleNavigation(event.getKeyCode(), event.getCtrlKey(),
  237. event.getShiftKey())) {
  238. feedbackPopup.show();
  239. delayedValueUpdater.trigger();
  240. DOM.eventPreventDefault(event);
  241. DOM.eventCancelBubble(event, true);
  242. }
  243. } else if (targ.equals(getElement())
  244. && DOM.eventGetType(event) == Event.ONFOCUS) {
  245. feedbackPopup.show();
  246. } else if (targ.equals(getElement())
  247. && DOM.eventGetType(event) == Event.ONBLUR) {
  248. feedbackPopup.hide();
  249. } else if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
  250. feedbackPopup.show();
  251. }
  252. if (Util.isTouchEvent(event)) {
  253. event.preventDefault(); // avoid simulated events
  254. event.stopPropagation();
  255. }
  256. }
  257. private void processMouseWheelEvent(final Event event) {
  258. final int dir = DOM.eventGetMouseWheelVelocityY(event);
  259. if (dir < 0) {
  260. increaseValue(false);
  261. } else {
  262. decreaseValue(false);
  263. }
  264. delayedValueUpdater.trigger();
  265. DOM.eventPreventDefault(event);
  266. DOM.eventCancelBubble(event, true);
  267. }
  268. private void processHandleEvent(Event event) {
  269. switch (DOM.eventGetType(event)) {
  270. case Event.ONMOUSEDOWN:
  271. case Event.ONTOUCHSTART:
  272. if (!disabled && !readonly) {
  273. focus();
  274. feedbackPopup.show();
  275. dragging = true;
  276. handle.setClassName(getStylePrimaryName() + "-handle");
  277. handle.addClassName(getStylePrimaryName() + "-handle-active");
  278. DOM.setCapture(getElement());
  279. DOM.eventPreventDefault(event); // prevent selecting text
  280. DOM.eventCancelBubble(event, true);
  281. event.stopPropagation();
  282. VConsole.log("Slider move start");
  283. }
  284. break;
  285. case Event.ONMOUSEMOVE:
  286. case Event.ONTOUCHMOVE:
  287. if (dragging) {
  288. VConsole.log("Slider move");
  289. setValueByEvent(event, false);
  290. updateFeedbackPosition();
  291. event.stopPropagation();
  292. }
  293. break;
  294. case Event.ONTOUCHEND:
  295. feedbackPopup.hide();
  296. case Event.ONMOUSEUP:
  297. // feedbackPopup.hide();
  298. VConsole.log("Slider move end");
  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)) / (double) (baseSize - handleSize))
  342. * (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 Util.getTouchOrMouseClientY(event);
  364. } else {
  365. return Util.getTouchOrMouseClientX(event);
  366. }
  367. }
  368. @Override
  369. public void iLayout() {
  370. if (isVertical()) {
  371. setHeight();
  372. }
  373. // Update handle position
  374. setValue(value, false);
  375. }
  376. private void setHeight() {
  377. // Calculate decoration size
  378. base.getStyle().setHeight(0, Unit.PX);
  379. base.getStyle().setOverflow(Overflow.HIDDEN);
  380. int h = getElement().getOffsetHeight();
  381. if (h < MIN_SIZE) {
  382. h = MIN_SIZE;
  383. }
  384. base.getStyle().setHeight(h, Unit.PX);
  385. base.getStyle().clearOverflow();
  386. }
  387. private void fireValueChanged() {
  388. ValueChangeEvent.fire(VSlider.this, value);
  389. }
  390. /**
  391. * Handles the keyboard events handled by the Slider
  392. *
  393. * @param event
  394. * The keyboard event received
  395. * @return true iff the navigation event was handled
  396. */
  397. public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  398. // No support for ctrl moving
  399. if (ctrl) {
  400. return false;
  401. }
  402. if ((keycode == getNavigationUpKey() && isVertical())
  403. || (keycode == getNavigationRightKey() && !isVertical())) {
  404. if (shift) {
  405. for (int a = 0; a < acceleration; a++) {
  406. increaseValue(false);
  407. }
  408. acceleration++;
  409. } else {
  410. increaseValue(false);
  411. }
  412. return true;
  413. } else if (keycode == getNavigationDownKey() && isVertical()
  414. || (keycode == getNavigationLeftKey() && !isVertical())) {
  415. if (shift) {
  416. for (int a = 0; a < acceleration; a++) {
  417. decreaseValue(false);
  418. }
  419. acceleration++;
  420. } else {
  421. decreaseValue(false);
  422. }
  423. return true;
  424. }
  425. return false;
  426. }
  427. /**
  428. * Get the key that increases the vertical slider. By default it is the up
  429. * arrow key but by overriding this you can change the key to whatever you
  430. * want.
  431. *
  432. * @return The keycode of the key
  433. */
  434. protected int getNavigationUpKey() {
  435. return KeyCodes.KEY_UP;
  436. }
  437. /**
  438. * Get the key that decreases the vertical slider. By default it is the down
  439. * arrow key but by overriding this you can change the key to whatever you
  440. * want.
  441. *
  442. * @return The keycode of the key
  443. */
  444. protected int getNavigationDownKey() {
  445. return KeyCodes.KEY_DOWN;
  446. }
  447. /**
  448. * Get the key that decreases the horizontal slider. By default it is the
  449. * left arrow key but by overriding this you can change the key to whatever
  450. * you want.
  451. *
  452. * @return The keycode of the key
  453. */
  454. protected int getNavigationLeftKey() {
  455. return KeyCodes.KEY_LEFT;
  456. }
  457. /**
  458. * Get the key that increases the horizontal slider. By default it is the
  459. * right arrow key but by overriding this you can change the key to whatever
  460. * you want.
  461. *
  462. * @return The keycode of the key
  463. */
  464. protected int getNavigationRightKey() {
  465. return KeyCodes.KEY_RIGHT;
  466. }
  467. public void setConnection(ApplicationConnection client) {
  468. this.client = client;
  469. }
  470. public void setId(String id) {
  471. this.id = id;
  472. }
  473. public void setImmediate(boolean immediate) {
  474. this.immediate = immediate;
  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. }