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

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