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 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.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 java.util.logging.Logger;
  31. import org.jsoup.nodes.Attribute;
  32. import org.jsoup.nodes.Attributes;
  33. import org.jsoup.nodes.Element;
  34. import com.vaadin.data.HasValue;
  35. import com.vaadin.event.ActionManager;
  36. import com.vaadin.event.ConnectorActionManager;
  37. import com.vaadin.event.ContextClickEvent;
  38. import com.vaadin.event.ContextClickEvent.ContextClickListener;
  39. import com.vaadin.event.ContextClickEvent.ContextClickNotifier;
  40. import com.vaadin.event.ShortcutListener;
  41. import com.vaadin.server.AbstractClientConnector;
  42. import com.vaadin.server.AbstractErrorMessage.ContentMode;
  43. import com.vaadin.server.ComponentSizeValidator;
  44. import com.vaadin.server.ErrorMessage;
  45. import com.vaadin.server.ErrorMessage.ErrorLevel;
  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.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 = null;
  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 || "".equals(style)) {
  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 || "".equals(style)) {
  197. return;
  198. }
  199. if (style.contains(" ")) {
  200. // Split space separated style names and add them one by one.
  201. StringTokenizer tokenizer = new StringTokenizer(style, " ");
  202. while (tokenizer.hasMoreTokens()) {
  203. addStyleName(tokenizer.nextToken());
  204. }
  205. return;
  206. }
  207. if (getState().styles == null) {
  208. getState().styles = new ArrayList<>();
  209. }
  210. List<String> styles = getState().styles;
  211. if (!styles.contains(style)) {
  212. styles.add(style);
  213. }
  214. }
  215. @Override
  216. public void removeStyleName(String style) {
  217. if (ComponentStateUtil.hasStyles(getState())) {
  218. StringTokenizer tokenizer = new StringTokenizer(style, " ");
  219. while (tokenizer.hasMoreTokens()) {
  220. getState().styles.remove(tokenizer.nextToken());
  221. }
  222. }
  223. }
  224. /**
  225. * Adds or removes a style name. Multiple styles can be specified as a
  226. * space-separated list of style names.
  227. *
  228. * If the {@code add} parameter is true, the style name is added to the
  229. * component. If the {@code add} parameter is false, the style name is
  230. * removed from the component.
  231. * <p>
  232. * Functionally this is equivalent to using {@link #addStyleName(String)} or
  233. * {@link #removeStyleName(String)}
  234. *
  235. * @since 7.5
  236. * @param style
  237. * the style name to be added or removed
  238. * @param add
  239. * <code>true</code> to add the given style, <code>false</code>
  240. * to remove it
  241. * @see #addStyleName(String)
  242. * @see #removeStyleName(String)
  243. */
  244. public void setStyleName(String style, boolean add) {
  245. if (add) {
  246. addStyleName(style);
  247. } else {
  248. removeStyleName(style);
  249. }
  250. }
  251. /*
  252. * Get's the component's caption. Don't add a JavaDoc comment here, we use
  253. * the default documentation from implemented interface.
  254. */
  255. @Override
  256. public String getCaption() {
  257. return getState(false).caption;
  258. }
  259. /**
  260. * Sets the component's caption <code>String</code>. Caption is the visible
  261. * name of the component.
  262. *
  263. * @param caption
  264. * the new caption <code>String</code> for the component.
  265. */
  266. @Override
  267. public void setCaption(String caption) {
  268. getState().caption = caption;
  269. }
  270. /**
  271. * Sets whether the caption is rendered as HTML.
  272. * <p>
  273. * If set to true, the captions are rendered in the browser as HTML and the
  274. * developer is responsible for ensuring no harmful HTML is used. If set to
  275. * false, the caption is rendered in the browser as plain text.
  276. * <p>
  277. * The default is false, i.e. to render that caption as plain text.
  278. *
  279. * @param captionAsHtml
  280. * true if the captions are rendered as HTML, false if rendered
  281. * as plain text
  282. */
  283. public void setCaptionAsHtml(boolean captionAsHtml) {
  284. getState().captionAsHtml = captionAsHtml;
  285. }
  286. /**
  287. * Checks whether captions are rendered as HTML
  288. * <p>
  289. * The default is false, i.e. to render that caption as plain text.
  290. *
  291. * @return true if the captions are rendered as HTML, false if rendered as
  292. * plain text
  293. */
  294. public boolean isCaptionAsHtml() {
  295. return getState(false).captionAsHtml;
  296. }
  297. /*
  298. * Don't add a JavaDoc comment here, we use the default documentation from
  299. * implemented interface.
  300. */
  301. @Override
  302. public Locale getLocale() {
  303. if (locale != null) {
  304. return locale;
  305. }
  306. HasComponents parent = getParent();
  307. if (parent != null) {
  308. return parent.getLocale();
  309. }
  310. final VaadinSession session = getSession();
  311. if (session != null) {
  312. return session.getLocale();
  313. }
  314. return null;
  315. }
  316. /**
  317. * Sets the locale of this component.
  318. *
  319. * <pre>
  320. * // Component for which the locale is meaningful
  321. * InlineDateField date = new InlineDateField(&quot;Datum&quot;);
  322. *
  323. * // German language specified with ISO 639-1 language
  324. * // code and ISO 3166-1 alpha-2 country code.
  325. * date.setLocale(new Locale(&quot;de&quot;, &quot;DE&quot;));
  326. *
  327. * date.setResolution(DateField.RESOLUTION_DAY);
  328. * layout.addComponent(date);
  329. * </pre>
  330. *
  331. *
  332. * @param locale
  333. * the locale to become this component's locale.
  334. */
  335. public void setLocale(Locale locale) {
  336. this.locale = locale;
  337. if (locale != null && isAttached()) {
  338. getUI().getLocaleService().addLocale(locale);
  339. }
  340. markAsDirty();
  341. }
  342. /*
  343. * Gets the component's icon resource. Don't add a JavaDoc comment here, we
  344. * use the default documentation from implemented interface.
  345. */
  346. @Override
  347. public Resource getIcon() {
  348. return getResource(ComponentConstants.ICON_RESOURCE);
  349. }
  350. /**
  351. * Sets the component's icon.
  352. *
  353. * @param icon
  354. * the icon to be shown with the component's caption.
  355. */
  356. @Override
  357. public void setIcon(Resource icon) {
  358. setResource(ComponentConstants.ICON_RESOURCE, icon);
  359. }
  360. /*
  361. * (non-Javadoc)
  362. *
  363. * @see com.vaadin.ui.Component#isEnabled()
  364. */
  365. @Override
  366. public boolean isEnabled() {
  367. return getState(false).enabled;
  368. }
  369. /*
  370. * (non-Javadoc)
  371. *
  372. * @see com.vaadin.ui.Component#setEnabled(boolean)
  373. */
  374. @Override
  375. public void setEnabled(boolean enabled) {
  376. getState().enabled = enabled;
  377. }
  378. /*
  379. * (non-Javadoc)
  380. *
  381. * @see com.vaadin.client.Connector#isConnectorEnabled()
  382. */
  383. @Override
  384. public boolean isConnectorEnabled() {
  385. if (!isVisible()) {
  386. return false;
  387. } else if (!isEnabled()) {
  388. return false;
  389. } else if (!super.isConnectorEnabled()) {
  390. return false;
  391. } else if (getParent() instanceof SelectiveRenderer
  392. && !((SelectiveRenderer) getParent()).isRendered(this)) {
  393. return false;
  394. } else {
  395. return true;
  396. }
  397. }
  398. /*
  399. * (non-Javadoc)
  400. *
  401. * @see com.vaadin.ui.Component#isVisible()
  402. */
  403. @Override
  404. public boolean isVisible() {
  405. return visible;
  406. }
  407. /*
  408. * (non-Javadoc)
  409. *
  410. * @see com.vaadin.ui.Component#setVisible(boolean)
  411. */
  412. @Override
  413. public void setVisible(boolean visible) {
  414. if (isVisible() == visible) {
  415. return;
  416. }
  417. this.visible = visible;
  418. if (visible) {
  419. /*
  420. * If the visibility state is toggled from invisible to visible it
  421. * affects all children (the whole hierarchy) in addition to this
  422. * component.
  423. */
  424. markAsDirtyRecursive();
  425. }
  426. if (getParent() != null) {
  427. // Must always repaint the parent (at least the hierarchy) when
  428. // visibility of a child component changes.
  429. getParent().markAsDirty();
  430. }
  431. }
  432. /*
  433. * (non-Javadoc)
  434. *
  435. * @see com.vaadin.ui.Component#getDescription()
  436. */
  437. @Override
  438. public String getDescription() {
  439. return getState(false).description;
  440. }
  441. /**
  442. * Sets the component's description. See {@link #getDescription()} for more
  443. * information on what the description is. This method will trigger a
  444. * {@link RepaintRequestEvent}.
  445. *
  446. * The description is displayed as HTML in tooltips or directly in certain
  447. * components so care should be taken to avoid creating the possibility for
  448. * HTML injection and possibly XSS vulnerabilities.
  449. *
  450. * @param description
  451. * the new description string for the component.
  452. */
  453. public void setDescription(String description) {
  454. getState().description = description;
  455. }
  456. /*
  457. * Gets the component's parent component. Don't add a JavaDoc comment here,
  458. * we use the default documentation from implemented interface.
  459. */
  460. @Override
  461. public HasComponents getParent() {
  462. return parent;
  463. }
  464. @Override
  465. public void setParent(HasComponents parent) {
  466. // If the parent is not changed, don't do anything
  467. if (parent == null ? this.parent == null : parent.equals(this.parent)) {
  468. return;
  469. }
  470. if (parent != null && this.parent != null) {
  471. throw new IllegalStateException(
  472. getClass().getName() + " already has a parent.");
  473. }
  474. // Send a detach event if the component is currently attached
  475. if (isAttached()) {
  476. detach();
  477. }
  478. // Connect to new parent
  479. this.parent = parent;
  480. // Send attach event if the component is now attached
  481. if (isAttached()) {
  482. attach();
  483. }
  484. }
  485. /**
  486. * Returns the closest ancestor with the given type.
  487. * <p>
  488. * To find the Window that contains the component, use {@code Window w =
  489. * getParent(Window.class);}
  490. * </p>
  491. *
  492. * @param <T>
  493. * The type of the ancestor
  494. * @param parentType
  495. * The ancestor class we are looking for
  496. * @return The first ancestor that can be assigned to the given class. Null
  497. * if no ancestor with the correct type could be found.
  498. */
  499. public <T extends HasComponents> T findAncestor(Class<T> parentType) {
  500. HasComponents p = getParent();
  501. while (p != null) {
  502. if (parentType.isAssignableFrom(p.getClass())) {
  503. return parentType.cast(p);
  504. }
  505. p = p.getParent();
  506. }
  507. return null;
  508. }
  509. /**
  510. * Gets the error message for this component.
  511. *
  512. * @return ErrorMessage containing the description of the error state of the
  513. * component or null, if the component contains no errors. Extending
  514. * classes should override this method if they support other error
  515. * message types such as validation errors or buffering errors. The
  516. * returned error message contains information about all the errors.
  517. */
  518. public ErrorMessage getErrorMessage() {
  519. return componentError;
  520. }
  521. /**
  522. * Gets the component's error message.
  523. *
  524. * @link Terminal.ErrorMessage#ErrorMessage(String, int)
  525. *
  526. * @return the component's error message.
  527. */
  528. public ErrorMessage getComponentError() {
  529. return componentError;
  530. }
  531. /**
  532. * Sets the component's error message. The message may contain certain XML
  533. * tags, for more information see
  534. *
  535. * @link Component.ErrorMessage#ErrorMessage(String, int)
  536. *
  537. * @param componentError
  538. * the new <code>ErrorMessage</code> of the component.
  539. */
  540. public void setComponentError(ErrorMessage componentError) {
  541. this.componentError = componentError;
  542. fireComponentErrorEvent();
  543. markAsDirty();
  544. }
  545. /*
  546. * Notify the component that it's attached to a window. Don't add a JavaDoc
  547. * comment here, we use the default documentation from implemented
  548. * interface.
  549. */
  550. @Override
  551. public void attach() {
  552. super.attach();
  553. if (delayedFocus) {
  554. focus();
  555. }
  556. setActionManagerViewer();
  557. if (locale != null) {
  558. getUI().getLocaleService().addLocale(locale);
  559. }
  560. }
  561. /*
  562. * Detach the component from application. Don't add a JavaDoc comment here,
  563. * we use the default documentation from implemented interface.
  564. */
  565. @Override
  566. public void detach() {
  567. super.detach();
  568. if (actionManager != null) {
  569. // Remove any existing viewer. UI cast is just to make the
  570. // compiler happy
  571. actionManager.setViewer((UI) null);
  572. }
  573. }
  574. /**
  575. * Sets the focus for this component if the component is {@link Focusable}.
  576. */
  577. protected void focus() {
  578. if (this instanceof Focusable) {
  579. final VaadinSession session = getSession();
  580. if (session != null) {
  581. getUI().setFocusedComponent((Focusable) this);
  582. delayedFocus = false;
  583. } else {
  584. delayedFocus = true;
  585. }
  586. }
  587. }
  588. /**
  589. * Build CSS compatible string representation of height.
  590. *
  591. * @return CSS height
  592. */
  593. private String getCSSHeight() {
  594. return getHeight() + getHeightUnits().getSymbol();
  595. }
  596. /**
  597. * Build CSS compatible string representation of width.
  598. *
  599. * @return CSS width
  600. */
  601. private String getCSSWidth() {
  602. return getWidth() + getWidthUnits().getSymbol();
  603. }
  604. /**
  605. * Returns the shared state bean with information to be sent from the server
  606. * to the client.
  607. *
  608. * Subclasses should override this method and set any relevant fields of the
  609. * state returned by super.getState().
  610. *
  611. * @since 7.0
  612. *
  613. * @return updated component shared state
  614. */
  615. @Override
  616. protected AbstractComponentState getState() {
  617. return (AbstractComponentState) super.getState();
  618. }
  619. @Override
  620. protected AbstractComponentState getState(boolean markAsDirty) {
  621. return (AbstractComponentState) super.getState(markAsDirty);
  622. }
  623. @Override
  624. public void beforeClientResponse(boolean initial) {
  625. super.beforeClientResponse(initial);
  626. // TODO This logic should be on the client side and the state should
  627. // simply be a data object with "width" and "height".
  628. if (getHeight() >= 0 && (getHeightUnits() != Unit.PERCENTAGE
  629. || ComponentSizeValidator.parentCanDefineHeight(this))) {
  630. getState().height = "" + getCSSHeight();
  631. } else {
  632. getState().height = "";
  633. }
  634. if (getWidth() >= 0 && (getWidthUnits() != Unit.PERCENTAGE
  635. || ComponentSizeValidator.parentCanDefineWidth(this))) {
  636. getState().width = "" + getCSSWidth();
  637. } else {
  638. getState().width = "";
  639. }
  640. ErrorMessage error = getErrorMessage();
  641. if (null != error) {
  642. getState().errorMessage = error.getFormattedHtmlMessage();
  643. } else {
  644. getState().errorMessage = null;
  645. }
  646. }
  647. /* General event framework */
  648. private static final Method COMPONENT_EVENT_METHOD = ReflectTools
  649. .findMethod(Component.Listener.class, "componentEvent",
  650. Component.Event.class);
  651. /* Component event framework */
  652. /*
  653. * Registers a new listener to listen events generated by this component.
  654. * Don't add a JavaDoc comment here, we use the default documentation from
  655. * implemented interface.
  656. */
  657. @Override
  658. public Registration addListener(Component.Listener listener) {
  659. addListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD);
  660. return () -> removeListener(Component.Event.class, listener,
  661. COMPONENT_EVENT_METHOD);
  662. }
  663. @Override
  664. @Deprecated
  665. public void removeListener(Component.Listener listener) {
  666. removeListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD);
  667. }
  668. /**
  669. * Emits the component event. It is transmitted to all registered listeners
  670. * interested in such events.
  671. */
  672. protected void fireComponentEvent() {
  673. fireEvent(new Component.Event(this));
  674. }
  675. /**
  676. * Emits the component error event. It is transmitted to all registered
  677. * listeners interested in such events.
  678. */
  679. protected void fireComponentErrorEvent() {
  680. fireEvent(new Component.ErrorEvent(getComponentError(), this));
  681. }
  682. /**
  683. * Sets the data object, that can be used for any application specific data.
  684. * The component does not use or modify this data.
  685. *
  686. * @param data
  687. * the Application specific data.
  688. * @since 3.1
  689. */
  690. public void setData(Object data) {
  691. applicationData = data;
  692. }
  693. /**
  694. * Gets the application specific data. See {@link #setData(Object)}.
  695. *
  696. * @return the Application specific data set with setData function.
  697. * @since 3.1
  698. */
  699. public Object getData() {
  700. return applicationData;
  701. }
  702. /* Sizeable and other size related methods */
  703. /*
  704. * (non-Javadoc)
  705. *
  706. * @see com.vaadin.Sizeable#getHeight()
  707. */
  708. @Override
  709. public float getHeight() {
  710. return height;
  711. }
  712. /*
  713. * (non-Javadoc)
  714. *
  715. * @see com.vaadin.server.Sizeable#getHeightUnits()
  716. */
  717. @Override
  718. public Unit getHeightUnits() {
  719. return heightUnit;
  720. }
  721. /*
  722. * (non-Javadoc)
  723. *
  724. * @see com.vaadin.server.Sizeable#getWidth()
  725. */
  726. @Override
  727. public float getWidth() {
  728. return width;
  729. }
  730. /*
  731. * (non-Javadoc)
  732. *
  733. * @see com.vaadin.server.Sizeable#getWidthUnits()
  734. */
  735. @Override
  736. public Unit getWidthUnits() {
  737. return widthUnit;
  738. }
  739. /*
  740. * (non-Javadoc)
  741. *
  742. * @see com.vaadin.server.Sizeable#setHeight(float, Unit)
  743. */
  744. @Override
  745. public void setHeight(float height, Unit unit) {
  746. if (unit == null) {
  747. throw new IllegalArgumentException("Unit can not be null");
  748. }
  749. this.height = height;
  750. heightUnit = unit;
  751. markAsDirty();
  752. // ComponentSizeValidator.setHeightLocation(this);
  753. }
  754. /*
  755. * (non-Javadoc)
  756. *
  757. * @see com.vaadin.server.Sizeable#setSizeFull()
  758. */
  759. @Override
  760. public void setSizeFull() {
  761. setWidth(100, Unit.PERCENTAGE);
  762. setHeight(100, Unit.PERCENTAGE);
  763. }
  764. /*
  765. * (non-Javadoc)
  766. *
  767. * @see com.vaadin.server.Sizeable#setSizeUndefined()
  768. */
  769. @Override
  770. public void setSizeUndefined() {
  771. setWidthUndefined();
  772. setHeightUndefined();
  773. }
  774. /*
  775. * (non-Javadoc)
  776. *
  777. * @see com.vaadin.server.Sizeable#setWidthUndefined()
  778. */
  779. @Override
  780. public void setWidthUndefined() {
  781. setWidth(-1, Unit.PIXELS);
  782. }
  783. /*
  784. * (non-Javadoc)
  785. *
  786. * @see com.vaadin.server.Sizeable#setHeightUndefined()
  787. */
  788. @Override
  789. public void setHeightUndefined() {
  790. setHeight(-1, Unit.PIXELS);
  791. }
  792. /*
  793. * (non-Javadoc)
  794. *
  795. * @see com.vaadin.server.Sizeable#setWidth(float, Unit)
  796. */
  797. @Override
  798. public void setWidth(float width, Unit unit) {
  799. if (unit == null) {
  800. throw new IllegalArgumentException("Unit can not be null");
  801. }
  802. this.width = width;
  803. widthUnit = unit;
  804. markAsDirty();
  805. // ComponentSizeValidator.setWidthLocation(this);
  806. }
  807. /*
  808. * (non-Javadoc)
  809. *
  810. * @see com.vaadin.server.Sizeable#setWidth(java.lang.String)
  811. */
  812. @Override
  813. public void setWidth(String width) {
  814. SizeWithUnit size = SizeWithUnit.parseStringSize(width);
  815. if (size != null) {
  816. setWidth(size.getSize(), size.getUnit());
  817. } else {
  818. setWidth(-1, Unit.PIXELS);
  819. }
  820. }
  821. /*
  822. * (non-Javadoc)
  823. *
  824. * @see com.vaadin.server.Sizeable#setHeight(java.lang.String)
  825. */
  826. @Override
  827. public void setHeight(String height) {
  828. SizeWithUnit size = SizeWithUnit.parseStringSize(height);
  829. if (size != null) {
  830. setHeight(size.getSize(), size.getUnit());
  831. } else {
  832. setHeight(-1, Unit.PIXELS);
  833. }
  834. }
  835. /*
  836. * (non-Javadoc)
  837. *
  838. * @see com.vaadin.ui.Component#readDesign(org.jsoup.nodes.Element,
  839. * com.vaadin.ui.declarative.DesignContext)
  840. */
  841. @Override
  842. public void readDesign(Element design, DesignContext designContext) {
  843. Attributes attr = design.attributes();
  844. // handle default attributes
  845. for (String attribute : getDefaultAttributes()) {
  846. if (design.hasAttr(attribute)) {
  847. DesignAttributeHandler.assignValue(this, attribute,
  848. design.attr(attribute));
  849. }
  850. }
  851. // handle locale
  852. if (attr.hasKey("locale")) {
  853. setLocale(getLocaleFromString(attr.get("locale")));
  854. }
  855. // handle width and height
  856. readSize(attr);
  857. // handle component error
  858. if (attr.hasKey("error")) {
  859. UserError error = new UserError(attr.get("error"), ContentMode.HTML,
  860. ErrorLevel.ERROR);
  861. setComponentError(error);
  862. }
  863. // Tab index when applicable
  864. if (design.hasAttr("tabindex") && this instanceof Focusable) {
  865. ((Focusable) this).setTabIndex(DesignAttributeHandler.readAttribute(
  866. "tabindex", design.attributes(), Integer.class));
  867. }
  868. // check for unsupported attributes
  869. Set<String> supported = new HashSet<>();
  870. supported.addAll(getDefaultAttributes());
  871. supported.addAll(getCustomAttributes());
  872. for (Attribute a : attr) {
  873. if (!a.getKey().startsWith(":")
  874. && !supported.contains(a.getKey())) {
  875. // Add unknown attributes as custom attributes to the context
  876. designContext.setCustomAttribute(this, a.getKey(),
  877. a.getValue());
  878. }
  879. }
  880. }
  881. /**
  882. * Constructs a Locale corresponding to the given string. The string should
  883. * consist of one, two or three parts with '_' between the different parts
  884. * if there is more than one part. The first part specifies the language,
  885. * the second part the country and the third part the variant of the locale.
  886. *
  887. * @param localeString
  888. * the locale specified as a string
  889. * @return the Locale object corresponding to localeString
  890. */
  891. private Locale getLocaleFromString(String localeString) {
  892. if (localeString == null) {
  893. return null;
  894. }
  895. String[] parts = localeString.split("_");
  896. if (parts.length > 3) {
  897. throw new RuntimeException(
  898. "Cannot parse the locale string: " + localeString);
  899. }
  900. switch (parts.length) {
  901. case 1:
  902. return new Locale(parts[0]);
  903. case 2:
  904. return new Locale(parts[0], parts[1]);
  905. default:
  906. return new Locale(parts[0], parts[1], parts[2]);
  907. }
  908. }
  909. /**
  910. * Toggles responsiveness of this component.
  911. *
  912. * @since 7.5.0
  913. * @param responsive
  914. * boolean enables responsiveness, false disables
  915. */
  916. public void setResponsive(boolean responsive) {
  917. if (responsive) {
  918. // make responsive if necessary
  919. if (!isResponsive()) {
  920. Responsive.makeResponsive(this);
  921. }
  922. } else {
  923. // remove responsive extensions
  924. List<Extension> extensions = new ArrayList<>(getExtensions());
  925. for (Extension e : extensions) {
  926. if (e instanceof Responsive) {
  927. removeExtension(e);
  928. }
  929. }
  930. }
  931. }
  932. /**
  933. * Returns true if the component is responsive.
  934. *
  935. * @since 7.5.0
  936. * @return true if the component is responsive
  937. */
  938. public boolean isResponsive() {
  939. for (Extension e : getExtensions()) {
  940. if (e instanceof Responsive) {
  941. return true;
  942. }
  943. }
  944. return false;
  945. }
  946. /**
  947. * Sets the read-only status in the state of this {@code AbstractComponent}.
  948. * This method should be made public in {@link Component Components} that
  949. * implement {@link HasValue}.
  950. *
  951. * @param readOnly
  952. * a boolean value specifying whether the component is put
  953. * read-only mode or not
  954. */
  955. protected void setReadOnly(boolean readOnly) {
  956. if (getState(false) instanceof AbstractFieldState) {
  957. if (readOnly != isReadOnly()) {
  958. ((AbstractFieldState) getState()).readOnly = readOnly;
  959. }
  960. } else {
  961. throw new IllegalStateException(
  962. "This component does not support the read-only mode, since state is of type "
  963. + getStateType().getSimpleName()
  964. + " and does not inherit "
  965. + AbstractFieldState.class.getSimpleName());
  966. }
  967. }
  968. /**
  969. * Returns the read-only status from the state of this
  970. * {@code AbstractComponent}. This method should be made public in
  971. * {@link Component Components} that implement {@link HasValue}.
  972. *
  973. * @return {@code true} if state has read-only on; {@code false} if not
  974. * @see #setReadOnly(boolean)
  975. */
  976. protected boolean isReadOnly() {
  977. if (getState(false) instanceof AbstractFieldState) {
  978. return ((AbstractFieldState) getState(false)).readOnly;
  979. }
  980. throw new IllegalStateException(
  981. "This component does not support the read-only mode, since state is of type "
  982. + getStateType().getSimpleName()
  983. + " and does not inherit "
  984. + AbstractFieldState.class.getSimpleName());
  985. }
  986. /**
  987. * Reads the size of this component from the given design attributes. If the
  988. * attributes do not contain relevant size information, defaults is
  989. * consulted.
  990. *
  991. * @param attributes
  992. * the design attributes
  993. * @param defaultInstance
  994. * instance of the class that has default sizing.
  995. */
  996. private void readSize(Attributes attributes) {
  997. // read width
  998. if (attributes.hasKey("width-auto") || attributes.hasKey("size-auto")) {
  999. this.setWidth(null);
  1000. } else if (attributes.hasKey("width-full")
  1001. || attributes.hasKey("size-full")) {
  1002. this.setWidth("100%");
  1003. } else if (attributes.hasKey("width")) {
  1004. this.setWidth(attributes.get("width"));
  1005. }
  1006. // read height
  1007. if (attributes.hasKey("height-auto")
  1008. || attributes.hasKey("size-auto")) {
  1009. this.setHeight(null);
  1010. } else if (attributes.hasKey("height-full")
  1011. || attributes.hasKey("size-full")) {
  1012. this.setHeight("100%");
  1013. } else if (attributes.hasKey("height")) {
  1014. this.setHeight(attributes.get("height"));
  1015. }
  1016. }
  1017. /**
  1018. * Writes the size related attributes for the component if they differ from
  1019. * the defaults
  1020. *
  1021. * @param component
  1022. * the component
  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} and {@link writeDesign}
  1122. * methods. Typically these are handled in a custom way in the overridden
  1123. * versions of the above methods
  1124. *
  1125. * @since 7.4
  1126. *
  1127. * @return the collection of attributes that are not handled by the basic
  1128. * implementation
  1129. */
  1130. protected Collection<String> getCustomAttributes() {
  1131. ArrayList<String> l = new ArrayList<>(Arrays.asList(customAttributes));
  1132. if (this instanceof Focusable) {
  1133. l.add("tab-index");
  1134. l.add("tabindex");
  1135. }
  1136. return l;
  1137. }
  1138. private static final String[] customAttributes = new String[] { "width",
  1139. "height", "debug-id", "error", "width-auto", "height-auto",
  1140. "width-full", "height-full", "size-auto", "size-full", "immediate",
  1141. "locale", "read-only", "_id" };
  1142. /*
  1143. * (non-Javadoc)
  1144. *
  1145. * @see com.vaadin.ui.Component#writeDesign(org.jsoup.nodes.Element,
  1146. * com.vaadin.ui.declarative.DesignContext)
  1147. */
  1148. @Override
  1149. public void writeDesign(Element design, DesignContext designContext) {
  1150. AbstractComponent def = designContext.getDefaultInstance(this);
  1151. Attributes attr = design.attributes();
  1152. // handle default attributes
  1153. for (String attribute : getDefaultAttributes()) {
  1154. DesignAttributeHandler.writeAttribute(this, attribute, attr, def,
  1155. designContext);
  1156. }
  1157. // handle locale
  1158. if (getLocale() != null && (getParent() == null
  1159. || !getLocale().equals(getParent().getLocale()))) {
  1160. design.attr("locale", getLocale().toString());
  1161. }
  1162. // handle size
  1163. writeSize(attr, def);
  1164. // handle component error
  1165. String errorMsg = getComponentError() != null
  1166. ? getComponentError().getFormattedHtmlMessage() : null;
  1167. String defErrorMsg = def.getComponentError() != null
  1168. ? def.getComponentError().getFormattedHtmlMessage() : null;
  1169. if (!SharedUtil.equals(errorMsg, defErrorMsg)) {
  1170. attr.put("error", errorMsg);
  1171. }
  1172. // handle tab index
  1173. if (this instanceof Focusable) {
  1174. DesignAttributeHandler.writeAttribute("tabindex", attr,
  1175. ((Focusable) this).getTabIndex(),
  1176. ((Focusable) def).getTabIndex(), Integer.class,
  1177. designContext);
  1178. }
  1179. // handle custom attributes
  1180. Map<String, String> customAttributes = designContext
  1181. .getCustomAttributes(this);
  1182. if (customAttributes != null) {
  1183. for (Entry<String, String> entry : customAttributes.entrySet()) {
  1184. attr.put(entry.getKey(), entry.getValue());
  1185. }
  1186. }
  1187. }
  1188. /*
  1189. * Actions
  1190. */
  1191. /**
  1192. * Gets the {@link ActionManager} used to manage the
  1193. * {@link ShortcutListener}s added to this component.
  1194. *
  1195. * @return the ActionManager in use
  1196. */
  1197. protected ActionManager getActionManager() {
  1198. if (actionManager == null) {
  1199. actionManager = new ConnectorActionManager(this);
  1200. setActionManagerViewer();
  1201. }
  1202. return actionManager;
  1203. }
  1204. /**
  1205. * Set a viewer for the action manager to be the parent sub window (if the
  1206. * component is in a window) or the UI (otherwise). This is still a
  1207. * simplification of the real case as this should be handled by the parent
  1208. * VOverlay (on the client side) if the component is inside an VOverlay
  1209. * component.
  1210. */
  1211. private void setActionManagerViewer() {
  1212. if (actionManager != null && getUI() != null) {
  1213. // Attached and has action manager
  1214. Window w = findAncestor(Window.class);
  1215. if (w != null) {
  1216. actionManager.setViewer(w);
  1217. } else {
  1218. actionManager.setViewer(getUI());
  1219. }
  1220. }
  1221. }
  1222. public Registration addShortcutListener(ShortcutListener shortcut) {
  1223. Objects.requireNonNull(shortcut, "Listener must not be null.");
  1224. getActionManager().addAction(shortcut);
  1225. return () -> getActionManager().removeAction(shortcut);
  1226. }
  1227. @Deprecated
  1228. public void removeShortcutListener(ShortcutListener shortcut) {
  1229. getActionManager().removeAction(shortcut);
  1230. }
  1231. /**
  1232. * Determine whether a <code>content</code> component is equal to, or the
  1233. * ancestor of this component.
  1234. *
  1235. * @param content
  1236. * the potential ancestor element
  1237. * @return <code>true</code> if the relationship holds
  1238. */
  1239. protected boolean isOrHasAncestor(Component content) {
  1240. if (content instanceof HasComponents) {
  1241. for (Component parent = this; parent != null; parent = parent
  1242. .getParent()) {
  1243. if (parent.equals(content)) {
  1244. return true;
  1245. }
  1246. }
  1247. }
  1248. return false;
  1249. }
  1250. @Override
  1251. public Registration addContextClickListener(ContextClickListener listener) {
  1252. // Register default Context Click RPC if needed. This RPC won't be
  1253. // called if there are no listeners on the server-side. A client-side
  1254. // connector can override this and use a different RPC channel.
  1255. if (getRpcManager(ContextClickRpc.class.getName()) == null) {
  1256. registerRpc((ContextClickRpc) (MouseEventDetails details) -> {
  1257. fireEvent(new ContextClickEvent(AbstractComponent.this,
  1258. details));
  1259. });
  1260. }
  1261. addListener(EventId.CONTEXT_CLICK, ContextClickEvent.class, listener,
  1262. ContextClickEvent.CONTEXT_CLICK_METHOD);
  1263. return () -> removeListener(EventId.CONTEXT_CLICK,
  1264. ContextClickEvent.class, listener);
  1265. }
  1266. @Override
  1267. @Deprecated
  1268. public void removeContextClickListener(ContextClickListener listener) {
  1269. removeListener(EventId.CONTEXT_CLICK, ContextClickEvent.class,
  1270. listener);
  1271. }
  1272. /**
  1273. * Sets the visibility of the required indicator. <strong>NOTE: Does not
  1274. * apply for all components!</strong>.
  1275. * <p>
  1276. * If the component supports the required indicator (state extends
  1277. * {@link AbstractFieldState}), then expose this method and
  1278. * {@link #isRequiredIndicatorVisible()} as {@code public} in the component
  1279. * and call this method.
  1280. * <p>
  1281. * This method will throw a {@link IllegalStateException} if the component
  1282. * state (returned by {@link #getState()}) does not inherit
  1283. * {@link AbstractFieldState}.
  1284. *
  1285. * @param visible
  1286. * <code>true</code> to make the required indicator visible,
  1287. * <code>false</code> if not
  1288. */
  1289. protected void setRequiredIndicatorVisible(boolean visible) {
  1290. if (getState(false) instanceof AbstractFieldState) {
  1291. ((AbstractFieldState) getState()).required = visible;
  1292. } else {
  1293. throw new IllegalStateException(
  1294. "This component does not support the required indicator, since state is of type "
  1295. + getStateType().getSimpleName()
  1296. + " and does not inherit "
  1297. + AbstractFieldState.class.getSimpleName());
  1298. }
  1299. }
  1300. /**
  1301. * Checks whether the required indicator is visible or not. <strong>NOTE:
  1302. * Does not apply for all components!</strong>.
  1303. * <p>
  1304. * This method will throw a {@link IllegalStateException} if the component
  1305. * state (returned by {@link #getState()}) does not inherit
  1306. * {@link AbstractFieldState}.
  1307. *
  1308. * @return <code>true</code> if visible, <code>false</code> if not
  1309. * @see #setRequiredIndicatorVisible(boolean)
  1310. */
  1311. protected boolean isRequiredIndicatorVisible() {
  1312. if (getState(false) instanceof AbstractFieldState) {
  1313. return ((AbstractFieldState) getState(false)).required;
  1314. }
  1315. throw new IllegalStateException(
  1316. "This component does not support the required indicator, since state is of type "
  1317. + getStateType().getSimpleName()
  1318. + " and does not inherit "
  1319. + AbstractFieldState.class.getSimpleName());
  1320. }
  1321. private static final Logger getLogger() {
  1322. return Logger.getLogger(AbstractComponent.class.getName());
  1323. }
  1324. }