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

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