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

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