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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. /*
  2. * Copyright 2000-2018 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 java.util.logging.Logger;
  18. import com.google.gwt.core.client.GWT;
  19. import com.google.gwt.core.client.JsArrayString;
  20. import com.google.gwt.dom.client.Element;
  21. import com.google.gwt.dom.client.EventTarget;
  22. import com.google.gwt.dom.client.Touch;
  23. import com.google.gwt.event.dom.client.ContextMenuEvent;
  24. import com.google.gwt.event.dom.client.TouchEndEvent;
  25. import com.google.gwt.event.dom.client.TouchMoveEvent;
  26. import com.google.gwt.event.dom.client.TouchMoveHandler;
  27. import com.google.gwt.event.dom.client.TouchStartEvent;
  28. import com.google.gwt.event.shared.HandlerRegistration;
  29. import com.google.gwt.user.client.Timer;
  30. import com.google.gwt.user.client.ui.Focusable;
  31. import com.google.gwt.user.client.ui.HasEnabled;
  32. import com.google.gwt.user.client.ui.Widget;
  33. import com.vaadin.client.BrowserInfo;
  34. import com.vaadin.client.HasComponentsConnector;
  35. import com.vaadin.client.LayoutManager;
  36. import com.vaadin.client.MouseEventDetailsBuilder;
  37. import com.vaadin.client.Profiler;
  38. import com.vaadin.client.ServerConnector;
  39. import com.vaadin.client.StyleConstants;
  40. import com.vaadin.client.TooltipInfo;
  41. import com.vaadin.client.UIDL;
  42. import com.vaadin.client.Util;
  43. import com.vaadin.client.WidgetUtil;
  44. import com.vaadin.client.WidgetUtil.ErrorUtil;
  45. import com.vaadin.client.annotations.OnStateChange;
  46. import com.vaadin.client.communication.StateChangeEvent;
  47. import com.vaadin.client.extensions.DragSourceExtensionConnector;
  48. import com.vaadin.client.extensions.DropTargetExtensionConnector;
  49. import com.vaadin.client.metadata.NoDataException;
  50. import com.vaadin.client.metadata.Type;
  51. import com.vaadin.client.metadata.TypeData;
  52. import com.vaadin.client.ui.ui.UIConnector;
  53. import com.vaadin.shared.AbstractComponentState;
  54. import com.vaadin.shared.ComponentConstants;
  55. import com.vaadin.shared.Connector;
  56. import com.vaadin.shared.ContextClickRpc;
  57. import com.vaadin.shared.EventId;
  58. import com.vaadin.shared.MouseEventDetails;
  59. import com.vaadin.shared.ui.ComponentStateUtil;
  60. import com.vaadin.shared.ui.TabIndexState;
  61. import com.vaadin.shared.ui.ui.UIState;
  62. public abstract class AbstractComponentConnector extends AbstractConnector
  63. implements HasErrorIndicator {
  64. private HandlerRegistration contextHandler = null;
  65. private Widget widget;
  66. private String lastKnownWidth = "";
  67. private String lastKnownHeight = "";
  68. private boolean tooltipListenersAttached = false;
  69. /**
  70. * The style names from getState().getStyles() which are currently applied
  71. * to the widget.
  72. */
  73. private JsArrayString styleNames = JsArrayString.createArray().cast();
  74. private Timer longTouchTimer;
  75. // TODO encapsulate into a nested class
  76. private HandlerRegistration touchStartHandler;
  77. private HandlerRegistration touchMoveHandler;
  78. private HandlerRegistration touchEndHandler;
  79. private int touchStartX;
  80. private int touchStartY;
  81. private boolean preventNextTouchEnd = false;
  82. protected int SIGNIFICANT_MOVE_THRESHOLD = 20; // pixels
  83. // long touch event delay
  84. // TODO replace with global constant for accessibility
  85. private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
  86. /**
  87. * Default constructor.
  88. */
  89. public AbstractComponentConnector() {
  90. }
  91. @OnStateChange("registeredEventListeners")
  92. void handleContextClickListenerChange() {
  93. if (contextHandler == null && hasEventListener(EventId.CONTEXT_CLICK)) {
  94. contextHandler = getWidget().addDomHandler(event -> {
  95. final MouseEventDetails mouseEventDetails = MouseEventDetailsBuilder
  96. .buildMouseEventDetails(event.getNativeEvent(),
  97. getWidget().getElement());
  98. event.preventDefault();
  99. event.stopPropagation();
  100. sendContextClickEvent(mouseEventDetails,
  101. event.getNativeEvent().getEventTarget());
  102. }, ContextMenuEvent.getType());
  103. // if the widget has a contextclick listener, add touch support as
  104. // well.
  105. if (shouldHandleLongTap()) {
  106. registerTouchHandlers();
  107. }
  108. } else if (contextHandler != null
  109. && !hasEventListener(EventId.CONTEXT_CLICK)) {
  110. contextHandler.removeHandler();
  111. contextHandler = null;
  112. // remove the touch handlers as well
  113. unregisterTouchHandlers();
  114. }
  115. }
  116. /**
  117. * The new default behavior is for long taps to fire a contextclick event if
  118. * there's a contextclick listener attached to the component.
  119. *
  120. * If you do not want this in your component, override this with a blank
  121. * method to get rid of said behavior.
  122. *
  123. * @since 7.6
  124. */
  125. protected void unregisterTouchHandlers() {
  126. if (touchStartHandler != null) {
  127. touchStartHandler.removeHandler();
  128. touchStartHandler = null;
  129. }
  130. if (touchMoveHandler != null) {
  131. touchMoveHandler.removeHandler();
  132. touchMoveHandler = null;
  133. }
  134. if (touchEndHandler != null) {
  135. touchEndHandler.removeHandler();
  136. touchEndHandler = null;
  137. }
  138. }
  139. /**
  140. * The new default behavior is for long taps to fire a contextclick event if
  141. * there's a contextclick listener attached to the component.
  142. *
  143. * If you do not want this in your component, override this with a blank
  144. * method to get rid of said behavior.
  145. *
  146. * Some Vaadin Components already handle the long tap as a context menu.
  147. * This method is unnecessary for those.
  148. *
  149. * @since 7.6
  150. */
  151. protected void registerTouchHandlers() {
  152. Widget widget = getWidget();
  153. touchStartHandler = widget.addDomHandler(event -> {
  154. if (longTouchTimer != null && longTouchTimer.isRunning()) {
  155. return;
  156. }
  157. // Prevent selection for the element while pending long tap.
  158. WidgetUtil.setTextSelectionEnabled(widget.getElement(), false);
  159. if (BrowserInfo.get().isAndroid()) {
  160. // Android fires ContextMenu events automatically.
  161. return;
  162. }
  163. /*
  164. * we need to build mouseEventDetails eagerly - the event won't be
  165. * guaranteed to be around when the timer executes. At least this
  166. * was the case with iOS devices.
  167. */
  168. final MouseEventDetails mouseEventDetails = MouseEventDetailsBuilder
  169. .buildMouseEventDetails(event.getNativeEvent(),
  170. widget.getElement());
  171. final EventTarget eventTarget = event.getNativeEvent()
  172. .getEventTarget();
  173. longTouchTimer = new Timer() {
  174. @Override
  175. public void run() {
  176. // we're handling this event, our parent components
  177. // don't need to bother with it anymore.
  178. cancelParentTouchTimers();
  179. // The default context click
  180. // implementation only provides the
  181. // mouse coordinates relative to root
  182. // element of widget.
  183. sendContextClickEvent(mouseEventDetails, eventTarget);
  184. preventNextTouchEnd = true;
  185. }
  186. };
  187. Touch touch = event.getChangedTouches().get(0);
  188. touchStartX = touch.getClientX();
  189. touchStartY = touch.getClientY();
  190. longTouchTimer.schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
  191. }, TouchStartEvent.getType());
  192. touchMoveHandler = widget.addDomHandler(new TouchMoveHandler() {
  193. @Override
  194. public void onTouchMove(TouchMoveEvent event) {
  195. if (isSignificantMove(event)) {
  196. // Moved finger before the context menu timer
  197. // expired, so let the browser handle the event.
  198. cancelTouchTimer();
  199. }
  200. }
  201. // mostly copy-pasted code from VScrollTable
  202. // TODO refactor main logic to a common class
  203. private boolean isSignificantMove(TouchMoveEvent event) {
  204. if (longTouchTimer == null) {
  205. // no touch start
  206. return false;
  207. }
  208. // Calculate the distance between touch start and the current
  209. // touch
  210. // position
  211. Touch touch = event.getChangedTouches().get(0);
  212. int deltaX = touch.getClientX() - touchStartX;
  213. int deltaY = touch.getClientY() - touchStartY;
  214. int delta = deltaX * deltaX + deltaY * deltaY;
  215. // Compare to the square of the significant move threshold to
  216. // remove the need for a square root
  217. if (delta > SIGNIFICANT_MOVE_THRESHOLD
  218. * SIGNIFICANT_MOVE_THRESHOLD) {
  219. return true;
  220. }
  221. return false;
  222. }
  223. }, TouchMoveEvent.getType());
  224. touchEndHandler = widget.addDomHandler(event -> {
  225. // cancel the timer so the event doesn't fire
  226. cancelTouchTimer();
  227. if (preventNextTouchEnd) {
  228. event.preventDefault();
  229. preventNextTouchEnd = false;
  230. }
  231. }, TouchEndEvent.getType());
  232. }
  233. protected boolean shouldHandleLongTap() {
  234. return BrowserInfo.get().isTouchDevice();
  235. }
  236. /**
  237. * If a long touch event timer is running, cancel it.
  238. *
  239. * @since 7.6
  240. */
  241. private void cancelTouchTimer() {
  242. WidgetUtil.setTextSelectionEnabled(getWidget().getElement(), true);
  243. if (longTouchTimer != null) {
  244. // Re-enable text selection
  245. longTouchTimer.cancel();
  246. }
  247. }
  248. /**
  249. * Cancel the timer recursively for parent components that have timers
  250. * running
  251. *
  252. * @since 7.6
  253. */
  254. private void cancelParentTouchTimers() {
  255. ServerConnector parent = getParent();
  256. // we have to account for the parent being something other than an
  257. // abstractcomponent. getParent returns null for the root element.
  258. while (parent != null) {
  259. if (parent instanceof AbstractComponentConnector) {
  260. ((AbstractComponentConnector) parent).cancelTouchTimer();
  261. }
  262. parent = parent.getParent();
  263. }
  264. }
  265. /**
  266. * This method sends the context menu event to the server-side. Can be
  267. * overridden to provide extra information through an alternative RPC
  268. * interface.
  269. *
  270. * @since 7.6
  271. * @param details
  272. * @param eventTarget
  273. */
  274. protected void sendContextClickEvent(MouseEventDetails details,
  275. EventTarget eventTarget) {
  276. // The default context click implementation only provides the mouse
  277. // coordinates relative to root element of widget.
  278. getRpcProxy(ContextClickRpc.class).contextClick(details);
  279. WidgetUtil.clearTextSelection();
  280. }
  281. /**
  282. * Creates and returns the widget for this VPaintableWidget. This method
  283. * should only be called once when initializing the paintable.
  284. * <p>
  285. * You should typically not override this method since the framework by
  286. * default generates an implementation that uses {@link GWT#create(Class)}
  287. * to create a widget of the same type as returned by the most specific
  288. * override of {@link #getWidget()}. If you do override the method, you
  289. * can't call <code>super.createWidget()</code> since the metadata needed
  290. * for that implementation is not generated if there's an override of the
  291. * method.
  292. *
  293. * @return a new widget instance to use for this component connector
  294. */
  295. protected Widget createWidget() {
  296. Type type = TypeData.getType(getClass());
  297. try {
  298. Type widgetType = type.getMethod("getWidget").getReturnType();
  299. Object instance = widgetType.createInstance();
  300. return (Widget) instance;
  301. } catch (NoDataException e) {
  302. throw new IllegalStateException(
  303. "Default implementation of createWidget() does not work for "
  304. + getClass().getSimpleName()
  305. + ". This might be caused by explicitely using "
  306. + "super.createWidget() or some unspecified "
  307. + "problem with the widgetset compilation.",
  308. e);
  309. }
  310. }
  311. /**
  312. * Returns the widget associated with this paintable. The widget returned by
  313. * this method must not changed during the life time of the paintable.
  314. *
  315. * @return The widget associated with this paintable
  316. */
  317. @Override
  318. public Widget getWidget() {
  319. if (widget == null) {
  320. if (Profiler.isEnabled()) {
  321. Profiler.enter("AbstractComponentConnector.createWidget for "
  322. + getClass().getSimpleName());
  323. }
  324. widget = createWidget();
  325. if (Profiler.isEnabled()) {
  326. Profiler.leave("AbstractComponentConnector.createWidget for "
  327. + getClass().getSimpleName());
  328. }
  329. }
  330. return widget;
  331. }
  332. @Deprecated
  333. public static boolean isRealUpdate(UIDL uidl) {
  334. return !uidl.hasAttribute("cached");
  335. }
  336. @Override
  337. public AbstractComponentState getState() {
  338. return (AbstractComponentState) super.getState();
  339. }
  340. @Override
  341. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  342. Profiler.enter("AbstractComponentConnector.onStateChanged");
  343. Profiler.enter("AbstractComponentConnector.onStateChanged update id");
  344. if (stateChangeEvent.hasPropertyChanged("id")) {
  345. if (getState().id != null) {
  346. getWidget().getElement().setId(getState().id);
  347. } else if (!stateChangeEvent.isInitialStateChange()) {
  348. getWidget().getElement().removeAttribute("id");
  349. }
  350. }
  351. Profiler.leave("AbstractComponentConnector.onStateChanged update id");
  352. /*
  353. * Disabled state may affect (override) tabindex so the order must be
  354. * first setting tabindex, then enabled state (through super
  355. * implementation).
  356. */
  357. Profiler.enter(
  358. "AbstractComponentConnector.onStateChanged update tab index");
  359. if (getState() instanceof TabIndexState) {
  360. if (getWidget() instanceof Focusable) {
  361. ((Focusable) getWidget())
  362. .setTabIndex(((TabIndexState) getState()).tabIndex);
  363. } else {
  364. /*
  365. * TODO Enable this error when all widgets have been fixed to
  366. * properly support tabIndex, i.e. implement Focusable
  367. */
  368. // getLogger().severe("Tab index received for "
  369. // + Util.getSimpleName(getWidget())
  370. // + " which does not implement Focusable");
  371. }
  372. } else if (getState() instanceof UIState
  373. && getWidget() instanceof Focusable) {
  374. // UI behaves like a component with TabIndexState
  375. ((Focusable) getWidget())
  376. .setTabIndex(((UIState) getState()).tabIndex);
  377. }
  378. Profiler.leave(
  379. "AbstractComponentConnector.onStateChanged update tab index");
  380. Profiler.enter(
  381. "AbstractComponentConnector.onStateChanged AbstractConnector.onStateChanged()");
  382. super.onStateChanged(stateChangeEvent);
  383. Profiler.leave(
  384. "AbstractComponentConnector.onStateChanged AbstractConnector.onStateChanged()");
  385. // Style names
  386. Profiler.enter(
  387. "AbstractComponentConnector.onStateChanged updateWidgetStyleNames");
  388. updateWidgetStyleNames();
  389. Profiler.leave(
  390. "AbstractComponentConnector.onStateChanged updateWidgetStyleNames");
  391. /*
  392. * updateComponentSize need to be after caption update so caption can be
  393. * taken into account
  394. */
  395. Profiler.enter(
  396. "AbstractComponentConnector.onStateChanged updateComponentSize");
  397. updateComponentSize();
  398. Profiler.leave(
  399. "AbstractComponentConnector.onStateChanged updateComponentSize");
  400. Profiler.enter(
  401. "AbstractComponentContainer.onStateChanged check tooltip");
  402. if (!tooltipListenersAttached && hasTooltip()) {
  403. /*
  404. * Add event handlers for tooltips if they are needed but have not
  405. * yet been added.
  406. */
  407. tooltipListenersAttached = true;
  408. getConnection().getVTooltip().connectHandlersToWidget(getWidget());
  409. }
  410. Profiler.leave(
  411. "AbstractComponentContainer.onStateChanged check tooltip");
  412. Profiler.leave("AbstractComponentConnector.onStateChanged");
  413. }
  414. @OnStateChange({ "errorMessage", "errorLevel" })
  415. private void setErrorLevel() {
  416. Widget widget = getWidget();
  417. // Add or remove the widget's error level style name
  418. ErrorUtil.setErrorLevelStyle(widget.getElement(),
  419. widget.getStylePrimaryName() + StyleConstants.ERROR_EXT,
  420. getState().errorLevel);
  421. // Add or remove error indicator element
  422. if (widget instanceof HasErrorIndicatorElement) {
  423. HasErrorIndicatorElement hasErrorIndicatorElement = (HasErrorIndicatorElement) widget;
  424. if (getState().errorMessage != null) {
  425. hasErrorIndicatorElement.setErrorIndicatorElementVisible(true);
  426. ErrorUtil.setErrorLevelStyle(
  427. hasErrorIndicatorElement.getErrorIndicatorElement(),
  428. StyleConstants.STYLE_NAME_ERROR_INDICATOR,
  429. getState().errorLevel);
  430. } else {
  431. hasErrorIndicatorElement.setErrorIndicatorElementVisible(false);
  432. }
  433. }
  434. }
  435. @Override
  436. public void setWidgetEnabled(boolean widgetEnabled) {
  437. // add or remove v-disabled style name from the widget
  438. setWidgetStyleName(StyleConstants.DISABLED, !widgetEnabled);
  439. if (getWidget() instanceof HasEnabled) {
  440. // set widget specific enabled state
  441. ((HasEnabled) getWidget()).setEnabled(widgetEnabled);
  442. }
  443. // make sure the caption has or has not v-disabled style
  444. if (delegateCaptionHandling()) {
  445. ServerConnector parent = getParent();
  446. if (parent instanceof HasComponentsConnector) {
  447. ((HasComponentsConnector) parent).updateCaption(this);
  448. } else if (parent == null && !(this instanceof UIConnector)) {
  449. getLogger().severe("Parent of connector "
  450. + Util.getConnectorString(this)
  451. + " is null. This is typically an indication of a broken component hierarchy");
  452. }
  453. }
  454. }
  455. /**
  456. * Updates the component size based on the shared state, invoking the
  457. * {@link LayoutManager layout manager} if necessary.
  458. */
  459. protected void updateComponentSize() {
  460. updateComponentSize(getState().width == null ? "" : getState().width,
  461. getState().height == null ? "" : getState().height);
  462. }
  463. /**
  464. * Updates the component size, invoking the {@link LayoutManager layout
  465. * manager} if necessary.
  466. *
  467. * @param newWidth
  468. * The new width as a CSS string. Cannot be null.
  469. * @param newHeight
  470. * The new height as a CSS string. Cannot be null.
  471. */
  472. protected void updateComponentSize(String newWidth, String newHeight) {
  473. Profiler.enter("AbstractComponentConnector.updateComponentSize");
  474. // Parent should be updated if either dimension changed between relative
  475. // and non-relative
  476. if (newWidth.endsWith("%") != lastKnownWidth.endsWith("%")) {
  477. Connector parent = getParent();
  478. if (parent instanceof ManagedLayout) {
  479. getLayoutManager()
  480. .setNeedsHorizontalLayout((ManagedLayout) parent);
  481. }
  482. }
  483. if (newHeight.endsWith("%") != lastKnownHeight.endsWith("%")) {
  484. Connector parent = getParent();
  485. if (parent instanceof ManagedLayout) {
  486. getLayoutManager()
  487. .setNeedsVerticalLayout((ManagedLayout) parent);
  488. }
  489. }
  490. lastKnownWidth = newWidth;
  491. lastKnownHeight = newHeight;
  492. // Set defined sizes
  493. Widget widget = getWidget();
  494. Profiler.enter(
  495. "AbstractComponentConnector.updateComponentSize update styleNames");
  496. widget.setStyleName("v-has-width", !isUndefinedWidth());
  497. widget.setStyleName("v-has-height", !isUndefinedHeight());
  498. Profiler.leave(
  499. "AbstractComponentConnector.updateComponentSize update styleNames");
  500. Profiler.enter(
  501. "AbstractComponentConnector.updateComponentSize update DOM");
  502. updateWidgetSize(newWidth, newHeight);
  503. Profiler.leave(
  504. "AbstractComponentConnector.updateComponentSize update DOM");
  505. Profiler.leave("AbstractComponentConnector.updateComponentSize");
  506. }
  507. /**
  508. * Updates the DOM size of this connector's {@link #getWidget() widget}.
  509. *
  510. * @since 7.1.15
  511. * @param newWidth
  512. * The new width as a CSS string. Cannot be null.
  513. * @param newHeight
  514. * The new height as a CSS string. Cannot be null.
  515. */
  516. protected void updateWidgetSize(String newWidth, String newHeight) {
  517. getWidget().setWidth(newWidth);
  518. getWidget().setHeight(newHeight);
  519. }
  520. @Override
  521. public boolean isRelativeHeight() {
  522. return ComponentStateUtil.isRelativeHeight(getState());
  523. }
  524. @Override
  525. public boolean isRelativeWidth() {
  526. return ComponentStateUtil.isRelativeWidth(getState());
  527. }
  528. @Override
  529. public boolean isUndefinedHeight() {
  530. return ComponentStateUtil.isUndefinedHeight(getState());
  531. }
  532. @Override
  533. public boolean isUndefinedWidth() {
  534. return ComponentStateUtil.isUndefinedWidth(getState());
  535. }
  536. /*
  537. * (non-Javadoc)
  538. *
  539. * @see com.vaadin.client.ComponentConnector#delegateCaptionHandling ()
  540. */
  541. @Override
  542. public boolean delegateCaptionHandling() {
  543. return true;
  544. }
  545. /**
  546. * Updates the user defined, read-only and error style names for the widget
  547. * based the shared state. User defined style names are prefixed with the
  548. * primary style name of the widget returned by {@link #getWidget()}
  549. * <p>
  550. * This method can be overridden to provide additional style names for the
  551. * component, for example see {@code AbstractFieldConnector}
  552. * </p>
  553. */
  554. protected void updateWidgetStyleNames() {
  555. Profiler.enter("AbstractComponentConnector.updateWidgetStyleNames");
  556. AbstractComponentState state = getState();
  557. String primaryStyleName = getWidget().getStylePrimaryName();
  558. // Set the core 'v' style name for the widget
  559. setWidgetStyleName(StyleConstants.UI_WIDGET, true);
  560. // add / remove error style name
  561. setWidgetStyleNameWithPrefix(primaryStyleName, StyleConstants.ERROR_EXT,
  562. null != state.errorMessage);
  563. // add additional user defined style names as class names, prefixed with
  564. // component default class name. remove nonexistent style names.
  565. // Remove all old stylenames
  566. for (int i = 0; i < styleNames.length(); i++) {
  567. String oldStyle = styleNames.get(i);
  568. setWidgetStyleName(oldStyle, false);
  569. setWidgetStyleNameWithPrefix(primaryStyleName + "-", oldStyle,
  570. false);
  571. }
  572. styleNames.setLength(0);
  573. if (ComponentStateUtil.hasStyles(state)) {
  574. // add new style names
  575. for (String newStyle : state.styles) {
  576. setWidgetStyleName(newStyle, true);
  577. setWidgetStyleNameWithPrefix(primaryStyleName + "-", newStyle,
  578. true);
  579. styleNames.push(newStyle);
  580. }
  581. }
  582. if (state.primaryStyleName != null
  583. && !state.primaryStyleName.equals(primaryStyleName)) {
  584. /*
  585. * We overwrite the widgets primary stylename if state defines a
  586. * primary stylename. This has to be done after updating other
  587. * styles to be sure the dependent styles are updated correctly.
  588. */
  589. getWidget().setStylePrimaryName(state.primaryStyleName);
  590. }
  591. // set required style name if components supports that
  592. if (this instanceof HasRequiredIndicator) {
  593. getWidget().setStyleName(StyleConstants.REQUIRED,
  594. ((HasRequiredIndicator) this).isRequiredIndicatorVisible());
  595. }
  596. Profiler.leave("AbstractComponentConnector.updateWidgetStyleNames");
  597. }
  598. /**
  599. * This is used to add / remove state related style names from the widget.
  600. * <p>
  601. * Override this method for example if the style name given here should be
  602. * updated in another widget in addition to the one returned by the
  603. * {@link #getWidget()}.
  604. * </p>
  605. *
  606. * @param styleName
  607. * the style name to be added or removed
  608. * @param add
  609. * <code>true</code> to add the given style, <code>false</code>
  610. * to remove it
  611. */
  612. protected void setWidgetStyleName(String styleName, boolean add) {
  613. getWidget().setStyleName(styleName, add);
  614. }
  615. /**
  616. * This is used to add / remove state related prefixed style names from the
  617. * widget.
  618. * <p>
  619. * Override this method if the prefixed style name given here should be
  620. * updated in another widget in addition to the one returned by the
  621. * <code>Connector</code>'s {@link #getWidget()}, or if the prefix should be
  622. * different. For example see
  623. * {@link com.vaadin.client.ui.datefield.TextualDateConnector#setWidgetStyleNameWithPrefix(String, String, boolean)}
  624. * </p>
  625. *
  626. * @param styleName
  627. * the style name to be added or removed
  628. * @param add
  629. * <code>true</code> to add the given style, <code>false</code>
  630. * to remove it
  631. * @deprecated This will be removed once styles are no longer added with
  632. * prefixes.
  633. */
  634. @Deprecated
  635. protected void setWidgetStyleNameWithPrefix(String prefix, String styleName,
  636. boolean add) {
  637. if (!styleName.startsWith("-")) {
  638. if (!prefix.endsWith("-")) {
  639. prefix += "-";
  640. }
  641. } else {
  642. if (prefix.endsWith("-")) {
  643. styleName.replaceFirst("-", "");
  644. }
  645. }
  646. getWidget().setStyleName(prefix + styleName, add);
  647. }
  648. @Override
  649. public LayoutManager getLayoutManager() {
  650. return LayoutManager.get(getConnection());
  651. }
  652. @Override
  653. public void updateEnabledState(boolean enabledState) {
  654. super.updateEnabledState(enabledState);
  655. setWidgetEnabled(isEnabled());
  656. }
  657. @Override
  658. public void onUnregister() {
  659. super.onUnregister();
  660. // Show an error if widget is still attached to DOM. It should never be
  661. // at this point.
  662. if (getWidget() != null && getWidget().isAttached()) {
  663. getWidget().removeFromParent();
  664. getLogger().severe(
  665. "Widget is still attached to the DOM after the connector ("
  666. + Util.getConnectorString(this)
  667. + ") has been unregistered. Widget was removed.");
  668. }
  669. }
  670. @Override
  671. public TooltipInfo getTooltipInfo(Element element) {
  672. return new TooltipInfo(getState().description,
  673. getState().descriptionContentMode, getState().errorMessage,
  674. null, getState().errorLevel);
  675. }
  676. @Override
  677. public boolean hasTooltip() {
  678. // Normally, there is a tooltip if description or errorMessage is set
  679. AbstractComponentState state = getState();
  680. if (state.description != null && !state.description.isEmpty()) {
  681. return true;
  682. }
  683. return state.errorMessage != null && !state.errorMessage.isEmpty();
  684. }
  685. /**
  686. * Gets the URI of the icon set for this component.
  687. *
  688. * @return the URI of the icon, or <code>null</code> if no icon has been
  689. * defined.
  690. */
  691. protected String getIconUri() {
  692. return getResourceUrl(ComponentConstants.ICON_RESOURCE);
  693. }
  694. /**
  695. * Gets the icon set for this component.
  696. *
  697. * @return the icon, or <code>null</code> if no icon has been defined.
  698. */
  699. protected Icon getIcon() {
  700. return getConnection().getIcon(getIconUri());
  701. }
  702. /*
  703. * (non-Javadoc)
  704. *
  705. * @see com.vaadin.client.ComponentConnector#flush()
  706. */
  707. @Override
  708. public void flush() {
  709. // No generic implementation. Override if needed
  710. }
  711. @Override
  712. public boolean isErrorIndicatorVisible() {
  713. return getState().errorMessage != null;
  714. }
  715. /**
  716. * Invoked when a {@link DragSourceExtensionConnector} has been attached to
  717. * this component.
  718. * <p>
  719. * By default, does nothing. If you need to apply some changes to the
  720. * widget, override this method.
  721. * <p>
  722. * This is a framework internal method, and should not be invoked manually.
  723. *
  724. * @since 8.1
  725. * @see #onDragSourceDetached()
  726. */
  727. public void onDragSourceAttached() {
  728. }
  729. /**
  730. * Invoked when a {@link DragSourceExtensionConnector} has been removed from
  731. * this component.
  732. * <p>
  733. * By default, does nothing.
  734. * <p>
  735. * This is a framework internal method, and should not be invoked manually.
  736. *
  737. * @since 8.1
  738. * @see #onDragSourceAttached()
  739. */
  740. public void onDragSourceDetached() {
  741. }
  742. /**
  743. * Invoked when a {@link DropTargetExtensionConnector} has been attached to
  744. * this component.
  745. * <p>
  746. * By default, does nothing. If you need to apply some changes to the
  747. * widget, override this method.
  748. * <p>
  749. * This is a framework internal method, and should not be invoked manually.
  750. *
  751. * @since 8.1
  752. * @see #onDropTargetDetached()
  753. */
  754. public void onDropTargetAttached() {
  755. }
  756. /**
  757. * Invoked when a {@link DropTargetExtensionConnector} has been removed from
  758. * this component.
  759. * <p>
  760. * By default, does nothing.
  761. * <p>
  762. * This is a framework internal method, and should not be invoked manually.
  763. *
  764. * @since 8.1
  765. * @see #onDropTargetAttached()
  766. */
  767. public void onDropTargetDetached() {
  768. }
  769. private static Logger getLogger() {
  770. return Logger.getLogger(AbstractComponentConnector.class.getName());
  771. }
  772. }