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

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