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

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