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.

AbstractComponent.java 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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.lang.reflect.Method;
  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collection;
  21. import java.util.HashSet;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.Locale;
  25. import java.util.Map;
  26. import java.util.Map.Entry;
  27. import java.util.Objects;
  28. import java.util.Set;
  29. import java.util.StringTokenizer;
  30. import org.jsoup.nodes.Attribute;
  31. import org.jsoup.nodes.Attributes;
  32. import org.jsoup.nodes.Element;
  33. import com.vaadin.data.HasValue;
  34. import com.vaadin.event.ActionManager;
  35. import com.vaadin.event.ConnectorActionManager;
  36. import com.vaadin.event.ContextClickEvent;
  37. import com.vaadin.event.ContextClickEvent.ContextClickListener;
  38. import com.vaadin.event.ContextClickEvent.ContextClickNotifier;
  39. import com.vaadin.event.ShortcutListener;
  40. import com.vaadin.server.AbstractClientConnector;
  41. import com.vaadin.server.ClientConnector;
  42. import com.vaadin.server.ComponentSizeValidator;
  43. import com.vaadin.server.ErrorMessage;
  44. import com.vaadin.server.Extension;
  45. import com.vaadin.server.Resource;
  46. import com.vaadin.server.Responsive;
  47. import com.vaadin.server.SizeWithUnit;
  48. import com.vaadin.server.Sizeable;
  49. import com.vaadin.server.UserError;
  50. import com.vaadin.server.VaadinSession;
  51. import com.vaadin.shared.AbstractComponentState;
  52. import com.vaadin.shared.AbstractFieldState;
  53. import com.vaadin.shared.ComponentConstants;
  54. import com.vaadin.shared.ContextClickRpc;
  55. import com.vaadin.shared.EventId;
  56. import com.vaadin.shared.MouseEventDetails;
  57. import com.vaadin.shared.Registration;
  58. import com.vaadin.shared.ui.ComponentStateUtil;
  59. import com.vaadin.shared.ui.ContentMode;
  60. import com.vaadin.shared.ui.ErrorLevel;
  61. import com.vaadin.shared.util.SharedUtil;
  62. import com.vaadin.ui.declarative.DesignAttributeHandler;
  63. import com.vaadin.ui.declarative.DesignContext;
  64. import com.vaadin.util.ReflectTools;
  65. /**
  66. * An abstract class that defines default implementation for the
  67. * {@link Component} interface. Basic UI components that are not derived from an
  68. * external component can inherit this class to easily qualify as Vaadin
  69. * components. Most components in Vaadin do just that.
  70. *
  71. * @author Vaadin Ltd.
  72. * @since 3.0
  73. */
  74. @SuppressWarnings("serial")
  75. public abstract class AbstractComponent extends AbstractClientConnector
  76. implements Component, ContextClickNotifier {
  77. /* Private members */
  78. /**
  79. * Application specific data object. The component does not use or modify
  80. * this.
  81. */
  82. private Object applicationData;
  83. /**
  84. * The internal error message of the component.
  85. */
  86. private ErrorMessage componentError;
  87. /**
  88. * Locale of this component.
  89. */
  90. private Locale locale;
  91. /**
  92. * The component should receive focus (if {@link Focusable}) when attached.
  93. */
  94. private boolean delayedFocus;
  95. /* Sizeable fields */
  96. private float width = SIZE_UNDEFINED;
  97. private float height = SIZE_UNDEFINED;
  98. private Unit widthUnit = Unit.PIXELS;
  99. private Unit heightUnit = Unit.PIXELS;
  100. /**
  101. * Keeps track of the Actions added to this component; the actual
  102. * handling/notifying is delegated, usually to the containing window.
  103. */
  104. private ConnectorActionManager actionManager;
  105. private boolean visible = true;
  106. private HasComponents parent;
  107. protected static final String DESIGN_ATTR_PLAIN_TEXT = "plain-text";
  108. /* Constructor */
  109. /**
  110. * Constructs a new Component.
  111. */
  112. public AbstractComponent() {
  113. // ComponentSizeValidator.setCreationLocation(this);
  114. }
  115. /* Get/Set component properties */
  116. /*
  117. * (non-Javadoc)
  118. *
  119. * @see com.vaadin.ui.Component#setId(java.lang.String)
  120. */
  121. @Override
  122. public void setId(String id) {
  123. getState().id = id;
  124. }
  125. /*
  126. * (non-Javadoc)
  127. *
  128. * @see com.vaadin.ui.Component#getId()
  129. */
  130. @Override
  131. public String getId() {
  132. return getState(false).id;
  133. }
  134. /**
  135. * @deprecated As of 7.0. Use {@link #setId(String)}
  136. */
  137. @Deprecated
  138. public void setDebugId(String id) {
  139. setId(id);
  140. }
  141. /**
  142. * @deprecated As of 7.0. Use {@link #getId()}
  143. */
  144. @Deprecated
  145. public String getDebugId() {
  146. return getId();
  147. }
  148. /*
  149. * Gets the component's style. Don't add a JavaDoc comment here, we use the
  150. * default documentation from implemented interface.
  151. */
  152. @Override
  153. public String getStyleName() {
  154. String s = "";
  155. if (ComponentStateUtil.hasStyles(getState(false))) {
  156. for (final Iterator<String> it = getState(false).styles
  157. .iterator(); it.hasNext();) {
  158. s += it.next();
  159. if (it.hasNext()) {
  160. s += " ";
  161. }
  162. }
  163. }
  164. return s;
  165. }
  166. /*
  167. * Sets the component's style. Don't add a JavaDoc comment here, we use the
  168. * default documentation from implemented interface.
  169. */
  170. @Override
  171. public void setStyleName(String style) {
  172. if (style == null || style.isEmpty()) {
  173. getState().styles = null;
  174. return;
  175. }
  176. if (getState().styles == null) {
  177. getState().styles = new ArrayList<>();
  178. }
  179. List<String> styles = getState().styles;
  180. styles.clear();
  181. StringTokenizer tokenizer = new StringTokenizer(style, " ");
  182. while (tokenizer.hasMoreTokens()) {
  183. styles.add(tokenizer.nextToken());
  184. }
  185. }
  186. @Override
  187. public void setPrimaryStyleName(String style) {
  188. getState().primaryStyleName = style;
  189. }
  190. @Override
  191. public String getPrimaryStyleName() {
  192. return getState(false).primaryStyleName;
  193. }
  194. @Override
  195. public void addStyleName(String style) {
  196. if (style == null || style.isEmpty()) {
  197. return;
  198. }
  199. if (getState().styles != null && getState().styles.contains(style)) {
  200. return;
  201. }
  202. if (style.contains(" ")) {
  203. // Split space separated style names and add them one by one.
  204. StringTokenizer tokenizer = new StringTokenizer(style, " ");
  205. while (tokenizer.hasMoreTokens()) {
  206. addStyleName(tokenizer.nextToken());
  207. }
  208. return;
  209. }
  210. if (getState().styles == null) {
  211. getState().styles = new ArrayList<>();
  212. }
  213. List<String> styles = getState().styles;
  214. styles.add(style);
  215. }
  216. @Override
  217. public void removeStyleName(String style) {
  218. if (ComponentStateUtil.hasStyles(getState())) {
  219. StringTokenizer tokenizer = new StringTokenizer(style, " ");
  220. while (tokenizer.hasMoreTokens()) {
  221. getState().styles.remove(tokenizer.nextToken());
  222. }
  223. }
  224. }
  225. /*
  226. * Get's the component's caption. Don't add a JavaDoc comment here, we use
  227. * the default documentation from implemented interface.
  228. */
  229. @Override
  230. public String getCaption() {
  231. return getState(false).caption;
  232. }
  233. @Override
  234. public void setCaption(String caption) {
  235. getState().caption = caption;
  236. }
  237. /**
  238. * Sets whether the caption is rendered as HTML.
  239. * <p>
  240. * If set to true, the captions are rendered in the browser as HTML and the
  241. * developer is responsible for ensuring no harmful HTML is used. If set to
  242. * false, the caption is rendered in the browser as plain text.
  243. * <p>
  244. * The default is false, i.e. to render that caption as plain text.
  245. *
  246. * @param captionAsHtml
  247. * true if the captions are rendered as HTML, false if rendered
  248. * as plain text
  249. */
  250. public void setCaptionAsHtml(boolean captionAsHtml) {
  251. getState().captionAsHtml = captionAsHtml;
  252. }
  253. /**
  254. * Checks whether captions are rendered as HTML
  255. * <p>
  256. * The default is false, i.e. to render that caption as plain text.
  257. *
  258. * @return true if the captions are rendered as HTML, false if rendered as
  259. * plain text
  260. */
  261. public boolean isCaptionAsHtml() {
  262. return getState(false).captionAsHtml;
  263. }
  264. /*
  265. * Don't add a JavaDoc comment here, we use the default documentation from
  266. * implemented interface.
  267. */
  268. @Override
  269. public Locale getLocale() {
  270. if (locale != null) {
  271. return locale;
  272. }
  273. HasComponents parent = getParent();
  274. if (parent != null) {
  275. return parent.getLocale();
  276. }
  277. final VaadinSession session = getSession();
  278. if (session != null) {
  279. return session.getLocale();
  280. }
  281. return null;
  282. }
  283. /**
  284. * Sets the locale of this component.
  285. *
  286. * <pre>
  287. * // Component for which the locale is meaningful
  288. * InlineDateField date = new InlineDateField(&quot;Datum&quot;);
  289. *
  290. * // German language specified with ISO 639-1 language
  291. * // code and ISO 3166-1 alpha-2 country code.
  292. * date.setLocale(new Locale(&quot;de&quot;, &quot;DE&quot;));
  293. *
  294. * date.setResolution(DateField.RESOLUTION_DAY);
  295. * layout.addComponent(date);
  296. * </pre>
  297. *
  298. *
  299. * @param locale
  300. * the locale to become this component's locale.
  301. */
  302. public void setLocale(Locale locale) {
  303. this.locale = locale;
  304. if (locale != null && isAttached()) {
  305. getUI().getLocaleService().addLocale(locale);
  306. }
  307. markAsDirty();
  308. }
  309. /*
  310. * Gets the component's icon resource. Don't add a JavaDoc comment here, we
  311. * use the default documentation from implemented interface.
  312. */
  313. @Override
  314. public Resource getIcon() {
  315. return getResource(ComponentConstants.ICON_RESOURCE);
  316. }
  317. /**
  318. * Sets the component's icon.
  319. *
  320. * @param icon
  321. * the icon to be shown with the component's caption.
  322. */
  323. @Override
  324. public void setIcon(Resource icon) {
  325. setResource(ComponentConstants.ICON_RESOURCE, icon);
  326. }
  327. /*
  328. * (non-Javadoc)
  329. *
  330. * @see com.vaadin.ui.Component#isEnabled()
  331. */
  332. @Override
  333. public boolean isEnabled() {
  334. return getState(false).enabled;
  335. }
  336. /*
  337. * (non-Javadoc)
  338. *
  339. * @see com.vaadin.ui.Component#setEnabled(boolean)
  340. */
  341. @Override
  342. public void setEnabled(boolean enabled) {
  343. getState().enabled = enabled;
  344. }
  345. /*
  346. * (non-Javadoc)
  347. *
  348. * @see com.vaadin.client.Connector#isConnectorEnabled()
  349. */
  350. @Override
  351. public boolean isConnectorEnabled() {
  352. if (!isVisible()) {
  353. return false;
  354. } else if (!isEnabled()) {
  355. return false;
  356. } else if (!super.isConnectorEnabled()) {
  357. return false;
  358. }
  359. return !(getParent() instanceof SelectiveRenderer)
  360. || ((SelectiveRenderer) getParent()).isRendered(this);
  361. }
  362. /*
  363. * (non-Javadoc)
  364. *
  365. * @see com.vaadin.ui.Component#isVisible()
  366. */
  367. @Override
  368. public boolean isVisible() {
  369. return visible;
  370. }
  371. /*
  372. * (non-Javadoc)
  373. *
  374. * @see com.vaadin.ui.Component#setVisible(boolean)
  375. */
  376. @Override
  377. public void setVisible(boolean visible) {
  378. if (isVisible() == visible) {
  379. return;
  380. }
  381. this.visible = visible;
  382. if (visible) {
  383. /*
  384. * If the visibility state is toggled from invisible to visible it
  385. * affects all children (the whole hierarchy) in addition to this
  386. * component.
  387. */
  388. markAsDirtyRecursive();
  389. }
  390. if (getParent() != null) {
  391. // Must always repaint the parent (at least the hierarchy) when
  392. // visibility of a child component changes.
  393. getParent().markAsDirty();
  394. }
  395. }
  396. /*
  397. * (non-Javadoc)
  398. *
  399. * @see com.vaadin.ui.Component#getDescription()
  400. */
  401. @Override
  402. public String getDescription() {
  403. return getState(false).description;
  404. }
  405. /**
  406. * Sets the component's description. See {@link #getDescription()} for more
  407. * information on what the description is.
  408. *
  409. * @see #setDescription(String, ContentMode)
  410. * @param description
  411. * the new description string for the component.
  412. */
  413. public void setDescription(String description) {
  414. setDescription(description, ContentMode.PREFORMATTED);
  415. }
  416. /**
  417. * Sets the component's description using given content {@code mode}. See
  418. * {@link #getDescription()} for more information on what the description
  419. * is.
  420. * <p>
  421. * If the content {@code mode} is {@literal ContentMode.HTML} the
  422. * description is displayed as HTML in tooltips or directly in certain
  423. * components so care should be taken to avoid creating the possibility for
  424. * HTML injection and possibly XSS vulnerabilities.
  425. *
  426. * @param description
  427. * the new description string for the component.
  428. * @param mode
  429. * the content mode for the description
  430. * @since 8.0
  431. */
  432. public void setDescription(String description, ContentMode mode) {
  433. getState().description = description;
  434. getState().descriptionContentMode = mode;
  435. }
  436. /*
  437. * Gets the component's parent component. Don't add a JavaDoc comment here,
  438. * we use the default documentation from implemented interface.
  439. */
  440. @Override
  441. public HasComponents getParent() {
  442. return parent;
  443. }
  444. @Override
  445. public void setParent(HasComponents parent) {
  446. // If the parent is not changed, don't do anything
  447. if (parent == null ? this.parent == null : parent.equals(this.parent)) {
  448. return;
  449. }
  450. if (parent != null && this.parent != null) {
  451. throw new IllegalStateException(
  452. getClass().getName() + " already has a parent.");
  453. }
  454. ClientConnector oldParent = getParent();
  455. // Send a detach event if the component is currently attached
  456. if (isAttached()) {
  457. detach();
  458. }
  459. // Connect to new parent
  460. this.parent = parent;
  461. // Send attach event if the component is now attached
  462. if (isAttached()) {
  463. attach();
  464. }
  465. if (oldParent != null) {
  466. oldParent.markAsDirty();
  467. }
  468. }
  469. /**
  470. * Returns the closest ancestor with the given type.
  471. * <p>
  472. * To find the Window that contains the component, use {@code Window w =
  473. * getParent(Window.class);}
  474. * </p>
  475. *
  476. * @param <T>
  477. * The type of the ancestor
  478. * @param parentType
  479. * The ancestor class we are looking for
  480. * @return The first ancestor that can be assigned to the given class. Null
  481. * if no ancestor with the correct type could be found.
  482. */
  483. public <T extends HasComponents> T findAncestor(Class<T> parentType) {
  484. HasComponents p = getParent();
  485. while (p != null) {
  486. if (parentType.isAssignableFrom(p.getClass())) {
  487. return parentType.cast(p);
  488. }
  489. p = p.getParent();
  490. }
  491. return null;
  492. }
  493. /**
  494. * Gets the error message for this component.
  495. *
  496. * @return ErrorMessage containing the description of the error state of the
  497. * component or null, if the component contains no errors. Extending
  498. * classes should override this method if they support other error
  499. * message types such as validation errors or buffering errors. The
  500. * returned error message contains information about all the errors.
  501. */
  502. public ErrorMessage getErrorMessage() {
  503. return componentError;
  504. }
  505. /**
  506. * Gets the component's error message.
  507. *
  508. * @link Terminal.ErrorMessage#ErrorMessage(String, int)
  509. *
  510. * @return the component's error message.
  511. */
  512. public ErrorMessage getComponentError() {
  513. return componentError;
  514. }
  515. /**
  516. * Sets the component's error message. The message may contain certain XML
  517. * tags, for more information see
  518. *
  519. * @link Component.ErrorMessage#ErrorMessage(String, int)
  520. *
  521. * @param componentError
  522. * the new <code>ErrorMessage</code> of the component.
  523. */
  524. public void setComponentError(ErrorMessage componentError) {
  525. this.componentError = componentError;
  526. fireComponentErrorEvent();
  527. markAsDirty();
  528. }
  529. /*
  530. * Notify the component that it's attached to a window. Don't add a JavaDoc
  531. * comment here, we use the default documentation from implemented
  532. * interface.
  533. */
  534. @Override
  535. public void attach() {
  536. super.attach();
  537. if (delayedFocus) {
  538. focus();
  539. }
  540. setActionManagerViewer();
  541. if (locale != null) {
  542. getUI().getLocaleService().addLocale(locale);
  543. }
  544. }
  545. /*
  546. * Detach the component from application. Don't add a JavaDoc comment here,
  547. * we use the default documentation from implemented interface.
  548. */
  549. @Override
  550. public void detach() {
  551. super.detach();
  552. if (actionManager != null) {
  553. // Remove any existing viewer. UI cast is just to make the
  554. // compiler happy
  555. actionManager.setViewer((UI) null);
  556. }
  557. }
  558. /**
  559. * Sets the focus for this component if the component is {@link Focusable}.
  560. */
  561. protected void focus() {
  562. if (this instanceof Focusable) {
  563. final VaadinSession session = getSession();
  564. if (session != null) {
  565. getUI().setFocusedComponent((Focusable) this);
  566. delayedFocus = false;
  567. } else {
  568. delayedFocus = true;
  569. }
  570. }
  571. }
  572. /**
  573. * Build CSS compatible string representation of height.
  574. *
  575. * @return CSS height
  576. */
  577. private String getCSSHeight() {
  578. return getHeight() + getHeightUnits().getSymbol();
  579. }
  580. /**
  581. * Build CSS compatible string representation of width.
  582. *
  583. * @return CSS width
  584. */
  585. private String getCSSWidth() {
  586. return getWidth() + getWidthUnits().getSymbol();
  587. }
  588. /**
  589. * Returns the shared state bean with information to be sent from the server
  590. * to the client.
  591. *
  592. * Subclasses should override this method and set any relevant fields of the
  593. * state returned by super.getState().
  594. *
  595. * @since 7.0
  596. *
  597. * @return updated component shared state
  598. */
  599. @Override
  600. protected AbstractComponentState getState() {
  601. return (AbstractComponentState) super.getState();
  602. }
  603. @Override
  604. protected AbstractComponentState getState(boolean markAsDirty) {
  605. return (AbstractComponentState) super.getState(markAsDirty);
  606. }
  607. @Override
  608. public void beforeClientResponse(boolean initial) {
  609. super.beforeClientResponse(initial);
  610. // TODO This logic should be on the client side and the state should
  611. // simply be a data object with "width" and "height".
  612. if (getHeight() >= 0 && (getHeightUnits() != Unit.PERCENTAGE
  613. || ComponentSizeValidator.parentCanDefineHeight(this))) {
  614. getState().height = "" + getCSSHeight();
  615. } else {
  616. getState().height = "";
  617. }
  618. if (getWidth() >= 0 && (getWidthUnits() != Unit.PERCENTAGE
  619. || ComponentSizeValidator.parentCanDefineWidth(this))) {
  620. getState().width = "" + getCSSWidth();
  621. } else {
  622. getState().width = "";
  623. }
  624. ErrorMessage error = getErrorMessage();
  625. if (null != error) {
  626. getState().errorMessage = error.getFormattedHtmlMessage();
  627. getState().errorLevel = error.getErrorLevel();
  628. } else {
  629. getState().errorMessage = null;
  630. getState().errorLevel = null;
  631. }
  632. }
  633. /* General event framework */
  634. private static final Method COMPONENT_EVENT_METHOD = ReflectTools
  635. .findMethod(Component.Listener.class, "componentEvent",
  636. Component.Event.class);
  637. /* Component event framework */
  638. /*
  639. * Registers a new listener to listen events generated by this component.
  640. * Don't add a JavaDoc comment here, we use the default documentation from
  641. * implemented interface.
  642. */
  643. @Override
  644. public Registration addListener(Component.Listener listener) {
  645. return addListener(Component.Event.class, listener,
  646. COMPONENT_EVENT_METHOD);
  647. }
  648. @Override
  649. @Deprecated
  650. public void removeListener(Component.Listener listener) {
  651. removeListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD);
  652. }
  653. /**
  654. * Emits the component event. It is transmitted to all registered listeners
  655. * interested in such events.
  656. */
  657. protected void fireComponentEvent() {
  658. fireEvent(new Component.Event(this));
  659. }
  660. /**
  661. * Emits the component error event. It is transmitted to all registered
  662. * listeners interested in such events.
  663. */
  664. protected void fireComponentErrorEvent() {
  665. fireEvent(new Component.ErrorEvent(getComponentError(), this));
  666. }
  667. /**
  668. * Sets the data object, that can be used for any application specific data.
  669. * The component does not use or modify this data.
  670. *
  671. * @param data
  672. * the Application specific data.
  673. * @since 3.1
  674. */
  675. public void setData(Object data) {
  676. applicationData = data;
  677. }
  678. /**
  679. * Gets the application specific data. See {@link #setData(Object)}.
  680. *
  681. * @return the Application specific data set with setData function.
  682. * @since 3.1
  683. */
  684. public Object getData() {
  685. return applicationData;
  686. }
  687. /* Sizeable and other size related methods */
  688. /*
  689. * (non-Javadoc)
  690. *
  691. * @see com.vaadin.Sizeable#getHeight()
  692. */
  693. @Override
  694. public float getHeight() {
  695. return height;
  696. }
  697. /*
  698. * (non-Javadoc)
  699. *
  700. * @see com.vaadin.server.Sizeable#getHeightUnits()
  701. */
  702. @Override
  703. public Unit getHeightUnits() {
  704. return heightUnit;
  705. }
  706. /*
  707. * (non-Javadoc)
  708. *
  709. * @see com.vaadin.server.Sizeable#getWidth()
  710. */
  711. @Override
  712. public float getWidth() {
  713. return width;
  714. }
  715. /*
  716. * (non-Javadoc)
  717. *
  718. * @see com.vaadin.server.Sizeable#getWidthUnits()
  719. */
  720. @Override
  721. public Unit getWidthUnits() {
  722. return widthUnit;
  723. }
  724. /*
  725. * (non-Javadoc)
  726. *
  727. * @see com.vaadin.server.Sizeable#setHeight(float, Unit)
  728. */
  729. @Override
  730. public void setHeight(float height, Unit unit) {
  731. if (unit == null) {
  732. throw new IllegalArgumentException("Unit can not be null");
  733. }
  734. this.height = height;
  735. heightUnit = unit;
  736. markAsDirty();
  737. // ComponentSizeValidator.setHeightLocation(this);
  738. }
  739. /*
  740. * (non-Javadoc)
  741. *
  742. * @see com.vaadin.server.Sizeable#setSizeFull()
  743. */
  744. @Override
  745. public void setSizeFull() {
  746. setWidth(100, Unit.PERCENTAGE);
  747. setHeight(100, Unit.PERCENTAGE);
  748. }
  749. /*
  750. * (non-Javadoc)
  751. *
  752. * @see com.vaadin.server.Sizeable#setWidthFull()
  753. */
  754. @Override
  755. public void setWidthFull() {
  756. setWidth(100, Unit.PERCENTAGE);
  757. }
  758. /*
  759. * (non-Javadoc)
  760. *
  761. * @see com.vaadin.server.Sizeable#setHeightFull()
  762. */
  763. @Override
  764. public void setHeightFull() {
  765. setHeight(100, Unit.PERCENTAGE);
  766. }
  767. /*
  768. * (non-Javadoc)
  769. *
  770. * @see com.vaadin.server.Sizeable#setSizeUndefined()
  771. */
  772. @Override
  773. public void setSizeUndefined() {
  774. setWidthUndefined();
  775. setHeightUndefined();
  776. }
  777. /*
  778. * (non-Javadoc)
  779. *
  780. * @see com.vaadin.server.Sizeable#setWidthUndefined()
  781. */
  782. @Override
  783. public void setWidthUndefined() {
  784. setWidth(-1, Unit.PIXELS);
  785. }
  786. /*
  787. * (non-Javadoc)
  788. *
  789. * @see com.vaadin.server.Sizeable#setHeightUndefined()
  790. */
  791. @Override
  792. public void setHeightUndefined() {
  793. setHeight(-1, Unit.PIXELS);
  794. }
  795. /*
  796. * (non-Javadoc)
  797. *
  798. * @see com.vaadin.server.Sizeable#setWidth(float, Unit)
  799. */
  800. @Override
  801. public void setWidth(float width, Unit unit) {
  802. if (unit == null) {
  803. throw new IllegalArgumentException("Unit can not be null");
  804. }
  805. this.width = width;
  806. widthUnit = unit;
  807. markAsDirty();
  808. // ComponentSizeValidator.setWidthLocation(this);
  809. }
  810. /*
  811. * (non-Javadoc)
  812. *
  813. * @see com.vaadin.server.Sizeable#setWidth(java.lang.String)
  814. */
  815. @Override
  816. public void setWidth(String width) {
  817. SizeWithUnit size = SizeWithUnit.parseStringSize(width);
  818. if (size != null) {
  819. setWidth(size.getSize(), size.getUnit());
  820. } else {
  821. setWidth(-1, Unit.PIXELS);
  822. }
  823. }
  824. /*
  825. * (non-Javadoc)
  826. *
  827. * @see com.vaadin.server.Sizeable#setHeight(java.lang.String)
  828. */
  829. @Override
  830. public void setHeight(String height) {
  831. SizeWithUnit size = SizeWithUnit.parseStringSize(height);
  832. if (size != null) {
  833. setHeight(size.getSize(), size.getUnit());
  834. } else {
  835. setHeight(-1, Unit.PIXELS);
  836. }
  837. }
  838. /*
  839. * (non-Javadoc)
  840. *
  841. * @see com.vaadin.ui.Component#readDesign(org.jsoup.nodes.Element,
  842. * com.vaadin.ui.declarative.DesignContext)
  843. */
  844. @Override
  845. public void readDesign(Element design, DesignContext designContext) {
  846. Attributes attr = design.attributes();
  847. // handle default attributes
  848. for (String attribute : getDefaultAttributes()) {
  849. if (design.hasAttr(attribute)) {
  850. DesignAttributeHandler.assignValue(this, attribute,
  851. design.attr(attribute));
  852. }
  853. }
  854. // handle locale
  855. if (attr.hasKey("locale")) {
  856. setLocale(getLocaleFromString(attr.get("locale")));
  857. }
  858. // handle width and height
  859. readSize(attr);
  860. // handle component error
  861. if (attr.hasKey("error")) {
  862. UserError error = new UserError(attr.get("error"),
  863. com.vaadin.server.AbstractErrorMessage.ContentMode.HTML,
  864. ErrorLevel.ERROR);
  865. setComponentError(error);
  866. }
  867. // Tab index when applicable
  868. if (design.hasAttr("tabindex") && this instanceof Focusable) {
  869. ((Focusable) this).setTabIndex(DesignAttributeHandler.readAttribute(
  870. "tabindex", design.attributes(), Integer.class));
  871. }
  872. // check for unsupported attributes
  873. Set<String> supported = new HashSet<>();
  874. supported.addAll(getDefaultAttributes());
  875. supported.addAll(getCustomAttributes());
  876. for (Attribute a : attr) {
  877. if (!a.getKey().startsWith(":")
  878. && !supported.contains(a.getKey())) {
  879. // Add unknown attributes as custom attributes to the context
  880. designContext.setCustomAttribute(this, a.getKey(),
  881. a.getValue());
  882. }
  883. }
  884. }
  885. /**
  886. * Constructs a Locale corresponding to the given string. The string should
  887. * consist of one, two or three parts with '_' between the different parts
  888. * if there is more than one part. The first part specifies the language,
  889. * the second part the country and the third part the variant of the locale.
  890. *
  891. * @param localeString
  892. * the locale specified as a string
  893. * @return the Locale object corresponding to localeString
  894. */
  895. private Locale getLocaleFromString(String localeString) {
  896. if (localeString == null) {
  897. return null;
  898. }
  899. String[] parts = localeString.split("_");
  900. if (parts.length > 3) {
  901. throw new RuntimeException(
  902. "Cannot parse the locale string: " + localeString);
  903. }
  904. switch (parts.length) {
  905. case 1:
  906. return new Locale(parts[0]);
  907. case 2:
  908. return new Locale(parts[0], parts[1]);
  909. default:
  910. return new Locale(parts[0], parts[1], parts[2]);
  911. }
  912. }
  913. /**
  914. * Toggles responsiveness of this component.
  915. *
  916. * @since 7.5.0
  917. * @param responsive
  918. * boolean enables responsiveness, false disables
  919. */
  920. public void setResponsive(boolean responsive) {
  921. if (responsive) {
  922. // make responsive if necessary
  923. if (!isResponsive()) {
  924. Responsive.makeResponsive(this);
  925. }
  926. } else {
  927. // remove responsive extensions
  928. List<Extension> extensions = new ArrayList<>(getExtensions());
  929. for (Extension e : extensions) {
  930. if (e instanceof Responsive) {
  931. removeExtension(e);
  932. }
  933. }
  934. }
  935. }
  936. /**
  937. * Returns true if the component is responsive.
  938. *
  939. * @since 7.5.0
  940. * @return true if the component is responsive
  941. */
  942. public boolean isResponsive() {
  943. for (Extension e : getExtensions()) {
  944. if (e instanceof Responsive) {
  945. return true;
  946. }
  947. }
  948. return false;
  949. }
  950. /**
  951. * Sets the read-only status in the state of this {@code AbstractComponent}.
  952. * This method should be made public in {@link Component Components} that
  953. * implement {@link HasValue}.
  954. *
  955. * @param readOnly
  956. * a boolean value specifying whether the component is put
  957. * read-only mode or not
  958. */
  959. protected void setReadOnly(boolean readOnly) {
  960. if (getState(false) instanceof AbstractFieldState) {
  961. if (readOnly != isReadOnly()) {
  962. ((AbstractFieldState) getState()).readOnly = readOnly;
  963. }
  964. } else {
  965. throw new IllegalStateException(
  966. "This component does not support the read-only mode, since state is of type "
  967. + getStateType().getSimpleName()
  968. + " and does not inherit "
  969. + AbstractFieldState.class.getSimpleName());
  970. }
  971. }
  972. /**
  973. * Returns the read-only status from the state of this
  974. * {@code AbstractComponent}. This method should be made public in
  975. * {@link Component Components} that implement {@link HasValue}.
  976. *
  977. * @return {@code true} if state has read-only on; {@code false} if not
  978. * @see #setReadOnly(boolean)
  979. */
  980. protected boolean isReadOnly() {
  981. if (getState(false) instanceof AbstractFieldState) {
  982. return ((AbstractFieldState) getState(false)).readOnly;
  983. }
  984. throw new IllegalStateException(
  985. "This component does not support the read-only mode, since state is of type "
  986. + getStateType().getSimpleName()
  987. + " and does not inherit "
  988. + AbstractFieldState.class.getSimpleName());
  989. }
  990. /**
  991. * Reads the size of this component from the given design attributes. If the
  992. * attributes do not contain relevant size information, defaults is
  993. * consulted.
  994. *
  995. * @param attributes
  996. * the design attributes
  997. */
  998. private void readSize(Attributes attributes) {
  999. // read width
  1000. if (attributes.hasKey("width-auto") || attributes.hasKey("size-auto")) {
  1001. this.setWidth(null);
  1002. } else if (attributes.hasKey("width-full")
  1003. || attributes.hasKey("size-full")) {
  1004. this.setWidth("100%");
  1005. } else if (attributes.hasKey("width")) {
  1006. this.setWidth(attributes.get("width"));
  1007. }
  1008. // read height
  1009. if (attributes.hasKey("height-auto")
  1010. || attributes.hasKey("size-auto")) {
  1011. this.setHeight(null);
  1012. } else if (attributes.hasKey("height-full")
  1013. || attributes.hasKey("size-full")) {
  1014. this.setHeight("100%");
  1015. } else if (attributes.hasKey("height")) {
  1016. this.setHeight(attributes.get("height"));
  1017. }
  1018. }
  1019. /**
  1020. * Writes the size related attributes for the component if they differ from
  1021. * the defaults
  1022. *
  1023. * @param attributes
  1024. * the attribute map where the attribute are written
  1025. * @param defaultInstance
  1026. * the default instance of the class for fetching the default
  1027. * values
  1028. */
  1029. private void writeSize(Attributes attributes, Component defaultInstance) {
  1030. if (hasEqualSize(defaultInstance)) {
  1031. // we have default values -> ignore
  1032. return;
  1033. }
  1034. boolean widthFull = getWidth() == 100f
  1035. && getWidthUnits().equals(Sizeable.Unit.PERCENTAGE);
  1036. boolean heightFull = getHeight() == 100f
  1037. && getHeightUnits().equals(Sizeable.Unit.PERCENTAGE);
  1038. boolean widthAuto = getWidth() == -1;
  1039. boolean heightAuto = getHeight() == -1;
  1040. // first try the full shorthands
  1041. if (widthFull && heightFull) {
  1042. attributes.put("size-full", true);
  1043. } else if (widthAuto && heightAuto) {
  1044. attributes.put("size-auto", true);
  1045. } else {
  1046. // handle width
  1047. if (!hasEqualWidth(defaultInstance)) {
  1048. if (widthFull) {
  1049. attributes.put("width-full", true);
  1050. } else if (widthAuto) {
  1051. attributes.put("width-auto", true);
  1052. } else {
  1053. String widthString = DesignAttributeHandler.getFormatter()
  1054. .format(getWidth()) + getWidthUnits().getSymbol();
  1055. attributes.put("width", widthString);
  1056. }
  1057. }
  1058. if (!hasEqualHeight(defaultInstance)) {
  1059. // handle height
  1060. if (heightFull) {
  1061. attributes.put("height-full", true);
  1062. } else if (heightAuto) {
  1063. attributes.put("height-auto", true);
  1064. } else {
  1065. String heightString = DesignAttributeHandler.getFormatter()
  1066. .format(getHeight()) + getHeightUnits().getSymbol();
  1067. attributes.put("height", heightString);
  1068. }
  1069. }
  1070. }
  1071. }
  1072. /**
  1073. * Test if the given component has equal width with this instance
  1074. *
  1075. * @param component
  1076. * the component for the width comparison
  1077. * @return true if the widths are equal
  1078. */
  1079. private boolean hasEqualWidth(Component component) {
  1080. return getWidth() == component.getWidth()
  1081. && getWidthUnits().equals(component.getWidthUnits());
  1082. }
  1083. /**
  1084. * Test if the given component has equal height with this instance
  1085. *
  1086. * @param component
  1087. * the component for the height comparison
  1088. * @return true if the heights are equal
  1089. */
  1090. private boolean hasEqualHeight(Component component) {
  1091. return getHeight() == component.getHeight()
  1092. && getHeightUnits().equals(component.getHeightUnits());
  1093. }
  1094. /**
  1095. * Test if the given components has equal size with this instance
  1096. *
  1097. * @param component
  1098. * the component for the size comparison
  1099. * @return true if the sizes are equal
  1100. */
  1101. private boolean hasEqualSize(Component component) {
  1102. return hasEqualWidth(component) && hasEqualHeight(component);
  1103. }
  1104. /**
  1105. * Returns a collection of attributes that do not require custom handling
  1106. * when reading or writing design. These are typically attributes of some
  1107. * primitive type. The default implementation searches setters with
  1108. * primitive values
  1109. *
  1110. * @return a collection of attributes that can be read and written using the
  1111. * default approach.
  1112. */
  1113. private Collection<String> getDefaultAttributes() {
  1114. Collection<String> attributes = DesignAttributeHandler
  1115. .getSupportedAttributes(this.getClass());
  1116. attributes.removeAll(getCustomAttributes());
  1117. return attributes;
  1118. }
  1119. /**
  1120. * Returns a collection of attributes that should not be handled by the
  1121. * basic implementation of the {@link #readDesign(Element, DesignContext)}
  1122. * and {@link #writeDesign(Element, DesignContext)} methods. Typically these
  1123. * are handled in a custom way in the overridden versions of the above
  1124. * methods
  1125. *
  1126. * @since 7.4
  1127. *
  1128. * @return the collection of attributes that are not handled by the basic
  1129. * implementation
  1130. */
  1131. protected Collection<String> getCustomAttributes() {
  1132. List<String> l = new ArrayList<>(Arrays.asList(CUSTOM_ATTRIBUTES));
  1133. if (this instanceof Focusable) {
  1134. l.add("tab-index");
  1135. l.add("tabindex");
  1136. }
  1137. return l;
  1138. }
  1139. private static final String[] CUSTOM_ATTRIBUTES = { "width", "height",
  1140. "debug-id", "error", "width-auto", "height-auto", "width-full",
  1141. "height-full", "size-auto", "size-full", "immediate", "locale",
  1142. "read-only", "_id" };
  1143. /*
  1144. * (non-Javadoc)
  1145. *
  1146. * @see com.vaadin.ui.Component#writeDesign(org.jsoup.nodes.Element,
  1147. * com.vaadin.ui.declarative.DesignContext)
  1148. */
  1149. @Override
  1150. public void writeDesign(Element design, DesignContext designContext) {
  1151. AbstractComponent def = designContext.getDefaultInstance(this);
  1152. Attributes attr = design.attributes();
  1153. // handle default attributes
  1154. for (String attribute : getDefaultAttributes()) {
  1155. DesignAttributeHandler.writeAttribute(this, attribute, attr, def,
  1156. designContext);
  1157. }
  1158. // handle locale
  1159. if (getLocale() != null && (getParent() == null
  1160. || !getLocale().equals(getParent().getLocale()))) {
  1161. design.attr("locale", getLocale().toString());
  1162. }
  1163. // handle size
  1164. writeSize(attr, def);
  1165. // handle component error
  1166. String errorMsg = getComponentError() != null
  1167. ? getComponentError().getFormattedHtmlMessage()
  1168. : null;
  1169. String defErrorMsg = def.getComponentError() != null
  1170. ? def.getComponentError().getFormattedHtmlMessage()
  1171. : null;
  1172. if (!SharedUtil.equals(errorMsg, defErrorMsg)) {
  1173. attr.put("error", errorMsg);
  1174. }
  1175. // handle tab index
  1176. if (this instanceof Focusable) {
  1177. DesignAttributeHandler.writeAttribute("tabindex", attr,
  1178. ((Focusable) this).getTabIndex(),
  1179. ((Focusable) def).getTabIndex(), Integer.class,
  1180. designContext);
  1181. }
  1182. // handle custom attributes
  1183. Map<String, String> customAttributes = designContext
  1184. .getCustomAttributes(this);
  1185. if (customAttributes != null) {
  1186. for (Entry<String, String> entry : customAttributes.entrySet()) {
  1187. attr.put(entry.getKey(), entry.getValue());
  1188. }
  1189. }
  1190. }
  1191. /*
  1192. * Actions
  1193. */
  1194. /**
  1195. * Gets the {@link ActionManager} used to manage the
  1196. * {@link ShortcutListener}s added to this component.
  1197. *
  1198. * @return the ActionManager in use
  1199. */
  1200. protected ActionManager getActionManager() {
  1201. if (actionManager == null) {
  1202. actionManager = new ConnectorActionManager(this);
  1203. setActionManagerViewer();
  1204. }
  1205. return actionManager;
  1206. }
  1207. /**
  1208. * Set a viewer for the action manager to be the parent sub window (if the
  1209. * component is in a window) or the UI (otherwise). This is still a
  1210. * simplification of the real case as this should be handled by the parent
  1211. * VOverlay (on the client side) if the component is inside an VOverlay
  1212. * component.
  1213. */
  1214. private void setActionManagerViewer() {
  1215. if (actionManager != null && getUI() != null) {
  1216. // Attached and has action manager
  1217. Window w = findAncestor(Window.class);
  1218. if (w != null) {
  1219. actionManager.setViewer(w);
  1220. } else {
  1221. actionManager.setViewer(getUI());
  1222. }
  1223. }
  1224. }
  1225. public Registration addShortcutListener(ShortcutListener shortcut) {
  1226. Objects.requireNonNull(shortcut, "Listener must not be null.");
  1227. getActionManager().addAction(shortcut);
  1228. return () -> getActionManager().removeAction(shortcut);
  1229. }
  1230. @Deprecated
  1231. public void removeShortcutListener(ShortcutListener shortcut) {
  1232. getActionManager().removeAction(shortcut);
  1233. }
  1234. /**
  1235. * Determine whether a <code>content</code> component is equal to, or the
  1236. * ancestor of this component.
  1237. *
  1238. * @param content
  1239. * the potential ancestor element
  1240. * @return <code>true</code> if the relationship holds
  1241. */
  1242. protected boolean isOrHasAncestor(Component content) {
  1243. if (content instanceof HasComponents) {
  1244. for (Component parent = this; parent != null; parent = parent
  1245. .getParent()) {
  1246. if (parent.equals(content)) {
  1247. return true;
  1248. }
  1249. }
  1250. }
  1251. return false;
  1252. }
  1253. @Override
  1254. public Registration addContextClickListener(ContextClickListener listener) {
  1255. // Register default Context Click RPC if needed. This RPC won't be
  1256. // called if there are no listeners on the server-side. A client-side
  1257. // connector can override this and use a different RPC channel.
  1258. if (getRpcManager(ContextClickRpc.class.getName()) == null) {
  1259. registerRpc(
  1260. (ContextClickRpc) (MouseEventDetails details) -> fireEvent(
  1261. new ContextClickEvent(AbstractComponent.this,
  1262. details)));
  1263. }
  1264. return addListener(EventId.CONTEXT_CLICK, ContextClickEvent.class,
  1265. listener, ContextClickEvent.CONTEXT_CLICK_METHOD);
  1266. }
  1267. @Override
  1268. @Deprecated
  1269. public void removeContextClickListener(ContextClickListener listener) {
  1270. removeListener(EventId.CONTEXT_CLICK, ContextClickEvent.class,
  1271. listener);
  1272. }
  1273. /**
  1274. * Sets the visibility of the required indicator. <strong>NOTE: Does not
  1275. * apply for all components!</strong>.
  1276. * <p>
  1277. * If the component supports the required indicator (state extends
  1278. * {@link AbstractFieldState}), then expose this method and
  1279. * {@link #isRequiredIndicatorVisible()} as {@code public} in the component
  1280. * and call this method.
  1281. * <p>
  1282. * This method will throw a {@link IllegalStateException} if the component
  1283. * state (returned by {@link #getState()}) does not inherit
  1284. * {@link AbstractFieldState}.
  1285. *
  1286. * @param visible
  1287. * <code>true</code> to make the required indicator visible,
  1288. * <code>false</code> if not
  1289. * @since 8.0
  1290. */
  1291. protected void setRequiredIndicatorVisible(boolean visible) {
  1292. if (getState(false) instanceof AbstractFieldState) {
  1293. ((AbstractFieldState) getState()).required = visible;
  1294. } else {
  1295. throw new IllegalStateException(
  1296. "This component does not support the required indicator, since state is of type "
  1297. + getStateType().getSimpleName()
  1298. + " and does not inherit "
  1299. + AbstractFieldState.class.getSimpleName());
  1300. }
  1301. }
  1302. /**
  1303. * Checks whether the required indicator is visible or not. <strong>NOTE:
  1304. * Does not apply for all components!</strong>.
  1305. * <p>
  1306. * This method will throw a {@link IllegalStateException} if the component
  1307. * state (returned by {@link #getState()}) does not inherit
  1308. * {@link AbstractFieldState}.
  1309. *
  1310. * @return <code>true</code> if visible, <code>false</code> if not
  1311. * @see #setRequiredIndicatorVisible(boolean)
  1312. * @since 8.0
  1313. */
  1314. protected boolean isRequiredIndicatorVisible() {
  1315. if (getState(false) instanceof AbstractFieldState) {
  1316. return ((AbstractFieldState) getState(false)).required;
  1317. }
  1318. throw new IllegalStateException(
  1319. "This component does not support the required indicator, since state is of type "
  1320. + getStateType().getSimpleName()
  1321. + " and does not inherit "
  1322. + AbstractFieldState.class.getSimpleName());
  1323. }
  1324. }