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

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