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