You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ApplicationConnection.java 80KB

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