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.

ApplicationConnection.java 80KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.HashSet;
  10. import java.util.Iterator;
  11. import java.util.LinkedList;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Set;
  15. import com.google.gwt.core.client.Duration;
  16. import com.google.gwt.core.client.GWT;
  17. import com.google.gwt.core.client.JavaScriptObject;
  18. import com.google.gwt.core.client.JsArray;
  19. import com.google.gwt.core.client.JsArrayString;
  20. import com.google.gwt.core.client.Scheduler;
  21. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  22. import com.google.gwt.http.client.Request;
  23. import com.google.gwt.http.client.RequestBuilder;
  24. import com.google.gwt.http.client.RequestCallback;
  25. import com.google.gwt.http.client.RequestException;
  26. import com.google.gwt.http.client.Response;
  27. import com.google.gwt.json.client.JSONArray;
  28. import com.google.gwt.json.client.JSONString;
  29. import com.google.gwt.regexp.shared.MatchResult;
  30. import com.google.gwt.regexp.shared.RegExp;
  31. import com.google.gwt.user.client.Command;
  32. import com.google.gwt.user.client.DOM;
  33. import com.google.gwt.user.client.Element;
  34. import com.google.gwt.user.client.Event;
  35. import com.google.gwt.user.client.Timer;
  36. import com.google.gwt.user.client.ui.HasWidgets;
  37. import com.google.gwt.user.client.ui.Widget;
  38. import com.vaadin.terminal.gwt.client.ApplicationConfiguration.ErrorMessage;
  39. import com.vaadin.terminal.gwt.client.communication.JsonDecoder;
  40. import com.vaadin.terminal.gwt.client.communication.JsonEncoder;
  41. import com.vaadin.terminal.gwt.client.communication.MethodInvocation;
  42. import com.vaadin.terminal.gwt.client.communication.RpcManager;
  43. import com.vaadin.terminal.gwt.client.communication.SharedState;
  44. import com.vaadin.terminal.gwt.client.ui.RootConnector;
  45. import com.vaadin.terminal.gwt.client.ui.VContextMenu;
  46. import com.vaadin.terminal.gwt.client.ui.VNotification;
  47. import com.vaadin.terminal.gwt.client.ui.VNotification.HideEvent;
  48. import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
  49. import com.vaadin.terminal.gwt.server.AbstractCommunicationManager;
  50. /**
  51. * This is the client side communication "engine", managing client-server
  52. * communication with its server side counterpart
  53. * {@link AbstractCommunicationManager}.
  54. *
  55. * Client-side widgets receive updates from the corresponding server-side
  56. * components as calls to
  57. * {@link ComponentConnector#updateFromUIDL(UIDL, ApplicationConnection)} (not
  58. * to be confused with the server side interface
  59. * {@link com.vaadin.terminal.Paintable} ). Any client-side changes (typically
  60. * resulting from user actions) are sent back to the server as variable changes
  61. * (see {@link #updateVariable()}).
  62. *
  63. * TODO document better
  64. *
  65. * Entry point classes (widgetsets) define <code>onModuleLoad()</code>.
  66. */
  67. public class ApplicationConnection {
  68. // This indicates the whole page is generated by us (not embedded)
  69. public static final String GENERATED_BODY_CLASSNAME = "v-generated-body";
  70. public static final String MODIFIED_CLASSNAME = "v-modified";
  71. public static final String DISABLED_CLASSNAME = "v-disabled";
  72. public static final String REQUIRED_CLASSNAME_EXT = "-required";
  73. public static final String ERROR_CLASSNAME_EXT = "-error";
  74. public static final String UPDATE_VARIABLE_INTERFACE = "v";
  75. public static final String UPDATE_VARIABLE_METHOD = "v";
  76. public static final char VAR_BURST_SEPARATOR = '\u001d';
  77. public static final char VAR_ESCAPE_CHARACTER = '\u001b';
  78. public static final String UIDL_SECURITY_TOKEN_ID = "Vaadin-Security-Key";
  79. /**
  80. * Name of the parameter used to transmit root ids back and forth
  81. */
  82. public static final String ROOT_ID_PARAMETER = "rootId";
  83. /**
  84. * @deprecated use UIDL_SECURITY_TOKEN_ID instead
  85. */
  86. @Deprecated
  87. public static final String UIDL_SECURITY_HEADER = UIDL_SECURITY_TOKEN_ID;
  88. public static final String PARAM_UNLOADBURST = "onunloadburst";
  89. /**
  90. * A string that, if found in a non-JSON response to a UIDL request, will
  91. * cause the browser to refresh the page. If followed by a colon, optional
  92. * whitespace, and a URI, causes the browser to synchronously load the URI.
  93. *
  94. * <p>
  95. * This allows, for instance, a servlet filter to redirect the application
  96. * to a custom login page when the session expires. For example:
  97. * </p>
  98. *
  99. * <pre>
  100. * if (sessionExpired) {
  101. * response.setHeader(&quot;Content-Type&quot;, &quot;text/html&quot;);
  102. * response.getWriter().write(
  103. * myLoginPageHtml + &quot;&lt;!-- Vaadin-Refresh: &quot;
  104. * + request.getContextPath() + &quot; --&gt;&quot;);
  105. * }
  106. * </pre>
  107. */
  108. public static final String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";
  109. // will hold the UIDL security key (for XSS protection) once received
  110. private String uidlSecurityKey = "init";
  111. private final HashMap<String, String> resourcesMap = new HashMap<String, String>();
  112. private ArrayList<MethodInvocation> pendingInvocations = new ArrayList<MethodInvocation>();
  113. private WidgetSet widgetSet;
  114. private VContextMenu contextMenu = null;
  115. private Timer loadTimer;
  116. private Timer loadTimer2;
  117. private Timer loadTimer3;
  118. private Element loadElement;
  119. private final RootConnector view;
  120. protected boolean applicationRunning = false;
  121. private int activeRequests = 0;
  122. protected boolean cssLoaded = false;
  123. /** Parameters for this application connection loaded from the web-page */
  124. private ApplicationConfiguration configuration;
  125. /** List of pending variable change bursts that must be submitted in order */
  126. private final ArrayList<ArrayList<MethodInvocation>> pendingBursts = new ArrayList<ArrayList<MethodInvocation>>();
  127. /** Timer for automatic refirect to SessionExpiredURL */
  128. private Timer redirectTimer;
  129. /** redirectTimer scheduling interval in seconds */
  130. private int sessionExpirationInterval;
  131. private ArrayList<Widget> componentCaptionSizeChanges = new ArrayList<Widget>();
  132. private Date requestStartTime;
  133. private boolean validatingLayouts = false;
  134. private Set<ComponentConnector> zeroWidthComponents = null;
  135. private Set<ComponentConnector> zeroHeightComponents = null;
  136. private final LayoutManager layoutManager = new LayoutManager(this);
  137. private final RpcManager rpcManager = GWT.create(RpcManager.class);
  138. public ApplicationConnection() {
  139. view = GWT.create(RootConnector.class);
  140. }
  141. public void init(WidgetSet widgetSet, ApplicationConfiguration cnf) {
  142. VConsole.log("Starting application " + cnf.getRootPanelId());
  143. VConsole.log("Vaadin application servlet version: "
  144. + cnf.getServletVersion());
  145. VConsole.log("Application version: " + cnf.getApplicationVersion());
  146. if (!cnf.getServletVersion().equals(ApplicationConfiguration.VERSION)) {
  147. VConsole.error("Warning: your widget set seems to be built with a different "
  148. + "version than the one used on server. Unexpected "
  149. + "behavior may occur.");
  150. }
  151. this.widgetSet = widgetSet;
  152. configuration = cnf;
  153. ComponentLocator componentLocator = new ComponentLocator(this);
  154. String appRootPanelName = cnf.getRootPanelId();
  155. // remove the end (window name) of autogenerated rootpanel id
  156. appRootPanelName = appRootPanelName.replaceFirst("-\\d+$", "");
  157. initializeTestbenchHooks(componentLocator, appRootPanelName);
  158. initializeClientHooks();
  159. view.init(cnf.getRootPanelId(), this);
  160. showLoadingIndicator();
  161. }
  162. /**
  163. * Starts this application. Don't call this method directly - it's called by
  164. * {@link ApplicationConfiguration#startNextApplication()}, which should be
  165. * called once this application has started (first response received) or
  166. * failed to start. This ensures that the applications are started in order,
  167. * to avoid session-id problems.
  168. *
  169. */
  170. public void start() {
  171. String jsonText = configuration.getUIDL();
  172. if (jsonText == null) {
  173. // inital UIDL not in DOM, request later
  174. repaintAll();
  175. } else {
  176. // Update counter so TestBench knows something is still going on
  177. incrementActiveRequests();
  178. // initial UIDL provided in DOM, continue as if returned by request
  179. handleJSONText(jsonText);
  180. }
  181. }
  182. private native void initializeTestbenchHooks(
  183. ComponentLocator componentLocator, String TTAppId)
  184. /*-{
  185. var ap = this;
  186. var client = {};
  187. client.isActive = function() {
  188. return ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::hasActiveRequest()()
  189. || ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::isExecutingDeferredCommands()();
  190. }
  191. var vi = ap.@com.vaadin.terminal.gwt.client.ApplicationConnection::getVersionInfo()();
  192. if (vi) {
  193. client.getVersionInfo = function() {
  194. return vi;
  195. }
  196. }
  197. client.getElementByPath = function(id) {
  198. return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getElementByPath(Ljava/lang/String;)(id);
  199. }
  200. client.getPathForElement = function(element) {
  201. return componentLocator.@com.vaadin.terminal.gwt.client.ComponentLocator::getPathForElement(Lcom/google/gwt/user/client/Element;)(element);
  202. }
  203. $wnd.vaadin.clients[TTAppId] = client;
  204. }-*/;
  205. /**
  206. * Helper for tt initialization
  207. */
  208. private JavaScriptObject getVersionInfo() {
  209. return configuration.getVersionInfoJSObject();
  210. }
  211. /**
  212. * Publishes a JavaScript API for mash-up applications.
  213. * <ul>
  214. * <li><code>vaadin.forceSync()</code> sends pending variable changes, in
  215. * effect synchronizing the server and client state. This is done for all
  216. * applications on host page.</li>
  217. * <li><code>vaadin.postRequestHooks</code> is a map of functions which gets
  218. * called after each XHR made by vaadin application. Note, that it is
  219. * attaching js functions responsibility to create the variable like this:
  220. *
  221. * <code><pre>
  222. * if(!vaadin.postRequestHooks) {vaadin.postRequestHooks = new Object();}
  223. * postRequestHooks.myHook = function(appId) {
  224. * if(appId == "MyAppOfInterest") {
  225. * // do the staff you need on xhr activity
  226. * }
  227. * }
  228. * </pre></code> First parameter passed to these functions is the identifier
  229. * of Vaadin application that made the request.
  230. * </ul>
  231. *
  232. * TODO make this multi-app aware
  233. */
  234. private native void initializeClientHooks()
  235. /*-{
  236. var app = this;
  237. var oldSync;
  238. if ($wnd.vaadin.forceSync) {
  239. oldSync = $wnd.vaadin.forceSync;
  240. }
  241. $wnd.vaadin.forceSync = function() {
  242. if (oldSync) {
  243. oldSync();
  244. }
  245. app.@com.vaadin.terminal.gwt.client.ApplicationConnection::sendPendingVariableChanges()();
  246. }
  247. var oldForceLayout;
  248. if ($wnd.vaadin.forceLayout) {
  249. oldForceLayout = $wnd.vaadin.forceLayout;
  250. }
  251. $wnd.vaadin.forceLayout = function() {
  252. if (oldForceLayout) {
  253. oldForceLayout();
  254. }
  255. app.@com.vaadin.terminal.gwt.client.ApplicationConnection::forceLayout()();
  256. }
  257. }-*/;
  258. /**
  259. * Runs possibly registered client side post request hooks. This is expected
  260. * to be run after each uidl request made by Vaadin application.
  261. *
  262. * @param appId
  263. */
  264. private static native void runPostRequestHooks(String appId)
  265. /*-{
  266. if ($wnd.vaadin.postRequestHooks) {
  267. for ( var hook in $wnd.vaadin.postRequestHooks) {
  268. if (typeof ($wnd.vaadin.postRequestHooks[hook]) == "function") {
  269. try {
  270. $wnd.vaadin.postRequestHooks[hook](appId);
  271. } catch (e) {
  272. }
  273. }
  274. }
  275. }
  276. }-*/;
  277. /**
  278. * Get the active Console for writing debug messages. May return an actual
  279. * logging console, or the NullConsole if debugging is not turned on.
  280. *
  281. * @deprecated Developers should use {@link VConsole} since 6.4.5
  282. *
  283. * @return the active Console
  284. */
  285. @Deprecated
  286. public static Console getConsole() {
  287. return VConsole.getImplementation();
  288. }
  289. /**
  290. * Checks if client side is in debug mode. Practically this is invoked by
  291. * adding ?debug parameter to URI.
  292. *
  293. * @deprecated use ApplicationConfiguration isDebugMode instead.
  294. *
  295. * @return true if client side is currently been debugged
  296. */
  297. @Deprecated
  298. public static boolean isDebugMode() {
  299. return ApplicationConfiguration.isDebugMode();
  300. }
  301. /**
  302. * Gets the application base URI. Using this other than as the download
  303. * action URI can cause problems in Portlet 2.0 deployments.
  304. *
  305. * @return application base URI
  306. */
  307. public String getAppUri() {
  308. return configuration.getApplicationUri();
  309. };
  310. /**
  311. * Indicates whether or not there are currently active UIDL requests. Used
  312. * internally to squence requests properly, seldom needed in Widgets.
  313. *
  314. * @return true if there are active requests
  315. */
  316. public boolean hasActiveRequest() {
  317. return (activeRequests > 0);
  318. }
  319. public void incrementActiveRequests() {
  320. if (activeRequests < 0) {
  321. activeRequests = 1;
  322. } else {
  323. activeRequests++;
  324. }
  325. }
  326. public void decrementActiveRequests() {
  327. if (activeRequests > 0) {
  328. activeRequests--;
  329. }
  330. }
  331. private String getRepaintAllParameters() {
  332. // collect some client side data that will be sent to server on
  333. // initial uidl request
  334. String nativeBootstrapParameters = getNativeBrowserDetailsParameters(getConfiguration()
  335. .getRootPanelId());
  336. String widgetsetVersion = ApplicationConfiguration.VERSION;
  337. // TODO figure out how client and view size could be used better on
  338. // server. screen size can be accessed via Browser object, but other
  339. // values currently only via transaction listener.
  340. String parameters = "repaintAll=1&" + nativeBootstrapParameters
  341. + "&wsver=" + widgetsetVersion;
  342. return parameters;
  343. }
  344. /**
  345. * Gets the browser detail parameters that are sent by the bootstrap
  346. * javascript for two-request initialization.
  347. *
  348. * @param parentElementId
  349. * @return
  350. */
  351. private static native String getNativeBrowserDetailsParameters(
  352. String parentElementId)
  353. /*-{
  354. return $wnd.vaadin.getBrowserDetailsParameters(parentElementId);
  355. }-*/;
  356. protected void repaintAll() {
  357. String repainAllParameters = getRepaintAllParameters();
  358. makeUidlRequest("", repainAllParameters, false);
  359. }
  360. /**
  361. * Requests an analyze of layouts, to find inconsistencies. Exclusively used
  362. * for debugging during development.
  363. */
  364. public void analyzeLayouts() {
  365. String params = getRepaintAllParameters() + "&analyzeLayouts=1";
  366. makeUidlRequest("", params, false);
  367. }
  368. /**
  369. * Sends a request to the server to print details to console that will help
  370. * developer to locate component in the source code.
  371. *
  372. * @param paintable
  373. */
  374. void highlightComponent(ComponentConnector paintable) {
  375. String params = getRepaintAllParameters() + "&highlightComponent="
  376. + connectorMap.getConnectorId(paintable);
  377. makeUidlRequest("", params, false);
  378. }
  379. /**
  380. * Makes an UIDL request to the server.
  381. *
  382. * @param requestData
  383. * Data that is passed to the server.
  384. * @param extraParams
  385. * Parameters that are added as GET parameters to the url.
  386. * Contains key=value pairs joined by & characters or is empty if
  387. * no parameters should be added. Should not start with any
  388. * special character.
  389. * @param forceSync
  390. * true if the request should be synchronous, false otherwise
  391. */
  392. protected void makeUidlRequest(final String requestData,
  393. final String extraParams, final boolean forceSync) {
  394. startRequest();
  395. // Security: double cookie submission pattern
  396. final String payload = uidlSecurityKey + VAR_BURST_SEPARATOR
  397. + requestData;
  398. VConsole.log("Making UIDL Request with params: " + payload);
  399. String uri;
  400. if (configuration.usePortletURLs()) {
  401. uri = configuration.getPortletUidlURLBase();
  402. } else {
  403. uri = getAppUri() + "UIDL";
  404. }
  405. if (extraParams != null && extraParams.length() > 0) {
  406. uri = addGetParameters(uri, extraParams);
  407. }
  408. uri = addGetParameters(uri,
  409. ROOT_ID_PARAMETER + "=" + configuration.getRootId());
  410. doUidlRequest(uri, payload, forceSync);
  411. }
  412. /**
  413. * Sends an asynchronous or synchronous UIDL request to the server using the
  414. * given URI.
  415. *
  416. * @param uri
  417. * The URI to use for the request. May includes GET parameters
  418. * @param payload
  419. * The contents of the request to send
  420. * @param synchronous
  421. * true if the request should be synchronous, false otherwise
  422. */
  423. protected void doUidlRequest(final String uri, final String payload,
  424. final boolean synchronous) {
  425. if (!synchronous) {
  426. RequestCallback requestCallback = new RequestCallback() {
  427. public void onError(Request request, Throwable exception) {
  428. showCommunicationError(exception.getMessage());
  429. endRequest();
  430. }
  431. public void onResponseReceived(Request request,
  432. Response response) {
  433. VConsole.log("Server visit took "
  434. + String.valueOf((new Date()).getTime()
  435. - requestStartTime.getTime()) + "ms");
  436. int statusCode = response.getStatusCode();
  437. switch (statusCode) {
  438. case 0:
  439. showCommunicationError("Invalid status code 0 (server down?)");
  440. endRequest();
  441. return;
  442. case 401:
  443. /*
  444. * Authorization has failed. Could be that the session
  445. * has timed out and the container is redirecting to a
  446. * login page.
  447. */
  448. showAuthenticationError("");
  449. endRequest();
  450. return;
  451. case 503:
  452. // We'll assume msec instead of the usual seconds
  453. int delay = Integer.parseInt(response
  454. .getHeader("Retry-After"));
  455. VConsole.log("503, retrying in " + delay + "msec");
  456. (new Timer() {
  457. @Override
  458. public void run() {
  459. decrementActiveRequests();
  460. doUidlRequest(uri, payload, synchronous);
  461. }
  462. }).schedule(delay);
  463. return;
  464. }
  465. if ((statusCode / 100) == 4) {
  466. // Handle all 4xx errors the same way as (they are
  467. // all permanent errors)
  468. showCommunicationError("UIDL could not be read from server. Check servlets mappings. Error code: "
  469. + statusCode);
  470. endRequest();
  471. return;
  472. }
  473. String contentType = response.getHeader("Content-Type");
  474. if (contentType == null
  475. || !contentType.startsWith("application/json")) {
  476. /*
  477. * A servlet filter or equivalent may have intercepted
  478. * the request and served non-UIDL content (for
  479. * instance, a login page if the session has expired.)
  480. * If the response contains a magic substring, do a
  481. * synchronous refresh. See #8241.
  482. */
  483. MatchResult refreshToken = RegExp.compile(
  484. UIDL_REFRESH_TOKEN + "(:\\s*(.*?))?(\\s|$)")
  485. .exec(response.getText());
  486. if (refreshToken != null) {
  487. redirect(refreshToken.getGroup(2));
  488. return;
  489. }
  490. }
  491. // for(;;);[realjson]
  492. final String jsonText = response.getText().substring(9,
  493. response.getText().length() - 1);
  494. handleJSONText(jsonText);
  495. }
  496. };
  497. try {
  498. doAsyncUIDLRequest(uri, payload, requestCallback);
  499. } catch (RequestException e) {
  500. VConsole.error(e);
  501. endRequest();
  502. }
  503. } else {
  504. // Synchronized call, discarded response (leaving the page)
  505. SynchronousXHR syncXHR = (SynchronousXHR) SynchronousXHR.create();
  506. syncXHR.synchronousPost(uri + "&" + PARAM_UNLOADBURST + "=1",
  507. payload);
  508. /*
  509. * Although we are in theory leaving the page, the page may still
  510. * stay open. End request properly here too. See #3289
  511. */
  512. endRequest();
  513. }
  514. }
  515. /**
  516. * Handles received UIDL JSON text, parsing it, and passing it on to the
  517. * appropriate handlers, while logging timiing information.
  518. *
  519. * @param jsonText
  520. */
  521. private void handleJSONText(String jsonText) {
  522. final Date start = new Date();
  523. final ValueMap json;
  524. try {
  525. json = parseJSONResponse(jsonText);
  526. } catch (final Exception e) {
  527. endRequest();
  528. showCommunicationError(e.getMessage() + " - Original JSON-text:"
  529. + jsonText);
  530. return;
  531. }
  532. VConsole.log("JSON parsing took "
  533. + (new Date().getTime() - start.getTime()) + "ms");
  534. if (applicationRunning) {
  535. handleReceivedJSONMessage(start, jsonText, json);
  536. } else {
  537. applicationRunning = true;
  538. handleWhenCSSLoaded(jsonText, json);
  539. }
  540. }
  541. /**
  542. * Sends an asynchronous UIDL request to the server using the given URI.
  543. *
  544. * @param uri
  545. * The URI to use for the request. May includes GET parameters
  546. * @param payload
  547. * The contents of the request to send
  548. * @param requestCallback
  549. * The handler for the response
  550. * @throws RequestException
  551. * if the request could not be sent
  552. */
  553. protected void doAsyncUIDLRequest(String uri, String payload,
  554. RequestCallback requestCallback) throws RequestException {
  555. RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
  556. // TODO enable timeout
  557. // rb.setTimeoutMillis(timeoutMillis);
  558. rb.setHeader("Content-Type", "text/plain;charset=utf-8");
  559. rb.setRequestData(payload);
  560. rb.setCallback(requestCallback);
  561. rb.send();
  562. }
  563. int cssWaits = 0;
  564. static final int MAX_CSS_WAITS = 100;
  565. protected void handleWhenCSSLoaded(final String jsonText,
  566. final ValueMap json) {
  567. if (!isCSSLoaded() && cssWaits < MAX_CSS_WAITS) {
  568. (new Timer() {
  569. @Override
  570. public void run() {
  571. handleWhenCSSLoaded(jsonText, json);
  572. }
  573. }).schedule(50);
  574. VConsole.log("Assuming CSS loading is not complete, "
  575. + "postponing render phase. "
  576. + "(.v-loading-indicator height == 0)");
  577. cssWaits++;
  578. } else {
  579. cssLoaded = true;
  580. handleReceivedJSONMessage(new Date(), jsonText, json);
  581. if (cssWaits >= MAX_CSS_WAITS) {
  582. VConsole.error("CSS files may have not loaded properly.");
  583. }
  584. }
  585. }
  586. /**
  587. * Checks whether or not the CSS is loaded. By default checks the size of
  588. * the loading indicator element.
  589. *
  590. * @return
  591. */
  592. protected boolean isCSSLoaded() {
  593. return cssLoaded
  594. || DOM.getElementPropertyInt(loadElement, "offsetHeight") != 0;
  595. }
  596. /**
  597. * Shows the communication error notification.
  598. *
  599. * @param details
  600. * Optional details for debugging.
  601. */
  602. protected void showCommunicationError(String details) {
  603. VConsole.error("Communication error: " + details);
  604. ErrorMessage communicationError = configuration.getCommunicationError();
  605. showError(details, communicationError.getCaption(),
  606. communicationError.getMessage(), communicationError.getUrl());
  607. }
  608. /**
  609. * Shows the authentication error notification.
  610. *
  611. * @param details
  612. * Optional details for debugging.
  613. */
  614. protected void showAuthenticationError(String details) {
  615. VConsole.error("Authentication error: " + details);
  616. ErrorMessage authorizationError = configuration.getAuthorizationError();
  617. showError(details, authorizationError.getCaption(),
  618. authorizationError.getMessage(), authorizationError.getUrl());
  619. }
  620. /**
  621. * Shows the error notification.
  622. *
  623. * @param details
  624. * Optional details for debugging.
  625. */
  626. private void showError(String details, String caption, String message,
  627. String url) {
  628. StringBuilder html = new StringBuilder();
  629. if (caption != null) {
  630. html.append("<h1>");
  631. html.append(caption);
  632. html.append("</h1>");
  633. }
  634. if (message != null) {
  635. html.append("<p>");
  636. html.append(message);
  637. html.append("</p>");
  638. }
  639. if (html.length() > 0) {
  640. // Add error description
  641. html.append("<br/><p><I style=\"font-size:0.7em\">");
  642. html.append(details);
  643. html.append("</I></p>");
  644. VNotification n = VNotification.createNotification(1000 * 60 * 45);
  645. n.addEventListener(new NotificationRedirect(url));
  646. n.show(html.toString(), VNotification.CENTERED_TOP,
  647. VNotification.STYLE_SYSTEM);
  648. } else {
  649. redirect(url);
  650. }
  651. }
  652. protected void startRequest() {
  653. incrementActiveRequests();
  654. requestStartTime = new Date();
  655. // show initial throbber
  656. if (loadTimer == null) {
  657. loadTimer = new Timer() {
  658. @Override
  659. public void run() {
  660. /*
  661. * IE7 does not properly cancel the event with
  662. * loadTimer.cancel() so we have to check that we really
  663. * should make it visible
  664. */
  665. if (loadTimer != null) {
  666. showLoadingIndicator();
  667. }
  668. }
  669. };
  670. // First one kicks in at 300ms
  671. }
  672. loadTimer.schedule(300);
  673. }
  674. protected void endRequest() {
  675. if (applicationRunning) {
  676. checkForPendingVariableBursts();
  677. runPostRequestHooks(configuration.getRootPanelId());
  678. }
  679. decrementActiveRequests();
  680. // deferring to avoid flickering
  681. Scheduler.get().scheduleDeferred(new Command() {
  682. public void execute() {
  683. if (!hasActiveRequest()) {
  684. hideLoadingIndicator();
  685. }
  686. }
  687. });
  688. }
  689. /**
  690. * This method is called after applying uidl change set to application.
  691. *
  692. * It will clean current and queued variable change sets. And send next
  693. * change set if it exists.
  694. */
  695. private void checkForPendingVariableBursts() {
  696. cleanVariableBurst(pendingInvocations);
  697. if (pendingBursts.size() > 0) {
  698. for (Iterator<ArrayList<MethodInvocation>> iterator = pendingBursts
  699. .iterator(); iterator.hasNext();) {
  700. cleanVariableBurst(iterator.next());
  701. }
  702. ArrayList<MethodInvocation> nextBurst = pendingBursts.get(0);
  703. pendingBursts.remove(0);
  704. buildAndSendVariableBurst(nextBurst, false);
  705. }
  706. }
  707. /**
  708. * Cleans given queue of variable changes of such changes that came from
  709. * components that do not exist anymore.
  710. *
  711. * @param variableBurst
  712. */
  713. private void cleanVariableBurst(ArrayList<MethodInvocation> variableBurst) {
  714. for (int i = 1; i < variableBurst.size(); i++) {
  715. String id = variableBurst.get(i).getConnectorId();
  716. if (!getConnectorMap().hasConnector(id)
  717. && !getConnectorMap().isDragAndDropPaintable(id)) {
  718. // variable owner does not exist anymore
  719. variableBurst.remove(i);
  720. VConsole.log("Removed variable from removed component: " + id);
  721. }
  722. }
  723. }
  724. private void showLoadingIndicator() {
  725. // show initial throbber
  726. if (loadElement == null) {
  727. loadElement = DOM.createDiv();
  728. DOM.setStyleAttribute(loadElement, "position", "absolute");
  729. DOM.appendChild(view.getWidget().getElement(), loadElement);
  730. VConsole.log("inserting load indicator");
  731. }
  732. DOM.setElementProperty(loadElement, "className", "v-loading-indicator");
  733. DOM.setStyleAttribute(loadElement, "display", "block");
  734. // Initialize other timers
  735. loadTimer2 = new Timer() {
  736. @Override
  737. public void run() {
  738. DOM.setElementProperty(loadElement, "className",
  739. "v-loading-indicator-delay");
  740. }
  741. };
  742. // Second one kicks in at 1500ms from request start
  743. loadTimer2.schedule(1200);
  744. loadTimer3 = new Timer() {
  745. @Override
  746. public void run() {
  747. DOM.setElementProperty(loadElement, "className",
  748. "v-loading-indicator-wait");
  749. }
  750. };
  751. // Third one kicks in at 5000ms from request start
  752. loadTimer3.schedule(4700);
  753. }
  754. private void hideLoadingIndicator() {
  755. if (loadTimer != null) {
  756. loadTimer.cancel();
  757. loadTimer = null;
  758. }
  759. if (loadTimer2 != null) {
  760. loadTimer2.cancel();
  761. loadTimer3.cancel();
  762. loadTimer2 = null;
  763. loadTimer3 = null;
  764. }
  765. if (loadElement != null) {
  766. DOM.setStyleAttribute(loadElement, "display", "none");
  767. }
  768. }
  769. /**
  770. * Checks if deferred commands are (potentially) still being executed as a
  771. * result of an update from the server. Returns true if a deferred command
  772. * might still be executing, false otherwise. This will not work correctly
  773. * if a deferred command is added in another deferred command.
  774. * <p>
  775. * Used by the native "client.isActive" function.
  776. * </p>
  777. *
  778. * @return true if deferred commands are (potentially) being executed, false
  779. * otherwise
  780. */
  781. private boolean isExecutingDeferredCommands() {
  782. Scheduler s = Scheduler.get();
  783. if (s instanceof VSchedulerImpl) {
  784. return ((VSchedulerImpl) s).hasWorkQueued();
  785. } else {
  786. return false;
  787. }
  788. }
  789. /**
  790. * Determines whether or not the loading indicator is showing.
  791. *
  792. * @return true if the loading indicator is visible
  793. */
  794. public boolean isLoadingIndicatorVisible() {
  795. if (loadElement == null) {
  796. return false;
  797. }
  798. if (loadElement.getStyle().getProperty("display").equals("none")) {
  799. return false;
  800. }
  801. return true;
  802. }
  803. private static native ValueMap parseJSONResponse(String jsonText)
  804. /*-{
  805. try {
  806. return JSON.parse(jsonText);
  807. } catch (ignored) {
  808. return eval('(' + jsonText + ')');
  809. }
  810. }-*/;
  811. private void handleReceivedJSONMessage(Date start, String jsonText,
  812. ValueMap json) {
  813. handleUIDLMessage(start, jsonText, json);
  814. }
  815. protected void handleUIDLMessage(final Date start, final String jsonText,
  816. final ValueMap json) {
  817. VConsole.log("Handling message from server");
  818. // Handle redirect
  819. if (json.containsKey("redirect")) {
  820. String url = json.getValueMap("redirect").getString("url");
  821. VConsole.log("redirecting to " + url);
  822. redirect(url);
  823. return;
  824. }
  825. // Get security key
  826. if (json.containsKey(UIDL_SECURITY_TOKEN_ID)) {
  827. uidlSecurityKey = json.getString(UIDL_SECURITY_TOKEN_ID);
  828. }
  829. if (json.containsKey("resources")) {
  830. ValueMap resources = json.getValueMap("resources");
  831. JsArrayString keyArray = resources.getKeyArray();
  832. int l = keyArray.length();
  833. for (int i = 0; i < l; i++) {
  834. String key = keyArray.get(i);
  835. resourcesMap.put(key, resources.getAsString(key));
  836. }
  837. }
  838. if (json.containsKey("typeMappings")) {
  839. configuration.addComponentMappings(
  840. json.getValueMap("typeMappings"), widgetSet);
  841. }
  842. Command c = new Command() {
  843. public void execute() {
  844. VConsole.dirUIDL(json, configuration);
  845. if (json.containsKey("locales")) {
  846. VConsole.log(" * Handling locales");
  847. // Store locale data
  848. JsArray<ValueMap> valueMapArray = json
  849. .getJSValueMapArray("locales");
  850. LocaleService.addLocales(valueMapArray);
  851. }
  852. boolean repaintAll = false;
  853. ValueMap meta = null;
  854. if (json.containsKey("meta")) {
  855. VConsole.log(" * Handling meta information");
  856. meta = json.getValueMap("meta");
  857. if (meta.containsKey("repaintAll")) {
  858. repaintAll = true;
  859. view.getWidget().clear();
  860. getConnectorMap().clear();
  861. if (meta.containsKey("invalidLayouts")) {
  862. validatingLayouts = true;
  863. zeroWidthComponents = new HashSet<ComponentConnector>();
  864. zeroHeightComponents = new HashSet<ComponentConnector>();
  865. }
  866. }
  867. if (meta.containsKey("timedRedirect")) {
  868. final ValueMap timedRedirect = meta
  869. .getValueMap("timedRedirect");
  870. redirectTimer = new Timer() {
  871. @Override
  872. public void run() {
  873. redirect(timedRedirect.getString("url"));
  874. }
  875. };
  876. sessionExpirationInterval = timedRedirect
  877. .getInt("interval");
  878. }
  879. }
  880. if (redirectTimer != null) {
  881. redirectTimer.schedule(1000 * sessionExpirationInterval);
  882. }
  883. componentCaptionSizeChanges.clear();
  884. Duration updateDuration = new Duration();
  885. // Ensure that all connectors that we are about to update exist
  886. createConnectorsIfNeeded(json);
  887. // Update states, do not fire events
  888. updateConnectorState(json);
  889. // Update hierarchy, do not fire events
  890. Collection<ConnectorHierarchyChangedEvent> pendingHierarchyChangeEvents = updateConnectorHierarchy(json);
  891. // Fire state change events (TODO)
  892. VConsole.log(" * Sending state change events");
  893. // Fire hierarchy change events
  894. sendHierarchyChangeEvents(pendingHierarchyChangeEvents);
  895. // Update of legacy (UIDL) style connectors
  896. updateVaadin6StyleConnectors(json);
  897. // Handle any RPC invocations done on the server side
  898. handleRpcInvocations(json);
  899. if (json.containsKey("dd")) {
  900. // response contains data for drag and drop service
  901. VDragAndDropManager.get().handleServerResponse(
  902. json.getValueMap("dd"));
  903. }
  904. VConsole.log("updateFromUidl: "
  905. + updateDuration.elapsedMillis() + " ms");
  906. doLayout(false);
  907. if (meta != null) {
  908. if (meta.containsKey("appError")) {
  909. ValueMap error = meta.getValueMap("appError");
  910. String html = "";
  911. if (error.containsKey("caption")
  912. && error.getString("caption") != null) {
  913. html += "<h1>" + error.getAsString("caption")
  914. + "</h1>";
  915. }
  916. if (error.containsKey("message")
  917. && error.getString("message") != null) {
  918. html += "<p>" + error.getAsString("message")
  919. + "</p>";
  920. }
  921. String url = null;
  922. if (error.containsKey("url")) {
  923. url = error.getString("url");
  924. }
  925. if (html.length() != 0) {
  926. /* 45 min */
  927. VNotification n = VNotification
  928. .createNotification(1000 * 60 * 45);
  929. n.addEventListener(new NotificationRedirect(url));
  930. n.show(html, VNotification.CENTERED_TOP,
  931. VNotification.STYLE_SYSTEM);
  932. } else {
  933. redirect(url);
  934. }
  935. applicationRunning = false;
  936. }
  937. if (validatingLayouts) {
  938. VConsole.printLayoutProblems(meta,
  939. ApplicationConnection.this,
  940. zeroHeightComponents, zeroWidthComponents);
  941. zeroHeightComponents = null;
  942. zeroWidthComponents = null;
  943. validatingLayouts = false;
  944. }
  945. }
  946. if (repaintAll) {
  947. /*
  948. * idToPaintableDetail is already cleanded at the start of
  949. * the changeset handling, bypass cleanup.
  950. */
  951. connectorMap.purgeUnregistryBag(false);
  952. } else {
  953. connectorMap.purgeUnregistryBag(true);
  954. }
  955. // TODO build profiling for widget impl loading time
  956. final long prosessingTime = (new Date().getTime())
  957. - start.getTime();
  958. VConsole.log(" Processing time was "
  959. + String.valueOf(prosessingTime) + "ms for "
  960. + jsonText.length() + " characters of JSON");
  961. VConsole.log("Referenced paintables: " + connectorMap.size());
  962. endRequest();
  963. }
  964. private void createConnectorsIfNeeded(ValueMap json) {
  965. VConsole.log(" * Creating connectors (if needed)");
  966. ValueMap types = json.getValueMap("types");
  967. JsArrayString keyArray = types.getKeyArray();
  968. for (int i = 0; i < keyArray.length(); i++) {
  969. try {
  970. String connectorId = keyArray.get(i);
  971. String connectorType = types.getString(connectorId);
  972. ServerConnector connector = connectorMap
  973. .getConnector(connectorId);
  974. if (connector != null) {
  975. continue;
  976. }
  977. // Connector does not exist so we must create it
  978. if (!connectorType.equals(configuration
  979. .getEncodedWindowTag())) {
  980. // create, initialize and register the paintable
  981. getConnector(connectorId, connectorType);
  982. } else {
  983. // First RootConnector update. Before this the
  984. // RootConnector has been created but not
  985. // initialized as the connector id has not been
  986. // known
  987. connectorMap.registerConnector(connectorId, view);
  988. view.doInit(connectorId, ApplicationConnection.this);
  989. }
  990. } catch (final Throwable e) {
  991. VConsole.error(e);
  992. }
  993. }
  994. }
  995. private void updateVaadin6StyleConnectors(ValueMap json) {
  996. JsArray<ValueMap> changes = json.getJSValueMapArray("changes");
  997. int length = changes.length();
  998. VConsole.log(" * Passing UIDL to Vaadin 6 style connectors");
  999. // update paintables
  1000. for (int i = 0; i < length; i++) {
  1001. try {
  1002. final UIDL change = changes.get(i).cast();
  1003. final UIDL uidl = change.getChildUIDL(0);
  1004. String connectorId = uidl.getId();
  1005. final ComponentConnector paintable = (ComponentConnector) connectorMap
  1006. .getConnector(connectorId);
  1007. if (paintable != null) {
  1008. paintable.updateFromUIDL(uidl,
  1009. ApplicationConnection.this);
  1010. } else {
  1011. VConsole.error("Received update for "
  1012. + uidl.getTag()
  1013. + ", but there is no such paintable ("
  1014. + connectorId + ") rendered.");
  1015. }
  1016. } catch (final Throwable e) {
  1017. VConsole.error(e);
  1018. }
  1019. }
  1020. }
  1021. private void sendHierarchyChangeEvents(
  1022. Collection<ConnectorHierarchyChangedEvent> pendingHierarchyChangeEvents) {
  1023. if (pendingHierarchyChangeEvents.isEmpty()) {
  1024. return;
  1025. }
  1026. VConsole.log(" * Sending hierarchy change events");
  1027. for (ConnectorHierarchyChangedEvent event : pendingHierarchyChangeEvents) {
  1028. event.getParent().connectorHierarchyChanged(event);
  1029. }
  1030. }
  1031. private void updateConnectorState(ValueMap json) {
  1032. VConsole.log(" * Updating connector states");
  1033. // set states for all paintables mentioned in "state"
  1034. ValueMap states = json.getValueMap("state");
  1035. JsArrayString keyArray = states.getKeyArray();
  1036. for (int i = 0; i < keyArray.length(); i++) {
  1037. try {
  1038. String connectorId = keyArray.get(i);
  1039. ServerConnector paintable = connectorMap
  1040. .getConnector(connectorId);
  1041. if (null != paintable) {
  1042. JSONArray stateDataAndType = new JSONArray(
  1043. states.getJavaScriptObject(connectorId));
  1044. Object state = JsonDecoder.decodeValue(
  1045. stateDataAndType, connectorMap,
  1046. ApplicationConnection.this);
  1047. paintable.setState((SharedState) state);
  1048. }
  1049. } catch (final Throwable e) {
  1050. VConsole.error(e);
  1051. }
  1052. }
  1053. }
  1054. /**
  1055. * Updates the connector hierarchy and returns a list of events that
  1056. * should be fired after update of the hierarchy and the state is
  1057. * done.
  1058. *
  1059. * @param json
  1060. * The JSON containing the hierarchy information
  1061. * @return A collection of events that should be fired when update
  1062. * of hierarchy and state is complete
  1063. */
  1064. private Collection<ConnectorHierarchyChangedEvent> updateConnectorHierarchy(
  1065. ValueMap json) {
  1066. List<ConnectorHierarchyChangedEvent> events = new LinkedList<ConnectorHierarchyChangedEvent>();
  1067. VConsole.log(" * Updating connector hierarchy");
  1068. ValueMap hierarchies = json.getValueMap("hierarchy");
  1069. JsArrayString hierarchyKeys = hierarchies.getKeyArray();
  1070. for (int i = 0; i < hierarchyKeys.length(); i++) {
  1071. try {
  1072. String connectorId = hierarchyKeys.get(i);
  1073. ServerConnector connector = connectorMap
  1074. .getConnector(connectorId);
  1075. if (!(connector instanceof ComponentContainerConnector)) {
  1076. VConsole.error("Retrieved a hierarchy update for a connector ("
  1077. + connectorId
  1078. + ") that is not a ComponentContainerConnector");
  1079. continue;
  1080. }
  1081. ComponentContainerConnector ccc = (ComponentContainerConnector) connector;
  1082. JsArrayString childConnectorIds = hierarchies
  1083. .getJSStringArray(connectorId);
  1084. int childConnectorSize = childConnectorIds.length();
  1085. List<ServerConnector> newChildren = new ArrayList<ServerConnector>();
  1086. for (int connectorIndex = 0; connectorIndex < childConnectorSize; connectorIndex++) {
  1087. String childConnectorId = childConnectorIds
  1088. .get(connectorIndex);
  1089. ComponentConnector childConnector = (ComponentConnector) connectorMap
  1090. .getConnector(childConnectorId);
  1091. newChildren.add(childConnector);
  1092. if (childConnector.getParent() != ccc) {
  1093. // Avoid extra calls to setParent
  1094. childConnector.setParent(ccc);
  1095. }
  1096. }
  1097. // TODO This check should be done on the server side in
  1098. // the future so the hierarchy update is only sent when
  1099. // something actually has changed
  1100. List<ComponentConnector> oldChildren = ccc
  1101. .getChildren();
  1102. boolean actuallyChanged = !Util.collectionsEquals(
  1103. oldChildren, newChildren);
  1104. if (!actuallyChanged) {
  1105. continue;
  1106. }
  1107. // Fire change event if the hierarchy has changed
  1108. ConnectorHierarchyChangedEvent event = GWT
  1109. .create(ConnectorHierarchyChangedEvent.class);
  1110. event.setOldChildren(oldChildren);
  1111. event.setParent(ccc);
  1112. ccc.setChildren((List) newChildren);
  1113. events.add(event);
  1114. } catch (final Throwable e) {
  1115. VConsole.error(e);
  1116. }
  1117. }
  1118. return events;
  1119. }
  1120. private void handleRpcInvocations(ValueMap json) {
  1121. if (json.containsKey("rpc")) {
  1122. VConsole.log(" * Performing server to client RPC calls");
  1123. JSONArray rpcCalls = new JSONArray(
  1124. json.getJavaScriptObject("rpc"));
  1125. int rpcLength = rpcCalls.size();
  1126. for (int i = 0; i < rpcLength; i++) {
  1127. try {
  1128. JSONArray rpcCall = (JSONArray) rpcCalls.get(i);
  1129. MethodInvocation invocation = parseMethodInvocation(rpcCall);
  1130. VConsole.log("Server to client RPC call: "
  1131. + invocation);
  1132. rpcManager.applyInvocation(invocation,
  1133. getConnectorMap());
  1134. } catch (final Throwable e) {
  1135. VConsole.error(e);
  1136. }
  1137. }
  1138. }
  1139. }
  1140. };
  1141. ApplicationConfiguration.runWhenWidgetsLoaded(c);
  1142. }
  1143. private MethodInvocation parseMethodInvocation(JSONArray rpcCall) {
  1144. String connectorId = ((JSONString) rpcCall.get(0)).stringValue();
  1145. String interfaceName = ((JSONString) rpcCall.get(1)).stringValue();
  1146. String methodName = ((JSONString) rpcCall.get(2)).stringValue();
  1147. JSONArray parametersJson = (JSONArray) rpcCall.get(3);
  1148. Object[] parameters = new Object[parametersJson.size()];
  1149. for (int j = 0; j < parametersJson.size(); ++j) {
  1150. parameters[j] = JsonDecoder.decodeValue(
  1151. (JSONArray) parametersJson.get(j), getConnectorMap(), this);
  1152. }
  1153. return new MethodInvocation(connectorId, interfaceName, methodName,
  1154. parameters);
  1155. }
  1156. // Redirect browser, null reloads current page
  1157. private static native void redirect(String url)
  1158. /*-{
  1159. if (url) {
  1160. $wnd.location = url;
  1161. } else {
  1162. $wnd.location.reload(false);
  1163. }
  1164. }-*/;
  1165. private void addVariableToQueue(String connectorId, String variableName,
  1166. Object value, boolean immediate) {
  1167. // note that type is now deduced from value
  1168. // TODO could eliminate invocations of same shared variable setter
  1169. addMethodInvocationToQueue(new MethodInvocation(connectorId,
  1170. UPDATE_VARIABLE_INTERFACE, UPDATE_VARIABLE_METHOD,
  1171. new Object[] { variableName, value }), immediate);
  1172. }
  1173. /**
  1174. * Adds an explicit RPC method invocation to the send queue.
  1175. *
  1176. * @since 7.0
  1177. *
  1178. * @param invocation
  1179. * RPC method invocation
  1180. * @param immediate
  1181. * true to trigger sending within a short time window (possibly
  1182. * combining subsequent calls to a single request), false to let
  1183. * the framework delay sending of RPC calls and variable changes
  1184. * until the next immediate change
  1185. */
  1186. public void addMethodInvocationToQueue(MethodInvocation invocation,
  1187. boolean immediate) {
  1188. pendingInvocations.add(invocation);
  1189. if (immediate) {
  1190. sendPendingVariableChanges();
  1191. }
  1192. }
  1193. /**
  1194. * This method sends currently queued variable changes to server. It is
  1195. * called when immediate variable update must happen.
  1196. *
  1197. * To ensure correct order for variable changes (due servers multithreading
  1198. * or network), we always wait for active request to be handler before
  1199. * sending a new one. If there is an active request, we will put varible
  1200. * "burst" to queue that will be purged after current request is handled.
  1201. *
  1202. */
  1203. public void sendPendingVariableChanges() {
  1204. if (!deferedSendPending) {
  1205. deferedSendPending = true;
  1206. Scheduler.get().scheduleDeferred(sendPendingCommand);
  1207. }
  1208. }
  1209. private final ScheduledCommand sendPendingCommand = new ScheduledCommand() {
  1210. public void execute() {
  1211. deferedSendPending = false;
  1212. doSendPendingVariableChanges();
  1213. }
  1214. };
  1215. private boolean deferedSendPending = false;
  1216. @SuppressWarnings("unchecked")
  1217. private void doSendPendingVariableChanges() {
  1218. if (applicationRunning) {
  1219. if (hasActiveRequest()) {
  1220. // skip empty queues if there are pending bursts to be sent
  1221. if (pendingInvocations.size() > 0 || pendingBursts.size() == 0) {
  1222. pendingBursts.add(pendingInvocations);
  1223. pendingInvocations = new ArrayList<MethodInvocation>();
  1224. }
  1225. } else {
  1226. buildAndSendVariableBurst(pendingInvocations, false);
  1227. }
  1228. }
  1229. }
  1230. /**
  1231. * Build the variable burst and send it to server.
  1232. *
  1233. * When sync is forced, we also force sending of all pending variable-bursts
  1234. * at the same time. This is ok as we can assume that DOM will never be
  1235. * updated after this.
  1236. *
  1237. * @param pendingInvocations
  1238. * List of RPC method invocations to send
  1239. * @param forceSync
  1240. * Should we use synchronous request?
  1241. */
  1242. private void buildAndSendVariableBurst(
  1243. ArrayList<MethodInvocation> pendingInvocations, boolean forceSync) {
  1244. final StringBuffer req = new StringBuffer();
  1245. while (!pendingInvocations.isEmpty()) {
  1246. if (ApplicationConfiguration.isDebugMode()) {
  1247. Util.logVariableBurst(this, pendingInvocations);
  1248. }
  1249. JSONArray reqJson = new JSONArray();
  1250. for (MethodInvocation invocation : pendingInvocations) {
  1251. JSONArray invocationJson = new JSONArray();
  1252. invocationJson.set(0,
  1253. new JSONString(invocation.getConnectorId()));
  1254. invocationJson.set(1,
  1255. new JSONString(invocation.getInterfaceName()));
  1256. invocationJson.set(2,
  1257. new JSONString(invocation.getMethodName()));
  1258. JSONArray paramJson = new JSONArray();
  1259. for (int i = 0; i < invocation.getParameters().length; ++i) {
  1260. // TODO non-static encoder? type registration?
  1261. paramJson.set(i, JsonEncoder.encode(
  1262. invocation.getParameters()[i], getConnectorMap(),
  1263. this));
  1264. }
  1265. invocationJson.set(3, paramJson);
  1266. reqJson.set(reqJson.size(), invocationJson);
  1267. }
  1268. // escape burst separators (if any)
  1269. req.append(escapeBurstContents(reqJson.toString()));
  1270. pendingInvocations.clear();
  1271. // Append all the bursts to this synchronous request
  1272. if (forceSync && !pendingBursts.isEmpty()) {
  1273. pendingInvocations = pendingBursts.get(0);
  1274. pendingBursts.remove(0);
  1275. req.append(VAR_BURST_SEPARATOR);
  1276. }
  1277. }
  1278. // Include the browser detail parameters if they aren't already sent
  1279. String extraParams;
  1280. if (!getConfiguration().isBrowserDetailsSent()) {
  1281. extraParams = getNativeBrowserDetailsParameters(getConfiguration()
  1282. .getRootPanelId());
  1283. getConfiguration().setBrowserDetailsSent();
  1284. } else {
  1285. extraParams = "";
  1286. }
  1287. makeUidlRequest(req.toString(), extraParams, forceSync);
  1288. }
  1289. private void makeUidlRequest(String string) {
  1290. makeUidlRequest(string, "", false);
  1291. }
  1292. /**
  1293. * Sends a new value for the given paintables given variable to the server.
  1294. * <p>
  1295. * The update is actually queued to be sent at a suitable time. If immediate
  1296. * is true, the update is sent as soon as possible. If immediate is false,
  1297. * the update will be sent along with the next immediate update.
  1298. * </p>
  1299. *
  1300. * @param paintableId
  1301. * the id of the paintable that owns the variable
  1302. * @param variableName
  1303. * the name of the variable
  1304. * @param newValue
  1305. * the new value to be sent
  1306. * @param immediate
  1307. * true if the update is to be sent as soon as possible
  1308. */
  1309. public void updateVariable(String paintableId, String variableName,
  1310. ServerConnector newValue, boolean immediate) {
  1311. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1312. }
  1313. /**
  1314. * Sends a new value for the given paintables given variable to the server.
  1315. * <p>
  1316. * The update is actually queued to be sent at a suitable time. If immediate
  1317. * is true, the update is sent as soon as possible. If immediate is false,
  1318. * the update will be sent along with the next immediate update.
  1319. * </p>
  1320. *
  1321. * @param paintableId
  1322. * the id of the paintable that owns the variable
  1323. * @param variableName
  1324. * the name of the variable
  1325. * @param newValue
  1326. * the new value to be sent
  1327. * @param immediate
  1328. * true if the update is to be sent as soon as possible
  1329. */
  1330. public void updateVariable(String paintableId, String variableName,
  1331. String newValue, boolean immediate) {
  1332. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1333. }
  1334. /**
  1335. * Sends a new value for the given paintables given variable to the server.
  1336. * <p>
  1337. * The update is actually queued to be sent at a suitable time. If immediate
  1338. * is true, the update is sent as soon as possible. If immediate is false,
  1339. * the update will be sent along with the next immediate update.
  1340. * </p>
  1341. *
  1342. * @param paintableId
  1343. * the id of the paintable that owns the variable
  1344. * @param variableName
  1345. * the name of the variable
  1346. * @param newValue
  1347. * the new value to be sent
  1348. * @param immediate
  1349. * true if the update is to be sent as soon as possible
  1350. */
  1351. public void updateVariable(String paintableId, String variableName,
  1352. int newValue, boolean immediate) {
  1353. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1354. }
  1355. /**
  1356. * Sends a new value for the given paintables given variable to the server.
  1357. * <p>
  1358. * The update is actually queued to be sent at a suitable time. If immediate
  1359. * is true, the update is sent as soon as possible. If immediate is false,
  1360. * the update will be sent along with the next immediate update.
  1361. * </p>
  1362. *
  1363. * @param paintableId
  1364. * the id of the paintable that owns the variable
  1365. * @param variableName
  1366. * the name of the variable
  1367. * @param newValue
  1368. * the new value to be sent
  1369. * @param immediate
  1370. * true if the update is to be sent as soon as possible
  1371. */
  1372. public void updateVariable(String paintableId, String variableName,
  1373. long newValue, boolean immediate) {
  1374. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1375. }
  1376. /**
  1377. * Sends a new value for the given paintables given variable to the server.
  1378. * <p>
  1379. * The update is actually queued to be sent at a suitable time. If immediate
  1380. * is true, the update is sent as soon as possible. If immediate is false,
  1381. * the update will be sent along with the next immediate update.
  1382. * </p>
  1383. *
  1384. * @param paintableId
  1385. * the id of the paintable that owns the variable
  1386. * @param variableName
  1387. * the name of the variable
  1388. * @param newValue
  1389. * the new value to be sent
  1390. * @param immediate
  1391. * true if the update is to be sent as soon as possible
  1392. */
  1393. public void updateVariable(String paintableId, String variableName,
  1394. float newValue, boolean immediate) {
  1395. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1396. }
  1397. /**
  1398. * Sends a new value for the given paintables given variable to the server.
  1399. * <p>
  1400. * The update is actually queued to be sent at a suitable time. If immediate
  1401. * is true, the update is sent as soon as possible. If immediate is false,
  1402. * the update will be sent along with the next immediate update.
  1403. * </p>
  1404. *
  1405. * @param paintableId
  1406. * the id of the paintable that owns the variable
  1407. * @param variableName
  1408. * the name of the variable
  1409. * @param newValue
  1410. * the new value to be sent
  1411. * @param immediate
  1412. * true if the update is to be sent as soon as possible
  1413. */
  1414. public void updateVariable(String paintableId, String variableName,
  1415. double newValue, boolean immediate) {
  1416. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1417. }
  1418. /**
  1419. * Sends a new value for the given paintables given variable to the server.
  1420. * <p>
  1421. * The update is actually queued to be sent at a suitable time. If immediate
  1422. * is true, the update is sent as soon as possible. If immediate is false,
  1423. * the update will be sent along with the next immediate update.
  1424. * </p>
  1425. *
  1426. * @param paintableId
  1427. * the id of the paintable that owns the variable
  1428. * @param variableName
  1429. * the name of the variable
  1430. * @param newValue
  1431. * the new value to be sent
  1432. * @param immediate
  1433. * true if the update is to be sent as soon as possible
  1434. */
  1435. public void updateVariable(String paintableId, String variableName,
  1436. boolean newValue, boolean immediate) {
  1437. addVariableToQueue(paintableId, variableName, newValue, immediate);
  1438. }
  1439. /**
  1440. * Sends a new value for the given paintables given variable to the server.
  1441. * <p>
  1442. * The update is actually queued to be sent at a suitable time. If immediate
  1443. * is true, the update is sent as soon as possible. If immediate is false,
  1444. * the update will be sent along with the next immediate update.
  1445. * </p>
  1446. *
  1447. * @param paintableId
  1448. * the id of the paintable that owns the variable
  1449. * @param variableName
  1450. * the name of the variable
  1451. * @param map
  1452. * the new values to be sent
  1453. * @param immediate
  1454. * true if the update is to be sent as soon as possible
  1455. */
  1456. public void updateVariable(String paintableId, String variableName,
  1457. Map<String, Object> map, boolean immediate) {
  1458. addVariableToQueue(paintableId, variableName, map, immediate);
  1459. }
  1460. /**
  1461. * Sends a new value for the given paintables given variable to the server.
  1462. *
  1463. * The update is actually queued to be sent at a suitable time. If immediate
  1464. * is true, the update is sent as soon as possible. If immediate is false,
  1465. * the update will be sent along with the next immediate update.
  1466. *
  1467. * A null array is sent as an empty array.
  1468. *
  1469. * @param paintableId
  1470. * the id of the paintable that owns the variable
  1471. * @param variableName
  1472. * the name of the variable
  1473. * @param values
  1474. * the new value to be sent
  1475. * @param immediate
  1476. * true if the update is to be sent as soon as possible
  1477. */
  1478. public void updateVariable(String paintableId, String variableName,
  1479. String[] values, boolean immediate) {
  1480. addVariableToQueue(paintableId, variableName, values, immediate);
  1481. }
  1482. /**
  1483. * Sends a new value for the given paintables given variable to the server.
  1484. *
  1485. * The update is actually queued to be sent at a suitable time. If immediate
  1486. * is true, the update is sent as soon as possible. If immediate is false,
  1487. * the update will be sent along with the next immediate update. </p>
  1488. *
  1489. * A null array is sent as an empty array.
  1490. *
  1491. *
  1492. * @param paintableId
  1493. * the id of the paintable that owns the variable
  1494. * @param variableName
  1495. * the name of the variable
  1496. * @param values
  1497. * the new value to be sent
  1498. * @param immediate
  1499. * true if the update is to be sent as soon as possible
  1500. */
  1501. public void updateVariable(String paintableId, String variableName,
  1502. Object[] values, boolean immediate) {
  1503. addVariableToQueue(paintableId, variableName, values, immediate);
  1504. }
  1505. /**
  1506. * Encode burst separator characters in a String for transport over the
  1507. * network. This protects from separator injection attacks.
  1508. *
  1509. * @param value
  1510. * to encode
  1511. * @return encoded value
  1512. */
  1513. protected String escapeBurstContents(String value) {
  1514. final StringBuilder result = new StringBuilder();
  1515. for (int i = 0; i < value.length(); ++i) {
  1516. char character = value.charAt(i);
  1517. switch (character) {
  1518. case VAR_ESCAPE_CHARACTER:
  1519. // fall-through - escape character is duplicated
  1520. case VAR_BURST_SEPARATOR:
  1521. result.append(VAR_ESCAPE_CHARACTER);
  1522. // encode as letters for easier reading
  1523. result.append(((char) (character + 0x30)));
  1524. break;
  1525. default:
  1526. // the char is not a special one - add it to the result as is
  1527. result.append(character);
  1528. break;
  1529. }
  1530. }
  1531. return result.toString();
  1532. }
  1533. private boolean runningLayout = false;
  1534. /**
  1535. * Causes a re-calculation/re-layout of all paintables in a container.
  1536. *
  1537. * @param container
  1538. */
  1539. public void runDescendentsLayout(HasWidgets container) {
  1540. if (runningLayout) {
  1541. return;
  1542. }
  1543. runningLayout = true;
  1544. internalRunDescendentsLayout(container);
  1545. runningLayout = false;
  1546. }
  1547. /**
  1548. * This will cause re-layouting of all components. Mainly used for
  1549. * development. Published to JavaScript.
  1550. */
  1551. public void forceLayout() {
  1552. Duration duration = new Duration();
  1553. layoutManager.foceLayout();
  1554. VConsole.log("forceLayout in " + duration.elapsedMillis() + " ms");
  1555. }
  1556. private void internalRunDescendentsLayout(HasWidgets container) {
  1557. // getConsole().log(
  1558. // "runDescendentsLayout(" + Util.getSimpleName(container) + ")");
  1559. final Iterator<Widget> childWidgets = container.iterator();
  1560. while (childWidgets.hasNext()) {
  1561. final Widget child = childWidgets.next();
  1562. if (getConnectorMap().isConnector(child)) {
  1563. if (handleComponentRelativeSize(child)) {
  1564. /*
  1565. * Only need to propagate event if "child" has a relative
  1566. * size
  1567. */
  1568. if (child instanceof ContainerResizedListener) {
  1569. ((ContainerResizedListener) child).iLayout();
  1570. }
  1571. if (child instanceof HasWidgets) {
  1572. final HasWidgets childContainer = (HasWidgets) child;
  1573. internalRunDescendentsLayout(childContainer);
  1574. }
  1575. }
  1576. } else if (child instanceof HasWidgets) {
  1577. // propagate over non Paintable HasWidgets
  1578. internalRunDescendentsLayout((HasWidgets) child);
  1579. }
  1580. }
  1581. }
  1582. /**
  1583. * Converts relative sizes into pixel sizes.
  1584. *
  1585. * @param child
  1586. * @return true if the child has a relative size
  1587. */
  1588. private boolean handleComponentRelativeSize(ComponentConnector paintable) {
  1589. return false;
  1590. }
  1591. /**
  1592. * Converts relative sizes into pixel sizes.
  1593. *
  1594. * @param child
  1595. * @return true if the child has a relative size
  1596. */
  1597. public boolean handleComponentRelativeSize(Widget widget) {
  1598. return handleComponentRelativeSize(connectorMap.getConnector(widget));
  1599. }
  1600. @Deprecated
  1601. public ComponentConnector getPaintable(UIDL uidl) {
  1602. return getConnector(uidl.getId(), uidl.getTag());
  1603. }
  1604. /**
  1605. * Get either an existing ComponentConnector or create a new
  1606. * ComponentConnector with the given type and id.
  1607. *
  1608. * If a ComponentConnector with the given id already exists, returns it.
  1609. * Otherwise creates and registers a new ComponentConnector of the given
  1610. * type.
  1611. *
  1612. * @param connectorId
  1613. * Id of the paintable
  1614. * @param connectorType
  1615. * Type of the connector, as passed from the server side
  1616. *
  1617. * @return Either an existing ComponentConnector or a new ComponentConnector
  1618. * of the given type
  1619. */
  1620. public ComponentConnector getConnector(String connectorId,
  1621. String connectorType) {
  1622. if (!connectorMap.hasConnector(connectorId)) {
  1623. return createAndRegisterConnector(connectorId, connectorType);
  1624. }
  1625. return (ComponentConnector) connectorMap.getConnector(connectorId);
  1626. }
  1627. /**
  1628. * Creates a new ComponentConnector with the given type and id.
  1629. *
  1630. * Creates and registers a new ComponentConnector of the given type. Should
  1631. * never be called with the connector id of an existing connector.
  1632. *
  1633. * @param connectorId
  1634. * Id of the new connector
  1635. * @param connectorType
  1636. * Type of the connector, as passed from the server side
  1637. *
  1638. * @return A new ComponentConnector of the given type
  1639. */
  1640. private ComponentConnector createAndRegisterConnector(String connectorId,
  1641. String connectorType) {
  1642. // Create and register a new connector with the given type
  1643. ComponentConnector p = widgetSet.createWidget(connectorType,
  1644. configuration);
  1645. connectorMap.registerConnector(connectorId, p);
  1646. p.doInit(connectorId, this);
  1647. return p;
  1648. }
  1649. /**
  1650. * Gets a recource that has been pre-loaded via UIDL, such as custom
  1651. * layouts.
  1652. *
  1653. * @param name
  1654. * identifier of the resource to get
  1655. * @return the resource
  1656. */
  1657. public String getResource(String name) {
  1658. return resourcesMap.get(name);
  1659. }
  1660. /**
  1661. * Singleton method to get instance of app's context menu.
  1662. *
  1663. * @return VContextMenu object
  1664. */
  1665. public VContextMenu getContextMenu() {
  1666. if (contextMenu == null) {
  1667. contextMenu = new VContextMenu();
  1668. DOM.setElementProperty(contextMenu.getElement(), "id",
  1669. "PID_VAADIN_CM");
  1670. }
  1671. return contextMenu;
  1672. }
  1673. /**
  1674. * Translates custom protocols in UIDL URI's to be recognizable by browser.
  1675. * All uri's from UIDL should be routed via this method before giving them
  1676. * to browser due URI's in UIDL may contain custom protocols like theme://.
  1677. *
  1678. * @param uidlUri
  1679. * Vaadin URI from uidl
  1680. * @return translated URI ready for browser
  1681. */
  1682. public String translateVaadinUri(String uidlUri) {
  1683. if (uidlUri == null) {
  1684. return null;
  1685. }
  1686. if (uidlUri.startsWith("theme://")) {
  1687. final String themeUri = configuration.getThemeUri();
  1688. if (themeUri == null) {
  1689. VConsole.error("Theme not set: ThemeResource will not be found. ("
  1690. + uidlUri + ")");
  1691. }
  1692. uidlUri = themeUri + uidlUri.substring(7);
  1693. }
  1694. if (uidlUri.startsWith("app://")) {
  1695. uidlUri = getAppUri() + uidlUri.substring(6);
  1696. }
  1697. return uidlUri;
  1698. }
  1699. /**
  1700. * Gets the URI for the current theme. Can be used to reference theme
  1701. * resources.
  1702. *
  1703. * @return URI to the current theme
  1704. */
  1705. public String getThemeUri() {
  1706. return configuration.getThemeUri();
  1707. }
  1708. /**
  1709. * Listens for Notification hide event, and redirects. Used for system
  1710. * messages, such as session expired.
  1711. *
  1712. */
  1713. private class NotificationRedirect implements VNotification.EventListener {
  1714. String url;
  1715. NotificationRedirect(String url) {
  1716. this.url = url;
  1717. }
  1718. public void notificationHidden(HideEvent event) {
  1719. redirect(url);
  1720. }
  1721. }
  1722. /* Extended title handling */
  1723. /**
  1724. * Data showed in tooltips are stored centrilized as it may be needed in
  1725. * varios place: caption, layouts, and in owner components themselves.
  1726. *
  1727. * Updating TooltipInfo is done in updateComponent method.
  1728. *
  1729. */
  1730. public TooltipInfo getTooltipTitleInfo(ComponentConnector titleOwner,
  1731. Object key) {
  1732. if (null == titleOwner) {
  1733. return null;
  1734. }
  1735. return connectorMap.getTooltipInfo(titleOwner, key);
  1736. }
  1737. private final VTooltip tooltip = new VTooltip(this);
  1738. /**
  1739. * Component may want to delegate Tooltip handling to client. Layouts add
  1740. * Tooltip (description, errors) to caption, but some components may want
  1741. * them to appear one other elements too.
  1742. *
  1743. * Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
  1744. *
  1745. * @param event
  1746. * @param owner
  1747. */
  1748. public void handleTooltipEvent(Event event, ComponentConnector owner) {
  1749. tooltip.handleTooltipEvent(event, owner, null);
  1750. }
  1751. /**
  1752. * Component may want to delegate Tooltip handling to client. Layouts add
  1753. * Tooltip (description, errors) to caption, but some components may want
  1754. * them to appear one other elements too.
  1755. *
  1756. * Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
  1757. *
  1758. * @param event
  1759. * @param owner
  1760. * @param key
  1761. * the key for tooltip if this is "additional" tooltip, null for
  1762. * components "main tooltip"
  1763. */
  1764. public void handleTooltipEvent(Event event, ComponentConnector owner,
  1765. Object key) {
  1766. tooltip.handleTooltipEvent(event, owner, key);
  1767. }
  1768. /*
  1769. * Helper to run layout functions triggered by child components with a
  1770. * decent interval.
  1771. */
  1772. private final Timer layoutTimer = new Timer() {
  1773. private boolean isPending = false;
  1774. @Override
  1775. public void schedule(int delayMillis) {
  1776. if (!isPending) {
  1777. super.schedule(delayMillis);
  1778. isPending = true;
  1779. }
  1780. }
  1781. @Override
  1782. public void run() {
  1783. VConsole.log("Running re-layout of " + view.getClass().getName());
  1784. runDescendentsLayout(view.getWidget());
  1785. isPending = false;
  1786. }
  1787. };
  1788. private ConnectorMap connectorMap = GWT.create(ConnectorMap.class);
  1789. /**
  1790. * Components can call this function to run all layout functions. This is
  1791. * usually done, when component knows that its size has changed.
  1792. */
  1793. public void requestLayoutPhase() {
  1794. layoutTimer.schedule(500);
  1795. }
  1796. protected String getUidlSecurityKey() {
  1797. return uidlSecurityKey;
  1798. }
  1799. /**
  1800. * Use to notify that the given component's caption has changed; layouts may
  1801. * have to be recalculated.
  1802. *
  1803. * @param component
  1804. * the Paintable whose caption has changed
  1805. */
  1806. public void captionSizeUpdated(Widget widget) {
  1807. componentCaptionSizeChanges.add(widget);
  1808. }
  1809. /**
  1810. * Gets the main view
  1811. *
  1812. * @return the main view
  1813. */
  1814. public RootConnector getView() {
  1815. return view;
  1816. }
  1817. /**
  1818. * If component has several tooltips in addition to the one provided by
  1819. * {@link com.vaadin.ui.AbstractComponent}, component can register them with
  1820. * this method.
  1821. * <p>
  1822. * Component must also pipe events to
  1823. * {@link #handleTooltipEvent(Event, ComponentConnector, Object)} method.
  1824. * <p>
  1825. * This method can also be used to deregister tooltips by using null as
  1826. * tooltip
  1827. *
  1828. * @param paintable
  1829. * Paintable "owning" this tooltip
  1830. * @param key
  1831. * key assosiated with given tooltip. Can be any object. For
  1832. * example a related dom element. Same key must be given for
  1833. * {@link #handleTooltipEvent(Event, ComponentConnector, Object)}
  1834. * method.
  1835. *
  1836. * @param tooltip
  1837. * the TooltipInfo object containing details shown in tooltip,
  1838. * null if deregistering tooltip
  1839. */
  1840. public void registerTooltip(ComponentConnector paintable, Object key,
  1841. TooltipInfo tooltip) {
  1842. connectorMap.registerTooltip(paintable, key, tooltip);
  1843. }
  1844. /**
  1845. * Gets the {@link ApplicationConfiguration} for the current application.
  1846. *
  1847. * @see ApplicationConfiguration
  1848. * @return the configuration for this application
  1849. */
  1850. public ApplicationConfiguration getConfiguration() {
  1851. return configuration;
  1852. }
  1853. /**
  1854. * Checks if there is a registered server side listener for the event. The
  1855. * list of events which has server side listeners is updated automatically
  1856. * before the component is updated so the value is correct if called from
  1857. * updatedFromUIDL.
  1858. *
  1859. * @param eventIdentifier
  1860. * The identifier for the event
  1861. * @return true if at least one listener has been registered on server side
  1862. * for the event identified by eventIdentifier.
  1863. */
  1864. public boolean hasEventListeners(ComponentConnector paintable,
  1865. String eventIdentifier) {
  1866. return connectorMap.hasEventListeners(paintable, eventIdentifier);
  1867. }
  1868. /**
  1869. * Adds the get parameters to the uri and returns the new uri that contains
  1870. * the parameters.
  1871. *
  1872. * @param uri
  1873. * The uri to which the parameters should be added.
  1874. * @param extraParams
  1875. * One or more parameters in the format "a=b" or "c=d&e=f". An
  1876. * empty string is allowed but will not modify the url.
  1877. * @return The modified URI with the get parameters in extraParams added.
  1878. */
  1879. public static String addGetParameters(String uri, String extraParams) {
  1880. if (extraParams == null || extraParams.length() == 0) {
  1881. return uri;
  1882. }
  1883. // RFC 3986: The query component is indicated by the first question
  1884. // mark ("?") character and terminated by a number sign ("#") character
  1885. // or by the end of the URI.
  1886. String fragment = null;
  1887. int hashPosition = uri.indexOf('#');
  1888. if (hashPosition != -1) {
  1889. // Fragment including "#"
  1890. fragment = uri.substring(hashPosition);
  1891. // The full uri before the fragment
  1892. uri = uri.substring(0, hashPosition);
  1893. }
  1894. if (uri.contains("?")) {
  1895. uri += "&";
  1896. } else {
  1897. uri += "?";
  1898. }
  1899. uri += extraParams;
  1900. if (fragment != null) {
  1901. uri += fragment;
  1902. }
  1903. return uri;
  1904. }
  1905. ConnectorMap getConnectorMap() {
  1906. return connectorMap;
  1907. }
  1908. @Deprecated
  1909. public void unregisterPaintable(ServerConnector p) {
  1910. connectorMap.unregisterConnector(p);
  1911. }
  1912. public VTooltip getVTooltip() {
  1913. return tooltip;
  1914. }
  1915. @Deprecated
  1916. public void handleTooltipEvent(Event event, Widget owner, Object key) {
  1917. handleTooltipEvent(event, getConnectorMap().getConnector(owner), key);
  1918. }
  1919. @Deprecated
  1920. public void handleTooltipEvent(Event event, Widget owner) {
  1921. handleTooltipEvent(event, getConnectorMap().getConnector(owner));
  1922. }
  1923. @Deprecated
  1924. public void registerTooltip(Widget owner, Object key, TooltipInfo info) {
  1925. registerTooltip(getConnectorMap().getConnector(owner), key, info);
  1926. }
  1927. @Deprecated
  1928. public boolean hasEventListeners(Widget widget, String eventIdentifier) {
  1929. return hasEventListeners(getConnectorMap().getConnector(widget),
  1930. eventIdentifier);
  1931. }
  1932. private boolean layoutPending = false;
  1933. private ScheduledCommand layoutCommand = new ScheduledCommand() {
  1934. public void execute() {
  1935. /*
  1936. * Layout again if a new layout is requested while the current one
  1937. * is running.
  1938. */
  1939. while (layoutPending) {
  1940. layoutPending = false;
  1941. layoutManager.doLayout();
  1942. }
  1943. }
  1944. };
  1945. public void doLayout(boolean lazy) {
  1946. if (!lazy) {
  1947. layoutPending = true;
  1948. layoutCommand.execute();
  1949. } else if (!layoutPending) {
  1950. layoutPending = true;
  1951. /*
  1952. * Current layoutCommand will do layouts again if layoutScheduled is
  1953. * set to true -> no need to schedule another command
  1954. */
  1955. if (!layoutManager.isLayoutRunning()) {
  1956. Scheduler.get().scheduleDeferred(layoutCommand);
  1957. }
  1958. }
  1959. }
  1960. LayoutManager getLayoutManager() {
  1961. return layoutManager;
  1962. }
  1963. }