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

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