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

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