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.

Button.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /*
  2. * Copyright 2000-2018 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.ui;
  17. import java.io.Serializable;
  18. import java.lang.reflect.Method;
  19. import java.util.Collection;
  20. import org.jsoup.nodes.Attributes;
  21. import org.jsoup.nodes.Element;
  22. import com.vaadin.event.Action;
  23. import com.vaadin.event.ShortcutAction;
  24. import com.vaadin.event.ShortcutAction.KeyCode;
  25. import com.vaadin.event.ShortcutAction.ModifierKey;
  26. import com.vaadin.event.ShortcutListener;
  27. import com.vaadin.server.Resource;
  28. import com.vaadin.shared.MouseEventDetails;
  29. import com.vaadin.shared.Registration;
  30. import com.vaadin.shared.ui.button.ButtonServerRpc;
  31. import com.vaadin.shared.ui.button.ButtonState;
  32. import com.vaadin.ui.declarative.DesignAttributeHandler;
  33. import com.vaadin.ui.declarative.DesignContext;
  34. import com.vaadin.ui.declarative.DesignFormatter;
  35. import com.vaadin.util.ReflectTools;
  36. import elemental.json.Json;
  37. /**
  38. * A generic button component.
  39. *
  40. * @author Vaadin Ltd.
  41. * @since 3.0
  42. */
  43. @SuppressWarnings("serial")
  44. public class Button extends AbstractFocusable
  45. implements Action.ShortcutNotifier {
  46. private ButtonServerRpc rpc = new ButtonServerRpc() {
  47. @Override
  48. public void click(MouseEventDetails mouseEventDetails) {
  49. fireClick(mouseEventDetails);
  50. }
  51. @Override
  52. public void disableOnClick() throws RuntimeException {
  53. setEnabled(false);
  54. // Makes sure the enabled=false state is noticed at once - otherwise
  55. // a following setEnabled(true) call might have no effect. see
  56. // ticket #10030
  57. updateDiffstate("enabled", Json.create(false));
  58. }
  59. };
  60. /**
  61. * Creates a new push button.
  62. */
  63. public Button() {
  64. registerRpc(rpc);
  65. }
  66. /**
  67. * Creates a new push button with the given caption.
  68. *
  69. * @param caption
  70. * the Button caption.
  71. */
  72. public Button(String caption) {
  73. this();
  74. setCaption(caption);
  75. }
  76. /**
  77. * Creates a new push button with the given icon.
  78. *
  79. * @param icon
  80. * the icon
  81. */
  82. public Button(Resource icon) {
  83. this();
  84. setIcon(icon);
  85. }
  86. /**
  87. * Creates a new push button with the given caption and icon.
  88. *
  89. * @param caption
  90. * the caption
  91. * @param icon
  92. * the icon
  93. */
  94. public Button(String caption, Resource icon) {
  95. this();
  96. setCaption(caption);
  97. setIcon(icon);
  98. }
  99. /**
  100. * Creates a new push button with a click listener.
  101. *
  102. * @param caption
  103. * the Button caption.
  104. * @param listener
  105. * the Button click listener.
  106. */
  107. public Button(String caption, ClickListener listener) {
  108. this(caption);
  109. addClickListener(listener);
  110. }
  111. /**
  112. * Creates a new push button with a click listener.
  113. *
  114. * @param icon
  115. * the Button icon.
  116. * @param listener
  117. * the Button click listener.
  118. * @since 8.2
  119. */
  120. public Button(Resource icon, ClickListener listener) {
  121. this(icon);
  122. addClickListener(listener);
  123. }
  124. /**
  125. * Click event. This event is thrown, when the button is clicked.
  126. *
  127. * @author Vaadin Ltd.
  128. * @since 3.0
  129. */
  130. public static class ClickEvent extends Component.Event {
  131. private final MouseEventDetails details;
  132. /**
  133. * New instance of text change event.
  134. *
  135. * @param source
  136. * the Source of the event.
  137. */
  138. public ClickEvent(Component source) {
  139. super(source);
  140. details = null;
  141. }
  142. /**
  143. * Constructor with mouse details.
  144. *
  145. * @param source
  146. * The source where the click took place
  147. * @param details
  148. * Details about the mouse click
  149. */
  150. public ClickEvent(Component source, MouseEventDetails details) {
  151. super(source);
  152. this.details = details;
  153. }
  154. /**
  155. * Gets the Button where the event occurred.
  156. *
  157. * @return the Source of the event.
  158. */
  159. public Button getButton() {
  160. return (Button) getSource();
  161. }
  162. /**
  163. * Returns the mouse position (x coordinate) when the click took place.
  164. * The position is relative to the browser client area.
  165. *
  166. * @return The mouse cursor x position or -1 if unknown
  167. */
  168. public int getClientX() {
  169. if (null != details) {
  170. return details.getClientX();
  171. } else {
  172. return -1;
  173. }
  174. }
  175. /**
  176. * Returns the mouse position (y coordinate) when the click took place.
  177. * The position is relative to the browser client area.
  178. *
  179. * @return The mouse cursor y position or -1 if unknown
  180. */
  181. public int getClientY() {
  182. if (null != details) {
  183. return details.getClientY();
  184. } else {
  185. return -1;
  186. }
  187. }
  188. /**
  189. * Returns the relative mouse position (x coordinate) when the click
  190. * took place. The position is relative to the clicked component.
  191. *
  192. * @return The mouse cursor x position relative to the clicked layout
  193. * component or -1 if no x coordinate available
  194. */
  195. public int getRelativeX() {
  196. if (null != details) {
  197. return details.getRelativeX();
  198. } else {
  199. return -1;
  200. }
  201. }
  202. /**
  203. * Returns the relative mouse position (y coordinate) when the click
  204. * took place. The position is relative to the clicked component.
  205. *
  206. * @return The mouse cursor y position relative to the clicked layout
  207. * component or -1 if no y coordinate available
  208. */
  209. public int getRelativeY() {
  210. if (null != details) {
  211. return details.getRelativeY();
  212. } else {
  213. return -1;
  214. }
  215. }
  216. /**
  217. * Checks if the Alt key was down when the mouse event took place.
  218. *
  219. * @return true if Alt was down when the event occurred, false otherwise
  220. * or if unknown
  221. */
  222. public boolean isAltKey() {
  223. if (null != details) {
  224. return details.isAltKey();
  225. } else {
  226. return false;
  227. }
  228. }
  229. /**
  230. * Checks if the Ctrl key was down when the mouse event took place.
  231. *
  232. * @return true if Ctrl was pressed when the event occurred, false
  233. * otherwise or if unknown
  234. */
  235. public boolean isCtrlKey() {
  236. if (null != details) {
  237. return details.isCtrlKey();
  238. } else {
  239. return false;
  240. }
  241. }
  242. /**
  243. * Checks if the Meta key was down when the mouse event took place.
  244. *
  245. * @return true if Meta was pressed when the event occurred, false
  246. * otherwise or if unknown
  247. */
  248. public boolean isMetaKey() {
  249. if (null != details) {
  250. return details.isMetaKey();
  251. } else {
  252. return false;
  253. }
  254. }
  255. /**
  256. * Checks if the Shift key was down when the mouse event took place.
  257. *
  258. * @return true if Shift was pressed when the event occurred, false
  259. * otherwise or if unknown
  260. */
  261. public boolean isShiftKey() {
  262. if (null != details) {
  263. return details.isShiftKey();
  264. } else {
  265. return false;
  266. }
  267. }
  268. }
  269. /**
  270. * Interface for listening for a {@link ClickEvent} fired by a
  271. * {@link Component}.
  272. *
  273. * @author Vaadin Ltd.
  274. * @since 3.0
  275. */
  276. @FunctionalInterface
  277. public interface ClickListener extends Serializable {
  278. public static final Method BUTTON_CLICK_METHOD = ReflectTools
  279. .findMethod(ClickListener.class, "buttonClick",
  280. ClickEvent.class);
  281. /**
  282. * Called when a {@link Button} has been clicked. A reference to the
  283. * button is given by {@link ClickEvent#getButton()}.
  284. *
  285. * @param event
  286. * An event containing information about the click.
  287. */
  288. public void buttonClick(ClickEvent event);
  289. }
  290. /**
  291. * Adds the button click listener.
  292. *
  293. * @see Registration
  294. *
  295. * @param listener
  296. * the Listener to be added.
  297. * @return a registration object for removing the listener
  298. * @since 8.0
  299. */
  300. public Registration addClickListener(ClickListener listener) {
  301. return addListener(ClickEvent.class, listener,
  302. ClickListener.BUTTON_CLICK_METHOD);
  303. }
  304. /**
  305. * Removes the button click listener.
  306. *
  307. * @param listener
  308. * the Listener to be removed.
  309. *
  310. * @deprecated As of 8.0, replaced by {@link Registration#remove()} in the
  311. * registration object returned from
  312. * {@link #addClickListener(ClickListener)}.
  313. */
  314. @Deprecated
  315. public void removeClickListener(ClickListener listener) {
  316. removeListener(ClickEvent.class, listener,
  317. ClickListener.BUTTON_CLICK_METHOD);
  318. }
  319. /**
  320. * Simulates a button click, notifying all server-side listeners.
  321. * <p>
  322. * No action is taken if the button is disabled.
  323. */
  324. public void click() {
  325. if (isEnabled()) {
  326. fireClick();
  327. }
  328. }
  329. /**
  330. * Fires a click event to all listeners without any event details.
  331. * <p>
  332. * In subclasses, override {@link #fireClick(MouseEventDetails)} instead of
  333. * this method.
  334. */
  335. protected void fireClick() {
  336. fireEvent(new Button.ClickEvent(this));
  337. }
  338. /**
  339. * Fires a click event to all listeners.
  340. *
  341. * @param details
  342. * MouseEventDetails from which keyboard modifiers and other
  343. * information about the mouse click can be obtained. If the
  344. * button was clicked by a keyboard event, some of the fields may
  345. * be empty/undefined.
  346. */
  347. protected void fireClick(MouseEventDetails details) {
  348. fireEvent(new Button.ClickEvent(this, details));
  349. }
  350. /*
  351. * Actions
  352. */
  353. protected ClickShortcut clickShortcut;
  354. /**
  355. * Makes it possible to invoke a click on this button by pressing the given
  356. * {@link KeyCode} and (optional) {@link ModifierKey}s.<br/>
  357. * The shortcut is global (bound to the containing Window).
  358. *
  359. * @param keyCode
  360. * the keycode for invoking the shortcut
  361. * @param modifiers
  362. * the (optional) modifiers for invoking the shortcut, null for
  363. * none
  364. */
  365. public void setClickShortcut(int keyCode, int... modifiers) {
  366. if (clickShortcut != null) {
  367. removeShortcutListener(clickShortcut);
  368. }
  369. clickShortcut = new ClickShortcut(this, keyCode, modifiers);
  370. addShortcutListener(clickShortcut);
  371. getState().clickShortcutKeyCode = clickShortcut.getKeyCode();
  372. }
  373. /**
  374. * Removes the keyboard shortcut previously set with
  375. * {@link #setClickShortcut(int, int...)}.
  376. */
  377. public void removeClickShortcut() {
  378. if (clickShortcut != null) {
  379. removeShortcutListener(clickShortcut);
  380. clickShortcut = null;
  381. getState().clickShortcutKeyCode = 0;
  382. }
  383. }
  384. /**
  385. * A {@link ShortcutListener} specifically made to define a keyboard
  386. * shortcut that invokes a click on the given button.
  387. */
  388. public static class ClickShortcut extends ShortcutListener {
  389. protected Button button;
  390. /**
  391. * Creates a keyboard shortcut for clicking the given button using the
  392. * shorthand notation defined in {@link ShortcutAction}.
  393. *
  394. * @param button
  395. * to be clicked when the shortcut is invoked
  396. * @param shorthandCaption
  397. * the caption with shortcut keycode and modifiers indicated
  398. */
  399. public ClickShortcut(Button button, String shorthandCaption) {
  400. super(shorthandCaption);
  401. this.button = button;
  402. }
  403. /**
  404. * Creates a keyboard shortcut for clicking the given button using the
  405. * given {@link KeyCode} and {@link ModifierKey}s.
  406. *
  407. * @param button
  408. * to be clicked when the shortcut is invoked
  409. * @param keyCode
  410. * KeyCode to react to
  411. * @param modifiers
  412. * optional modifiers for shortcut
  413. */
  414. public ClickShortcut(Button button, int keyCode, int... modifiers) {
  415. super(null, keyCode, modifiers);
  416. this.button = button;
  417. }
  418. /**
  419. * Creates a keyboard shortcut for clicking the given button using the
  420. * given {@link KeyCode}.
  421. *
  422. * @param button
  423. * to be clicked when the shortcut is invoked
  424. * @param keyCode
  425. * KeyCode to react to
  426. */
  427. public ClickShortcut(Button button, int keyCode) {
  428. this(button, keyCode, null);
  429. }
  430. @Override
  431. public void handleAction(Object sender, Object target) {
  432. button.click();
  433. }
  434. }
  435. /**
  436. * Determines if a button is automatically disabled when clicked. See
  437. * {@link #setDisableOnClick(boolean)} for details.
  438. *
  439. * @return true if the button is disabled when clicked, false otherwise
  440. */
  441. public boolean isDisableOnClick() {
  442. return getState(false).disableOnClick;
  443. }
  444. /**
  445. * Determines if a button is automatically disabled when clicked. If this is
  446. * set to true the button will be automatically disabled when clicked,
  447. * typically to prevent (accidental) extra clicks on a button.
  448. * <p>
  449. * Note that this is only used when the click comes from the user, not when
  450. * calling {@link #click()} method programmatically. Also, if developer
  451. * wants to re-enable the button, it needs to be done programmatically.
  452. * </p>
  453. *
  454. * @param disableOnClick
  455. * true to disable button when it is clicked, false otherwise
  456. */
  457. public void setDisableOnClick(boolean disableOnClick) {
  458. getState().disableOnClick = disableOnClick;
  459. }
  460. @Override
  461. protected ButtonState getState() {
  462. return (ButtonState) super.getState();
  463. }
  464. @Override
  465. protected ButtonState getState(boolean markAsDirty) {
  466. return (ButtonState) super.getState(markAsDirty);
  467. }
  468. /**
  469. * Sets the component's icon and alt text.
  470. * <p>
  471. * An alt text is shown when an image could not be loaded, and read by
  472. * assistive devices.
  473. *
  474. * @param icon
  475. * the icon to be shown with the component's caption.
  476. * @param iconAltText
  477. * String to use as alt text
  478. */
  479. public void setIcon(Resource icon, String iconAltText) {
  480. super.setIcon(icon);
  481. getState().iconAltText = iconAltText == null ? "" : iconAltText;
  482. }
  483. /**
  484. * Returns the icon's alt text.
  485. *
  486. * @return String with the alt text
  487. */
  488. public String getIconAlternateText() {
  489. return getState(false).iconAltText;
  490. }
  491. public void setIconAlternateText(String iconAltText) {
  492. getState().iconAltText = iconAltText;
  493. }
  494. /**
  495. * Set whether the caption text is rendered as HTML or not. You might need
  496. * to re-theme button to allow higher content than the original text style.
  497. *
  498. * If set to true, the captions are passed to the browser as html and the
  499. * developer is responsible for ensuring no harmful html is used. If set to
  500. * false, the content is passed to the browser as plain text.
  501. *
  502. * @param htmlContentAllowed
  503. * <code>true</code> if caption is rendered as HTML,
  504. * <code>false</code> otherwise
  505. *
  506. * @deprecated as of 8.0.0, use {@link #setCaptionAsHtml(boolean)} instead.
  507. */
  508. @Deprecated
  509. public void setHtmlContentAllowed(boolean htmlContentAllowed) {
  510. getState().captionAsHtml = htmlContentAllowed;
  511. }
  512. /**
  513. * Return HTML rendering setting.
  514. *
  515. * @return <code>true</code> if the caption text is to be rendered as HTML,
  516. * <code>false</code> otherwise
  517. *
  518. * @deprecated as of 8.0.0, use {@link #isCaptionAsHtml()} instead.
  519. */
  520. @Deprecated
  521. public boolean isHtmlContentAllowed() {
  522. return getState(false).captionAsHtml;
  523. }
  524. /*
  525. * (non-Javadoc)
  526. *
  527. * @see com.vaadin.ui.AbstractComponent#readDesign(org.jsoup.nodes .Element,
  528. * com.vaadin.ui.declarative.DesignContext)
  529. */
  530. @Override
  531. public void readDesign(Element design, DesignContext designContext) {
  532. super.readDesign(design, designContext);
  533. Attributes attr = design.attributes();
  534. String content;
  535. // plain-text (default is html)
  536. Boolean plain = DesignAttributeHandler
  537. .readAttribute(DESIGN_ATTR_PLAIN_TEXT, attr, Boolean.class);
  538. if (plain == null || !plain) {
  539. setCaptionAsHtml(true);
  540. content = design.html();
  541. } else {
  542. // content is not intended to be interpreted as HTML,
  543. // so html entities need to be decoded
  544. content = DesignFormatter.decodeFromTextNode(design.html());
  545. }
  546. setCaption(content);
  547. if (attr.hasKey("icon-alt")) {
  548. setIconAlternateText(DesignAttributeHandler
  549. .readAttribute("icon-alt", attr, String.class));
  550. }
  551. // click-shortcut
  552. removeClickShortcut();
  553. ShortcutAction action = DesignAttributeHandler
  554. .readAttribute("click-shortcut", attr, ShortcutAction.class);
  555. if (action != null) {
  556. setClickShortcut(action.getKeyCode(), action.getModifiers());
  557. }
  558. }
  559. /*
  560. * (non-Javadoc)
  561. *
  562. * @see com.vaadin.ui.AbstractComponent#getCustomAttributes()
  563. */
  564. @Override
  565. protected Collection<String> getCustomAttributes() {
  566. Collection<String> result = super.getCustomAttributes();
  567. result.add(DESIGN_ATTR_PLAIN_TEXT);
  568. result.add("caption");
  569. result.add("icon-alt");
  570. result.add("icon-alternate-text");
  571. result.add("click-shortcut");
  572. result.add("html-content-allowed");
  573. result.add("caption-as-html");
  574. return result;
  575. }
  576. /*
  577. * (non-Javadoc)
  578. *
  579. * @see com.vaadin.ui.AbstractComponent#writeDesign(org.jsoup.nodes.Element
  580. * , com.vaadin.ui.declarative.DesignContext)
  581. */
  582. @Override
  583. public void writeDesign(Element design, DesignContext designContext) {
  584. super.writeDesign(design, designContext);
  585. Attributes attr = design.attributes();
  586. Button def = designContext.getDefaultInstance(this);
  587. String content = getCaption();
  588. if (content != null) {
  589. design.html(content);
  590. }
  591. // plain-text (default is html)
  592. if (!isHtmlContentAllowed()) {
  593. design.attr(DESIGN_ATTR_PLAIN_TEXT, true);
  594. // encode HTML entities
  595. if (content != null) {
  596. design.html(DesignFormatter.encodeForTextNode(content));
  597. }
  598. }
  599. // icon-alt
  600. DesignAttributeHandler.writeAttribute("icon-alt", attr,
  601. getIconAlternateText(), def.getIconAlternateText(),
  602. String.class, designContext);
  603. // click-shortcut
  604. if (clickShortcut != null) {
  605. DesignAttributeHandler.writeAttribute("click-shortcut", attr,
  606. clickShortcut, null, ShortcutAction.class, designContext);
  607. }
  608. }
  609. }