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

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