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.

VButton.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client.ui;
  5. import com.google.gwt.dom.client.Document;
  6. import com.google.gwt.dom.client.Element;
  7. import com.google.gwt.dom.client.NativeEvent;
  8. import com.google.gwt.event.dom.client.BlurEvent;
  9. import com.google.gwt.event.dom.client.BlurHandler;
  10. import com.google.gwt.event.dom.client.ClickEvent;
  11. import com.google.gwt.event.dom.client.ClickHandler;
  12. import com.google.gwt.event.dom.client.FocusEvent;
  13. import com.google.gwt.event.dom.client.FocusHandler;
  14. import com.google.gwt.event.dom.client.KeyCodes;
  15. import com.google.gwt.event.shared.HandlerRegistration;
  16. import com.google.gwt.user.client.DOM;
  17. import com.google.gwt.user.client.Event;
  18. import com.google.gwt.user.client.ui.Accessibility;
  19. import com.google.gwt.user.client.ui.FocusWidget;
  20. import com.google.gwt.user.client.ui.Widget;
  21. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  22. import com.vaadin.terminal.gwt.client.BrowserInfo;
  23. import com.vaadin.terminal.gwt.client.EventHelper;
  24. import com.vaadin.terminal.gwt.client.EventId;
  25. import com.vaadin.terminal.gwt.client.MouseEventDetails;
  26. import com.vaadin.terminal.gwt.client.VPaintableWidget;
  27. import com.vaadin.terminal.gwt.client.UIDL;
  28. import com.vaadin.terminal.gwt.client.Util;
  29. import com.vaadin.terminal.gwt.client.VTooltip;
  30. public class VButton extends FocusWidget implements VPaintableWidget,
  31. ClickHandler, FocusHandler, BlurHandler {
  32. public static final String CLASSNAME = "v-button";
  33. private static final String CLASSNAME_PRESSED = "v-pressed";
  34. public static final String ATTR_DISABLE_ON_CLICK = "dc";
  35. // mouse movement is checked before synthesizing click event on mouseout
  36. protected static int MOVE_THRESHOLD = 3;
  37. protected int mousedownX = 0;
  38. protected int mousedownY = 0;
  39. protected String id;
  40. protected ApplicationConnection client;
  41. protected final Element wrapper = DOM.createSpan();
  42. protected Element errorIndicatorElement;
  43. protected final Element captionElement = DOM.createSpan();
  44. protected Icon icon;
  45. /**
  46. * Helper flag to handle special-case where the button is moved from under
  47. * mouse while clicking it. In this case mouse leaves the button without
  48. * moving.
  49. */
  50. protected boolean clickPending;
  51. private boolean enabled = true;
  52. private int tabIndex = 0;
  53. private boolean disableOnClick = false;
  54. /*
  55. * BELOW PRIVATE MEMBERS COPY-PASTED FROM GWT CustomButton
  56. */
  57. /**
  58. * If <code>true</code>, this widget is capturing with the mouse held down.
  59. */
  60. private boolean isCapturing;
  61. /**
  62. * If <code>true</code>, this widget has focus with the space bar down.
  63. */
  64. private boolean isFocusing;
  65. /**
  66. * Used to decide whether to allow clicks to propagate up to the superclass
  67. * or container elements.
  68. */
  69. private boolean disallowNextClick = false;
  70. private boolean isHovering;
  71. private HandlerRegistration focusHandlerRegistration;
  72. private HandlerRegistration blurHandlerRegistration;
  73. private int clickShortcut = 0;
  74. public VButton() {
  75. super(DOM.createDiv());
  76. setTabIndex(0);
  77. sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS | Event.FOCUSEVENTS
  78. | Event.KEYEVENTS);
  79. sinkEvents(VTooltip.TOOLTIP_EVENTS);
  80. setStyleName(CLASSNAME);
  81. // Add a11y role "button"
  82. Accessibility.setRole(getElement(), Accessibility.ROLE_BUTTON);
  83. wrapper.setClassName(getStylePrimaryName() + "-wrap");
  84. getElement().appendChild(wrapper);
  85. captionElement.setClassName(getStylePrimaryName() + "-caption");
  86. wrapper.appendChild(captionElement);
  87. addClickHandler(this);
  88. }
  89. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  90. // Ensure correct implementation,
  91. // but don't let container manage caption etc.
  92. if (client.updateComponent(this, uidl, false)) {
  93. return;
  94. }
  95. focusHandlerRegistration = EventHelper.updateFocusHandler(this, client,
  96. focusHandlerRegistration);
  97. blurHandlerRegistration = EventHelper.updateBlurHandler(this, client,
  98. blurHandlerRegistration);
  99. // Save details
  100. this.client = client;
  101. id = uidl.getId();
  102. // Set text
  103. setText(uidl.getStringAttribute("caption"));
  104. disableOnClick = uidl.hasAttribute(ATTR_DISABLE_ON_CLICK);
  105. // handle error
  106. if (uidl.hasAttribute("error")) {
  107. if (errorIndicatorElement == null) {
  108. errorIndicatorElement = DOM.createSpan();
  109. errorIndicatorElement.setClassName("v-errorindicator");
  110. }
  111. wrapper.insertBefore(errorIndicatorElement, captionElement);
  112. } else if (errorIndicatorElement != null) {
  113. wrapper.removeChild(errorIndicatorElement);
  114. errorIndicatorElement = null;
  115. }
  116. if (uidl.hasAttribute("icon")) {
  117. if (icon == null) {
  118. icon = new Icon(client);
  119. wrapper.insertBefore(icon.getElement(), captionElement);
  120. }
  121. icon.setUri(uidl.getStringAttribute("icon"));
  122. } else {
  123. if (icon != null) {
  124. wrapper.removeChild(icon.getElement());
  125. icon = null;
  126. }
  127. }
  128. if (uidl.hasAttribute("keycode")) {
  129. clickShortcut = uidl.getIntAttribute("keycode");
  130. }
  131. }
  132. public void setText(String text) {
  133. captionElement.setInnerText(text);
  134. }
  135. @SuppressWarnings("deprecation")
  136. @Override
  137. /*
  138. * Copy-pasted from GWT CustomButton, some minor modifications done:
  139. *
  140. * -for IE/Opera added CLASSNAME_PRESSED
  141. *
  142. * -event.preventDefault() commented from ONMOUSEDOWN (Firefox won't apply
  143. * :active styles if it is present)
  144. *
  145. * -Tooltip event handling added
  146. *
  147. * -onload event handler added (for icon handling)
  148. */
  149. public void onBrowserEvent(Event event) {
  150. if (client != null) {
  151. client.handleTooltipEvent(event, this);
  152. }
  153. if (DOM.eventGetType(event) == Event.ONLOAD) {
  154. Util.notifyParentOfSizeChange(this, true);
  155. }
  156. // Should not act on button if disabled.
  157. if (!isEnabled()) {
  158. // This can happen when events are bubbled up from non-disabled
  159. // children
  160. return;
  161. }
  162. int type = DOM.eventGetType(event);
  163. switch (type) {
  164. case Event.ONCLICK:
  165. // If clicks are currently disallowed, keep it from bubbling or
  166. // being passed to the superclass.
  167. if (disallowNextClick) {
  168. event.stopPropagation();
  169. disallowNextClick = false;
  170. return;
  171. }
  172. break;
  173. case Event.ONMOUSEDOWN:
  174. if (DOM.isOrHasChild(getElement(), DOM.eventGetTarget(event))) {
  175. // This was moved from mouseover, which iOS sometimes skips.
  176. // We're certainly hovering at this point, and we don't actually
  177. // need that information before this point.
  178. setHovering(true);
  179. }
  180. if (event.getButton() == Event.BUTTON_LEFT) {
  181. // save mouse position to detect movement before synthesizing
  182. // event later
  183. mousedownX = event.getClientX();
  184. mousedownY = event.getClientY();
  185. disallowNextClick = true;
  186. clickPending = true;
  187. setFocus(true);
  188. DOM.setCapture(getElement());
  189. isCapturing = true;
  190. // Prevent dragging (on some browsers);
  191. // DOM.eventPreventDefault(event);
  192. if (BrowserInfo.get().isIE() || BrowserInfo.get().isOpera()) {
  193. addStyleName(CLASSNAME_PRESSED);
  194. }
  195. }
  196. break;
  197. case Event.ONMOUSEUP:
  198. if (isCapturing) {
  199. isCapturing = false;
  200. DOM.releaseCapture(getElement());
  201. if (isHovering() && event.getButton() == Event.BUTTON_LEFT) {
  202. // Click ok
  203. disallowNextClick = false;
  204. }
  205. if (BrowserInfo.get().isIE() || BrowserInfo.get().isOpera()) {
  206. removeStyleName(CLASSNAME_PRESSED);
  207. }
  208. }
  209. break;
  210. case Event.ONMOUSEMOVE:
  211. clickPending = false;
  212. if (isCapturing) {
  213. // Prevent dragging (on other browsers);
  214. DOM.eventPreventDefault(event);
  215. }
  216. break;
  217. case Event.ONMOUSEOUT:
  218. Element to = event.getRelatedTarget();
  219. if (getElement().isOrHasChild(DOM.eventGetTarget(event))
  220. && (to == null || !getElement().isOrHasChild(to))) {
  221. if (clickPending
  222. && Math.abs(mousedownX - event.getClientX()) < MOVE_THRESHOLD
  223. && Math.abs(mousedownY - event.getClientY()) < MOVE_THRESHOLD) {
  224. onClick();
  225. break;
  226. }
  227. clickPending = false;
  228. if (isCapturing) {
  229. }
  230. setHovering(false);
  231. if (BrowserInfo.get().isIE() || BrowserInfo.get().isOpera()) {
  232. removeStyleName(CLASSNAME_PRESSED);
  233. }
  234. }
  235. break;
  236. case Event.ONBLUR:
  237. if (isFocusing) {
  238. isFocusing = false;
  239. }
  240. break;
  241. case Event.ONLOSECAPTURE:
  242. if (isCapturing) {
  243. isCapturing = false;
  244. }
  245. break;
  246. }
  247. super.onBrowserEvent(event);
  248. // Synthesize clicks based on keyboard events AFTER the normal key
  249. // handling.
  250. if ((event.getTypeInt() & Event.KEYEVENTS) != 0) {
  251. switch (type) {
  252. case Event.ONKEYDOWN:
  253. if (event.getKeyCode() == 32 /* space */) {
  254. isFocusing = true;
  255. event.preventDefault();
  256. }
  257. break;
  258. case Event.ONKEYUP:
  259. if (isFocusing && event.getKeyCode() == 32 /* space */) {
  260. isFocusing = false;
  261. /*
  262. * If click shortcut is space then the shortcut handler will
  263. * take care of the click.
  264. */
  265. if (clickShortcut != 32 /* space */) {
  266. onClick();
  267. }
  268. event.preventDefault();
  269. }
  270. break;
  271. case Event.ONKEYPRESS:
  272. if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
  273. /*
  274. * If click shortcut is enter then the shortcut handler will
  275. * take care of the click.
  276. */
  277. if (clickShortcut != KeyCodes.KEY_ENTER) {
  278. onClick();
  279. }
  280. event.preventDefault();
  281. }
  282. break;
  283. }
  284. }
  285. }
  286. final void setHovering(boolean hovering) {
  287. if (hovering != isHovering()) {
  288. isHovering = hovering;
  289. }
  290. }
  291. final boolean isHovering() {
  292. return isHovering;
  293. }
  294. /*
  295. * (non-Javadoc)
  296. *
  297. * @see
  298. * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event
  299. * .dom.client.ClickEvent)
  300. */
  301. public void onClick(ClickEvent event) {
  302. if (id == null || client == null) {
  303. return;
  304. }
  305. if (BrowserInfo.get().isSafari()) {
  306. VButton.this.setFocus(true);
  307. }
  308. if (disableOnClick) {
  309. setEnabled(false);
  310. client.updateVariable(id, "disabledOnClick", true, false);
  311. }
  312. client.updateVariable(id, "state", true, false);
  313. // Add mouse details
  314. MouseEventDetails details = new MouseEventDetails(
  315. event.getNativeEvent(), getElement());
  316. client.updateVariable(id, "mousedetails", details.serialize(), true);
  317. clickPending = false;
  318. }
  319. /*
  320. * ALL BELOW COPY-PASTED FROM GWT CustomButton
  321. */
  322. /**
  323. * Called internally when the user finishes clicking on this button. The
  324. * default behavior is to fire the click event to listeners. Subclasses that
  325. * override {@link #onClickStart()} should override this method to restore
  326. * the normal widget display.
  327. * <p>
  328. * To add custom code for a click event, override
  329. * {@link #onClick(ClickEvent)} instead of this.
  330. */
  331. protected void onClick() {
  332. // Allow the click we're about to synthesize to pass through to the
  333. // superclass and containing elements. Element.dispatchEvent() is
  334. // synchronous, so we simply set and clear the flag within this method.
  335. disallowNextClick = false;
  336. // Mouse coordinates are not always available (e.g., when the click is
  337. // caused by a keyboard event).
  338. NativeEvent evt = Document.get().createClickEvent(1, 0, 0, 0, 0, false,
  339. false, false, false);
  340. getElement().dispatchEvent(evt);
  341. }
  342. /**
  343. * Sets whether this button is enabled.
  344. *
  345. * @param enabled
  346. * <code>true</code> to enable the button, <code>false</code> to
  347. * disable it
  348. */
  349. @Override
  350. public final void setEnabled(boolean enabled) {
  351. if (isEnabled() != enabled) {
  352. this.enabled = enabled;
  353. if (!enabled) {
  354. cleanupCaptureState();
  355. Accessibility.removeState(getElement(),
  356. Accessibility.STATE_PRESSED);
  357. super.setTabIndex(-1);
  358. addStyleName(ApplicationConnection.DISABLED_CLASSNAME);
  359. } else {
  360. Accessibility.setState(getElement(),
  361. Accessibility.STATE_PRESSED, "false");
  362. super.setTabIndex(tabIndex);
  363. removeStyleName(ApplicationConnection.DISABLED_CLASSNAME);
  364. }
  365. }
  366. }
  367. @Override
  368. public final boolean isEnabled() {
  369. return enabled;
  370. }
  371. @Override
  372. public final void setTabIndex(int index) {
  373. super.setTabIndex(index);
  374. tabIndex = index;
  375. }
  376. /**
  377. * Resets internal state if this button can no longer service events. This
  378. * can occur when the widget becomes detached or disabled.
  379. */
  380. private void cleanupCaptureState() {
  381. if (isCapturing || isFocusing) {
  382. DOM.releaseCapture(getElement());
  383. isCapturing = false;
  384. isFocusing = false;
  385. }
  386. }
  387. private static native int getHorizontalBorderAndPaddingWidth(Element elem)
  388. /*-{
  389. // THIS METHOD IS ONLY USED FOR INTERNET EXPLORER, IT DOESN'T WORK WITH OTHERS
  390. var convertToPixel = function(elem, value) {
  391. // From the awesome hack by Dean Edwards
  392. // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
  393. // Remember the original values
  394. var left = elem.style.left, rsLeft = elem.runtimeStyle.left;
  395. // Put in the new values to get a computed value out
  396. elem.runtimeStyle.left = elem.currentStyle.left;
  397. elem.style.left = value || 0;
  398. var ret = elem.style.pixelLeft;
  399. // Revert the changed values
  400. elem.style.left = left;
  401. elem.runtimeStyle.left = rsLeft;
  402. return ret;
  403. }
  404. var ret = 0;
  405. var sides = ["Right","Left"];
  406. for(var i=0; i<2; i++) {
  407. var side = sides[i];
  408. var value;
  409. // Border -------------------------------------------------------
  410. if(elem.currentStyle["border"+side+"Style"] != "none") {
  411. value = elem.currentStyle["border"+side+"Width"];
  412. if ( !/^\d+(px)?$/i.test( value ) && /^\d/.test( value ) ) {
  413. ret += convertToPixel(elem, value);
  414. } else if(value.length > 2) {
  415. ret += parseInt(value.substr(0, value.length-2));
  416. }
  417. }
  418. // Padding -------------------------------------------------------
  419. value = elem.currentStyle["padding"+side];
  420. if ( !/^\d+(px)?$/i.test( value ) && /^\d/.test( value ) ) {
  421. ret += convertToPixel(elem, value);
  422. } else if(value.length > 2) {
  423. ret += parseInt(value.substr(0, value.length-2));
  424. }
  425. }
  426. return ret;
  427. }-*/;
  428. public void onFocus(FocusEvent arg0) {
  429. client.updateVariable(id, EventId.FOCUS, "", true);
  430. }
  431. public void onBlur(BlurEvent arg0) {
  432. client.updateVariable(id, EventId.BLUR, "", true);
  433. }
  434. public Widget getWidgetForPaintable() {
  435. return this;
  436. }
  437. }