Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

VCustomLayout.java 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client.ui;
  5. import java.util.HashMap;
  6. import java.util.HashSet;
  7. import java.util.Iterator;
  8. import java.util.Set;
  9. import com.google.gwt.dom.client.ImageElement;
  10. import com.google.gwt.dom.client.NodeList;
  11. import com.google.gwt.user.client.DOM;
  12. import com.google.gwt.user.client.Element;
  13. import com.google.gwt.user.client.Event;
  14. import com.google.gwt.user.client.ui.ComplexPanel;
  15. import com.google.gwt.user.client.ui.Widget;
  16. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  17. import com.vaadin.terminal.gwt.client.BrowserInfo;
  18. import com.vaadin.terminal.gwt.client.Container;
  19. import com.vaadin.terminal.gwt.client.ContainerResizedListener;
  20. import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;
  21. import com.vaadin.terminal.gwt.client.RenderSpace;
  22. import com.vaadin.terminal.gwt.client.UIDL;
  23. import com.vaadin.terminal.gwt.client.Util;
  24. import com.vaadin.terminal.gwt.client.VCaption;
  25. import com.vaadin.terminal.gwt.client.VCaptionWrapper;
  26. import com.vaadin.terminal.gwt.client.VPaintableMap;
  27. import com.vaadin.terminal.gwt.client.VPaintableWidget;
  28. /**
  29. * Custom Layout implements complex layout defined with HTML template.
  30. *
  31. * @author Vaadin Ltd
  32. *
  33. */
  34. public class VCustomLayout extends ComplexPanel implements VPaintableWidget,
  35. Container, ContainerResizedListener {
  36. public static final String CLASSNAME = "v-customlayout";
  37. /** Location-name to containing element in DOM map */
  38. private final HashMap<String, Element> locationToElement = new HashMap<String, Element>();
  39. /** Location-name to contained widget map */
  40. private final HashMap<String, Widget> locationToWidget = new HashMap<String, Widget>();
  41. /** Widget to captionwrapper map */
  42. private final HashMap<VPaintableWidget, VCaptionWrapper> paintableToCaptionWrapper = new HashMap<VPaintableWidget, VCaptionWrapper>();
  43. /** Name of the currently rendered style */
  44. String currentTemplateName;
  45. /** Unexecuted scripts loaded from the template */
  46. private String scripts = "";
  47. /** Paintable ID of this paintable */
  48. private String pid;
  49. private ApplicationConnection client;
  50. /** Has the template been loaded from contents passed in UIDL **/
  51. private boolean hasTemplateContents = false;
  52. private Element elementWithNativeResizeFunction;
  53. private String height = "";
  54. private String width = "";
  55. private HashMap<String, FloatSize> locationToExtraSize = new HashMap<String, FloatSize>();
  56. public VCustomLayout() {
  57. setElement(DOM.createDiv());
  58. // Clear any unwanted styling
  59. DOM.setStyleAttribute(getElement(), "border", "none");
  60. DOM.setStyleAttribute(getElement(), "margin", "0");
  61. DOM.setStyleAttribute(getElement(), "padding", "0");
  62. if (BrowserInfo.get().isIE()) {
  63. DOM.setStyleAttribute(getElement(), "position", "relative");
  64. }
  65. setStyleName(CLASSNAME);
  66. }
  67. /**
  68. * Sets widget to given location.
  69. *
  70. * If location already contains a widget it will be removed.
  71. *
  72. * @param widget
  73. * Widget to be set into location.
  74. * @param location
  75. * location name where widget will be added
  76. *
  77. * @throws IllegalArgumentException
  78. * if no such location is found in the layout.
  79. */
  80. public void setWidget(Widget widget, String location) {
  81. if (widget == null) {
  82. return;
  83. }
  84. // If no given location is found in the layout, and exception is throws
  85. Element elem = locationToElement.get(location);
  86. if (elem == null && hasTemplate()) {
  87. throw new IllegalArgumentException("No location " + location
  88. + " found");
  89. }
  90. // Get previous widget
  91. final Widget previous = locationToWidget.get(location);
  92. // NOP if given widget already exists in this location
  93. if (previous == widget) {
  94. return;
  95. }
  96. if (previous != null) {
  97. remove(previous);
  98. }
  99. // if template is missing add element in order
  100. if (!hasTemplate()) {
  101. elem = getElement();
  102. }
  103. // Add widget to location
  104. super.add(widget, elem);
  105. locationToWidget.put(location, widget);
  106. }
  107. /** Update the layout from UIDL */
  108. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  109. this.client = client;
  110. // ApplicationConnection manages generic component features
  111. if (client.updateComponent(this, uidl, true)) {
  112. return;
  113. }
  114. pid = uidl.getId();
  115. if (!hasTemplate()) {
  116. // Update HTML template only once
  117. initializeHTML(uidl, client);
  118. }
  119. // Evaluate scripts
  120. eval(scripts);
  121. scripts = null;
  122. iLayout();
  123. // TODO Check if this is needed
  124. client.runDescendentsLayout(this);
  125. Set<Widget> oldWidgets = new HashSet<Widget>();
  126. oldWidgets.addAll(locationToWidget.values());
  127. // For all contained widgets
  128. for (final Iterator<?> i = uidl.getChildIterator(); i.hasNext();) {
  129. final UIDL uidlForChild = (UIDL) i.next();
  130. if (uidlForChild.getTag().equals("location")) {
  131. final String location = uidlForChild.getStringAttribute("name");
  132. UIDL childUIDL = uidlForChild.getChildUIDL(0);
  133. final VPaintableWidget childPaintable = client
  134. .getPaintable(childUIDL);
  135. Widget childWidget = childPaintable.getWidgetForPaintable();
  136. try {
  137. setWidget(childWidget, location);
  138. childPaintable.updateFromUIDL(childUIDL, client);
  139. } catch (final IllegalArgumentException e) {
  140. // If no location is found, this component is not visible
  141. }
  142. oldWidgets.remove(childWidget);
  143. }
  144. }
  145. for (Iterator<Widget> iterator = oldWidgets.iterator(); iterator
  146. .hasNext();) {
  147. Widget oldWidget = iterator.next();
  148. if (oldWidget.isAttached()) {
  149. // slot of this widget is emptied, remove it
  150. remove(oldWidget);
  151. }
  152. }
  153. iLayout();
  154. // TODO Check if this is needed
  155. client.runDescendentsLayout(this);
  156. }
  157. /** Initialize HTML-layout. */
  158. private void initializeHTML(UIDL uidl, ApplicationConnection client) {
  159. final String newTemplateContents = uidl
  160. .getStringAttribute("templateContents");
  161. final String newTemplate = uidl.getStringAttribute("template");
  162. currentTemplateName = null;
  163. hasTemplateContents = false;
  164. String template = "";
  165. if (newTemplate != null) {
  166. // Get the HTML-template from client
  167. template = client.getResource("layouts/" + newTemplate + ".html");
  168. if (template == null) {
  169. template = "<em>Layout file layouts/"
  170. + newTemplate
  171. + ".html is missing. Components will be drawn for debug purposes.</em>";
  172. } else {
  173. currentTemplateName = newTemplate;
  174. }
  175. } else {
  176. hasTemplateContents = true;
  177. template = newTemplateContents;
  178. }
  179. // Connect body of the template to DOM
  180. template = extractBodyAndScriptsFromTemplate(template);
  181. // TODO prefix img src:s here with a regeps, cannot work further with IE
  182. String themeUri = client.getThemeUri();
  183. String relImgPrefix = themeUri + "/layouts/";
  184. // prefix all relative image elements to point to theme dir with a
  185. // regexp search
  186. template = template.replaceAll(
  187. "<((?:img)|(?:IMG))\\s([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
  188. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  189. // also support src attributes without quotes
  190. template = template
  191. .replaceAll(
  192. "<((?:img)|(?:IMG))\\s([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
  193. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  194. // also prefix relative style="...url(...)..."
  195. template = template
  196. .replaceAll(
  197. "(<[^>]+style=\"[^\"]*url\\()((?![a-z]+:)[^/][^\"]+)(\\)[^>]*>)",
  198. "$1 " + relImgPrefix + "$2 $3");
  199. getElement().setInnerHTML(template);
  200. // Remap locations to elements
  201. locationToElement.clear();
  202. scanForLocations(getElement());
  203. initImgElements();
  204. elementWithNativeResizeFunction = DOM.getFirstChild(getElement());
  205. if (elementWithNativeResizeFunction == null) {
  206. elementWithNativeResizeFunction = getElement();
  207. }
  208. publishResizedFunction(elementWithNativeResizeFunction);
  209. }
  210. private native boolean uriEndsWithSlash()
  211. /*-{
  212. var path = $wnd.location.pathname;
  213. if(path.charAt(path.length - 1) == "/")
  214. return true;
  215. return false;
  216. }-*/;
  217. private boolean hasTemplate() {
  218. if (currentTemplateName == null && !hasTemplateContents) {
  219. return false;
  220. } else {
  221. return true;
  222. }
  223. }
  224. /** Collect locations from template */
  225. private void scanForLocations(Element elem) {
  226. final String location = elem.getAttribute("location");
  227. if (!"".equals(location)) {
  228. locationToElement.put(location, elem);
  229. elem.setInnerHTML("");
  230. int x = Util.measureHorizontalPaddingAndBorder(elem, 0);
  231. int y = Util.measureVerticalPaddingAndBorder(elem, 0);
  232. FloatSize fs = new FloatSize(x, y);
  233. locationToExtraSize.put(location, fs);
  234. } else {
  235. final int len = DOM.getChildCount(elem);
  236. for (int i = 0; i < len; i++) {
  237. scanForLocations(DOM.getChild(elem, i));
  238. }
  239. }
  240. }
  241. /** Evaluate given script in browser document */
  242. private static native void eval(String script)
  243. /*-{
  244. try {
  245. if (script != null)
  246. eval("{ var document = $doc; var window = $wnd; "+ script + "}");
  247. } catch (e) {
  248. }
  249. }-*/;
  250. /**
  251. * Img elements needs some special handling in custom layout. Img elements
  252. * will get their onload events sunk. This way custom layout can notify
  253. * parent about possible size change.
  254. */
  255. private void initImgElements() {
  256. NodeList<com.google.gwt.dom.client.Element> nodeList = getElement()
  257. .getElementsByTagName("IMG");
  258. for (int i = 0; i < nodeList.getLength(); i++) {
  259. com.google.gwt.dom.client.ImageElement img = (ImageElement) nodeList
  260. .getItem(i);
  261. DOM.sinkEvents((Element) img.cast(), Event.ONLOAD);
  262. }
  263. }
  264. /**
  265. * Extract body part and script tags from raw html-template.
  266. *
  267. * Saves contents of all script-tags to private property: scripts. Returns
  268. * contents of the body part for the html without script-tags. Also replaces
  269. * all _UID_ tags with an unique id-string.
  270. *
  271. * @param html
  272. * Original HTML-template received from server
  273. * @return html that is used to create the HTMLPanel.
  274. */
  275. private String extractBodyAndScriptsFromTemplate(String html) {
  276. // Replace UID:s
  277. html = html.replaceAll("_UID_", pid + "__");
  278. // Exctract script-tags
  279. scripts = "";
  280. int endOfPrevScript = 0;
  281. int nextPosToCheck = 0;
  282. String lc = html.toLowerCase();
  283. String res = "";
  284. int scriptStart = lc.indexOf("<script", nextPosToCheck);
  285. while (scriptStart > 0) {
  286. res += html.substring(endOfPrevScript, scriptStart);
  287. scriptStart = lc.indexOf(">", scriptStart);
  288. final int j = lc.indexOf("</script>", scriptStart);
  289. scripts += html.substring(scriptStart + 1, j) + ";";
  290. nextPosToCheck = endOfPrevScript = j + "</script>".length();
  291. scriptStart = lc.indexOf("<script", nextPosToCheck);
  292. }
  293. res += html.substring(endOfPrevScript);
  294. // Extract body
  295. html = res;
  296. lc = html.toLowerCase();
  297. int startOfBody = lc.indexOf("<body");
  298. if (startOfBody < 0) {
  299. res = html;
  300. } else {
  301. res = "";
  302. startOfBody = lc.indexOf(">", startOfBody) + 1;
  303. final int endOfBody = lc.indexOf("</body>", startOfBody);
  304. if (endOfBody > startOfBody) {
  305. res = html.substring(startOfBody, endOfBody);
  306. } else {
  307. res = html.substring(startOfBody);
  308. }
  309. }
  310. return res;
  311. }
  312. /** Replace child components */
  313. public void replaceChildComponent(Widget from, Widget to) {
  314. final String location = getLocation(from);
  315. if (location == null) {
  316. throw new IllegalArgumentException();
  317. }
  318. setWidget(to, location);
  319. }
  320. /** Does this layout contain given child */
  321. public boolean hasChildComponent(Widget component) {
  322. return locationToWidget.containsValue(component);
  323. }
  324. /** Update caption for given widget */
  325. public void updateCaption(VPaintableWidget paintable, UIDL uidl) {
  326. VCaptionWrapper wrapper = paintableToCaptionWrapper.get(paintable);
  327. Widget widget = paintable.getWidgetForPaintable();
  328. if (VCaption.isNeeded(uidl)) {
  329. if (wrapper == null) {
  330. // Add a wrapper between the layout and the child widget
  331. final String loc = getLocation(widget);
  332. super.remove(widget);
  333. wrapper = new VCaptionWrapper(paintable, client);
  334. super.add(wrapper, locationToElement.get(loc));
  335. paintableToCaptionWrapper.put(paintable, wrapper);
  336. }
  337. wrapper.updateCaption(uidl);
  338. } else {
  339. if (wrapper != null) {
  340. // Remove the wrapper and add the widget directly to the layout
  341. final String loc = getLocation(widget);
  342. super.remove(wrapper);
  343. super.add(widget, locationToElement.get(loc));
  344. paintableToCaptionWrapper.remove(paintable);
  345. }
  346. }
  347. }
  348. /** Get the location of an widget */
  349. public String getLocation(Widget w) {
  350. for (final Iterator<String> i = locationToWidget.keySet().iterator(); i
  351. .hasNext();) {
  352. final String location = i.next();
  353. if (locationToWidget.get(location) == w) {
  354. return location;
  355. }
  356. }
  357. return null;
  358. }
  359. /** Removes given widget from the layout */
  360. @Override
  361. public boolean remove(Widget w) {
  362. VPaintableWidget paintable = VPaintableMap.get(client).getPaintable(w);
  363. client.unregisterPaintable(paintable);
  364. final String location = getLocation(w);
  365. if (location != null) {
  366. locationToWidget.remove(location);
  367. }
  368. final VCaptionWrapper cw = paintableToCaptionWrapper.get(paintable);
  369. if (cw != null) {
  370. paintableToCaptionWrapper.remove(paintable);
  371. return super.remove(cw);
  372. } else if (w != null) {
  373. return super.remove(w);
  374. }
  375. return false;
  376. }
  377. /** Adding widget without specifying location is not supported */
  378. @Override
  379. public void add(Widget w) {
  380. throw new UnsupportedOperationException();
  381. }
  382. /** Clear all widgets from the layout */
  383. @Override
  384. public void clear() {
  385. super.clear();
  386. locationToWidget.clear();
  387. paintableToCaptionWrapper.clear();
  388. }
  389. public void iLayout() {
  390. iLayoutJS(DOM.getFirstChild(getElement()));
  391. }
  392. /**
  393. * This method is published to JS side with the same name into first DOM
  394. * node of custom layout. This way if one implements some resizeable
  395. * containers in custom layout he/she can notify children after resize.
  396. */
  397. public void notifyChildrenOfSizeChange() {
  398. client.runDescendentsLayout(this);
  399. }
  400. @Override
  401. public void onDetach() {
  402. super.onDetach();
  403. if (elementWithNativeResizeFunction != null) {
  404. detachResizedFunction(elementWithNativeResizeFunction);
  405. }
  406. }
  407. private native void detachResizedFunction(Element element)
  408. /*-{
  409. element.notifyChildrenOfSizeChange = null;
  410. }-*/;
  411. private native void publishResizedFunction(Element element)
  412. /*-{
  413. var self = this;
  414. element.notifyChildrenOfSizeChange = function() {
  415. self.@com.vaadin.terminal.gwt.client.ui.VCustomLayout::notifyChildrenOfSizeChange()();
  416. };
  417. }-*/;
  418. /**
  419. * In custom layout one may want to run layout functions made with
  420. * JavaScript. This function tests if one exists (with name "iLayoutJS" in
  421. * layouts first DOM node) and runs et. Return value is used to determine if
  422. * children needs to be notified of size changes.
  423. *
  424. * Note! When implementing a JS layout function you most likely want to call
  425. * notifyChildrenOfSizeChange() function on your custom layouts main
  426. * element. That method is used to control whether child components layout
  427. * functions are to be run.
  428. *
  429. * @param el
  430. * @return true if layout function exists and was run successfully, else
  431. * false.
  432. */
  433. private native boolean iLayoutJS(Element el)
  434. /*-{
  435. if(el && el.iLayoutJS) {
  436. try {
  437. el.iLayoutJS();
  438. return true;
  439. } catch (e) {
  440. return false;
  441. }
  442. } else {
  443. return false;
  444. }
  445. }-*/;
  446. public boolean requestLayout(Set<Widget> children) {
  447. updateRelativeSizedComponents(true, true);
  448. if (width.equals("") || height.equals("")) {
  449. /* Automatically propagated upwards if the size can change */
  450. return false;
  451. }
  452. return true;
  453. }
  454. public RenderSpace getAllocatedSpace(Widget child) {
  455. com.google.gwt.dom.client.Element pe = child.getElement()
  456. .getParentElement();
  457. FloatSize extra = locationToExtraSize.get(getLocation(child));
  458. return new RenderSpace(pe.getOffsetWidth() - (int) extra.getWidth(),
  459. pe.getOffsetHeight() - (int) extra.getHeight(),
  460. Util.mayHaveScrollBars(pe));
  461. }
  462. @Override
  463. public void onBrowserEvent(Event event) {
  464. super.onBrowserEvent(event);
  465. if (event.getTypeInt() == Event.ONLOAD) {
  466. Util.notifyParentOfSizeChange(this, true);
  467. event.cancelBubble(true);
  468. }
  469. }
  470. @Override
  471. public void setHeight(String height) {
  472. if (this.height.equals(height)) {
  473. return;
  474. }
  475. boolean shrinking = true;
  476. if (isLarger(height, this.height)) {
  477. shrinking = false;
  478. }
  479. this.height = height;
  480. super.setHeight(height);
  481. /*
  482. * If the height shrinks we must remove all components with relative
  483. * height from the DOM, update their height when they do not affect the
  484. * available space and finally restore them to the original state
  485. */
  486. if (shrinking) {
  487. updateRelativeSizedComponents(false, true);
  488. }
  489. }
  490. @Override
  491. public void setWidth(String width) {
  492. if (this.width.equals(width)) {
  493. return;
  494. }
  495. boolean shrinking = true;
  496. if (isLarger(width, this.width)) {
  497. shrinking = false;
  498. }
  499. super.setWidth(width);
  500. this.width = width;
  501. /*
  502. * If the width shrinks we must remove all components with relative
  503. * width from the DOM, update their width when they do not affect the
  504. * available space and finally restore them to the original state
  505. */
  506. if (shrinking) {
  507. updateRelativeSizedComponents(true, false);
  508. }
  509. }
  510. private void updateRelativeSizedComponents(boolean relativeWidth,
  511. boolean relativeHeight) {
  512. Set<Widget> relativeSizeWidgets = new HashSet<Widget>();
  513. for (Widget widget : locationToWidget.values()) {
  514. FloatSize relativeSize = client.getRelativeSize(widget);
  515. if (relativeSize != null) {
  516. if ((relativeWidth && (relativeSize.getWidth() >= 0.0f))
  517. || (relativeHeight && (relativeSize.getHeight() >= 0.0f))) {
  518. relativeSizeWidgets.add(widget);
  519. widget.getElement().getStyle()
  520. .setProperty("position", "absolute");
  521. }
  522. }
  523. }
  524. for (Widget widget : relativeSizeWidgets) {
  525. client.handleComponentRelativeSize(widget);
  526. widget.getElement().getStyle().setProperty("position", "");
  527. }
  528. }
  529. /**
  530. * Compares newSize with currentSize and returns true if it is clear that
  531. * newSize is larger than currentSize. Returns false if newSize is smaller
  532. * or if it is unclear which one is smaller.
  533. *
  534. * @param newSize
  535. * @param currentSize
  536. * @return
  537. */
  538. private boolean isLarger(String newSize, String currentSize) {
  539. if (newSize.equals("") || currentSize.equals("")) {
  540. return false;
  541. }
  542. if (!newSize.endsWith("px") || !currentSize.endsWith("px")) {
  543. return false;
  544. }
  545. int newSizePx = Integer.parseInt(newSize.substring(0,
  546. newSize.length() - 2));
  547. int currentSizePx = Integer.parseInt(currentSize.substring(0,
  548. currentSize.length() - 2));
  549. boolean larger = newSizePx > currentSizePx;
  550. return larger;
  551. }
  552. public Widget getWidgetForPaintable() {
  553. return this;
  554. }
  555. }