選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AbstractComponent.java 39KB

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