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

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