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

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