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

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