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

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