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

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