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

AbstractComponent.java 41KB

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