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

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