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.

VCustomLayout.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * Copyright 2000-2013 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import com.google.gwt.dom.client.Element;
  20. import com.google.gwt.dom.client.ImageElement;
  21. import com.google.gwt.dom.client.NodeList;
  22. import com.google.gwt.dom.client.Style;
  23. import com.google.gwt.dom.client.Style.BorderStyle;
  24. import com.google.gwt.dom.client.Style.Position;
  25. import com.google.gwt.dom.client.Style.Unit;
  26. import com.google.gwt.user.client.DOM;
  27. import com.google.gwt.user.client.Event;
  28. import com.google.gwt.user.client.ui.ComplexPanel;
  29. import com.google.gwt.user.client.ui.Widget;
  30. import com.vaadin.client.ApplicationConnection;
  31. import com.vaadin.client.BrowserInfo;
  32. import com.vaadin.client.ComponentConnector;
  33. import com.vaadin.client.StyleConstants;
  34. import com.vaadin.client.Util;
  35. import com.vaadin.client.VCaption;
  36. import com.vaadin.client.VCaptionWrapper;
  37. /**
  38. * Custom Layout implements complex layout defined with HTML template.
  39. *
  40. * @author Vaadin Ltd
  41. *
  42. */
  43. public class VCustomLayout extends ComplexPanel {
  44. public static final String CLASSNAME = "v-customlayout";
  45. /** Location-name to containing element in DOM map */
  46. private final HashMap<String, Element> locationToElement = new HashMap<String, Element>();
  47. /** Location-name to contained widget map */
  48. final HashMap<String, Widget> locationToWidget = new HashMap<String, Widget>();
  49. /** Widget to captionwrapper map */
  50. private final HashMap<Widget, VCaptionWrapper> childWidgetToCaptionWrapper = new HashMap<Widget, VCaptionWrapper>();
  51. /**
  52. * Unexecuted scripts loaded from the template.
  53. * <p>
  54. * For internal use only. May be removed or replaced in the future.
  55. */
  56. public String scripts = "";
  57. /**
  58. * Paintable ID of this paintable.
  59. * <p>
  60. * For internal use only. May be removed or replaced in the future.
  61. */
  62. public String pid;
  63. /** For internal use only. May be removed or replaced in the future. */
  64. public ApplicationConnection client;
  65. private boolean htmlInitialized = false;
  66. private Element elementWithNativeResizeFunction;
  67. private String height = "";
  68. private String width = "";
  69. public VCustomLayout() {
  70. setElement(DOM.createDiv());
  71. // Clear any unwanted styling
  72. Style style = getElement().getStyle();
  73. style.setBorderStyle(BorderStyle.NONE);
  74. style.setMargin(0, Unit.PX);
  75. style.setPadding(0, Unit.PX);
  76. if (BrowserInfo.get().isIE()) {
  77. style.setPosition(Position.RELATIVE);
  78. }
  79. setStyleName(CLASSNAME);
  80. }
  81. @Override
  82. public void setStyleName(String style) {
  83. super.setStyleName(style);
  84. addStyleName(StyleConstants.UI_LAYOUT);
  85. }
  86. /**
  87. * Sets widget to given location.
  88. *
  89. * If location already contains a widget it will be removed.
  90. *
  91. * @param widget
  92. * Widget to be set into location.
  93. * @param location
  94. * location name where widget will be added
  95. *
  96. * @throws IllegalArgumentException
  97. * if no such location is found in the layout.
  98. */
  99. public void setWidget(Widget widget, String location) {
  100. if (widget == null) {
  101. return;
  102. }
  103. // If no given location is found in the layout, and exception is throws
  104. Element elem = locationToElement.get(location);
  105. if (elem == null && hasTemplate()) {
  106. throw new IllegalArgumentException("No location " + location
  107. + " found");
  108. }
  109. // Get previous widget
  110. final Widget previous = locationToWidget.get(location);
  111. // NOP if given widget already exists in this location
  112. if (previous == widget) {
  113. return;
  114. }
  115. if (previous != null) {
  116. remove(previous);
  117. }
  118. // if template is missing add element in order
  119. if (!hasTemplate()) {
  120. elem = getElement();
  121. }
  122. // Add widget to location
  123. super.add(widget, elem);
  124. locationToWidget.put(location, widget);
  125. }
  126. /** Initialize HTML-layout. */
  127. public void initializeHTML(String template, String themeUri) {
  128. // Connect body of the template to DOM
  129. template = extractBodyAndScriptsFromTemplate(template);
  130. // TODO prefix img src:s here with a regeps, cannot work further with IE
  131. String relImgPrefix = themeUri + "/layouts/";
  132. // prefix all relative image elements to point to theme dir with a
  133. // regexp search
  134. template = template.replaceAll(
  135. "<((?:img)|(?:IMG))\\s([^>]*)src=\"((?![a-z]+:)[^/][^\"]+)\"",
  136. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  137. // also support src attributes without quotes
  138. template = template
  139. .replaceAll(
  140. "<((?:img)|(?:IMG))\\s([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
  141. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  142. // also prefix relative style="...url(...)..."
  143. template = template
  144. .replaceAll(
  145. "(<[^>]+style=\"[^\"]*url\\()((?![a-z]+:)[^/][^\"]+)(\\)[^>]*>)",
  146. "$1 " + relImgPrefix + "$2 $3");
  147. getElement().setInnerHTML(template);
  148. // Remap locations to elements
  149. locationToElement.clear();
  150. scanForLocations(getElement());
  151. initImgElements();
  152. elementWithNativeResizeFunction = DOM.getFirstChild(getElement());
  153. if (elementWithNativeResizeFunction == null) {
  154. elementWithNativeResizeFunction = getElement();
  155. }
  156. publishResizedFunction(elementWithNativeResizeFunction);
  157. htmlInitialized = true;
  158. }
  159. private native boolean uriEndsWithSlash()
  160. /*-{
  161. var path = $wnd.location.pathname;
  162. if(path.charAt(path.length - 1) == "/")
  163. return true;
  164. return false;
  165. }-*/;
  166. /** For internal use only. May be removed or replaced in the future. */
  167. public boolean hasTemplate() {
  168. return htmlInitialized;
  169. }
  170. /** Collect locations from template */
  171. private void scanForLocations(Element elem) {
  172. final String location = elem.getAttribute("location");
  173. if (!"".equals(location)) {
  174. locationToElement.put(location, elem);
  175. elem.setInnerHTML("");
  176. } else {
  177. final int len = DOM.getChildCount(elem);
  178. for (int i = 0; i < len; i++) {
  179. scanForLocations(DOM.getChild(elem, i));
  180. }
  181. }
  182. }
  183. /**
  184. * Evaluate given script in browser document.
  185. * <p>
  186. * For internal use only. May be removed or replaced in the future.
  187. */
  188. public static native void eval(String script)
  189. /*-{
  190. try {
  191. if (script != null)
  192. eval("{ var document = $doc; var window = $wnd; "+ script + "}");
  193. } catch (e) {
  194. }
  195. }-*/;
  196. /**
  197. * Img elements needs some special handling in custom layout. Img elements
  198. * will get their onload events sunk. This way custom layout can notify
  199. * parent about possible size change.
  200. */
  201. private void initImgElements() {
  202. NodeList<Element> nodeList = getElement().getElementsByTagName("IMG");
  203. for (int i = 0; i < nodeList.getLength(); i++) {
  204. ImageElement img = ImageElement.as(nodeList.getItem(i));
  205. DOM.sinkEvents(img, Event.ONLOAD);
  206. }
  207. }
  208. /**
  209. * Extract body part and script tags from raw html-template.
  210. *
  211. * Saves contents of all script-tags to private property: scripts. Returns
  212. * contents of the body part for the html without script-tags. Also replaces
  213. * all _UID_ tags with an unique id-string.
  214. *
  215. * @param html
  216. * Original HTML-template received from server
  217. * @return html that is used to create the HTMLPanel.
  218. */
  219. private String extractBodyAndScriptsFromTemplate(String html) {
  220. // Replace UID:s
  221. html = html.replaceAll("_UID_", pid + "__");
  222. // Exctract script-tags
  223. scripts = "";
  224. int endOfPrevScript = 0;
  225. int nextPosToCheck = 0;
  226. String lc = html.toLowerCase();
  227. String res = "";
  228. int scriptStart = lc.indexOf("<script", nextPosToCheck);
  229. while (scriptStart > 0) {
  230. res += html.substring(endOfPrevScript, scriptStart);
  231. scriptStart = lc.indexOf(">", scriptStart);
  232. final int j = lc.indexOf("</script>", scriptStart);
  233. scripts += html.substring(scriptStart + 1, j) + ";";
  234. nextPosToCheck = endOfPrevScript = j + "</script>".length();
  235. scriptStart = lc.indexOf("<script", nextPosToCheck);
  236. }
  237. res += html.substring(endOfPrevScript);
  238. // Extract body
  239. html = res;
  240. lc = html.toLowerCase();
  241. int startOfBody = lc.indexOf("<body");
  242. if (startOfBody < 0) {
  243. res = html;
  244. } else {
  245. res = "";
  246. startOfBody = lc.indexOf(">", startOfBody) + 1;
  247. final int endOfBody = lc.indexOf("</body>", startOfBody);
  248. if (endOfBody > startOfBody) {
  249. res = html.substring(startOfBody, endOfBody);
  250. } else {
  251. res = html.substring(startOfBody);
  252. }
  253. }
  254. return res;
  255. }
  256. /** Update caption for given widget */
  257. public void updateCaption(ComponentConnector paintable) {
  258. Widget widget = paintable.getWidget();
  259. VCaptionWrapper wrapper = childWidgetToCaptionWrapper.get(widget);
  260. if (VCaption.isNeeded(paintable.getState())) {
  261. if (wrapper == null) {
  262. // Add a wrapper between the layout and the child widget
  263. final String loc = getLocation(widget);
  264. super.remove(widget);
  265. wrapper = new VCaptionWrapper(paintable, client);
  266. super.add(wrapper, locationToElement.get(loc));
  267. childWidgetToCaptionWrapper.put(widget, wrapper);
  268. }
  269. wrapper.updateCaption();
  270. } else {
  271. if (wrapper != null) {
  272. // Remove the wrapper and add the widget directly to the layout
  273. final String loc = getLocation(widget);
  274. super.remove(wrapper);
  275. super.add(widget, locationToElement.get(loc));
  276. childWidgetToCaptionWrapper.remove(widget);
  277. }
  278. }
  279. }
  280. /** Get the location of an widget */
  281. public String getLocation(Widget w) {
  282. for (final Iterator<String> i = locationToWidget.keySet().iterator(); i
  283. .hasNext();) {
  284. final String location = i.next();
  285. if (locationToWidget.get(location) == w) {
  286. return location;
  287. }
  288. }
  289. return null;
  290. }
  291. /** Removes given widget from the layout */
  292. @Override
  293. public boolean remove(Widget w) {
  294. final String location = getLocation(w);
  295. if (location != null) {
  296. locationToWidget.remove(location);
  297. }
  298. final VCaptionWrapper cw = childWidgetToCaptionWrapper.get(w);
  299. if (cw != null) {
  300. childWidgetToCaptionWrapper.remove(w);
  301. return super.remove(cw);
  302. } else if (w != null) {
  303. return super.remove(w);
  304. }
  305. return false;
  306. }
  307. /** Adding widget without specifying location is not supported */
  308. @Override
  309. public void add(Widget w) {
  310. throw new UnsupportedOperationException();
  311. }
  312. /** Clear all widgets from the layout */
  313. @Override
  314. public void clear() {
  315. super.clear();
  316. locationToWidget.clear();
  317. childWidgetToCaptionWrapper.clear();
  318. }
  319. /**
  320. * This method is published to JS side with the same name into first DOM
  321. * node of custom layout. This way if one implements some resizeable
  322. * containers in custom layout he/she can notify children after resize.
  323. */
  324. public void notifyChildrenOfSizeChange() {
  325. client.runDescendentsLayout(this);
  326. }
  327. @Override
  328. public void onDetach() {
  329. super.onDetach();
  330. if (elementWithNativeResizeFunction != null) {
  331. detachResizedFunction(elementWithNativeResizeFunction);
  332. }
  333. }
  334. private native void detachResizedFunction(Element element)
  335. /*-{
  336. element.notifyChildrenOfSizeChange = null;
  337. }-*/;
  338. private native void publishResizedFunction(Element element)
  339. /*-{
  340. var self = this;
  341. element.notifyChildrenOfSizeChange = $entry(function() {
  342. self.@com.vaadin.client.ui.VCustomLayout::notifyChildrenOfSizeChange()();
  343. });
  344. }-*/;
  345. /**
  346. * In custom layout one may want to run layout functions made with
  347. * JavaScript. This function tests if one exists (with name "iLayoutJS" in
  348. * layouts first DOM node) and runs et. Return value is used to determine if
  349. * children needs to be notified of size changes.
  350. * <p>
  351. * Note! When implementing a JS layout function you most likely want to call
  352. * notifyChildrenOfSizeChange() function on your custom layouts main
  353. * element. That method is used to control whether child components layout
  354. * functions are to be run.
  355. * <p>
  356. * For internal use only. May be removed or replaced in the future.
  357. *
  358. * @param el
  359. * @return true if layout function exists and was run successfully, else
  360. * false.
  361. */
  362. public native boolean iLayoutJS(com.google.gwt.user.client.Element el)
  363. /*-{
  364. if(el && el.iLayoutJS) {
  365. try {
  366. el.iLayoutJS();
  367. return true;
  368. } catch (e) {
  369. return false;
  370. }
  371. } else {
  372. return false;
  373. }
  374. }-*/;
  375. @Override
  376. public void onBrowserEvent(Event event) {
  377. super.onBrowserEvent(event);
  378. if (event.getTypeInt() == Event.ONLOAD) {
  379. Util.notifyParentOfSizeChange(this, true);
  380. event.cancelBubble(true);
  381. }
  382. }
  383. }