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.

AbstractComponentConnector.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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.client.ui;
  17. import com.google.gwt.core.client.GWT;
  18. import com.google.gwt.core.client.JsArrayString;
  19. import com.google.gwt.dom.client.Element;
  20. import com.google.gwt.event.dom.client.ContextMenuEvent;
  21. import com.google.gwt.event.dom.client.ContextMenuHandler;
  22. import com.google.gwt.event.shared.HandlerRegistration;
  23. import com.google.gwt.user.client.ui.Focusable;
  24. import com.google.gwt.user.client.ui.HasEnabled;
  25. import com.google.gwt.user.client.ui.Widget;
  26. import com.vaadin.client.ComponentConnector;
  27. import com.vaadin.client.HasComponentsConnector;
  28. import com.vaadin.client.LayoutManager;
  29. import com.vaadin.client.MouseEventDetailsBuilder;
  30. import com.vaadin.client.Profiler;
  31. import com.vaadin.client.ServerConnector;
  32. import com.vaadin.client.StyleConstants;
  33. import com.vaadin.client.TooltipInfo;
  34. import com.vaadin.client.UIDL;
  35. import com.vaadin.client.Util;
  36. import com.vaadin.client.VConsole;
  37. import com.vaadin.client.annotations.OnStateChange;
  38. import com.vaadin.client.communication.StateChangeEvent;
  39. import com.vaadin.client.metadata.NoDataException;
  40. import com.vaadin.client.metadata.Type;
  41. import com.vaadin.client.metadata.TypeData;
  42. import com.vaadin.client.ui.ui.UIConnector;
  43. import com.vaadin.shared.AbstractComponentState;
  44. import com.vaadin.shared.ComponentConstants;
  45. import com.vaadin.shared.Connector;
  46. import com.vaadin.shared.ContextClickRpc;
  47. import com.vaadin.shared.EventId;
  48. import com.vaadin.shared.ui.ComponentStateUtil;
  49. import com.vaadin.shared.ui.TabIndexState;
  50. public abstract class AbstractComponentConnector extends AbstractConnector
  51. implements ComponentConnector {
  52. private HandlerRegistration contextHandler = null;
  53. private Widget widget;
  54. private String lastKnownWidth = "";
  55. private String lastKnownHeight = "";
  56. private boolean tooltipListenersAttached = false;
  57. /**
  58. * The style names from getState().getStyles() which are currently applied
  59. * to the widget.
  60. */
  61. private JsArrayString styleNames = JsArrayString.createArray().cast();
  62. /**
  63. * Default constructor
  64. */
  65. public AbstractComponentConnector() {
  66. }
  67. @OnStateChange("registeredEventListeners")
  68. void handleContextClickListenerChange() {
  69. if (contextHandler == null && hasEventListener(EventId.CONTEXT_CLICK)) {
  70. contextHandler = getWidget().addDomHandler(
  71. new ContextMenuHandler() {
  72. @Override
  73. public void onContextMenu(ContextMenuEvent event) {
  74. sendContextClickEvent(event);
  75. }
  76. }, ContextMenuEvent.getType());
  77. } else if (contextHandler != null
  78. && !hasEventListener(EventId.CONTEXT_CLICK)) {
  79. contextHandler.removeHandler();
  80. contextHandler = null;
  81. }
  82. }
  83. /**
  84. * This method sends the context menu event to the server-side. Can be
  85. * overridden to provide extra information through an alternative RPC
  86. * interface.
  87. *
  88. * @since 7.6
  89. * @param event
  90. */
  91. protected void sendContextClickEvent(ContextMenuEvent event) {
  92. event.preventDefault();
  93. event.stopPropagation();
  94. // The default context click implementation only provides the mouse
  95. // coordinates relative to root element of widget.
  96. getRpcProxy(ContextClickRpc.class).contextClick(
  97. MouseEventDetailsBuilder.buildMouseEventDetails(
  98. event.getNativeEvent(), getWidget().getElement()));
  99. }
  100. /**
  101. * Creates and returns the widget for this VPaintableWidget. This method
  102. * should only be called once when initializing the paintable.
  103. * <p>
  104. * You should typically not override this method since the framework by
  105. * default generates an implementation that uses {@link GWT#create(Class)}
  106. * to create a widget of the same type as returned by the most specific
  107. * override of {@link #getWidget()}. If you do override the method, you
  108. * can't call <code>super.createWidget()</code> since the metadata needed
  109. * for that implementation is not generated if there's an override of the
  110. * method.
  111. *
  112. * @return a new widget instance to use for this component connector
  113. */
  114. protected Widget createWidget() {
  115. Type type = TypeData.getType(getClass());
  116. try {
  117. Type widgetType = type.getMethod("getWidget").getReturnType();
  118. Object instance = widgetType.createInstance();
  119. return (Widget) instance;
  120. } catch (NoDataException e) {
  121. throw new IllegalStateException(
  122. "Default implementation of createWidget() does not work for "
  123. + getClass().getSimpleName()
  124. + ". This might be caused by explicitely using "
  125. + "super.createWidget() or some unspecified "
  126. + "problem with the widgetset compilation.", e);
  127. }
  128. }
  129. /**
  130. * Returns the widget associated with this paintable. The widget returned by
  131. * this method must not changed during the life time of the paintable.
  132. *
  133. * @return The widget associated with this paintable
  134. */
  135. @Override
  136. public Widget getWidget() {
  137. if (widget == null) {
  138. if (Profiler.isEnabled()) {
  139. Profiler.enter("AbstractComponentConnector.createWidget for "
  140. + getClass().getSimpleName());
  141. }
  142. widget = createWidget();
  143. if (Profiler.isEnabled()) {
  144. Profiler.leave("AbstractComponentConnector.createWidget for "
  145. + getClass().getSimpleName());
  146. }
  147. }
  148. return widget;
  149. }
  150. @Deprecated
  151. public static boolean isRealUpdate(UIDL uidl) {
  152. return !uidl.hasAttribute("cached");
  153. }
  154. @Override
  155. public AbstractComponentState getState() {
  156. return (AbstractComponentState) super.getState();
  157. }
  158. @Override
  159. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  160. Profiler.enter("AbstractComponentConnector.onStateChanged");
  161. Profiler.enter("AbstractComponentConnector.onStateChanged update id");
  162. if (stateChangeEvent.hasPropertyChanged("id")) {
  163. if (getState().id != null) {
  164. getWidget().getElement().setId(getState().id);
  165. } else if (!stateChangeEvent.isInitialStateChange()) {
  166. getWidget().getElement().removeAttribute("id");
  167. }
  168. }
  169. Profiler.leave("AbstractComponentConnector.onStateChanged update id");
  170. /*
  171. * Disabled state may affect (override) tabindex so the order must be
  172. * first setting tabindex, then enabled state (through super
  173. * implementation).
  174. */
  175. Profiler.enter("AbstractComponentConnector.onStateChanged update tab index");
  176. if (getState() instanceof TabIndexState) {
  177. if (getWidget() instanceof Focusable) {
  178. ((Focusable) getWidget())
  179. .setTabIndex(((TabIndexState) getState()).tabIndex);
  180. } else {
  181. /*
  182. * TODO Enable this error when all widgets have been fixed to
  183. * properly support tabIndex, i.e. implement Focusable
  184. */
  185. // VConsole.error("Tab index received for "
  186. // + Util.getSimpleName(getWidget())
  187. // + " which does not implement Focusable");
  188. }
  189. }
  190. Profiler.leave("AbstractComponentConnector.onStateChanged update tab index");
  191. Profiler.enter("AbstractComponentConnector.onStateChanged AbstractConnector.onStateChanged()");
  192. super.onStateChanged(stateChangeEvent);
  193. Profiler.leave("AbstractComponentConnector.onStateChanged AbstractConnector.onStateChanged()");
  194. // Style names
  195. Profiler.enter("AbstractComponentConnector.onStateChanged updateWidgetStyleNames");
  196. updateWidgetStyleNames();
  197. Profiler.leave("AbstractComponentConnector.onStateChanged updateWidgetStyleNames");
  198. /*
  199. * updateComponentSize need to be after caption update so caption can be
  200. * taken into account
  201. */
  202. Profiler.enter("AbstractComponentConnector.onStateChanged updateComponentSize");
  203. updateComponentSize();
  204. Profiler.leave("AbstractComponentConnector.onStateChanged updateComponentSize");
  205. Profiler.enter("AbstractComponentContainer.onStateChanged check tooltip");
  206. if (!tooltipListenersAttached && hasTooltip()) {
  207. /*
  208. * Add event handlers for tooltips if they are needed but have not
  209. * yet been added.
  210. */
  211. tooltipListenersAttached = true;
  212. getConnection().getVTooltip().connectHandlersToWidget(getWidget());
  213. }
  214. Profiler.leave("AbstractComponentContainer.onStateChanged check tooltip");
  215. Profiler.leave("AbstractComponentConnector.onStateChanged");
  216. }
  217. @Override
  218. public void setWidgetEnabled(boolean widgetEnabled) {
  219. // add or remove v-disabled style name from the widget
  220. setWidgetStyleName(StyleConstants.DISABLED, !widgetEnabled);
  221. if (getWidget() instanceof HasEnabled) {
  222. // set widget specific enabled state
  223. ((HasEnabled) getWidget()).setEnabled(widgetEnabled);
  224. }
  225. // make sure the caption has or has not v-disabled style
  226. if (delegateCaptionHandling()) {
  227. ServerConnector parent = getParent();
  228. if (parent instanceof HasComponentsConnector) {
  229. ((HasComponentsConnector) parent).updateCaption(this);
  230. } else if (parent == null && !(this instanceof UIConnector)) {
  231. VConsole.error("Parent of connector "
  232. + Util.getConnectorString(this)
  233. + " is null. This is typically an indication of a broken component hierarchy");
  234. }
  235. }
  236. }
  237. /**
  238. * Updates the component size based on the shared state, invoking the
  239. * {@link LayoutManager layout manager} if necessary.
  240. */
  241. protected void updateComponentSize() {
  242. updateComponentSize(getState().width == null ? "" : getState().width,
  243. getState().height == null ? "" : getState().height);
  244. }
  245. /**
  246. * Updates the component size, invoking the {@link LayoutManager layout
  247. * manager} if necessary.
  248. *
  249. * @param newWidth
  250. * The new width as a CSS string. Cannot be null.
  251. * @param newHeight
  252. * The new height as a CSS string. Cannot be null.
  253. */
  254. protected void updateComponentSize(String newWidth, String newHeight) {
  255. Profiler.enter("AbstractComponentConnector.updateComponentSize");
  256. // Parent should be updated if either dimension changed between relative
  257. // and non-relative
  258. if (newWidth.endsWith("%") != lastKnownWidth.endsWith("%")) {
  259. Connector parent = getParent();
  260. if (parent instanceof ManagedLayout) {
  261. getLayoutManager().setNeedsHorizontalLayout(
  262. (ManagedLayout) parent);
  263. }
  264. }
  265. if (newHeight.endsWith("%") != lastKnownHeight.endsWith("%")) {
  266. Connector parent = getParent();
  267. if (parent instanceof ManagedLayout) {
  268. getLayoutManager().setNeedsVerticalLayout(
  269. (ManagedLayout) parent);
  270. }
  271. }
  272. lastKnownWidth = newWidth;
  273. lastKnownHeight = newHeight;
  274. // Set defined sizes
  275. Widget widget = getWidget();
  276. Profiler.enter("AbstractComponentConnector.updateComponentSize update styleNames");
  277. widget.setStyleName("v-has-width", !isUndefinedWidth());
  278. widget.setStyleName("v-has-height", !isUndefinedHeight());
  279. Profiler.leave("AbstractComponentConnector.updateComponentSize update styleNames");
  280. Profiler.enter("AbstractComponentConnector.updateComponentSize update DOM");
  281. updateWidgetSize(newWidth, newHeight);
  282. Profiler.leave("AbstractComponentConnector.updateComponentSize update DOM");
  283. Profiler.leave("AbstractComponentConnector.updateComponentSize");
  284. }
  285. /**
  286. * Updates the DOM size of this connector's {@link #getWidget() widget}.
  287. *
  288. * @since 7.1.15
  289. * @param newWidth
  290. * The new width as a CSS string. Cannot be null.
  291. * @param newHeight
  292. * The new height as a CSS string. Cannot be null.
  293. */
  294. protected void updateWidgetSize(String newWidth, String newHeight) {
  295. getWidget().setWidth(newWidth);
  296. getWidget().setHeight(newHeight);
  297. }
  298. @Override
  299. public boolean isRelativeHeight() {
  300. return ComponentStateUtil.isRelativeHeight(getState());
  301. }
  302. @Override
  303. public boolean isRelativeWidth() {
  304. return ComponentStateUtil.isRelativeWidth(getState());
  305. }
  306. @Override
  307. public boolean isUndefinedHeight() {
  308. return ComponentStateUtil.isUndefinedHeight(getState());
  309. }
  310. @Override
  311. public boolean isUndefinedWidth() {
  312. return ComponentStateUtil.isUndefinedWidth(getState());
  313. }
  314. /*
  315. * (non-Javadoc)
  316. *
  317. * @see com.vaadin.client.ComponentConnector#delegateCaptionHandling ()
  318. */
  319. @Override
  320. public boolean delegateCaptionHandling() {
  321. return true;
  322. }
  323. /**
  324. * Updates the user defined, read-only and error style names for the widget
  325. * based the shared state. User defined style names are prefixed with the
  326. * primary style name of the widget returned by {@link #getWidget()}
  327. * <p>
  328. * This method can be overridden to provide additional style names for the
  329. * component, for example see
  330. * {@link AbstractFieldConnector#updateWidgetStyleNames()}
  331. * </p>
  332. */
  333. protected void updateWidgetStyleNames() {
  334. Profiler.enter("AbstractComponentConnector.updateWidgetStyleNames");
  335. AbstractComponentState state = getState();
  336. String primaryStyleName = getWidget().getStylePrimaryName();
  337. // Set the core 'v' style name for the widget
  338. setWidgetStyleName(StyleConstants.UI_WIDGET, true);
  339. // should be in AbstractFieldConnector ?
  340. // add / remove read-only style name
  341. setWidgetStyleName("v-readonly", isReadOnly());
  342. // add / remove error style name
  343. setWidgetStyleNameWithPrefix(primaryStyleName,
  344. StyleConstants.ERROR_EXT, null != state.errorMessage);
  345. // add additional user defined style names as class names, prefixed with
  346. // component default class name. remove nonexistent style names.
  347. // Remove all old stylenames
  348. for (int i = 0; i < styleNames.length(); i++) {
  349. String oldStyle = styleNames.get(i);
  350. setWidgetStyleName(oldStyle, false);
  351. setWidgetStyleNameWithPrefix(primaryStyleName + "-", oldStyle,
  352. false);
  353. }
  354. styleNames.setLength(0);
  355. if (ComponentStateUtil.hasStyles(state)) {
  356. // add new style names
  357. for (String newStyle : state.styles) {
  358. setWidgetStyleName(newStyle, true);
  359. setWidgetStyleNameWithPrefix(primaryStyleName + "-", newStyle,
  360. true);
  361. styleNames.push(newStyle);
  362. }
  363. }
  364. if (state.primaryStyleName != null
  365. && !state.primaryStyleName.equals(primaryStyleName)) {
  366. /*
  367. * We overwrite the widgets primary stylename if state defines a
  368. * primary stylename. This has to be done after updating other
  369. * styles to be sure the dependent styles are updated correctly.
  370. */
  371. getWidget().setStylePrimaryName(state.primaryStyleName);
  372. }
  373. Profiler.leave("AbstractComponentConnector.updateWidgetStyleNames");
  374. }
  375. /**
  376. * This is used to add / remove state related style names from the widget.
  377. * <p>
  378. * Override this method for example if the style name given here should be
  379. * updated in another widget in addition to the one returned by the
  380. * {@link #getWidget()}.
  381. * </p>
  382. *
  383. * @param styleName
  384. * the style name to be added or removed
  385. * @param add
  386. * <code>true</code> to add the given style, <code>false</code>
  387. * to remove it
  388. */
  389. protected void setWidgetStyleName(String styleName, boolean add) {
  390. getWidget().setStyleName(styleName, add);
  391. }
  392. /**
  393. * This is used to add / remove state related prefixed style names from the
  394. * widget.
  395. * <p>
  396. * Override this method if the prefixed style name given here should be
  397. * updated in another widget in addition to the one returned by the
  398. * <code>Connector</code>'s {@link #getWidget()}, or if the prefix should be
  399. * different. For example see
  400. * {@link com.vaadin.client.ui.datefield.DateFieldConnector#setWidgetStyleNameWithPrefix(String, String, boolean)}
  401. * </p>
  402. *
  403. * @param styleName
  404. * the style name to be added or removed
  405. * @param add
  406. * <code>true</code> to add the given style, <code>false</code>
  407. * to remove it
  408. * @deprecated This will be removed once styles are no longer added with
  409. * prefixes.
  410. */
  411. @Deprecated
  412. protected void setWidgetStyleNameWithPrefix(String prefix,
  413. String styleName, boolean add) {
  414. if (!styleName.startsWith("-")) {
  415. if (!prefix.endsWith("-")) {
  416. prefix += "-";
  417. }
  418. } else {
  419. if (prefix.endsWith("-")) {
  420. styleName.replaceFirst("-", "");
  421. }
  422. }
  423. getWidget().setStyleName(prefix + styleName, add);
  424. }
  425. /*
  426. * (non-Javadoc)
  427. *
  428. * @see com.vaadin.client.ComponentConnector#isReadOnly()
  429. */
  430. @Override
  431. @Deprecated
  432. public boolean isReadOnly() {
  433. return getState().readOnly;
  434. }
  435. @Override
  436. public LayoutManager getLayoutManager() {
  437. return LayoutManager.get(getConnection());
  438. }
  439. @Override
  440. public void updateEnabledState(boolean enabledState) {
  441. super.updateEnabledState(enabledState);
  442. setWidgetEnabled(isEnabled());
  443. }
  444. @Override
  445. public void onUnregister() {
  446. super.onUnregister();
  447. // Show an error if widget is still attached to DOM. It should never be
  448. // at this point.
  449. if (getWidget() != null && getWidget().isAttached()) {
  450. getWidget().removeFromParent();
  451. VConsole.error("Widget is still attached to the DOM after the connector ("
  452. + Util.getConnectorString(this)
  453. + ") has been unregistered. Widget was removed.");
  454. }
  455. }
  456. @Override
  457. public TooltipInfo getTooltipInfo(Element element) {
  458. return new TooltipInfo(getState().description, getState().errorMessage);
  459. }
  460. @Override
  461. public boolean hasTooltip() {
  462. // Normally, there is a tooltip if description or errorMessage is set
  463. AbstractComponentState state = getState();
  464. if (state.description != null && !state.description.equals("")) {
  465. return true;
  466. } else if (state.errorMessage != null && !state.errorMessage.equals("")) {
  467. return true;
  468. } else {
  469. return false;
  470. }
  471. }
  472. /**
  473. * Gets the URI of the icon set for this component.
  474. *
  475. * @return the URI of the icon, or <code>null</code> if no icon has been
  476. * defined.
  477. */
  478. protected String getIconUri() {
  479. return getResourceUrl(ComponentConstants.ICON_RESOURCE);
  480. }
  481. /**
  482. * Gets the icon set for this component.
  483. *
  484. * @return the icon, or <code>null</code> if no icon has been defined.
  485. */
  486. protected Icon getIcon() {
  487. return getConnection().getIcon(getIconUri());
  488. }
  489. /*
  490. * (non-Javadoc)
  491. *
  492. * @see com.vaadin.client.ComponentConnector#flush()
  493. */
  494. @Override
  495. public void flush() {
  496. // No generic implementation. Override if needed
  497. }
  498. }