Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

VButton.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. if (disallowNextClick || isPhantomClickPossible
  146. && (clickTime - lastClickTime < 100)) { // the maximum
  147. // interval observed
  148. // for phantom click
  149. // is 69, with
  150. // majority under
  151. // 50, so we select
  152. // 100 to be safe
  153. event.stopPropagation();
  154. disallowNextClick = false;
  155. return;
  156. }
  157. lastClickTime = clickTime;
  158. break;
  159. case Event.ONMOUSEDOWN:
  160. if (DOM.isOrHasChild(getElement(), DOM.eventGetTarget(event))) {
  161. // This was moved from mouseover, which iOS sometimes skips.
  162. // We're certainly hovering at this point, and we don't actually
  163. // need that information before this point.
  164. setHovering(true);
  165. }
  166. if (event.getButton() == Event.BUTTON_LEFT) {
  167. // save mouse position to detect movement before synthesizing
  168. // event later
  169. mousedownX = event.getClientX();
  170. mousedownY = event.getClientY();
  171. disallowNextClick = true;
  172. clickPending = true;
  173. setFocus(true);
  174. DOM.setCapture(getElement());
  175. isCapturing = true;
  176. addStyleName(CLASSNAME_PRESSED);
  177. }
  178. break;
  179. case Event.ONMOUSEUP:
  180. if (isCapturing) {
  181. isCapturing = false;
  182. DOM.releaseCapture(getElement());
  183. if (isHovering() && event.getButton() == Event.BUTTON_LEFT) {
  184. // Click ok
  185. disallowNextClick = false;
  186. }
  187. removeStyleName(CLASSNAME_PRESSED);
  188. }
  189. break;
  190. case Event.ONMOUSEMOVE:
  191. clickPending = false;
  192. if (isCapturing) {
  193. // Prevent dragging (on other browsers);
  194. DOM.eventPreventDefault(event);
  195. }
  196. break;
  197. case Event.ONMOUSEOVER:
  198. if (isCapturing && isTargetInsideButton(event)) {
  199. // This means a mousedown happened on the button and a mouseup
  200. // has not happened yet
  201. setHovering(true);
  202. addStyleName(CLASSNAME_PRESSED);
  203. }
  204. break;
  205. case Event.ONMOUSEOUT:
  206. if (isTargetInsideButton(event)) {
  207. if (clickPending
  208. && Math.abs(mousedownX
  209. - event.getClientX()) < MOVE_THRESHOLD
  210. && Math.abs(mousedownY
  211. - event.getClientY()) < MOVE_THRESHOLD) {
  212. onClick();
  213. break;
  214. }
  215. clickPending = false;
  216. setHovering(false);
  217. removeStyleName(CLASSNAME_PRESSED);
  218. }
  219. break;
  220. case Event.ONBLUR:
  221. if (isFocusing) {
  222. isFocusing = false;
  223. }
  224. break;
  225. case Event.ONLOSECAPTURE:
  226. if (isCapturing) {
  227. isCapturing = false;
  228. }
  229. break;
  230. }
  231. super.onBrowserEvent(event);
  232. // Synthesize clicks based on keyboard events AFTER the normal key
  233. // handling.
  234. if ((event.getTypeInt() & Event.KEYEVENTS) != 0) {
  235. switch (type) {
  236. case Event.ONKEYDOWN:
  237. // Stop propagation when the user starts pressing a button that
  238. // we are handling to prevent actions from getting triggered
  239. if (event.getKeyCode() == 32 /* space */) {
  240. isFocusing = true;
  241. event.preventDefault();
  242. event.stopPropagation();
  243. } else if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
  244. event.stopPropagation();
  245. }
  246. break;
  247. case Event.ONKEYUP:
  248. if (isFocusing && event.getKeyCode() == 32 /* space */) {
  249. isFocusing = false;
  250. onClick();
  251. event.stopPropagation();
  252. event.preventDefault();
  253. }
  254. break;
  255. case Event.ONKEYPRESS:
  256. if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
  257. onClick();
  258. event.stopPropagation();
  259. event.preventDefault();
  260. }
  261. break;
  262. }
  263. }
  264. }
  265. /**
  266. * Check if the event occurred over an element which is part of this button
  267. */
  268. private boolean isTargetInsideButton(Event event) {
  269. Element to = event.getRelatedTarget();
  270. return getElement().isOrHasChild(DOM.eventGetTarget(event))
  271. && (to == null || !getElement().isOrHasChild(to));
  272. }
  273. final void setHovering(boolean hovering) {
  274. if (hovering != isHovering()) {
  275. isHovering = hovering;
  276. }
  277. }
  278. final boolean isHovering() {
  279. return isHovering;
  280. }
  281. /*
  282. * (non-Javadoc)
  283. *
  284. * @see
  285. * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event
  286. * .dom.client.ClickEvent)
  287. */
  288. @Override
  289. public void onClick(ClickEvent event) {
  290. if (BrowserInfo.get().isSafari()) {
  291. VButton.this.setFocus(true);
  292. }
  293. clickPending = false;
  294. }
  295. /*
  296. * ALL BELOW COPY-PASTED FROM GWT CustomButton
  297. */
  298. /**
  299. * Called internally when the user finishes clicking on this button. The
  300. * default behavior is to fire the click event to listeners. Subclasses that
  301. * override {@link #onClickStart()} should override this method to restore
  302. * the normal widget display.
  303. * <p>
  304. * To add custom code for a click event, override
  305. * {@link #onClick(ClickEvent)} instead of this.
  306. * <p>
  307. * For internal use only. May be removed or replaced in the future.
  308. */
  309. public void onClick() {
  310. // Allow the click we're about to synthesize to pass through to the
  311. // superclass and containing elements. Element.dispatchEvent() is
  312. // synchronous, so we simply set and clear the flag within this method.
  313. disallowNextClick = false;
  314. // Screen coordinates are not always available (e.g., when the click is
  315. // caused by a keyboard event).
  316. // Set (x,y) client coordinates to the middle of the button
  317. int x = getElement().getAbsoluteLeft() - getElement().getScrollLeft()
  318. - getElement().getOwnerDocument().getScrollLeft()
  319. + WidgetUtil.getRequiredWidth(getElement()) / 2;
  320. int y = getElement().getAbsoluteTop() - getElement().getScrollTop()
  321. - getElement().getOwnerDocument().getScrollTop()
  322. + WidgetUtil.getRequiredHeight(getElement()) / 2;
  323. NativeEvent evt = Document.get().createClickEvent(1, 0, 0, x, y, false,
  324. false, false, false);
  325. getElement().dispatchEvent(evt);
  326. }
  327. /**
  328. * Sets whether this button is enabled.
  329. *
  330. * @param enabled
  331. * <code>true</code> to enable the button, <code>false</code> to
  332. * disable it
  333. */
  334. @Override
  335. public final void setEnabled(boolean enabled) {
  336. if (isEnabled() != enabled) {
  337. this.enabled = enabled;
  338. if (!enabled) {
  339. cleanupCaptureState();
  340. Roles.getButtonRole().setAriaDisabledState(getElement(),
  341. !enabled);
  342. super.setTabIndex(-1);
  343. } else {
  344. Roles.getButtonRole().removeAriaDisabledState(getElement());
  345. super.setTabIndex(tabIndex);
  346. }
  347. }
  348. }
  349. @Override
  350. public final boolean isEnabled() {
  351. return enabled;
  352. }
  353. @Override
  354. public final void setTabIndex(int index) {
  355. super.setTabIndex(index);
  356. tabIndex = index;
  357. }
  358. /**
  359. * Resets internal state if this button can no longer service events. This
  360. * can occur when the widget becomes detached or disabled.
  361. */
  362. private void cleanupCaptureState() {
  363. if (isCapturing || isFocusing) {
  364. DOM.releaseCapture(getElement());
  365. isCapturing = false;
  366. isFocusing = false;
  367. }
  368. }
  369. private static native int getHorizontalBorderAndPaddingWidth(Element elem)
  370. /*-{
  371. // THIS METHOD IS ONLY USED FOR INTERNET EXPLORER, IT DOESN'T WORK WITH OTHERS
  372. var convertToPixel = function(elem, value) {
  373. // From the awesome hack by Dean Edwards
  374. // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
  375. // Remember the original values
  376. var left = elem.style.left, rsLeft = elem.runtimeStyle.left;
  377. // Put in the new values to get a computed value out
  378. elem.runtimeStyle.left = elem.currentStyle.left;
  379. elem.style.left = value || 0;
  380. var ret = elem.style.pixelLeft;
  381. // Revert the changed values
  382. elem.style.left = left;
  383. elem.runtimeStyle.left = rsLeft;
  384. return ret;
  385. }
  386. var ret = 0;
  387. var sides = ["Right","Left"];
  388. for(var i=0; i<2; i++) {
  389. var side = sides[i];
  390. var value;
  391. // Border -------------------------------------------------------
  392. if(elem.currentStyle["border"+side+"Style"] != "none") {
  393. value = elem.currentStyle["border"+side+"Width"];
  394. if ( !/^\d+(px)?$/i.test( value ) && /^\d/.test( value ) ) {
  395. ret += convertToPixel(elem, value);
  396. } else if(value.length > 2) {
  397. ret += parseInt(value.substr(0, value.length-2));
  398. }
  399. }
  400. // Padding -------------------------------------------------------
  401. value = elem.currentStyle["padding"+side];
  402. if ( !/^\d+(px)?$/i.test( value ) && /^\d/.test( value ) ) {
  403. ret += convertToPixel(elem, value);
  404. } else if(value.length > 2) {
  405. ret += parseInt(value.substr(0, value.length-2));
  406. }
  407. }
  408. return ret;
  409. }-*/;
  410. }