Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Util.java 40KB

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