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.

UIConnector.java 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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.ui;
  17. import java.util.ArrayList;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import java.util.logging.Logger;
  21. import com.google.gwt.core.client.Scheduler;
  22. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  23. import com.google.gwt.dom.client.Document;
  24. import com.google.gwt.dom.client.Element;
  25. import com.google.gwt.dom.client.HeadElement;
  26. import com.google.gwt.dom.client.LinkElement;
  27. import com.google.gwt.dom.client.NativeEvent;
  28. import com.google.gwt.dom.client.NodeList;
  29. import com.google.gwt.dom.client.Style;
  30. import com.google.gwt.dom.client.Style.Position;
  31. import com.google.gwt.dom.client.StyleElement;
  32. import com.google.gwt.dom.client.StyleInjector;
  33. import com.google.gwt.event.dom.client.ScrollEvent;
  34. import com.google.gwt.event.dom.client.ScrollHandler;
  35. import com.google.gwt.event.logical.shared.ResizeEvent;
  36. import com.google.gwt.event.logical.shared.ResizeHandler;
  37. import com.google.gwt.http.client.URL;
  38. import com.google.gwt.user.client.Command;
  39. import com.google.gwt.user.client.DOM;
  40. import com.google.gwt.user.client.Event;
  41. import com.google.gwt.user.client.History;
  42. import com.google.gwt.user.client.Timer;
  43. import com.google.gwt.user.client.Window;
  44. import com.google.gwt.user.client.Window.Location;
  45. import com.google.gwt.user.client.ui.RootPanel;
  46. import com.google.gwt.user.client.ui.Widget;
  47. import com.google.web.bindery.event.shared.HandlerRegistration;
  48. import com.vaadin.client.ApplicationConnection;
  49. import com.vaadin.client.ApplicationConnection.ApplicationStoppedEvent;
  50. import com.vaadin.client.BrowserInfo;
  51. import com.vaadin.client.ComponentConnector;
  52. import com.vaadin.client.ConnectorHierarchyChangeEvent;
  53. import com.vaadin.client.Focusable;
  54. import com.vaadin.client.Paintable;
  55. import com.vaadin.client.ResourceLoader;
  56. import com.vaadin.client.ResourceLoader.ResourceLoadEvent;
  57. import com.vaadin.client.ResourceLoader.ResourceLoadListener;
  58. import com.vaadin.client.ServerConnector;
  59. import com.vaadin.client.UIDL;
  60. import com.vaadin.client.Util;
  61. import com.vaadin.client.VConsole;
  62. import com.vaadin.client.ValueMap;
  63. import com.vaadin.client.annotations.OnStateChange;
  64. import com.vaadin.client.communication.StateChangeEvent;
  65. import com.vaadin.client.communication.StateChangeEvent.StateChangeHandler;
  66. import com.vaadin.client.ui.AbstractConnector;
  67. import com.vaadin.client.ui.AbstractSingleComponentContainerConnector;
  68. import com.vaadin.client.ui.ClickEventHandler;
  69. import com.vaadin.client.ui.ShortcutActionHandler;
  70. import com.vaadin.client.ui.VNotification;
  71. import com.vaadin.client.ui.VOverlay;
  72. import com.vaadin.client.ui.VUI;
  73. import com.vaadin.client.ui.VWindow;
  74. import com.vaadin.client.ui.layout.MayScrollChildren;
  75. import com.vaadin.client.ui.window.WindowConnector;
  76. import com.vaadin.server.Page.Styles;
  77. import com.vaadin.shared.ApplicationConstants;
  78. import com.vaadin.shared.MouseEventDetails;
  79. import com.vaadin.shared.Version;
  80. import com.vaadin.shared.communication.MethodInvocation;
  81. import com.vaadin.shared.ui.ComponentStateUtil;
  82. import com.vaadin.shared.ui.Connect;
  83. import com.vaadin.shared.ui.Connect.LoadStyle;
  84. import com.vaadin.shared.ui.ui.DebugWindowClientRpc;
  85. import com.vaadin.shared.ui.ui.DebugWindowServerRpc;
  86. import com.vaadin.shared.ui.ui.PageClientRpc;
  87. import com.vaadin.shared.ui.ui.PageState;
  88. import com.vaadin.shared.ui.ui.ScrollClientRpc;
  89. import com.vaadin.shared.ui.ui.UIClientRpc;
  90. import com.vaadin.shared.ui.ui.UIConstants;
  91. import com.vaadin.shared.ui.ui.UIServerRpc;
  92. import com.vaadin.shared.ui.ui.UIState;
  93. import com.vaadin.shared.util.SharedUtil;
  94. import com.vaadin.ui.UI;
  95. @Connect(value = UI.class, loadStyle = LoadStyle.EAGER)
  96. public class UIConnector extends AbstractSingleComponentContainerConnector
  97. implements Paintable, MayScrollChildren {
  98. private HandlerRegistration childStateChangeHandlerRegistration;
  99. private String activeTheme = null;
  100. private final StateChangeHandler childStateChangeHandler = new StateChangeHandler() {
  101. @Override
  102. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  103. // TODO Should use a more specific handler that only reacts to
  104. // size changes
  105. onChildSizeChange();
  106. }
  107. };
  108. @Override
  109. protected void init() {
  110. super.init();
  111. registerRpc(PageClientRpc.class, new PageClientRpc() {
  112. @Override
  113. public void reload() {
  114. Window.Location.reload();
  115. }
  116. });
  117. registerRpc(ScrollClientRpc.class, new ScrollClientRpc() {
  118. @Override
  119. public void setScrollTop(int scrollTop) {
  120. getWidget().getElement().setScrollTop(scrollTop);
  121. }
  122. @Override
  123. public void setScrollLeft(int scrollLeft) {
  124. getWidget().getElement().setScrollLeft(scrollLeft);
  125. }
  126. });
  127. registerRpc(UIClientRpc.class, new UIClientRpc() {
  128. @Override
  129. public void uiClosed(final boolean sessionExpired) {
  130. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  131. @Override
  132. public void execute() {
  133. // Only notify user if we're still running and not eg.
  134. // navigating away (#12298)
  135. if (getConnection().isApplicationRunning()) {
  136. if (sessionExpired) {
  137. getConnection().showSessionExpiredError(null);
  138. } else {
  139. getState().enabled = false;
  140. updateEnabledState(getState().enabled);
  141. }
  142. getConnection().setApplicationRunning(false);
  143. }
  144. }
  145. });
  146. }
  147. });
  148. registerRpc(DebugWindowClientRpc.class, new DebugWindowClientRpc() {
  149. @Override
  150. public void reportLayoutProblems(String json) {
  151. VConsole.printLayoutProblems(getValueMap(json), getConnection());
  152. }
  153. private native ValueMap getValueMap(String json)
  154. /*-{
  155. return JSON.parse(json);
  156. }-*/;
  157. });
  158. getWidget().addResizeHandler(new ResizeHandler() {
  159. @Override
  160. public void onResize(ResizeEvent event) {
  161. getRpcProxy(UIServerRpc.class).resize(event.getHeight(),
  162. event.getWidth(), Window.getClientWidth(),
  163. Window.getClientHeight());
  164. if (getState().immediate || getPageState().hasResizeListeners) {
  165. getConnection().getServerRpcQueue().flush();
  166. }
  167. }
  168. });
  169. getWidget().addScrollHandler(new ScrollHandler() {
  170. private int lastSentScrollTop = Integer.MAX_VALUE;
  171. private int lastSentScrollLeft = Integer.MAX_VALUE;
  172. @Override
  173. public void onScroll(ScrollEvent event) {
  174. Element element = getWidget().getElement();
  175. int newScrollTop = element.getScrollTop();
  176. int newScrollLeft = element.getScrollLeft();
  177. if (newScrollTop != lastSentScrollTop
  178. || newScrollLeft != lastSentScrollLeft) {
  179. lastSentScrollTop = newScrollTop;
  180. lastSentScrollLeft = newScrollLeft;
  181. getRpcProxy(UIServerRpc.class).scroll(newScrollTop,
  182. newScrollLeft);
  183. }
  184. }
  185. });
  186. }
  187. private native void open(String url, String name)
  188. /*-{
  189. $wnd.open(url, name);
  190. }-*/;
  191. @Override
  192. public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) {
  193. getWidget().id = getConnectorId();
  194. boolean firstPaint = getWidget().connection == null;
  195. getWidget().connection = client;
  196. getWidget().immediate = getState().immediate;
  197. getWidget().resizeLazy = uidl.hasAttribute(UIConstants.RESIZE_LAZY);
  198. // this also implicitly removes old styles
  199. String styles = "";
  200. styles += getWidget().getStylePrimaryName() + " ";
  201. if (ComponentStateUtil.hasStyles(getState())) {
  202. for (String style : getState().styles) {
  203. styles += style + " ";
  204. }
  205. }
  206. if (!client.getConfiguration().isStandalone()) {
  207. styles += getWidget().getStylePrimaryName() + "-embedded";
  208. }
  209. getWidget().setStyleName(styles.trim());
  210. getWidget().makeScrollable();
  211. clickEventHandler.handleEventHandlerRegistration();
  212. // Process children
  213. int childIndex = 0;
  214. // Open URL:s
  215. boolean isClosed = false; // was this window closed?
  216. while (childIndex < uidl.getChildCount()
  217. && "open".equals(uidl.getChildUIDL(childIndex).getTag())) {
  218. final UIDL open = uidl.getChildUIDL(childIndex);
  219. final String url = client.translateVaadinUri(open
  220. .getStringAttribute("src"));
  221. final String target = open.getStringAttribute("name");
  222. if (target == null) {
  223. // source will be opened to this browser window, but we may have
  224. // to finish rendering this window in case this is a download
  225. // (and window stays open).
  226. Scheduler.get().scheduleDeferred(new Command() {
  227. @Override
  228. public void execute() {
  229. VUI.goTo(url);
  230. }
  231. });
  232. } else if ("_self".equals(target)) {
  233. // This window is closing (for sure). Only other opens are
  234. // relevant in this change. See #3558, #2144
  235. isClosed = true;
  236. VUI.goTo(url);
  237. } else {
  238. String options;
  239. boolean alwaysAsPopup = true;
  240. if (open.hasAttribute("popup")) {
  241. alwaysAsPopup = open.getBooleanAttribute("popup");
  242. }
  243. if (alwaysAsPopup) {
  244. if (open.hasAttribute("border")) {
  245. if (open.getStringAttribute("border").equals("minimal")) {
  246. options = "menubar=yes,location=no,status=no";
  247. } else {
  248. options = "menubar=no,location=no,status=no";
  249. }
  250. } else {
  251. options = "resizable=yes,menubar=yes,toolbar=yes,directories=yes,location=yes,scrollbars=yes,status=yes";
  252. }
  253. if (open.hasAttribute("width")) {
  254. int w = open.getIntAttribute("width");
  255. options += ",width=" + w;
  256. }
  257. if (open.hasAttribute("height")) {
  258. int h = open.getIntAttribute("height");
  259. options += ",height=" + h;
  260. }
  261. Window.open(url, target, options);
  262. } else {
  263. open(url, target);
  264. }
  265. }
  266. childIndex++;
  267. }
  268. if (isClosed) {
  269. // We're navigating away, so stop the application.
  270. client.setApplicationRunning(false);
  271. return;
  272. }
  273. // Handle other UIDL children
  274. UIDL childUidl;
  275. while ((childUidl = uidl.getChildUIDL(childIndex++)) != null) {
  276. String tag = childUidl.getTag().intern();
  277. if (tag == "actions") {
  278. if (getWidget().actionHandler == null) {
  279. getWidget().actionHandler = new ShortcutActionHandler(
  280. getWidget().id, client);
  281. }
  282. getWidget().actionHandler.updateActionMap(childUidl);
  283. } else if (tag == "notifications") {
  284. for (final Iterator<?> it = childUidl.getChildIterator(); it
  285. .hasNext();) {
  286. final UIDL notification = (UIDL) it.next();
  287. VNotification.showNotification(client, notification);
  288. }
  289. } else if (tag == "css-injections") {
  290. injectCSS(childUidl);
  291. }
  292. }
  293. if (uidl.hasAttribute("focused")) {
  294. // set focused component when render phase is finished
  295. Scheduler.get().scheduleDeferred(new Command() {
  296. @Override
  297. public void execute() {
  298. ComponentConnector connector = (ComponentConnector) uidl
  299. .getPaintableAttribute("focused", getConnection());
  300. if (connector == null) {
  301. // Do not try to focus invisible components which not
  302. // present in UIDL
  303. return;
  304. }
  305. final Widget toBeFocused = connector.getWidget();
  306. /*
  307. * Two types of Widgets can be focused, either implementing
  308. * GWT Focusable of a thinner Vaadin specific Focusable
  309. * interface.
  310. */
  311. if (toBeFocused instanceof com.google.gwt.user.client.ui.Focusable) {
  312. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) toBeFocused;
  313. toBeFocusedWidget.setFocus(true);
  314. } else if (toBeFocused instanceof Focusable) {
  315. ((Focusable) toBeFocused).focus();
  316. } else {
  317. getLogger()
  318. .severe("Server is trying to set focus to the widget of connector "
  319. + Util.getConnectorString(connector)
  320. + " but it is not focusable. The widget should implement either "
  321. + com.google.gwt.user.client.ui.Focusable.class
  322. .getName()
  323. + " or "
  324. + Focusable.class.getName());
  325. }
  326. }
  327. });
  328. }
  329. // Add window listeners on first paint, to prevent premature
  330. // variablechanges
  331. if (firstPaint) {
  332. Window.addWindowClosingHandler(getWidget());
  333. Window.addResizeHandler(getWidget());
  334. }
  335. if (uidl.hasAttribute("scrollTo")) {
  336. final ComponentConnector connector = (ComponentConnector) uidl
  337. .getPaintableAttribute("scrollTo", getConnection());
  338. scrollIntoView(connector);
  339. }
  340. if (uidl.hasAttribute(UIConstants.LOCATION_VARIABLE)) {
  341. String location = uidl
  342. .getStringAttribute(UIConstants.LOCATION_VARIABLE);
  343. String newFragment;
  344. int fragmentIndex = location.indexOf('#');
  345. if (fragmentIndex >= 0) {
  346. // Decode fragment to avoid double encoding (#10769)
  347. newFragment = URL.decodePathSegment(location
  348. .substring(fragmentIndex + 1));
  349. if (newFragment.isEmpty()
  350. && Location.getHref().indexOf('#') == -1) {
  351. // Ensure there is a trailing # even though History and
  352. // Location.getHash() treat null and "" the same way.
  353. Location.assign(Location.getHref() + "#");
  354. }
  355. } else {
  356. // No fragment in server-side location, but can't completely
  357. // remove the browser fragment since that would reload the page
  358. newFragment = "";
  359. }
  360. getWidget().currentFragment = newFragment;
  361. if (!newFragment.equals(History.getToken())) {
  362. History.newItem(newFragment, true);
  363. }
  364. }
  365. if (firstPaint) {
  366. // Queue the initial window size to be sent with the following
  367. // request.
  368. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  369. @Override
  370. public void execute() {
  371. getWidget().sendClientResized();
  372. }
  373. });
  374. }
  375. }
  376. /**
  377. * Reads CSS strings and resources injected by {@link Styles#inject} from
  378. * the UIDL stream.
  379. *
  380. * @param uidl
  381. * The uidl which contains "css-resource" and "css-string" tags
  382. */
  383. private void injectCSS(UIDL uidl) {
  384. /*
  385. * Search the UIDL stream for CSS resources and strings to be injected.
  386. */
  387. for (Iterator<?> it = uidl.getChildIterator(); it.hasNext();) {
  388. UIDL cssInjectionsUidl = (UIDL) it.next();
  389. // Check if we have resources to inject
  390. if (cssInjectionsUidl.getTag().equals("css-resource")) {
  391. String url = getWidget().connection
  392. .translateVaadinUri(cssInjectionsUidl
  393. .getStringAttribute("url"));
  394. LinkElement link = LinkElement.as(DOM
  395. .createElement(LinkElement.TAG));
  396. link.setRel("stylesheet");
  397. link.setHref(url);
  398. link.setType("text/css");
  399. getHead().appendChild(link);
  400. // Check if we have CSS string to inject
  401. } else if (cssInjectionsUidl.getTag().equals("css-string")) {
  402. for (Iterator<?> it2 = cssInjectionsUidl.getChildIterator(); it2
  403. .hasNext();) {
  404. StyleInjector.injectAtEnd((String) it2.next());
  405. StyleInjector.flush();
  406. }
  407. }
  408. }
  409. }
  410. /**
  411. * Internal helper to get the <head> tag of the page
  412. *
  413. * @since 7.3
  414. * @return the head element
  415. */
  416. private HeadElement getHead() {
  417. return HeadElement.as(Document.get()
  418. .getElementsByTagName(HeadElement.TAG).getItem(0));
  419. }
  420. /**
  421. * Internal helper for removing any stylesheet with the given URL
  422. *
  423. * @since 7.3
  424. * @param url
  425. * the url to match with existing stylesheets
  426. */
  427. private void removeStylesheet(String url) {
  428. NodeList<Element> linkTags = getHead().getElementsByTagName(
  429. LinkElement.TAG);
  430. for (int i = 0; i < linkTags.getLength(); i++) {
  431. LinkElement link = LinkElement.as(linkTags.getItem(i));
  432. if (!"stylesheet".equals(link.getRel())) {
  433. continue;
  434. }
  435. if (!"text/css".equals(link.getType())) {
  436. continue;
  437. }
  438. if (url.equals(link.getHref())) {
  439. getHead().removeChild(link);
  440. }
  441. }
  442. }
  443. public void init(String rootPanelId,
  444. ApplicationConnection applicationConnection) {
  445. // Create a style tag for style injections so they don't end up in
  446. // the theme tag in IE8-IE10 (we don't want to wipe them out if we
  447. // change theme).
  448. // StyleInjectorImplIE always injects to the last style tag on the page.
  449. if (BrowserInfo.get().isIE()
  450. && BrowserInfo.get().getBrowserMajorVersion() < 11) {
  451. StyleElement style = Document.get().createStyleElement();
  452. style.setType("text/css");
  453. getHead().appendChild(style);
  454. }
  455. DOM.sinkEvents(getWidget().getElement(), Event.ONKEYDOWN
  456. | Event.ONSCROLL);
  457. RootPanel root = RootPanel.get(rootPanelId);
  458. // Remove the v-app-loading or any splash screen added inside the div by
  459. // the user
  460. root.getElement().setInnerHTML("");
  461. // Activate the initial theme by only adding the class name. Not calling
  462. // activateTheme here as it will also cause a full layout and updates to
  463. // the overlay container which has not yet been created at this point
  464. activeTheme = applicationConnection.getConfiguration().getThemeName();
  465. root.addStyleName(activeTheme);
  466. root.add(getWidget());
  467. // Set default tab index before focus call. State change handler
  468. // will update this later if needed.
  469. getWidget().setTabIndex(1);
  470. if (applicationConnection.getConfiguration().isStandalone()) {
  471. // set focus to iview element by default to listen possible keyboard
  472. // shortcuts. For embedded applications this is unacceptable as we
  473. // don't want to steal focus from the main page nor we don't want
  474. // side-effects from focusing (scrollIntoView).
  475. getWidget().getElement().focus();
  476. }
  477. applicationConnection.addHandler(
  478. ApplicationConnection.ApplicationStoppedEvent.TYPE,
  479. new ApplicationConnection.ApplicationStoppedHandler() {
  480. @Override
  481. public void onApplicationStopped(
  482. ApplicationStoppedEvent event) {
  483. // Stop any polling
  484. if (pollTimer != null) {
  485. pollTimer.cancel();
  486. pollTimer = null;
  487. }
  488. }
  489. });
  490. }
  491. private ClickEventHandler clickEventHandler = new ClickEventHandler(this) {
  492. @Override
  493. protected void fireClick(NativeEvent event,
  494. MouseEventDetails mouseDetails) {
  495. getRpcProxy(UIServerRpc.class).click(mouseDetails);
  496. }
  497. };
  498. private Timer pollTimer = null;
  499. @Override
  500. public void updateCaption(ComponentConnector component) {
  501. // NOP The main view never draws caption for its layout
  502. }
  503. @Override
  504. public VUI getWidget() {
  505. return (VUI) super.getWidget();
  506. }
  507. @Override
  508. protected ComponentConnector getContent() {
  509. ComponentConnector connector = super.getContent();
  510. // VWindow (WindowConnector is its connector)is also a child component
  511. // but it's never a content widget
  512. if (connector instanceof WindowConnector) {
  513. return null;
  514. } else {
  515. return connector;
  516. }
  517. }
  518. protected void onChildSizeChange() {
  519. ComponentConnector child = getContent();
  520. if (child == null) {
  521. return;
  522. }
  523. Style childStyle = child.getWidget().getElement().getStyle();
  524. /*
  525. * Must set absolute position if the child has relative height and
  526. * there's a chance of horizontal scrolling as some browsers will
  527. * otherwise not take the scrollbar into account when calculating the
  528. * height. Assuming v-ui does not have an undefined width for now, see
  529. * #8460.
  530. */
  531. if (child.isRelativeHeight() && !BrowserInfo.get().isIE9()) {
  532. childStyle.setPosition(Position.ABSOLUTE);
  533. } else {
  534. childStyle.clearPosition();
  535. }
  536. }
  537. /**
  538. * Checks if the given sub window is a child of this UI Connector
  539. *
  540. * @deprecated Should be replaced by a more generic mechanism for getting
  541. * non-ComponentConnector children
  542. * @param wc
  543. * @return
  544. */
  545. @Deprecated
  546. public boolean hasSubWindow(WindowConnector wc) {
  547. return getChildComponents().contains(wc);
  548. }
  549. /**
  550. * Return an iterator for current subwindows. This method is meant for
  551. * testing purposes only.
  552. *
  553. * @return
  554. */
  555. public List<WindowConnector> getSubWindows() {
  556. ArrayList<WindowConnector> windows = new ArrayList<WindowConnector>();
  557. for (ComponentConnector child : getChildComponents()) {
  558. if (child instanceof WindowConnector) {
  559. windows.add((WindowConnector) child);
  560. }
  561. }
  562. return windows;
  563. }
  564. @Override
  565. public UIState getState() {
  566. return (UIState) super.getState();
  567. }
  568. /**
  569. * Returns the state of the Page associated with the UI.
  570. * <p>
  571. * Note that state is considered an internal part of the connector. You
  572. * should not rely on the state object outside of the connector who owns it.
  573. * If you depend on the state of other connectors you should use their
  574. * public API instead of their state object directly. The page state might
  575. * not be an independent state object but can be embedded in UI state.
  576. * </p>
  577. *
  578. * @since 7.1
  579. * @return state object of the page
  580. */
  581. public PageState getPageState() {
  582. return getState().pageState;
  583. }
  584. @Override
  585. public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent event) {
  586. ComponentConnector oldChild = null;
  587. ComponentConnector newChild = getContent();
  588. for (ComponentConnector c : event.getOldChildren()) {
  589. if (!(c instanceof WindowConnector)) {
  590. oldChild = c;
  591. break;
  592. }
  593. }
  594. if (oldChild != newChild) {
  595. if (childStateChangeHandlerRegistration != null) {
  596. childStateChangeHandlerRegistration.removeHandler();
  597. childStateChangeHandlerRegistration = null;
  598. }
  599. if (newChild != null) {
  600. getWidget().setWidget(newChild.getWidget());
  601. childStateChangeHandlerRegistration = newChild
  602. .addStateChangeHandler(childStateChangeHandler);
  603. // Must handle new child here as state change events are already
  604. // fired
  605. onChildSizeChange();
  606. } else {
  607. getWidget().setWidget(null);
  608. }
  609. }
  610. for (ComponentConnector c : getChildComponents()) {
  611. if (c instanceof WindowConnector) {
  612. WindowConnector wc = (WindowConnector) c;
  613. wc.setWindowOrderAndPosition();
  614. VWindow window = wc.getWidget();
  615. if (!window.isAttached()) {
  616. // Attach so that all widgets inside the Window are attached
  617. // when their onStateChange is run
  618. // Made invisible here for legacy reasons and made visible
  619. // at the end of stateChange. This dance could probably be
  620. // removed
  621. window.setVisible(false);
  622. window.show();
  623. }
  624. }
  625. }
  626. // Close removed sub windows
  627. for (ComponentConnector c : event.getOldChildren()) {
  628. if (c.getParent() != this && c instanceof WindowConnector) {
  629. ((WindowConnector) c).getWidget().hide();
  630. }
  631. }
  632. }
  633. @Override
  634. public boolean hasTooltip() {
  635. /*
  636. * Always return true so there's always top level tooltip handler that
  637. * takes care of hiding tooltips whenever the mouse is moved somewhere
  638. * else.
  639. */
  640. return true;
  641. }
  642. /**
  643. * Tries to scroll the viewport so that the given connector is in view.
  644. *
  645. * @param componentConnector
  646. * The connector which should be visible
  647. *
  648. */
  649. public void scrollIntoView(final ComponentConnector componentConnector) {
  650. if (componentConnector == null) {
  651. return;
  652. }
  653. Scheduler.get().scheduleDeferred(new Command() {
  654. @Override
  655. public void execute() {
  656. componentConnector.getWidget().getElement().scrollIntoView();
  657. }
  658. });
  659. }
  660. @Override
  661. public void onStateChanged(StateChangeEvent stateChangeEvent) {
  662. super.onStateChanged(stateChangeEvent);
  663. if (stateChangeEvent.hasPropertyChanged("tooltipConfiguration")) {
  664. getConnection().getVTooltip().setCloseTimeout(
  665. getState().tooltipConfiguration.closeTimeout);
  666. getConnection().getVTooltip().setOpenDelay(
  667. getState().tooltipConfiguration.openDelay);
  668. getConnection().getVTooltip().setQuickOpenDelay(
  669. getState().tooltipConfiguration.quickOpenDelay);
  670. getConnection().getVTooltip().setQuickOpenTimeout(
  671. getState().tooltipConfiguration.quickOpenTimeout);
  672. getConnection().getVTooltip().setMaxWidth(
  673. getState().tooltipConfiguration.maxWidth);
  674. }
  675. if (stateChangeEvent
  676. .hasPropertyChanged("loadingIndicatorConfiguration")) {
  677. getConnection().getLoadingIndicator().setFirstDelay(
  678. getState().loadingIndicatorConfiguration.firstDelay);
  679. getConnection().getLoadingIndicator().setSecondDelay(
  680. getState().loadingIndicatorConfiguration.secondDelay);
  681. getConnection().getLoadingIndicator().setThirdDelay(
  682. getState().loadingIndicatorConfiguration.thirdDelay);
  683. }
  684. if (stateChangeEvent.hasPropertyChanged("pollInterval")) {
  685. configurePolling();
  686. }
  687. if (stateChangeEvent.hasPropertyChanged("pageState.title")) {
  688. String title = getState().pageState.title;
  689. if (title != null) {
  690. com.google.gwt.user.client.Window.setTitle(title);
  691. }
  692. }
  693. if (stateChangeEvent.hasPropertyChanged("pushConfiguration")) {
  694. getConnection().getMessageSender().setPushEnabled(
  695. getState().pushConfiguration.mode.isEnabled());
  696. }
  697. if (stateChangeEvent.hasPropertyChanged("reconnectDialogConfiguration")) {
  698. getConnection().getConnectionStateHandler().configurationUpdated();
  699. }
  700. if (stateChangeEvent.hasPropertyChanged("overlayContainerLabel")) {
  701. VOverlay.setOverlayContainerLabel(getConnection(),
  702. getState().overlayContainerLabel);
  703. }
  704. }
  705. private void configurePolling() {
  706. if (pollTimer != null) {
  707. pollTimer.cancel();
  708. pollTimer = null;
  709. }
  710. if (getState().pollInterval >= 0) {
  711. pollTimer = new Timer() {
  712. @Override
  713. public void run() {
  714. if (getState().pollInterval < 0) {
  715. // Polling has been cancelled server side
  716. pollTimer.cancel();
  717. pollTimer = null;
  718. return;
  719. }
  720. getRpcProxy(UIServerRpc.class).poll();
  721. // Send changes even though poll is @Delayed
  722. getConnection().getServerRpcQueue().flush();
  723. }
  724. };
  725. pollTimer.scheduleRepeating(getState().pollInterval);
  726. } else {
  727. // Ensure no more polls are sent as polling has been disabled
  728. getConnection().getServerRpcQueue().removeMatching(
  729. new MethodInvocation(getConnectorId(), UIServerRpc.class
  730. .getName(), "poll"));
  731. }
  732. }
  733. /**
  734. * Invokes the layout analyzer on the server
  735. *
  736. * @since 7.1
  737. */
  738. public void analyzeLayouts() {
  739. getRpcProxy(DebugWindowServerRpc.class).analyzeLayouts();
  740. }
  741. /**
  742. * Sends a request to the server to print details to console that will help
  743. * the developer to locate the corresponding server-side connector in the
  744. * source code.
  745. *
  746. * @since 7.1
  747. * @param serverConnector
  748. * the connector to locate
  749. */
  750. public void showServerDebugInfo(ServerConnector serverConnector) {
  751. getRpcProxy(DebugWindowServerRpc.class).showServerDebugInfo(
  752. serverConnector);
  753. }
  754. /**
  755. * Sends a request to the server to print a design to the console for the
  756. * given component.
  757. *
  758. * @since 7.5
  759. * @param connector
  760. * the component connector to output a declarative design for
  761. */
  762. public void showServerDesign(ServerConnector connector) {
  763. getRpcProxy(DebugWindowServerRpc.class).showServerDesign(connector);
  764. }
  765. @OnStateChange("theme")
  766. void onThemeChange() {
  767. final String oldTheme = activeTheme;
  768. final String newTheme = getState().theme;
  769. final String oldThemeUrl = getThemeUrl(oldTheme);
  770. final String newThemeUrl = getThemeUrl(newTheme);
  771. if (SharedUtil.equals(oldTheme, newTheme)) {
  772. // This should only happen on the initial load when activeTheme has
  773. // been updated in init.
  774. if (newTheme == null) {
  775. return;
  776. }
  777. // For the embedded case we cannot be 100% sure that the theme has
  778. // been loaded and that the style names have been set.
  779. if (findStylesheetTag(oldThemeUrl) == null) {
  780. // If there is no style tag, load it the normal way (the class
  781. // name will be added when theme has been loaded)
  782. replaceTheme(null, newTheme, null, newThemeUrl);
  783. } else if (!getWidget().getParent().getElement()
  784. .hasClassName(newTheme)) {
  785. // If only the class name is missing, add that
  786. activateTheme(newTheme);
  787. }
  788. return;
  789. }
  790. getLogger().info("Changing theme from " + oldTheme + " to " + newTheme);
  791. replaceTheme(oldTheme, newTheme, oldThemeUrl, newThemeUrl);
  792. }
  793. /**
  794. * Loads the new theme and removes references to the old theme
  795. *
  796. * @since 7.4.3
  797. * @param oldTheme
  798. * The name of the old theme
  799. * @param newTheme
  800. * The name of the new theme
  801. * @param oldThemeUrl
  802. * The url of the old theme
  803. * @param newThemeUrl
  804. * The url of the new theme
  805. */
  806. protected void replaceTheme(final String oldTheme, final String newTheme,
  807. String oldThemeUrl, final String newThemeUrl) {
  808. LinkElement tagToReplace = null;
  809. if (oldTheme != null) {
  810. tagToReplace = findStylesheetTag(oldThemeUrl);
  811. if (tagToReplace == null) {
  812. getLogger()
  813. .warning(
  814. "Did not find the link tag for the old theme ("
  815. + oldThemeUrl
  816. + "), adding a new stylesheet for the new theme ("
  817. + newThemeUrl + ")");
  818. }
  819. }
  820. if (newTheme != null) {
  821. loadTheme(newTheme, newThemeUrl, tagToReplace);
  822. } else {
  823. if (tagToReplace != null) {
  824. tagToReplace.getParentElement().removeChild(tagToReplace);
  825. }
  826. activateTheme(null);
  827. }
  828. }
  829. private void updateVaadinFavicon(String newTheme) {
  830. NodeList<Element> iconElements = querySelectorAll("link[rel~=\"icon\"]");
  831. for (int i = 0; i < iconElements.getLength(); i++) {
  832. Element iconElement = iconElements.getItem(i);
  833. String href = iconElement.getAttribute("href");
  834. if (href != null && href.contains("VAADIN/themes")
  835. && href.endsWith("/favicon.ico")) {
  836. href = href.replaceFirst("VAADIN/themes/.+?/favicon.ico",
  837. "VAADIN/themes/" + newTheme + "/favicon.ico");
  838. iconElement.setAttribute("href", href);
  839. }
  840. }
  841. }
  842. private static native NodeList<Element> querySelectorAll(String selector)
  843. /*-{
  844. return $doc.querySelectorAll(selector);
  845. }-*/;
  846. /**
  847. * Finds a link tag for a style sheet with the given URL
  848. *
  849. * @since 7.3
  850. * @param url
  851. * the URL of the style sheet
  852. * @return the link tag or null if no matching link tag was found
  853. */
  854. private LinkElement findStylesheetTag(String url) {
  855. NodeList<Element> linkTags = getHead().getElementsByTagName(
  856. LinkElement.TAG);
  857. for (int i = 0; i < linkTags.getLength(); i++) {
  858. final LinkElement link = LinkElement.as(linkTags.getItem(i));
  859. if ("stylesheet".equals(link.getRel())
  860. && "text/css".equals(link.getType())
  861. && url.equals(link.getHref())) {
  862. return link;
  863. }
  864. }
  865. return null;
  866. }
  867. /**
  868. * Loads the given theme and replaces the given link element with the new
  869. * theme link element.
  870. *
  871. * @param newTheme
  872. * The name of the new theme
  873. * @param newThemeUrl
  874. * The url of the new theme
  875. * @param tagToReplace
  876. * The link element to replace. If null, then the new link
  877. * element is added at the end.
  878. */
  879. private void loadTheme(final String newTheme, final String newThemeUrl,
  880. final LinkElement tagToReplace) {
  881. LinkElement newThemeLinkElement = Document.get().createLinkElement();
  882. newThemeLinkElement.setRel("stylesheet");
  883. newThemeLinkElement.setType("text/css");
  884. newThemeLinkElement.setHref(newThemeUrl);
  885. ResourceLoader.addOnloadHandler(newThemeLinkElement,
  886. new ResourceLoadListener() {
  887. @Override
  888. public void onLoad(ResourceLoadEvent event) {
  889. getLogger().info(
  890. "Loading of " + newTheme + " from "
  891. + newThemeUrl + " completed");
  892. if (tagToReplace != null) {
  893. tagToReplace.getParentElement().removeChild(
  894. tagToReplace);
  895. }
  896. activateTheme(newTheme);
  897. }
  898. @Override
  899. public void onError(ResourceLoadEvent event) {
  900. getLogger().warning(
  901. "Could not load theme from "
  902. + getThemeUrl(newTheme));
  903. }
  904. }, null);
  905. if (tagToReplace != null) {
  906. getHead().insertBefore(newThemeLinkElement, tagToReplace);
  907. } else {
  908. getHead().appendChild(newThemeLinkElement);
  909. }
  910. }
  911. /**
  912. * Activates the new theme. Assumes the theme has been loaded and taken into
  913. * use in the browser.
  914. *
  915. * @since 7.4.3
  916. * @param newTheme
  917. * The name of the new theme
  918. */
  919. protected void activateTheme(String newTheme) {
  920. if (activeTheme != null) {
  921. getWidget().getParent().removeStyleName(activeTheme);
  922. VOverlay.getOverlayContainer(getConnection()).removeClassName(
  923. activeTheme);
  924. }
  925. String oldThemeBase = getConnection().translateVaadinUri("theme://");
  926. activeTheme = newTheme;
  927. if (newTheme != null) {
  928. getWidget().getParent().addStyleName(newTheme);
  929. VOverlay.getOverlayContainer(getConnection()).addClassName(
  930. activeTheme);
  931. updateVaadinFavicon(newTheme);
  932. }
  933. // Request a full resynchronization from the server to deal with legacy
  934. // components
  935. getConnection().getMessageSender().resynchronize();
  936. // Immediately update state and do layout while waiting for the resync
  937. forceStateChangeRecursively(UIConnector.this);
  938. getLayoutManager().forceLayout();
  939. }
  940. /**
  941. * Force a full recursive recheck of every connector's state variables.
  942. *
  943. * @see #forceStateChange()
  944. *
  945. * @since 7.3
  946. */
  947. protected static void forceStateChangeRecursively(
  948. AbstractConnector connector) {
  949. connector.forceStateChange();
  950. for (ServerConnector child : connector.getChildren()) {
  951. if (child instanceof AbstractConnector) {
  952. forceStateChangeRecursively((AbstractConnector) child);
  953. } else {
  954. getLogger().warning(
  955. "Could not force state change for unknown connector type: "
  956. + child.getClass().getName());
  957. }
  958. }
  959. }
  960. /**
  961. * Internal helper to get the theme URL for a given theme
  962. *
  963. * @since 7.3
  964. * @param theme
  965. * the name of the theme
  966. * @return The URL the theme can be loaded from
  967. */
  968. private String getThemeUrl(String theme) {
  969. String themeUrl = getConnection().translateVaadinUri(
  970. ApplicationConstants.VAADIN_PROTOCOL_PREFIX + "themes/" + theme
  971. + "/styles" + ".css");
  972. // Parameter appended to bypass caches after version upgrade.
  973. themeUrl += "?v=" + Version.getFullVersion();
  974. return themeUrl;
  975. }
  976. /**
  977. * Returns the name of the theme currently in used by the UI
  978. *
  979. * @since 7.3
  980. * @return the theme name used by this UI
  981. */
  982. public String getActiveTheme() {
  983. return activeTheme;
  984. }
  985. private static Logger getLogger() {
  986. return Logger.getLogger(UIConnector.class.getName());
  987. }
  988. }