Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

VCustomLayout.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * Copyright 2000-2016 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<>();
  48. /** Location-name to contained widget map */
  49. final HashMap<String, Widget> locationToWidget = new HashMap<>();
  50. /** Widget to captionwrapper map */
  51. private final HashMap<Widget, VCaptionWrapper> childWidgetToCaptionWrapper = new HashMap<>();
  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(
  108. "No location " + location + " 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.replaceAll(
  141. "<((?:img)|(?:IMG))\\s([^>]*)src=[^\"]((?![a-z]+:)[^/][^ />]+)[ />]",
  142. "<$1 $2src=\"" + relImgPrefix + "$3\"");
  143. // also prefix relative style="...url(...)..."
  144. template = template.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. if (elem.hasAttribute("location")) {
  173. final String location = elem.getAttribute("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. /**
  257. * Update caption for the given child connector.
  258. */
  259. public void updateCaption(ComponentConnector childConnector) {
  260. Widget widget = childConnector.getWidget();
  261. if (widget.getParent() != this) {
  262. // Widget has not been added because the location was not found
  263. return;
  264. }
  265. VCaptionWrapper wrapper = childWidgetToCaptionWrapper.get(widget);
  266. if (VCaption.isNeeded(childConnector)) {
  267. if (wrapper == null) {
  268. // Add a wrapper between the layout and the child widget
  269. final String loc = getLocation(widget);
  270. super.remove(widget);
  271. wrapper = new VCaptionWrapper(childConnector, client);
  272. super.add(wrapper, locationToElement.get(loc));
  273. childWidgetToCaptionWrapper.put(widget, wrapper);
  274. }
  275. wrapper.updateCaption();
  276. } else {
  277. if (wrapper != null) {
  278. // Remove the wrapper and add the widget directly to the layout
  279. final String loc = getLocation(widget);
  280. super.remove(wrapper);
  281. super.add(widget, locationToElement.get(loc));
  282. childWidgetToCaptionWrapper.remove(widget);
  283. }
  284. }
  285. }
  286. /** Get the location of an widget */
  287. public String getLocation(Widget w) {
  288. for (final Iterator<String> i = locationToWidget.keySet().iterator(); i
  289. .hasNext();) {
  290. final String location = i.next();
  291. if (locationToWidget.get(location) == w) {
  292. return location;
  293. }
  294. }
  295. return null;
  296. }
  297. /** Removes given widget from the layout */
  298. @Override
  299. public boolean remove(Widget w) {
  300. final String location = getLocation(w);
  301. if (location != null) {
  302. locationToWidget.remove(location);
  303. }
  304. final VCaptionWrapper cw = childWidgetToCaptionWrapper.get(w);
  305. if (cw != null) {
  306. childWidgetToCaptionWrapper.remove(w);
  307. return super.remove(cw);
  308. } else if (w != null) {
  309. return super.remove(w);
  310. }
  311. return false;
  312. }
  313. /** Adding widget without specifying location is not supported */
  314. @Override
  315. public void add(Widget w) {
  316. throw new UnsupportedOperationException();
  317. }
  318. /** Clear all widgets from the layout */
  319. @Override
  320. public void clear() {
  321. super.clear();
  322. locationToWidget.clear();
  323. childWidgetToCaptionWrapper.clear();
  324. }
  325. /**
  326. * This method is published to JS side with the same name into first DOM
  327. * node of custom layout. This way if one implements some resizeable
  328. * containers in custom layout he/she can notify children after resize.
  329. */
  330. public void notifyChildrenOfSizeChange() {
  331. client.runDescendentsLayout(this);
  332. }
  333. @Override
  334. public void onDetach() {
  335. super.onDetach();
  336. if (elementWithNativeResizeFunction != null) {
  337. detachResizedFunction(elementWithNativeResizeFunction);
  338. }
  339. }
  340. private native void detachResizedFunction(Element element)
  341. /*-{
  342. element.notifyChildrenOfSizeChange = null;
  343. }-*/;
  344. private native void publishResizedFunction(Element element)
  345. /*-{
  346. var self = this;
  347. element.notifyChildrenOfSizeChange = $entry(function() {
  348. self.@com.vaadin.client.ui.VCustomLayout::notifyChildrenOfSizeChange()();
  349. });
  350. }-*/;
  351. /**
  352. * In custom layout one may want to run layout functions made with
  353. * JavaScript. This function tests if one exists (with name "iLayoutJS" in
  354. * layouts first DOM node) and runs et. Return value is used to determine if
  355. * children needs to be notified of size changes.
  356. * <p>
  357. * Note! When implementing a JS layout function you most likely want to call
  358. * notifyChildrenOfSizeChange() function on your custom layouts main
  359. * element. That method is used to control whether child components layout
  360. * functions are to be run.
  361. * <p>
  362. * For internal use only. May be removed or replaced in the future.
  363. *
  364. * @param el
  365. * @return true if layout function exists and was run successfully, else
  366. * false.
  367. */
  368. public native boolean iLayoutJS(com.google.gwt.user.client.Element el)
  369. /*-{
  370. if(el && el.iLayoutJS) {
  371. try {
  372. el.iLayoutJS();
  373. return true;
  374. } catch (e) {
  375. return false;
  376. }
  377. } else {
  378. return false;
  379. }
  380. }-*/;
  381. @Override
  382. public void onBrowserEvent(Event event) {
  383. super.onBrowserEvent(event);
  384. if (event.getTypeInt() == Event.ONLOAD) {
  385. Util.notifyParentOfSizeChange(this, true);
  386. event.cancelBubble(true);
  387. }
  388. }
  389. }