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.

Util.java 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. /*
  2. * Copyright 2011 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.terminal.gwt.client;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.Collection;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import com.google.gwt.core.client.Scheduler;
  23. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  24. import com.google.gwt.dom.client.Document;
  25. import com.google.gwt.dom.client.NativeEvent;
  26. import com.google.gwt.dom.client.Node;
  27. import com.google.gwt.dom.client.NodeList;
  28. import com.google.gwt.dom.client.Style;
  29. import com.google.gwt.dom.client.Touch;
  30. import com.google.gwt.user.client.Command;
  31. import com.google.gwt.user.client.DOM;
  32. import com.google.gwt.user.client.Element;
  33. import com.google.gwt.user.client.Event;
  34. import com.google.gwt.user.client.EventListener;
  35. import com.google.gwt.user.client.Window;
  36. import com.google.gwt.user.client.ui.HasWidgets;
  37. import com.google.gwt.user.client.ui.RootPanel;
  38. import com.google.gwt.user.client.ui.Widget;
  39. import com.vaadin.shared.ApplicationConstants;
  40. import com.vaadin.shared.ComponentState;
  41. import com.vaadin.shared.communication.MethodInvocation;
  42. import com.vaadin.terminal.gwt.client.RenderInformation.FloatSize;
  43. import com.vaadin.terminal.gwt.client.ui.VOverlay;
  44. public class Util {
  45. /**
  46. * Helper method for debugging purposes.
  47. *
  48. * Stops execution on firefox browsers on a breakpoint.
  49. *
  50. */
  51. public static native void browserDebugger()
  52. /*-{
  53. if($wnd.console)
  54. debugger;
  55. }-*/;
  56. /**
  57. *
  58. * Returns the topmost element of from given coordinates.
  59. *
  60. * TODO fix crossplat issues clientX vs pageX. See quircksmode. Not critical
  61. * for vaadin as we scroll div istead of page.
  62. *
  63. * @param x
  64. * @param y
  65. * @return the element at given coordinates
  66. */
  67. public static native Element getElementFromPoint(int clientX, int clientY)
  68. /*-{
  69. var el = $wnd.document.elementFromPoint(clientX, clientY);
  70. if(el != null && el.nodeType == 3) {
  71. el = el.parentNode;
  72. }
  73. return el;
  74. }-*/;
  75. /**
  76. * This helper method can be called if components size have been changed
  77. * outside rendering phase. It notifies components parent about the size
  78. * change so it can react.
  79. *
  80. * When using this method, developer should consider if size changes could
  81. * be notified lazily. If lazy flag is true, method will save widget and
  82. * wait for a moment until it notifies parents in chunks. This may vastly
  83. * optimize layout in various situation. Example: if component have a lot of
  84. * images their onload events may fire "layout phase" many times in a short
  85. * period.
  86. *
  87. * @param widget
  88. * @param lazy
  89. * run componentSizeUpdated lazyly
  90. *
  91. * @deprecated since 7.0, use
  92. * {@link LayoutManager#setNeedsMeasure(ComponentConnector)}
  93. * instead
  94. */
  95. @Deprecated
  96. public static void notifyParentOfSizeChange(Widget widget, boolean lazy) {
  97. ComponentConnector connector = findConnectorFor(widget);
  98. if (connector != null) {
  99. connector.getLayoutManager().setNeedsMeasure(connector);
  100. if (!lazy) {
  101. connector.getLayoutManager().layoutNow();
  102. }
  103. }
  104. }
  105. private static ComponentConnector findConnectorFor(Widget widget) {
  106. List<ApplicationConnection> runningApplications = ApplicationConfiguration
  107. .getRunningApplications();
  108. for (ApplicationConnection applicationConnection : runningApplications) {
  109. ConnectorMap connectorMap = applicationConnection.getConnectorMap();
  110. ComponentConnector connector = connectorMap.getConnector(widget);
  111. if (connector == null) {
  112. continue;
  113. }
  114. if (connector.getConnection() == applicationConnection) {
  115. return connector;
  116. }
  117. }
  118. return null;
  119. }
  120. public static float parseRelativeSize(String size) {
  121. if (size == null || !size.endsWith("%")) {
  122. return -1;
  123. }
  124. try {
  125. return Float.parseFloat(size.substring(0, size.length() - 1));
  126. } catch (Exception e) {
  127. VConsole.log("Unable to parse relative size");
  128. return -1;
  129. }
  130. }
  131. private static final Element escapeHtmlHelper = DOM.createDiv();
  132. /**
  133. * Converts html entities to text.
  134. *
  135. * @param html
  136. * @return escaped string presentation of given html
  137. */
  138. public static String escapeHTML(String html) {
  139. DOM.setInnerText(escapeHtmlHelper, html);
  140. String escapedText = DOM.getInnerHTML(escapeHtmlHelper);
  141. if (BrowserInfo.get().isIE8()) {
  142. // #7478 IE8 "incorrectly" returns "<br>" for newlines set using
  143. // setInnerText. The same for " " which is converted to "&nbsp;"
  144. escapedText = escapedText.replaceAll("<(BR|br)>", "\n");
  145. escapedText = escapedText.replaceAll("&nbsp;", " ");
  146. }
  147. return escapedText;
  148. }
  149. /**
  150. * Escapes the string so it is safe to write inside an HTML attribute.
  151. *
  152. * @param attribute
  153. * The string to escape
  154. * @return An escaped version of <literal>attribute</literal>.
  155. */
  156. public static String escapeAttribute(String attribute) {
  157. attribute = attribute.replace("\"", "&quot;");
  158. attribute = attribute.replace("'", "&#39;");
  159. attribute = attribute.replace(">", "&gt;");
  160. attribute = attribute.replace("<", "&lt;");
  161. attribute = attribute.replace("&", "&amp;");
  162. return attribute;
  163. }
  164. /**
  165. * Clones given element as in JavaScript.
  166. *
  167. * Deprecate this if there appears similar method into GWT someday.
  168. *
  169. * @param element
  170. * @param deep
  171. * clone child tree also
  172. * @return
  173. */
  174. public static native Element cloneNode(Element element, boolean deep)
  175. /*-{
  176. return element.cloneNode(deep);
  177. }-*/;
  178. public static int measureHorizontalPaddingAndBorder(Element element,
  179. int paddingGuess) {
  180. String originalWidth = DOM.getStyleAttribute(element, "width");
  181. int originalOffsetWidth = element.getOffsetWidth();
  182. int widthGuess = (originalOffsetWidth - paddingGuess);
  183. if (widthGuess < 1) {
  184. widthGuess = 1;
  185. }
  186. DOM.setStyleAttribute(element, "width", widthGuess + "px");
  187. int padding = element.getOffsetWidth() - widthGuess;
  188. DOM.setStyleAttribute(element, "width", originalWidth);
  189. return padding;
  190. }
  191. public static int measureVerticalPaddingAndBorder(Element element,
  192. int paddingGuess) {
  193. String originalHeight = DOM.getStyleAttribute(element, "height");
  194. int originalOffsetHeight = element.getOffsetHeight();
  195. int widthGuess = (originalOffsetHeight - paddingGuess);
  196. if (widthGuess < 1) {
  197. widthGuess = 1;
  198. }
  199. DOM.setStyleAttribute(element, "height", widthGuess + "px");
  200. int padding = element.getOffsetHeight() - widthGuess;
  201. DOM.setStyleAttribute(element, "height", originalHeight);
  202. return padding;
  203. }
  204. public static int measureHorizontalBorder(Element element) {
  205. int borders;
  206. if (BrowserInfo.get().isIE()) {
  207. String width = element.getStyle().getProperty("width");
  208. String height = element.getStyle().getProperty("height");
  209. int offsetWidth = element.getOffsetWidth();
  210. int offsetHeight = element.getOffsetHeight();
  211. if (offsetHeight < 1) {
  212. offsetHeight = 1;
  213. }
  214. if (offsetWidth < 1) {
  215. offsetWidth = 10;
  216. }
  217. element.getStyle().setPropertyPx("height", offsetHeight);
  218. element.getStyle().setPropertyPx("width", offsetWidth);
  219. borders = element.getOffsetWidth() - element.getClientWidth();
  220. element.getStyle().setProperty("width", width);
  221. element.getStyle().setProperty("height", height);
  222. } else {
  223. borders = element.getOffsetWidth()
  224. - element.getPropertyInt("clientWidth");
  225. }
  226. assert borders >= 0;
  227. return borders;
  228. }
  229. public static int measureVerticalBorder(Element element) {
  230. int borders;
  231. if (BrowserInfo.get().isIE()) {
  232. String width = element.getStyle().getProperty("width");
  233. String height = element.getStyle().getProperty("height");
  234. int offsetWidth = element.getOffsetWidth();
  235. int offsetHeight = element.getOffsetHeight();
  236. if (offsetHeight < 1) {
  237. offsetHeight = 1;
  238. }
  239. if (offsetWidth < 1) {
  240. offsetWidth = 10;
  241. }
  242. element.getStyle().setPropertyPx("width", offsetWidth);
  243. element.getStyle().setPropertyPx("height", offsetHeight);
  244. borders = element.getOffsetHeight()
  245. - element.getPropertyInt("clientHeight");
  246. element.getStyle().setProperty("height", height);
  247. element.getStyle().setProperty("width", width);
  248. } else {
  249. borders = element.getOffsetHeight()
  250. - element.getPropertyInt("clientHeight");
  251. }
  252. assert borders >= 0;
  253. return borders;
  254. }
  255. public static int measureMarginLeft(Element element) {
  256. return element.getAbsoluteLeft()
  257. - element.getParentElement().getAbsoluteLeft();
  258. }
  259. public static int setHeightExcludingPaddingAndBorder(Widget widget,
  260. String height, int paddingBorderGuess) {
  261. if (height.equals("")) {
  262. setHeight(widget, "");
  263. return paddingBorderGuess;
  264. } else if (height.endsWith("px")) {
  265. int pixelHeight = Integer.parseInt(height.substring(0,
  266. height.length() - 2));
  267. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  268. pixelHeight, paddingBorderGuess, false);
  269. } else {
  270. // Set the height in unknown units
  271. setHeight(widget, height);
  272. // Use the offsetWidth
  273. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  274. widget.getOffsetHeight(), paddingBorderGuess, true);
  275. }
  276. }
  277. private static void setWidth(Widget widget, String width) {
  278. DOM.setStyleAttribute(widget.getElement(), "width", width);
  279. }
  280. private static void setHeight(Widget widget, String height) {
  281. DOM.setStyleAttribute(widget.getElement(), "height", height);
  282. }
  283. public static int setWidthExcludingPaddingAndBorder(Widget widget,
  284. String width, int paddingBorderGuess) {
  285. if (width.equals("")) {
  286. setWidth(widget, "");
  287. return paddingBorderGuess;
  288. } else if (width.endsWith("px")) {
  289. int pixelWidth = Integer.parseInt(width.substring(0,
  290. width.length() - 2));
  291. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  292. pixelWidth, paddingBorderGuess, false);
  293. } else {
  294. setWidth(widget, width);
  295. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  296. widget.getOffsetWidth(), paddingBorderGuess, true);
  297. }
  298. }
  299. public static int setWidthExcludingPaddingAndBorder(Element element,
  300. int requestedWidth, int horizontalPaddingBorderGuess,
  301. boolean requestedWidthIncludesPaddingBorder) {
  302. int widthGuess = requestedWidth - horizontalPaddingBorderGuess;
  303. if (widthGuess < 0) {
  304. widthGuess = 0;
  305. }
  306. DOM.setStyleAttribute(element, "width", widthGuess + "px");
  307. int captionOffsetWidth = DOM.getElementPropertyInt(element,
  308. "offsetWidth");
  309. int actualPadding = captionOffsetWidth - widthGuess;
  310. if (requestedWidthIncludesPaddingBorder) {
  311. actualPadding += actualPadding;
  312. }
  313. if (actualPadding != horizontalPaddingBorderGuess) {
  314. int w = requestedWidth - actualPadding;
  315. if (w < 0) {
  316. // Cannot set negative width even if we would want to
  317. w = 0;
  318. }
  319. DOM.setStyleAttribute(element, "width", w + "px");
  320. }
  321. return actualPadding;
  322. }
  323. public static int setHeightExcludingPaddingAndBorder(Element element,
  324. int requestedHeight, int verticalPaddingBorderGuess,
  325. boolean requestedHeightIncludesPaddingBorder) {
  326. int heightGuess = requestedHeight - verticalPaddingBorderGuess;
  327. if (heightGuess < 0) {
  328. heightGuess = 0;
  329. }
  330. DOM.setStyleAttribute(element, "height", heightGuess + "px");
  331. int captionOffsetHeight = DOM.getElementPropertyInt(element,
  332. "offsetHeight");
  333. int actualPadding = captionOffsetHeight - heightGuess;
  334. if (requestedHeightIncludesPaddingBorder) {
  335. actualPadding += actualPadding;
  336. }
  337. if (actualPadding != verticalPaddingBorderGuess) {
  338. int h = requestedHeight - actualPadding;
  339. if (h < 0) {
  340. // Cannot set negative height even if we would want to
  341. h = 0;
  342. }
  343. DOM.setStyleAttribute(element, "height", h + "px");
  344. }
  345. return actualPadding;
  346. }
  347. public static String getSimpleName(Object widget) {
  348. if (widget == null) {
  349. return "(null)";
  350. }
  351. String name = widget.getClass().getName();
  352. return name.substring(name.lastIndexOf('.') + 1);
  353. }
  354. public static void setFloat(Element element, String value) {
  355. if (BrowserInfo.get().isIE()) {
  356. DOM.setStyleAttribute(element, "styleFloat", value);
  357. } else {
  358. DOM.setStyleAttribute(element, "cssFloat", value);
  359. }
  360. }
  361. private static int detectedScrollbarSize = -1;
  362. public static int getNativeScrollbarSize() {
  363. if (detectedScrollbarSize < 0) {
  364. Element scroller = DOM.createDiv();
  365. scroller.getStyle().setProperty("width", "50px");
  366. scroller.getStyle().setProperty("height", "50px");
  367. scroller.getStyle().setProperty("overflow", "scroll");
  368. scroller.getStyle().setProperty("position", "absolute");
  369. scroller.getStyle().setProperty("marginLeft", "-5000px");
  370. RootPanel.getBodyElement().appendChild(scroller);
  371. detectedScrollbarSize = scroller.getOffsetWidth()
  372. - scroller.getPropertyInt("clientWidth");
  373. RootPanel.getBodyElement().removeChild(scroller);
  374. }
  375. return detectedScrollbarSize;
  376. }
  377. /**
  378. * Run workaround for webkits overflow auto issue.
  379. *
  380. * See: our bug #2138 and https://bugs.webkit.org/show_bug.cgi?id=21462
  381. *
  382. * @param elem
  383. * with overflow auto
  384. */
  385. public static void runWebkitOverflowAutoFix(final Element elem) {
  386. // Add max version if fix lands sometime to Webkit
  387. // Starting from Opera 11.00, also a problem in Opera
  388. if (BrowserInfo.get().requiresOverflowAutoFix()) {
  389. final String originalOverflow = elem.getStyle().getProperty(
  390. "overflow");
  391. if ("hidden".equals(originalOverflow)) {
  392. return;
  393. }
  394. // check the scrolltop value before hiding the element
  395. final int scrolltop = elem.getScrollTop();
  396. final int scrollleft = elem.getScrollLeft();
  397. elem.getStyle().setProperty("overflow", "hidden");
  398. Scheduler.get().scheduleDeferred(new Command() {
  399. @Override
  400. public void execute() {
  401. // Dough, Safari scroll auto means actually just a moped
  402. elem.getStyle().setProperty("overflow", originalOverflow);
  403. if (scrolltop > 0 || elem.getScrollTop() > 0) {
  404. int scrollvalue = scrolltop;
  405. if (scrollvalue == 0) {
  406. // mysterious are the ways of webkits scrollbar
  407. // handling. In some cases webkit reports bad (0)
  408. // scrolltop before hiding the element temporary,
  409. // sometimes after.
  410. scrollvalue = elem.getScrollTop();
  411. }
  412. // fix another bug where scrollbar remains in wrong
  413. // position
  414. elem.setScrollTop(scrollvalue - 1);
  415. elem.setScrollTop(scrollvalue);
  416. }
  417. // fix for #6940 : Table horizontal scroll sometimes not
  418. // updated when collapsing/expanding columns
  419. // Also appeared in Safari 5.1 with webkit 534 (#7667)
  420. if ((BrowserInfo.get().isChrome() || (BrowserInfo.get()
  421. .isSafari() && BrowserInfo.get().getWebkitVersion() >= 534))
  422. && (scrollleft > 0 || elem.getScrollLeft() > 0)) {
  423. int scrollvalue = scrollleft;
  424. if (scrollvalue == 0) {
  425. // mysterious are the ways of webkits scrollbar
  426. // handling. In some cases webkit may report a bad
  427. // (0) scrollleft before hiding the element
  428. // temporary, sometimes after.
  429. scrollvalue = elem.getScrollLeft();
  430. }
  431. // fix another bug where scrollbar remains in wrong
  432. // position
  433. elem.setScrollLeft(scrollvalue - 1);
  434. elem.setScrollLeft(scrollvalue);
  435. }
  436. }
  437. });
  438. }
  439. }
  440. /**
  441. * Parses shared state and fetches the relative size of the component. If a
  442. * dimension is not specified as relative it will return -1. If the shared
  443. * state does not contain width or height specifications this will return
  444. * null.
  445. *
  446. * @param state
  447. * @return
  448. */
  449. public static FloatSize parseRelativeSize(ComponentState state) {
  450. if (state.isUndefinedHeight() && state.isUndefinedWidth()) {
  451. return null;
  452. }
  453. float relativeWidth = Util.parseRelativeSize(state.getWidth());
  454. float relativeHeight = Util.parseRelativeSize(state.getHeight());
  455. FloatSize relativeSize = new FloatSize(relativeWidth, relativeHeight);
  456. return relativeSize;
  457. }
  458. @Deprecated
  459. public static boolean isCached(UIDL uidl) {
  460. return uidl.getBooleanAttribute("cached");
  461. }
  462. public static void alert(String string) {
  463. if (true) {
  464. Window.alert(string);
  465. }
  466. }
  467. public static boolean equals(Object a, Object b) {
  468. if (a == null) {
  469. return b == null;
  470. }
  471. return a.equals(b);
  472. }
  473. public static void updateRelativeChildrenAndSendSizeUpdateEvent(
  474. ApplicationConnection client, HasWidgets container, Widget widget) {
  475. notifyParentOfSizeChange(widget, false);
  476. }
  477. public static native int getRequiredWidth(
  478. com.google.gwt.dom.client.Element element)
  479. /*-{
  480. if (element.getBoundingClientRect) {
  481. var rect = element.getBoundingClientRect();
  482. return Math.ceil(rect.right - rect.left);
  483. } else {
  484. return element.offsetWidth;
  485. }
  486. }-*/;
  487. public static native int getRequiredHeight(
  488. com.google.gwt.dom.client.Element element)
  489. /*-{
  490. var height;
  491. if (element.getBoundingClientRect != null) {
  492. var rect = element.getBoundingClientRect();
  493. height = Math.ceil(rect.bottom - rect.top);
  494. } else {
  495. height = element.offsetHeight;
  496. }
  497. return height;
  498. }-*/;
  499. public static int getRequiredWidth(Widget widget) {
  500. return getRequiredWidth(widget.getElement());
  501. }
  502. public static int getRequiredHeight(Widget widget) {
  503. return getRequiredHeight(widget.getElement());
  504. }
  505. /**
  506. * Detects what is currently the overflow style attribute in given element.
  507. *
  508. * @param pe
  509. * the element to detect
  510. * @return true if auto or scroll
  511. */
  512. public static boolean mayHaveScrollBars(com.google.gwt.dom.client.Element pe) {
  513. String overflow = getComputedStyle(pe, "overflow");
  514. if (overflow != null) {
  515. if (overflow.equals("auto") || overflow.equals("scroll")) {
  516. return true;
  517. } else {
  518. return false;
  519. }
  520. } else {
  521. return false;
  522. }
  523. }
  524. /**
  525. * A simple helper method to detect "computed style" (aka style sheets +
  526. * element styles). Values returned differ a lot depending on browsers.
  527. * Always be very careful when using this.
  528. *
  529. * @param el
  530. * the element from which the style property is detected
  531. * @param p
  532. * the property to detect
  533. * @return String value of style property
  534. */
  535. private static native String getComputedStyle(
  536. com.google.gwt.dom.client.Element el, String p)
  537. /*-{
  538. try {
  539. if (el.currentStyle) {
  540. // IE
  541. return el.currentStyle[p];
  542. } else if (window.getComputedStyle) {
  543. // Sa, FF, Opera
  544. var view = el.ownerDocument.defaultView;
  545. return view.getComputedStyle(el,null).getPropertyValue(p);
  546. } else {
  547. // fall back for non IE, Sa, FF, Opera
  548. return "";
  549. }
  550. } catch (e) {
  551. return "";
  552. }
  553. }-*/;
  554. /**
  555. * Locates the nested child component of <literal>parent</literal> which
  556. * contains the element <literal>element</literal>. The child component is
  557. * also returned if "element" is part of its caption. If
  558. * <literal>element</literal> is not part of any child component, null is
  559. * returned.
  560. *
  561. * This method returns the deepest nested VPaintableWidget.
  562. *
  563. * @param client
  564. * A reference to ApplicationConnection
  565. * @param parent
  566. * The widget that contains <literal>element</literal>.
  567. * @param element
  568. * An element that is a sub element of the parent
  569. * @return The VPaintableWidget which the element is a part of. Null if the
  570. * element does not belong to a child.
  571. */
  572. public static ComponentConnector getConnectorForElement(
  573. ApplicationConnection client, Widget parent, Element element) {
  574. Element browseElement = element;
  575. Element rootElement = parent.getElement();
  576. while (browseElement != null && browseElement != rootElement) {
  577. ComponentConnector connector = ConnectorMap.get(client)
  578. .getConnector(browseElement);
  579. if (connector == null) {
  580. String ownerPid = VCaption.getCaptionOwnerPid(browseElement);
  581. if (ownerPid != null) {
  582. connector = (ComponentConnector) ConnectorMap.get(client)
  583. .getConnector(ownerPid);
  584. }
  585. }
  586. if (connector != null) {
  587. // check that inside the rootElement
  588. while (browseElement != null && browseElement != rootElement) {
  589. browseElement = (Element) browseElement.getParentElement();
  590. }
  591. if (browseElement != rootElement) {
  592. return null;
  593. } else {
  594. return connector;
  595. }
  596. }
  597. browseElement = (Element) browseElement.getParentElement();
  598. }
  599. // No connector found, element is possibly inside a VOverlay
  600. // If the overlay has an owner, try to find the owner's connector
  601. VOverlay overlay = findWidget(element, VOverlay.class);
  602. if (overlay != null && overlay.getOwner() != null) {
  603. return getConnectorForElement(client, RootPanel.get(), overlay
  604. .getOwner().getElement());
  605. } else {
  606. return null;
  607. }
  608. }
  609. /**
  610. * Will (attempt) to focus the given DOM Element.
  611. *
  612. * @param el
  613. * the element to focus
  614. */
  615. public static native void focus(Element el)
  616. /*-{
  617. try {
  618. el.focus();
  619. } catch (e) {
  620. }
  621. }-*/;
  622. /**
  623. * Helper method to find the nearest parent paintable instance by traversing
  624. * the DOM upwards from given element.
  625. *
  626. * @param element
  627. * the element to start from
  628. */
  629. public static ComponentConnector findPaintable(
  630. ApplicationConnection client, Element element) {
  631. Widget widget = Util.findWidget(element, null);
  632. ConnectorMap vPaintableMap = ConnectorMap.get(client);
  633. while (widget != null && !vPaintableMap.isConnector(widget)) {
  634. widget = widget.getParent();
  635. }
  636. return vPaintableMap.getConnector(widget);
  637. }
  638. /**
  639. * Helper method to find first instance of given Widget type found by
  640. * traversing DOM upwards from given element.
  641. *
  642. * @param element
  643. * the element where to start seeking of Widget
  644. * @param class1
  645. * the Widget type to seek for
  646. */
  647. public static <T> T findWidget(Element element,
  648. Class<? extends Widget> class1) {
  649. if (element != null) {
  650. /* First seek for the first EventListener (~Widget) from dom */
  651. EventListener eventListener = null;
  652. while (eventListener == null && element != null) {
  653. eventListener = Event.getEventListener(element);
  654. if (eventListener == null) {
  655. element = (Element) element.getParentElement();
  656. }
  657. }
  658. if (eventListener != null) {
  659. /*
  660. * Then find the first widget of type class1 from widget
  661. * hierarchy
  662. */
  663. Widget w = (Widget) eventListener;
  664. while (w != null) {
  665. if (class1 == null || w.getClass() == class1) {
  666. return (T) w;
  667. }
  668. w = w.getParent();
  669. }
  670. }
  671. }
  672. return null;
  673. }
  674. /**
  675. * Force webkit to redraw an element
  676. *
  677. * @param element
  678. * The element that should be redrawn
  679. */
  680. public static void forceWebkitRedraw(Element element) {
  681. Style style = element.getStyle();
  682. String s = style.getProperty("webkitTransform");
  683. if (s == null || s.length() == 0) {
  684. style.setProperty("webkitTransform", "scale(1)");
  685. } else {
  686. style.setProperty("webkitTransform", "");
  687. }
  688. }
  689. /**
  690. * Detaches and re-attaches the element from its parent. The element is
  691. * reattached at the same position in the DOM as it was before.
  692. *
  693. * Does nothing if the element is not attached to the DOM.
  694. *
  695. * @param element
  696. * The element to detach and re-attach
  697. */
  698. public static void detachAttach(Element element) {
  699. if (element == null) {
  700. return;
  701. }
  702. Node nextSibling = element.getNextSibling();
  703. Node parent = element.getParentNode();
  704. if (parent == null) {
  705. return;
  706. }
  707. parent.removeChild(element);
  708. if (nextSibling == null) {
  709. parent.appendChild(element);
  710. } else {
  711. parent.insertBefore(element, nextSibling);
  712. }
  713. }
  714. public static void sinkOnloadForImages(Element element) {
  715. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  716. .getElementsByTagName("img");
  717. for (int i = 0; i < imgElements.getLength(); i++) {
  718. DOM.sinkEvents((Element) imgElements.getItem(i), Event.ONLOAD);
  719. }
  720. }
  721. /**
  722. * Returns the index of the childElement within its parent.
  723. *
  724. * @param subElement
  725. * @return
  726. */
  727. public static int getChildElementIndex(Element childElement) {
  728. int idx = 0;
  729. Node n = childElement;
  730. while ((n = n.getPreviousSibling()) != null) {
  731. idx++;
  732. }
  733. return idx;
  734. }
  735. private static void printConnectorInvocations(
  736. ArrayList<MethodInvocation> invocations, String id,
  737. ApplicationConnection c) {
  738. ServerConnector connector = ConnectorMap.get(c).getConnector(id);
  739. if (connector != null) {
  740. VConsole.log("\t" + id + " (" + connector.getClass() + ") :");
  741. } else {
  742. VConsole.log("\t" + id
  743. + ": Warning: no corresponding connector for id " + id);
  744. }
  745. for (MethodInvocation invocation : invocations) {
  746. Object[] parameters = invocation.getParameters();
  747. String formattedParams = null;
  748. if (ApplicationConstants.UPDATE_VARIABLE_METHOD.equals(invocation
  749. .getMethodName()) && parameters.length == 2) {
  750. // name, value
  751. Object value = parameters[1];
  752. // TODO paintables inside lists/maps get rendered as
  753. // components in the debug console
  754. String formattedValue = value instanceof ServerConnector ? ((ServerConnector) value)
  755. .getConnectorId() : String.valueOf(value);
  756. formattedParams = parameters[0] + " : " + formattedValue;
  757. }
  758. if (null == formattedParams) {
  759. formattedParams = (null != parameters) ? Arrays
  760. .toString(parameters) : null;
  761. }
  762. VConsole.log("\t\t" + invocation.getInterfaceName() + "."
  763. + invocation.getMethodName() + "(" + formattedParams + ")");
  764. }
  765. }
  766. static void logVariableBurst(ApplicationConnection c,
  767. ArrayList<MethodInvocation> loggedBurst) {
  768. try {
  769. VConsole.log("Variable burst to be sent to server:");
  770. String curId = null;
  771. ArrayList<MethodInvocation> invocations = new ArrayList<MethodInvocation>();
  772. for (int i = 0; i < loggedBurst.size(); i++) {
  773. String id = loggedBurst.get(i).getConnectorId();
  774. if (curId == null) {
  775. curId = id;
  776. } else if (!curId.equals(id)) {
  777. printConnectorInvocations(invocations, curId, c);
  778. invocations.clear();
  779. curId = id;
  780. }
  781. invocations.add(loggedBurst.get(i));
  782. }
  783. if (!invocations.isEmpty()) {
  784. printConnectorInvocations(invocations, curId, c);
  785. }
  786. } catch (Exception e) {
  787. VConsole.error(e);
  788. }
  789. }
  790. /**
  791. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  792. * resets it to its current value. Used mainly to work around rendering
  793. * issues in IE (and possibly in other browsers)
  794. *
  795. * @param element
  796. * The target element
  797. * @param styleProperty
  798. * The name of the property to set
  799. * @param tempValue
  800. * The temporary value
  801. */
  802. public static void setStyleTemporarily(Element element,
  803. final String styleProperty, String tempValue) {
  804. final Style style = element.getStyle();
  805. final String currentValue = style.getProperty(styleProperty);
  806. style.setProperty(styleProperty, tempValue);
  807. element.getOffsetWidth();
  808. style.setProperty(styleProperty, currentValue);
  809. }
  810. /**
  811. * A helper method to return the client position from an event. Returns
  812. * position from either first changed touch (if touch event) or from the
  813. * event itself.
  814. *
  815. * @param event
  816. * @return
  817. */
  818. public static int getTouchOrMouseClientX(Event event) {
  819. if (isTouchEvent(event)) {
  820. return event.getChangedTouches().get(0).getClientX();
  821. } else {
  822. return event.getClientX();
  823. }
  824. }
  825. /**
  826. * Find the element corresponding to the coordinates in the passed mouse
  827. * event. Please note that this is not always the same as the target of the
  828. * event e.g. if event capture is used.
  829. *
  830. * @param event
  831. * the mouse event to get coordinates from
  832. * @return the element at the coordinates of the event
  833. */
  834. public static Element getElementUnderMouse(NativeEvent event) {
  835. int pageX = getTouchOrMouseClientX(event);
  836. int pageY = getTouchOrMouseClientY(event);
  837. return getElementFromPoint(pageX, pageY);
  838. }
  839. /**
  840. * A helper method to return the client position from an event. Returns
  841. * position from either first changed touch (if touch event) or from the
  842. * event itself.
  843. *
  844. * @param event
  845. * @return
  846. */
  847. public static int getTouchOrMouseClientY(Event event) {
  848. if (isTouchEvent(event)) {
  849. return event.getChangedTouches().get(0).getClientY();
  850. } else {
  851. return event.getClientY();
  852. }
  853. }
  854. /**
  855. *
  856. * @see #getTouchOrMouseClientY(Event)
  857. * @param currentGwtEvent
  858. * @return
  859. */
  860. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  861. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  862. }
  863. /**
  864. * @see #getTouchOrMouseClientX(Event)
  865. *
  866. * @param event
  867. * @return
  868. */
  869. public static int getTouchOrMouseClientX(NativeEvent event) {
  870. return getTouchOrMouseClientX(Event.as(event));
  871. }
  872. public static boolean isTouchEvent(Event event) {
  873. return event.getType().contains("touch");
  874. }
  875. public static boolean isTouchEvent(NativeEvent event) {
  876. return isTouchEvent(Event.as(event));
  877. }
  878. public static void simulateClickFromTouchEvent(Event touchevent,
  879. Widget widget) {
  880. Touch touch = touchevent.getChangedTouches().get(0);
  881. final NativeEvent createMouseUpEvent = Document.get()
  882. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  883. touch.getClientX(), touch.getClientY(), false, false,
  884. false, false, NativeEvent.BUTTON_LEFT);
  885. final NativeEvent createMouseDownEvent = Document.get()
  886. .createMouseDownEvent(0, touch.getScreenX(),
  887. touch.getScreenY(), touch.getClientX(),
  888. touch.getClientY(), false, false, false, false,
  889. NativeEvent.BUTTON_LEFT);
  890. final NativeEvent createMouseClickEvent = Document.get()
  891. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  892. touch.getClientX(), touch.getClientY(), false, false,
  893. false, false);
  894. /*
  895. * Get target with element from point as we want the actual element, not
  896. * the one that sunk the event.
  897. */
  898. final Element target = getElementFromPoint(touch.getClientX(),
  899. touch.getClientY());
  900. /*
  901. * Fixes infocusable form fields in Safari of iOS 5.x and some Android
  902. * browsers.
  903. */
  904. Widget targetWidget = findWidget(target, null);
  905. if (targetWidget instanceof com.google.gwt.user.client.ui.Focusable) {
  906. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) targetWidget;
  907. toBeFocusedWidget.setFocus(true);
  908. } else if (targetWidget instanceof Focusable) {
  909. ((Focusable) targetWidget).focus();
  910. }
  911. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  912. @Override
  913. public void execute() {
  914. try {
  915. target.dispatchEvent(createMouseDownEvent);
  916. target.dispatchEvent(createMouseUpEvent);
  917. target.dispatchEvent(createMouseClickEvent);
  918. } catch (Exception e) {
  919. }
  920. }
  921. });
  922. }
  923. /**
  924. * Gets the currently focused element for Internet Explorer.
  925. *
  926. * @return The currently focused element
  927. */
  928. public native static Element getIEFocusedElement()
  929. /*-{
  930. if ($wnd.document.activeElement) {
  931. return $wnd.document.activeElement;
  932. }
  933. return null;
  934. }-*/
  935. ;
  936. /**
  937. * Kind of stronger version of isAttached(). In addition to std isAttached,
  938. * this method checks that this widget nor any of its parents is hidden. Can
  939. * be e.g used to check whether component should react to some events or
  940. * not.
  941. *
  942. * @param widget
  943. * @return true if attached and displayed
  944. */
  945. public static boolean isAttachedAndDisplayed(Widget widget) {
  946. if (widget.isAttached()) {
  947. /*
  948. * Failfast using offset size, then by iterating the widget tree
  949. */
  950. boolean notZeroSized = widget.getOffsetHeight() > 0
  951. || widget.getOffsetWidth() > 0;
  952. return notZeroSized || checkVisibilityRecursively(widget);
  953. } else {
  954. return false;
  955. }
  956. }
  957. private static boolean checkVisibilityRecursively(Widget widget) {
  958. if (widget.isVisible()) {
  959. Widget parent = widget.getParent();
  960. if (parent == null) {
  961. return true; // root panel
  962. } else {
  963. return checkVisibilityRecursively(parent);
  964. }
  965. } else {
  966. return false;
  967. }
  968. }
  969. /**
  970. * Scrolls an element into view vertically only. Modified version of
  971. * Element.scrollIntoView.
  972. *
  973. * @param elem
  974. * The element to scroll into view
  975. */
  976. public static native void scrollIntoViewVertically(Element elem)
  977. /*-{
  978. var top = elem.offsetTop;
  979. var height = elem.offsetHeight;
  980. if (elem.parentNode != elem.offsetParent) {
  981. top -= elem.parentNode.offsetTop;
  982. }
  983. var cur = elem.parentNode;
  984. while (cur && (cur.nodeType == 1)) {
  985. if (top < cur.scrollTop) {
  986. cur.scrollTop = top;
  987. }
  988. if (top + height > cur.scrollTop + cur.clientHeight) {
  989. cur.scrollTop = (top + height) - cur.clientHeight;
  990. }
  991. var offsetTop = cur.offsetTop;
  992. if (cur.parentNode != cur.offsetParent) {
  993. offsetTop -= cur.parentNode.offsetTop;
  994. }
  995. top += offsetTop - cur.scrollTop;
  996. cur = cur.parentNode;
  997. }
  998. }-*/;
  999. /**
  1000. * Checks if the given event is either a touch event or caused by the left
  1001. * mouse button
  1002. *
  1003. * @param event
  1004. * @return true if the event is a touch event or caused by the left mouse
  1005. * button, false otherwise
  1006. */
  1007. public static boolean isTouchEventOrLeftMouseButton(Event event) {
  1008. boolean touchEvent = Util.isTouchEvent(event);
  1009. return touchEvent || event.getButton() == Event.BUTTON_LEFT;
  1010. }
  1011. /**
  1012. * Performs a shallow comparison of the collections.
  1013. *
  1014. * @param collection1
  1015. * The first collection
  1016. * @param collection2
  1017. * The second collection
  1018. * @return true if the collections contain the same elements in the same
  1019. * order, false otherwise
  1020. */
  1021. public static boolean collectionsEquals(Collection collection1,
  1022. Collection collection2) {
  1023. if (collection1 == null) {
  1024. return collection2 == null;
  1025. }
  1026. if (collection2 == null) {
  1027. return false;
  1028. }
  1029. Iterator<Object> collection1Iterator = collection1.iterator();
  1030. Iterator<Object> collection2Iterator = collection2.iterator();
  1031. while (collection1Iterator.hasNext()) {
  1032. if (!collection2Iterator.hasNext()) {
  1033. return false;
  1034. }
  1035. Object collection1Object = collection1Iterator.next();
  1036. Object collection2Object = collection2Iterator.next();
  1037. if (collection1Object != collection2Object) {
  1038. return false;
  1039. }
  1040. }
  1041. if (collection2Iterator.hasNext()) {
  1042. return false;
  1043. }
  1044. return true;
  1045. }
  1046. public static String getConnectorString(ServerConnector p) {
  1047. if (p == null) {
  1048. return "null";
  1049. }
  1050. return getSimpleName(p) + " (" + p.getConnectorId() + ")";
  1051. }
  1052. }