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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.itmill.toolkit.terminal.gwt.client;
  5. import java.util.Date;
  6. import java.util.HashMap;
  7. import java.util.Iterator;
  8. import java.util.Vector;
  9. import com.google.gwt.core.client.JavaScriptObject;
  10. import com.google.gwt.http.client.Request;
  11. import com.google.gwt.http.client.RequestBuilder;
  12. import com.google.gwt.http.client.RequestCallback;
  13. import com.google.gwt.http.client.RequestException;
  14. import com.google.gwt.http.client.Response;
  15. import com.google.gwt.json.client.JSONArray;
  16. import com.google.gwt.json.client.JSONObject;
  17. import com.google.gwt.json.client.JSONParser;
  18. import com.google.gwt.json.client.JSONString;
  19. import com.google.gwt.json.client.JSONValue;
  20. import com.google.gwt.user.client.Command;
  21. import com.google.gwt.user.client.DOM;
  22. import com.google.gwt.user.client.DeferredCommand;
  23. import com.google.gwt.user.client.Element;
  24. import com.google.gwt.user.client.Event;
  25. import com.google.gwt.user.client.Timer;
  26. import com.google.gwt.user.client.Window;
  27. import com.google.gwt.user.client.WindowCloseListener;
  28. import com.google.gwt.user.client.ui.FocusWidget;
  29. import com.google.gwt.user.client.ui.HasFocus;
  30. import com.google.gwt.user.client.ui.HasWidgets;
  31. import com.google.gwt.user.client.ui.Widget;
  32. import com.itmill.toolkit.terminal.gwt.client.ui.IContextMenu;
  33. import com.itmill.toolkit.terminal.gwt.client.ui.Field;
  34. import com.itmill.toolkit.terminal.gwt.client.ui.IView;
  35. import com.itmill.toolkit.terminal.gwt.client.ui.INotification;
  36. import com.itmill.toolkit.terminal.gwt.client.ui.INotification.HideEvent;
  37. /**
  38. * Entry point classes define <code>onModuleLoad()</code>.
  39. */
  40. public class ApplicationConnection {
  41. private static final String MODIFIED_CLASSNAME = "i-modified";
  42. private static final String REQUIRED_CLASSNAME_EXT = "-required";
  43. private static final String ERROR_CLASSNAME_EXT = "-error";
  44. public static final String VAR_RECORD_SEPARATOR = "\u001e";
  45. public static final String VAR_FIELD_SEPARATOR = "\u001f";
  46. private final HashMap resourcesMap = new HashMap();
  47. private static Console console;
  48. private static boolean testingMode;
  49. private final Vector pendingVariables = new Vector();
  50. private final HashMap idToPaintable = new HashMap();
  51. private final HashMap paintableToId = new HashMap();
  52. /** Contains ExtendedTitleInfo by paintable id */
  53. private final HashMap paintableToTitle = new HashMap();
  54. private final WidgetSet widgetSet;
  55. private IContextMenu contextMenu = null;
  56. private Timer loadTimer;
  57. private Timer loadTimer2;
  58. private Timer loadTimer3;
  59. private Element loadElement;
  60. private final IView view;
  61. private boolean applicationRunning = false;
  62. /**
  63. * True if each Paintable objects id is injected to DOM. Used for Testing
  64. * Tools.
  65. */
  66. private boolean usePaintableIdsInDOM = false;
  67. /**
  68. * Contains reference for client wrapper given to Testing Tools.
  69. *
  70. * Used in JSNI functions
  71. *
  72. * @SuppressWarnings
  73. */
  74. private final JavaScriptObject ttClientWrapper = null;
  75. private int activeRequests = 0;
  76. private final ApplicationConfiguration configuration;
  77. private final Vector pendingVariableBursts = new Vector();
  78. public ApplicationConnection(WidgetSet widgetSet,
  79. ApplicationConfiguration cnf) {
  80. this.widgetSet = widgetSet;
  81. configuration = cnf;
  82. if (isDebugMode()) {
  83. console = new IDebugConsole(this, cnf);
  84. } else {
  85. console = new NullConsole();
  86. }
  87. if (checkTestingMode()) {
  88. usePaintableIdsInDOM = true;
  89. initializeTestingTools();
  90. Window.addWindowCloseListener(new WindowCloseListener() {
  91. public void onWindowClosed() {
  92. uninitializeTestingTools();
  93. }
  94. public String onWindowClosing() {
  95. return null;
  96. }
  97. });
  98. }
  99. initializeClientHooks();
  100. // TODO remove hard coded id name
  101. view = new IView(cnf.getRootPanelId());
  102. makeUidlRequest("", true);
  103. applicationRunning = true;
  104. }
  105. /**
  106. * Method to check if application is in testing mode. Can be used after
  107. * application init.
  108. *
  109. * @return true if in testing mode
  110. */
  111. public static boolean isTestingMode() {
  112. return testingMode;
  113. }
  114. /**
  115. * Check is application is run in testing mode.
  116. *
  117. * @return true if in testing mode
  118. */
  119. private native static boolean checkTestingMode()
  120. /*-{
  121. @com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::testingMode = $wnd.top.itmill && $wnd.top.itmill.registerToTT ? true : false;
  122. return @com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::testingMode;
  123. }-*/;
  124. private native void initializeTestingTools()
  125. /*-{
  126. var ap = this;
  127. var client = {};
  128. client.isActive = function() {
  129. return ap.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::hasActiveRequest()();
  130. }
  131. var vi = ap.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::getVersionInfo()();
  132. if (vi) {
  133. client.getVersionInfo = function() {
  134. return vi;
  135. }
  136. }
  137. $wnd.top.itmill.registerToTT(client);
  138. this.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::ttClientWrapper = client;
  139. }-*/;
  140. /**
  141. * Helper for tt initialization
  142. */
  143. private JavaScriptObject getVersionInfo() {
  144. return configuration.getVersionInfoJSObject();
  145. }
  146. private native void uninitializeTestingTools()
  147. /*-{
  148. $wnd.top.itmill.unregisterFromTT(this.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::ttClientWrapper);
  149. }-*/;
  150. /**
  151. * Publishes a JavaScript API for mash-up applications.
  152. * <ul>
  153. * <li><code>itmill.forceSync()</code> sends pending variable changes, in
  154. * effect synchronizing the server and client state. This is done for all
  155. * applications on host page.</li>
  156. * </ul>
  157. *
  158. * TODO make this multi-app aware
  159. */
  160. private native void initializeClientHooks()
  161. /*-{
  162. var app = this;
  163. var oldSync;
  164. if($wnd.itmill.forceSync) {
  165. oldSync = $wnd.itmill.forceSync;
  166. }
  167. $wnd.itmill.forceSync = function() {
  168. if(oldSync) {
  169. oldSync();
  170. }
  171. app.@com.itmill.toolkit.terminal.gwt.client.ApplicationConnection::sendPendingVariableChanges()();
  172. }
  173. }-*/;
  174. public static Console getConsole() {
  175. return console;
  176. }
  177. private native static boolean isDebugMode()
  178. /*-{
  179. var uri = $wnd.location;
  180. var re = /debug[^\/]*$/;
  181. return re.test(uri);
  182. }-*/;
  183. public String getAppUri() {
  184. return configuration.getApplicationUri();
  185. };
  186. public boolean hasActiveRequest() {
  187. return (activeRequests > 0);
  188. }
  189. private void makeUidlRequest(String requestData, boolean repaintAll) {
  190. startRequest();
  191. console.log("Making UIDL Request with params: " + requestData);
  192. String uri = getAppUri() + "UIDL" + configuration.getPathInfo();
  193. if (repaintAll) {
  194. uri += "?repaintAll=1";
  195. }
  196. final RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, uri);
  197. // rb.setHeader("Content-Type",
  198. // "application/x-www-form-urlencoded; charset=utf-8");
  199. rb.setHeader("Content-Type", "text/plain;charset=utf-8");
  200. try {
  201. rb.sendRequest(requestData, new RequestCallback() {
  202. public void onError(Request request, Throwable exception) {
  203. // TODO Better reporting to user
  204. console.error("Got error");
  205. endRequest();
  206. }
  207. public void onResponseReceived(Request request,
  208. Response response) {
  209. handleReceivedJSONMessage(response);
  210. }
  211. });
  212. } catch (final RequestException e) {
  213. ClientExceptionHandler.displayError(e);
  214. endRequest();
  215. }
  216. }
  217. private void startRequest() {
  218. activeRequests++;
  219. showLoadingIndicator();
  220. }
  221. private void endRequest() {
  222. checkForPendingVariableBursts();
  223. activeRequests--;
  224. // deferring to avoid flickering
  225. DeferredCommand.addCommand(new Command() {
  226. public void execute() {
  227. if (activeRequests == 0) {
  228. hideLoadingIndicator();
  229. }
  230. }
  231. });
  232. }
  233. /**
  234. * This method is called after applying uidl change set to application.
  235. *
  236. * It will clean current and queued variable change sets. And send next
  237. * change set if it exists.
  238. */
  239. private void checkForPendingVariableBursts() {
  240. cleanVariableBurst(pendingVariables);
  241. if (pendingVariableBursts.size() > 0) {
  242. for (Iterator iterator = pendingVariableBursts.iterator(); iterator
  243. .hasNext();) {
  244. cleanVariableBurst((Vector) iterator.next());
  245. }
  246. Vector nextBurst = (Vector) pendingVariableBursts.firstElement();
  247. pendingVariableBursts.remove(0);
  248. buildAndSendVariableBurst(nextBurst);
  249. }
  250. }
  251. /**
  252. * Cleans given queue of variable changes of such changes that came from
  253. * components that do not exist anymore.
  254. *
  255. * @param variableBurst
  256. */
  257. private void cleanVariableBurst(Vector variableBurst) {
  258. for (int i = 1; i < variableBurst.size(); i += 2) {
  259. String id = (String) variableBurst.get(i);
  260. id = id.substring(0, id.indexOf(VAR_FIELD_SEPARATOR));
  261. if (!idToPaintable.containsKey(id)) {
  262. // variable owner does not exist anymore
  263. variableBurst.remove(i - 1);
  264. variableBurst.remove(i - 1);
  265. i -= 2;
  266. ApplicationConnection.getConsole().log(
  267. "Removed variable from removed component: " + id);
  268. }
  269. }
  270. }
  271. private void showLoadingIndicator() {
  272. // show initial throbber
  273. if (loadTimer == null) {
  274. loadTimer = new Timer() {
  275. public void run() {
  276. // show initial throbber
  277. if (loadElement == null) {
  278. loadElement = DOM.createDiv();
  279. DOM.setStyleAttribute(loadElement, "position",
  280. "absolute");
  281. DOM.appendChild(view.getElement(), loadElement);
  282. ApplicationConnection.getConsole().log(
  283. "inserting load indicator");
  284. // Position
  285. DOM.setStyleAttribute(loadElement, "top", (view
  286. .getAbsoluteTop() + 6)
  287. + "px");
  288. }
  289. DOM.setElementProperty(loadElement, "className",
  290. "i-loading-indicator");
  291. DOM.setStyleAttribute(loadElement, "display", "block");
  292. final int updatedX = Window.getScrollLeft()
  293. + view.getAbsoluteLeft()
  294. + view.getOffsetWidth()
  295. - DOM.getElementPropertyInt(loadElement,
  296. "offsetWidth") - 5;
  297. DOM.setStyleAttribute(loadElement, "left", updatedX + "px");
  298. final int updatedY = Window.getScrollTop() + 6
  299. + view.getAbsoluteTop();
  300. DOM.setStyleAttribute(loadElement, "top", updatedY + "px");
  301. // Initialize other timers
  302. loadTimer2 = new Timer() {
  303. public void run() {
  304. DOM.setElementProperty(loadElement, "className",
  305. "i-loading-indicator-delay");
  306. }
  307. };
  308. // Second one kicks in at 1500ms
  309. loadTimer2.schedule(1200);
  310. loadTimer3 = new Timer() {
  311. public void run() {
  312. DOM.setElementProperty(loadElement, "className",
  313. "i-loading-indicator-wait");
  314. }
  315. };
  316. // Third one kicks in at 5000ms
  317. loadTimer3.schedule(4700);
  318. }
  319. };
  320. // First one kicks in at 300ms
  321. loadTimer.schedule(300);
  322. }
  323. }
  324. private void hideLoadingIndicator() {
  325. if (loadTimer != null) {
  326. loadTimer.cancel();
  327. if (loadTimer2 != null) {
  328. loadTimer2.cancel();
  329. loadTimer3.cancel();
  330. }
  331. loadTimer = null;
  332. }
  333. if (loadElement != null) {
  334. DOM.removeChild(view.getElement(), loadElement);
  335. loadElement = null;
  336. }
  337. }
  338. private void handleReceivedJSONMessage(Response response) {
  339. final Date start = new Date();
  340. String jsonText = response.getText();
  341. // for(;;);[realjson]
  342. jsonText = jsonText.substring(9, jsonText.length() - 1);
  343. JSONValue json;
  344. try {
  345. json = JSONParser.parse(jsonText);
  346. } catch (final com.google.gwt.json.client.JSONException e) {
  347. endRequest();
  348. console.log(e.getMessage() + " - Original JSON-text:");
  349. console.log(jsonText);
  350. return;
  351. }
  352. // Handle redirect
  353. final JSONObject redirect = (JSONObject) ((JSONObject) json)
  354. .get("redirect");
  355. if (redirect != null) {
  356. final JSONString url = (JSONString) redirect.get("url");
  357. if (url != null) {
  358. console.log("redirecting to " + url.stringValue());
  359. redirect(url.stringValue());
  360. return;
  361. }
  362. }
  363. // Store resources
  364. final JSONObject resources = (JSONObject) ((JSONObject) json)
  365. .get("resources");
  366. for (final Iterator i = resources.keySet().iterator(); i.hasNext();) {
  367. final String key = (String) i.next();
  368. resourcesMap.put(key, ((JSONString) resources.get(key))
  369. .stringValue());
  370. }
  371. // Store locale data
  372. if (((JSONObject) json).containsKey("locales")) {
  373. final JSONArray l = (JSONArray) ((JSONObject) json).get("locales");
  374. for (int i = 0; i < l.size(); i++) {
  375. LocaleService.addLocale((JSONObject) l.get(i));
  376. }
  377. }
  378. JSONObject meta = null;
  379. if (((JSONObject) json).containsKey("meta")) {
  380. meta = ((JSONObject) json).get("meta").isObject();
  381. if (meta.containsKey("repaintAll")) {
  382. view.clear();
  383. idToPaintable.clear();
  384. paintableToId.clear();
  385. }
  386. }
  387. // Process changes
  388. final JSONArray changes = (JSONArray) ((JSONObject) json)
  389. .get("changes");
  390. for (int i = 0; i < changes.size(); i++) {
  391. try {
  392. final UIDL change = new UIDL((JSONArray) changes.get(i));
  393. try {
  394. console.dirUIDL(change);
  395. } catch (final Exception e) {
  396. ClientExceptionHandler.displayError(e);
  397. // TODO: dir doesn't work in any browser although it should
  398. // work (works in hosted mode)
  399. // it partially did at some part but now broken.
  400. }
  401. final UIDL uidl = change.getChildUIDL(0);
  402. final Paintable paintable = getPaintable(uidl.getId());
  403. if (paintable != null) {
  404. paintable.updateFromUIDL(uidl, this);
  405. } else {
  406. if (!uidl.getTag().equals("window")) {
  407. ClientExceptionHandler
  408. .displayError("Received update for "
  409. + uidl.getTag()
  410. + ", but there is no such paintable ("
  411. + uidl.getId() + ") rendered.");
  412. } else {
  413. view.updateFromUIDL(uidl, this);
  414. }
  415. }
  416. } catch (final Throwable e) {
  417. ClientExceptionHandler.displayError(e);
  418. }
  419. }
  420. if (meta != null) {
  421. if (meta.containsKey("focus")) {
  422. final String focusPid = meta.get("focus").isString()
  423. .stringValue();
  424. final Paintable toBeFocused = getPaintable(focusPid);
  425. if (toBeFocused instanceof HasFocus) {
  426. final HasFocus toBeFocusedWidget = (HasFocus) toBeFocused;
  427. toBeFocusedWidget.setFocus(true);
  428. } else if (toBeFocused instanceof Focusable) {
  429. ((Focusable) toBeFocused).focus();
  430. } else {
  431. getConsole().log("Could not focus component");
  432. }
  433. }
  434. if (meta.containsKey("appError")) {
  435. JSONObject error = meta.get("appError").isObject();
  436. JSONValue val = error.get("caption");
  437. String html = "";
  438. if (val.isString() != null) {
  439. html += "<h1>" + val.isString().stringValue() + "</h1>";
  440. }
  441. val = error.get("message");
  442. if (val.isString() != null) {
  443. html += "<p>" + val.isString().stringValue() + "</p>";
  444. }
  445. val = error.get("url");
  446. String url = null;
  447. if (val.isString() != null) {
  448. url = val.isString().stringValue();
  449. }
  450. if (html.length() != 0) {
  451. INotification n = new INotification(1000 * 60 * 45); // 45min
  452. n.addEventListener(new NotificationRedirect(url));
  453. n.show(html, INotification.CENTERED_TOP, "system");
  454. } else {
  455. redirect(url);
  456. }
  457. applicationRunning = false;
  458. }
  459. }
  460. final long prosessingTime = (new Date().getTime()) - start.getTime();
  461. console.log(" Processing time was " + String.valueOf(prosessingTime)
  462. + "ms for " + jsonText.length() + " characters of JSON");
  463. console.log("Referenced paintables: " + idToPaintable.size());
  464. endRequest();
  465. }
  466. // Redirect browser, null reloads current page
  467. private static native void redirect(String url)
  468. /*-{
  469. if (url) {
  470. $wnd.location = url;
  471. } else {
  472. $wnd.location = $wnd.location;
  473. }
  474. }-*/;
  475. public void registerPaintable(String id, Paintable paintable) {
  476. idToPaintable.put(id, paintable);
  477. paintableToId.put(paintable, id);
  478. }
  479. public void unregisterPaintable(Paintable p) {
  480. Object id = paintableToId.get(p);
  481. idToPaintable.remove(id);
  482. paintableToTitle.remove(id);
  483. paintableToId.remove(p);
  484. if (p instanceof HasWidgets) {
  485. unregisterChildPaintables((HasWidgets) p);
  486. }
  487. }
  488. public void unregisterChildPaintables(HasWidgets container) {
  489. final Iterator it = container.iterator();
  490. while (it.hasNext()) {
  491. final Widget w = (Widget) it.next();
  492. if (w instanceof Paintable) {
  493. unregisterPaintable((Paintable) w);
  494. } else if (w instanceof HasWidgets) {
  495. unregisterChildPaintables((HasWidgets) w);
  496. }
  497. }
  498. }
  499. /**
  500. * Returns Paintable element by its id
  501. *
  502. * @param id
  503. * Paintable ID
  504. */
  505. public Paintable getPaintable(String id) {
  506. return (Paintable) idToPaintable.get(id);
  507. }
  508. private void addVariableToQueue(String paintableId, String variableName,
  509. String encodedValue, boolean immediate, char type) {
  510. final String id = paintableId + VAR_FIELD_SEPARATOR + variableName
  511. + VAR_FIELD_SEPARATOR + type;
  512. for (int i = 1; i < pendingVariables.size(); i += 2) {
  513. if ((pendingVariables.get(i)).equals(id)) {
  514. pendingVariables.remove(i - 1);
  515. pendingVariables.remove(i - 1);
  516. break;
  517. }
  518. }
  519. pendingVariables.add(encodedValue);
  520. pendingVariables.add(id);
  521. if (immediate) {
  522. sendPendingVariableChanges();
  523. }
  524. }
  525. /**
  526. * This method sends currently queued variable changes to server. It is
  527. * called when immediate variable update must happen.
  528. *
  529. * To ensure correct order for variable changes (due servers multithreading
  530. * or network), we always wait for active request to be handler before
  531. * sending a new one. If there is an active request, we will put varible
  532. * "burst" to queue that will be purged after current request is handled.
  533. *
  534. */
  535. public void sendPendingVariableChanges() {
  536. if (applicationRunning) {
  537. if (hasActiveRequest()) {
  538. // skip empty queues if there are pending bursts to be sent
  539. if (pendingVariables.size() > 0
  540. || pendingVariableBursts.size() == 0) {
  541. Vector burst = (Vector) pendingVariables.clone();
  542. pendingVariableBursts.add(burst);
  543. }
  544. } else {
  545. buildAndSendVariableBurst(pendingVariables);
  546. }
  547. }
  548. }
  549. private void buildAndSendVariableBurst(Vector pendingVariables) {
  550. final StringBuffer req = new StringBuffer();
  551. for (int i = 0; i < pendingVariables.size(); i++) {
  552. if (i > 0) {
  553. if (i % 2 == 0) {
  554. req.append(VAR_RECORD_SEPARATOR);
  555. } else {
  556. req.append(VAR_FIELD_SEPARATOR);
  557. }
  558. }
  559. req.append(pendingVariables.get(i));
  560. }
  561. pendingVariables.clear();
  562. makeUidlRequest(req.toString(), false);
  563. }
  564. public void updateVariable(String paintableId, String variableName,
  565. String newValue, boolean immediate) {
  566. addVariableToQueue(paintableId, variableName, newValue, immediate, 's');
  567. }
  568. public void updateVariable(String paintableId, String variableName,
  569. int newValue, boolean immediate) {
  570. addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
  571. 'i');
  572. }
  573. public void updateVariable(String paintableId, String variableName,
  574. long newValue, boolean immediate) {
  575. addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
  576. 'l');
  577. }
  578. public void updateVariable(String paintableId, String variableName,
  579. float newValue, boolean immediate) {
  580. addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
  581. 'f');
  582. }
  583. public void updateVariable(String paintableId, String variableName,
  584. double newValue, boolean immediate) {
  585. addVariableToQueue(paintableId, variableName, "" + newValue, immediate,
  586. 'd');
  587. }
  588. public void updateVariable(String paintableId, String variableName,
  589. boolean newValue, boolean immediate) {
  590. addVariableToQueue(paintableId, variableName, newValue ? "true"
  591. : "false", immediate, 'b');
  592. }
  593. public void updateVariable(String paintableId, String variableName,
  594. Object[] values, boolean immediate) {
  595. final StringBuffer buf = new StringBuffer();
  596. for (int i = 0; i < values.length; i++) {
  597. if (i > 0) {
  598. buf.append(",");
  599. }
  600. buf.append(values[i].toString());
  601. }
  602. addVariableToQueue(paintableId, variableName, buf.toString(),
  603. immediate, 'a');
  604. }
  605. /**
  606. * Update generic component features.
  607. *
  608. * <h2>Selecting correct implementation</h2>
  609. *
  610. * <p>
  611. * The implementation of a component depends on many properties, including
  612. * styles, component features, etc. Sometimes the user changes those
  613. * properties after the component has been created. Calling this method in
  614. * the beginning of your updateFromUIDL -method automatically replaces your
  615. * component with more appropriate if the requested implementation changes.
  616. * </p>
  617. *
  618. * <h2>Caption, icon, error messages and description</h2>
  619. *
  620. * <p>
  621. * Component can delegate management of caption, icon, error messages and
  622. * description to parent layout. This is optional an should be decided by
  623. * component author
  624. * </p>
  625. *
  626. * <h2>Component visibility and disabling</h2>
  627. *
  628. * This method will manage component visibility automatically and if
  629. * component is an instanceof FocusWidget, also handle component disabling
  630. * when needed.
  631. *
  632. * @param component
  633. * Widget to be updated, expected to implement an instance of
  634. * Paintable
  635. * @param uidl
  636. * UIDL to be painted
  637. * @param manageCaption
  638. * True if you want to delegate caption, icon, description and
  639. * error message management to parent.
  640. *
  641. * @return Returns true iff no further painting is needed by caller
  642. */
  643. public boolean updateComponent(Widget component, UIDL uidl,
  644. boolean manageCaption) {
  645. // If the server request that a cached instance should be used, do
  646. // nothing
  647. if (uidl.getBooleanAttribute("cached")) {
  648. return true;
  649. }
  650. // Visibility
  651. boolean visible = !uidl.getBooleanAttribute("invisible");
  652. component.setVisible(visible);
  653. if (!visible) {
  654. return true;
  655. }
  656. // Switch to correct implementation if needed
  657. if (!widgetSet.isCorrectImplementation(component, uidl)) {
  658. final Container parent = Util.getParentLayout(component);
  659. if (parent != null) {
  660. final Widget w = (Widget) widgetSet.createWidget(uidl);
  661. parent.replaceChildComponent(component, w);
  662. registerPaintable(uidl.getId(), (Paintable) w);
  663. ((Paintable) w).updateFromUIDL(uidl, this);
  664. return true;
  665. }
  666. }
  667. updateComponentSize(component, uidl);
  668. boolean enabled = !uidl.getBooleanAttribute("disabled");
  669. if (component instanceof FocusWidget) {
  670. FocusWidget fw = (FocusWidget) component;
  671. fw.setEnabled(enabled);
  672. if (uidl.hasAttribute("tabindex")) {
  673. fw.setTabIndex(uidl.getIntAttribute("tabindex"));
  674. }
  675. }
  676. StringBuffer styleBuf = new StringBuffer();
  677. final String primaryName = component.getStylePrimaryName();
  678. styleBuf.append(primaryName);
  679. // first disabling and read-only status
  680. if (!enabled) {
  681. styleBuf.append(" ");
  682. styleBuf.append("i-disabled");
  683. }
  684. if (uidl.getBooleanAttribute("readonly")) {
  685. styleBuf.append(" ");
  686. styleBuf.append("i-readonly");
  687. }
  688. // add additional styles as css classes, prefixed with component default
  689. // stylename
  690. if (uidl.hasAttribute("style")) {
  691. final String[] styles = uidl.getStringAttribute("style").split(" ");
  692. for (int i = 0; i < styles.length; i++) {
  693. styleBuf.append(" ");
  694. styleBuf.append(primaryName);
  695. styleBuf.append("-");
  696. styleBuf.append(styles[i]);
  697. }
  698. }
  699. // add modified classname to Fields
  700. if (uidl.hasAttribute("modified") && component instanceof Field) {
  701. styleBuf.append(" ");
  702. styleBuf.append(MODIFIED_CLASSNAME);
  703. }
  704. TooltipInfo tooltipInfo = getTitleInfo((Paintable) component);
  705. if (uidl.hasAttribute("description")) {
  706. tooltipInfo.setTitle(uidl.getStringAttribute("description"));
  707. } else {
  708. tooltipInfo.setTitle(null);
  709. }
  710. // add error classname to components w/ error
  711. if (uidl.hasAttribute("error")) {
  712. styleBuf.append(" ");
  713. styleBuf.append(primaryName);
  714. styleBuf.append(ERROR_CLASSNAME_EXT);
  715. tooltipInfo.setErrorUidl(uidl.getErrors());
  716. } else {
  717. tooltipInfo.setErrorUidl(null);
  718. }
  719. // add required style to required components
  720. if (uidl.hasAttribute("required")) {
  721. styleBuf.append(" ");
  722. styleBuf.append(primaryName);
  723. styleBuf.append(REQUIRED_CLASSNAME_EXT);
  724. }
  725. // Styles + disabled & readonly
  726. component.setStyleName(styleBuf.toString());
  727. // Set captions
  728. if (manageCaption) {
  729. final Container parent = Util.getParentLayout(component);
  730. if (parent != null) {
  731. parent.updateCaption((Paintable) component, uidl);
  732. }
  733. }
  734. if (usePaintableIdsInDOM) {
  735. DOM.setElementProperty(component.getElement(), "id", uidl.getId());
  736. }
  737. return false;
  738. }
  739. private void updateComponentSize(Widget component, UIDL uidl) {
  740. String w = uidl.hasAttribute("width") ? uidl
  741. .getStringAttribute("width") : "";
  742. component.setWidth(w);
  743. String h = uidl.hasAttribute("height") ? uidl
  744. .getStringAttribute("height") : "";
  745. component.setHeight(h);
  746. }
  747. /**
  748. * Get either existing or new Paintable for given UIDL.
  749. *
  750. * If corresponding Paintable has been previously painted, return it.
  751. * Otherwise create and register a new Paintable from UIDL. Caller must
  752. * update the returned Paintable from UIDL after it has been connected to
  753. * parent.
  754. *
  755. * @param uidl
  756. * UIDL to create Paintable from.
  757. * @return Either existing or new Paintable corresponding to UIDL.
  758. */
  759. public Paintable getPaintable(UIDL uidl) {
  760. final String id = uidl.getId();
  761. Paintable w = getPaintable(id);
  762. if (w != null) {
  763. return w;
  764. }
  765. w = widgetSet.createWidget(uidl);
  766. registerPaintable(id, w);
  767. return w;
  768. }
  769. public String getResource(String name) {
  770. return (String) resourcesMap.get(name);
  771. }
  772. /**
  773. * Singleton method to get instance of app's context menu.
  774. *
  775. * @return IContextMenu object
  776. */
  777. public IContextMenu getContextMenu() {
  778. if (contextMenu == null) {
  779. contextMenu = new IContextMenu();
  780. if (usePaintableIdsInDOM) {
  781. DOM.setElementProperty(contextMenu.getElement(), "id",
  782. "PID_TOOLKIT_CM");
  783. }
  784. }
  785. return contextMenu;
  786. }
  787. /**
  788. * Translates custom protocols in UIRL URI's to be recognizable by browser.
  789. * All uri's from UIDL should be routed via this method before giving them
  790. * to browser due URI's in UIDL may contain custom protocols like theme://.
  791. *
  792. * @param toolkitUri
  793. * toolkit URI from uidl
  794. * @return translated URI ready for browser
  795. */
  796. public String translateToolkitUri(String toolkitUri) {
  797. if (toolkitUri == null) {
  798. return null;
  799. }
  800. if (toolkitUri.startsWith("theme://")) {
  801. final String themeUri = configuration.getThemeUri();
  802. if (themeUri == null) {
  803. console
  804. .error("Theme not set: ThemeResource will not be found. ("
  805. + toolkitUri + ")");
  806. }
  807. toolkitUri = themeUri + toolkitUri.substring(7);
  808. }
  809. return toolkitUri;
  810. }
  811. public String getThemeUri() {
  812. return configuration.getThemeUri();
  813. }
  814. /**
  815. * Listens for Notification hide event, and redirects. Used for system
  816. * messages, such as session expired.
  817. *
  818. */
  819. private class NotificationRedirect implements INotification.EventListener {
  820. String url;
  821. NotificationRedirect(String url) {
  822. this.url = url;
  823. }
  824. public void notificationHidden(HideEvent event) {
  825. redirect(url);
  826. }
  827. }
  828. /* Extended title handling */
  829. /**
  830. * Data showed in tooltips are stored centrilized as it may be needed in
  831. * varios place: caption, layouts, and in owner components themselves.
  832. *
  833. * Updating TooltipInfo is done in updateComponent method.
  834. *
  835. */
  836. public TooltipInfo getTitleInfo(Paintable titleOwner) {
  837. TooltipInfo info = (TooltipInfo) paintableToTitle.get(titleOwner);
  838. if (info == null) {
  839. info = new TooltipInfo();
  840. paintableToTitle.put(titleOwner, info);
  841. }
  842. return info;
  843. }
  844. private final ITooltip tooltip = new ITooltip(this);
  845. /**
  846. * Component may want to delegate Tooltip handling to client. Layouts add
  847. * Tooltip (description, errors) to caption, but some components may want
  848. * them to appear one other elements too.
  849. *
  850. * Events wanted by this handler are same as in Tooltip.TOOLTIP_EVENTS
  851. *
  852. * @param event
  853. * @param owner
  854. */
  855. public void handleTooltipEvent(Event event, Paintable owner) {
  856. tooltip.handleTooltipEvent(event, owner);
  857. }
  858. /**
  859. * Adds PNG-fix conditionally (only for IE6) to the specified IMG -element.
  860. *
  861. * @param el
  862. * the IMG element to fix
  863. */
  864. public void addPngFix(Element el) {
  865. BrowserInfo b = BrowserInfo.get();
  866. if (b.isIE6()) {
  867. Util.addPngFix(el, getThemeUri()
  868. + "/../default/common/img/blank.gif");
  869. }
  870. }
  871. /*
  872. * Helper to run layout functions triggered by child components with a
  873. * decent interval.
  874. */
  875. private final Timer layoutTimer = new Timer() {
  876. private boolean isPending = false;
  877. public void schedule(int delayMillis) {
  878. if (!isPending) {
  879. super.schedule(delayMillis);
  880. isPending = true;
  881. }
  882. }
  883. public void run() {
  884. getConsole().log("Running re-layout");
  885. Util.runDescendentsLayout(view);
  886. isPending = false;
  887. }
  888. };
  889. /**
  890. * Components can call this function to run all layout functions. This is
  891. * usually done, when component knows that its size has changed.
  892. */
  893. public void requestLayoutPhase() {
  894. layoutTimer.schedule(500);
  895. }
  896. }