Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

VCustomLayout.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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.ImageElement;
  20. import com.google.gwt.dom.client.NodeList;
  21. import com.google.gwt.dom.client.Style;
  22. import com.google.gwt.dom.client.Style.BorderStyle;
  23. import com.google.gwt.dom.client.Style.Position;
  24. import com.google.gwt.dom.client.Style.Unit;
  25. import com.google.gwt.user.client.DOM;
  26. import com.google.gwt.user.client.Event;
  27. import com.google.gwt.user.client.ui.ComplexPanel;
  28. import com.google.gwt.user.client.ui.Widget;
  29. import com.vaadin.client.ApplicationConnection;
  30. import com.vaadin.client.BrowserInfo;
  31. import com.vaadin.client.ComponentConnector;
  32. import com.vaadin.client.StyleConstants;
  33. import com.vaadin.client.Util;
  34. import com.vaadin.client.VCaption;
  35. import com.vaadin.client.VCaptionWrapper;
  36. /**
  37. * Custom Layout implements complex layout defined with HTML template.
  38. *
  39. * @author Vaadin Ltd
  40. *
  41. */
  42. public class VCustomLayout extends ComplexPanel {
  43. public static final String CLASSNAME = "v-customlayout";
  44. /** Location-name to containing element in DOM map */
  45. private final HashMap<String, com.google.gwt.user.client.Element> locationToElement = new HashMap<String, com.google.gwt.user.client.Element>();
  46. /** Location-name to contained widget map */
  47. final HashMap<String, Widget> locationToWidget = new HashMap<String, Widget>();
  48. /** Widget to captionwrapper map */
  49. private final HashMap<Widget, VCaptionWrapper> childWidgetToCaptionWrapper = new HashMap<Widget, VCaptionWrapper>();
  50. /**
  51. * Unexecuted scripts loaded from the template.
  52. * <p>
  53. * For internal use only. May be removed or replaced in the future.
  54. */
  55. public String scripts = "";
  56. /**
  57. * Paintable ID of this paintable.
  58. * <p>
  59. * For internal use only. May be removed or replaced in the future.
  60. */
  61. public String pid;
  62. /** For internal use only. May be removed or replaced in the future. */
  63. public ApplicationConnection client;
  64. private boolean htmlInitialized = false;
  65. private com.google.gwt.user.client.Element elementWithNativeResizeFunction;
  66. private String height = "";
  67. private String width = "";
  68. public VCustomLayout() {
  69. setElement(DOM.createDiv());
  70. // Clear any unwanted styling
  71. Style style = getElement().getStyle();
  72. style.setBorderStyle(BorderStyle.NONE);
  73. style.setMargin(0, Unit.PX);
  74. style.setPadding(0, Unit.PX);
  75. if (BrowserInfo.get().isIE()) {
  76. style.setPosition(Position.RELATIVE);
  77. }
  78. setStyleName(CLASSNAME);
  79. }
  80. @Override
  81. public void setStyleName(String style) {
  82. super.setStyleName(style);
  83. addStyleName(StyleConstants.UI_LAYOUT);
  84. }
  85. /**
  86. * Sets widget to given location.
  87. *
  88. * If location already contains a widget it will be removed.
  89. *
  90. * @param widget
  91. * Widget to be set into location.
  92. * @param location
  93. * location name where widget will be added
  94. *
  95. * @throws IllegalArgumentException
  96. * if no such location is found in the layout.
  97. */
  98. public void setWidget(Widget widget, String location) {
  99. if (widget == null) {
  100. return;
  101. }
  102. // If no given location is found in the layout, and exception is throws
  103. com.google.gwt.user.client.Element elem = locationToElement
  104. .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(com.google.gwt.user.client.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<com.google.gwt.dom.client.Element> nodeList = getElement()
  203. .getElementsByTagName("IMG");
  204. for (int i = 0; i < nodeList.getLength(); i++) {
  205. com.google.gwt.dom.client.ImageElement img = (ImageElement) nodeList
  206. .getItem(i);
  207. DOM.sinkEvents((com.google.gwt.user.client.Element) img.cast(),
  208. Event.ONLOAD);
  209. }
  210. }
  211. /**
  212. * Extract body part and script tags from raw html-template.
  213. *
  214. * Saves contents of all script-tags to private property: scripts. Returns
  215. * contents of the body part for the html without script-tags. Also replaces
  216. * all _UID_ tags with an unique id-string.
  217. *
  218. * @param html
  219. * Original HTML-template received from server
  220. * @return html that is used to create the HTMLPanel.
  221. */
  222. private String extractBodyAndScriptsFromTemplate(String html) {
  223. // Replace UID:s
  224. html = html.replaceAll("_UID_", pid + "__");
  225. // Exctract script-tags
  226. scripts = "";
  227. int endOfPrevScript = 0;
  228. int nextPosToCheck = 0;
  229. String lc = html.toLowerCase();
  230. String res = "";
  231. int scriptStart = lc.indexOf("<script", nextPosToCheck);
  232. while (scriptStart > 0) {
  233. res += html.substring(endOfPrevScript, scriptStart);
  234. scriptStart = lc.indexOf(">", scriptStart);
  235. final int j = lc.indexOf("</script>", scriptStart);
  236. scripts += html.substring(scriptStart + 1, j) + ";";
  237. nextPosToCheck = endOfPrevScript = j + "</script>".length();
  238. scriptStart = lc.indexOf("<script", nextPosToCheck);
  239. }
  240. res += html.substring(endOfPrevScript);
  241. // Extract body
  242. html = res;
  243. lc = html.toLowerCase();
  244. int startOfBody = lc.indexOf("<body");
  245. if (startOfBody < 0) {
  246. res = html;
  247. } else {
  248. res = "";
  249. startOfBody = lc.indexOf(">", startOfBody) + 1;
  250. final int endOfBody = lc.indexOf("</body>", startOfBody);
  251. if (endOfBody > startOfBody) {
  252. res = html.substring(startOfBody, endOfBody);
  253. } else {
  254. res = html.substring(startOfBody);
  255. }
  256. }
  257. return res;
  258. }
  259. /** Update caption for given widget */
  260. public void updateCaption(ComponentConnector paintable) {
  261. Widget widget = paintable.getWidget();
  262. VCaptionWrapper wrapper = childWidgetToCaptionWrapper.get(widget);
  263. if (VCaption.isNeeded(paintable.getState())) {
  264. if (wrapper == null) {
  265. // Add a wrapper between the layout and the child widget
  266. final String loc = getLocation(widget);
  267. super.remove(widget);
  268. wrapper = new VCaptionWrapper(paintable, client);
  269. super.add(wrapper, locationToElement.get(loc));
  270. childWidgetToCaptionWrapper.put(widget, wrapper);
  271. }
  272. wrapper.updateCaption();
  273. } else {
  274. if (wrapper != null) {
  275. // Remove the wrapper and add the widget directly to the layout
  276. final String loc = getLocation(widget);
  277. super.remove(wrapper);
  278. super.add(widget, locationToElement.get(loc));
  279. childWidgetToCaptionWrapper.remove(widget);
  280. }
  281. }
  282. }
  283. /** Get the location of an widget */
  284. public String getLocation(Widget w) {
  285. for (final Iterator<String> i = locationToWidget.keySet().iterator(); i
  286. .hasNext();) {
  287. final String location = i.next();
  288. if (locationToWidget.get(location) == w) {
  289. return location;
  290. }
  291. }
  292. return null;
  293. }
  294. /** Removes given widget from the layout */
  295. @Override
  296. public boolean remove(Widget w) {
  297. final String location = getLocation(w);
  298. if (location != null) {
  299. locationToWidget.remove(location);
  300. }
  301. final VCaptionWrapper cw = childWidgetToCaptionWrapper.get(w);
  302. if (cw != null) {
  303. childWidgetToCaptionWrapper.remove(w);
  304. return super.remove(cw);
  305. } else if (w != null) {
  306. return super.remove(w);
  307. }
  308. return false;
  309. }
  310. /** Adding widget without specifying location is not supported */
  311. @Override
  312. public void add(Widget w) {
  313. throw new UnsupportedOperationException();
  314. }
  315. /** Clear all widgets from the layout */
  316. @Override
  317. public void clear() {
  318. super.clear();
  319. locationToWidget.clear();
  320. childWidgetToCaptionWrapper.clear();
  321. }
  322. /**
  323. * This method is published to JS side with the same name into first DOM
  324. * node of custom layout. This way if one implements some resizeable
  325. * containers in custom layout he/she can notify children after resize.
  326. */
  327. public void notifyChildrenOfSizeChange() {
  328. client.runDescendentsLayout(this);
  329. }
  330. @Override
  331. public void onDetach() {
  332. super.onDetach();
  333. if (elementWithNativeResizeFunction != null) {
  334. detachResizedFunction(elementWithNativeResizeFunction);
  335. }
  336. }
  337. private native void detachResizedFunction(
  338. com.google.gwt.user.client.Element element)
  339. /*-{
  340. element.notifyChildrenOfSizeChange = null;
  341. }-*/;
  342. private native void publishResizedFunction(
  343. com.google.gwt.user.client.Element element)
  344. /*-{
  345. var self = this;
  346. element.notifyChildrenOfSizeChange = $entry(function() {
  347. self.@com.vaadin.client.ui.VCustomLayout::notifyChildrenOfSizeChange()();
  348. });
  349. }-*/;
  350. /**
  351. * In custom layout one may want to run layout functions made with
  352. * JavaScript. This function tests if one exists (with name "iLayoutJS" in
  353. * layouts first DOM node) and runs et. Return value is used to determine if
  354. * children needs to be notified of size changes.
  355. * <p>
  356. * Note! When implementing a JS layout function you most likely want to call
  357. * notifyChildrenOfSizeChange() function on your custom layouts main
  358. * element. That method is used to control whether child components layout
  359. * functions are to be run.
  360. * <p>
  361. * For internal use only. May be removed or replaced in the future.
  362. *
  363. * @param el
  364. * @return true if layout function exists and was run successfully, else
  365. * false.
  366. */
  367. public native boolean iLayoutJS(com.google.gwt.user.client.Element el)
  368. /*-{
  369. if(el && el.iLayoutJS) {
  370. try {
  371. el.iLayoutJS();
  372. return true;
  373. } catch (e) {
  374. return false;
  375. }
  376. } else {
  377. return false;
  378. }
  379. }-*/;
  380. @Override
  381. public void onBrowserEvent(Event event) {
  382. super.onBrowserEvent(event);
  383. if (event.getTypeInt() == Event.ONLOAD) {
  384. Util.notifyParentOfSizeChange(this, true);
  385. event.cancelBubble(true);
  386. }
  387. }
  388. }