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 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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.terminal.gwt.client.RenderInformation.FloatSize;
  28. import com.vaadin.terminal.gwt.client.communication.MethodInvocation;
  29. public class Util {
  30. /**
  31. * Helper method for debugging purposes.
  32. *
  33. * Stops execution on firefox browsers on a breakpoint.
  34. *
  35. */
  36. public static native void browserDebugger()
  37. /*-{
  38. if($wnd.console)
  39. debugger;
  40. }-*/;
  41. /**
  42. *
  43. * Returns the topmost element of from given coordinates.
  44. *
  45. * TODO fix crossplat issues clientX vs pageX. See quircksmode. Not critical
  46. * for vaadin as we scroll div istead of page.
  47. *
  48. * @param x
  49. * @param y
  50. * @return the element at given coordinates
  51. */
  52. public static native Element getElementFromPoint(int clientX, int clientY)
  53. /*-{
  54. var el = $wnd.document.elementFromPoint(clientX, clientY);
  55. if(el != null && el.nodeType == 3) {
  56. el = el.parentNode;
  57. }
  58. return el;
  59. }-*/;
  60. /**
  61. * This helper method can be called if components size have been changed
  62. * outside rendering phase. It notifies components parent about the size
  63. * change so it can react.
  64. *
  65. * When using this method, developer should consider if size changes could
  66. * be notified lazily. If lazy flag is true, method will save widget and
  67. * wait for a moment until it notifies parents in chunks. This may vastly
  68. * optimize layout in various situation. Example: if component have a lot of
  69. * images their onload events may fire "layout phase" many times in a short
  70. * period.
  71. *
  72. * @param widget
  73. * @param lazy
  74. * run componentSizeUpdated lazyly
  75. */
  76. public static void notifyParentOfSizeChange(Widget widget, boolean lazy) {
  77. ApplicationConnection applicationConnection = findApplicationConnectionFor(widget);
  78. if (applicationConnection != null) {
  79. applicationConnection.doLayout(lazy);
  80. }
  81. }
  82. private static boolean findAppConnectionWarningDisplayed = false;
  83. private static ApplicationConnection findApplicationConnectionFor(
  84. Widget widget) {
  85. if (!findAppConnectionWarningDisplayed) {
  86. findAppConnectionWarningDisplayed = true;
  87. VConsole.log("Warning: Using Util.findApplicationConnectionFor which should be eliminated once there is a better way to find the ApplicationConnection for a Paintable");
  88. }
  89. List<ApplicationConnection> runningApplications = ApplicationConfiguration
  90. .getRunningApplications();
  91. for (ApplicationConnection applicationConnection : runningApplications) {
  92. ConnectorMap paintableMap = applicationConnection.getConnectorMap();
  93. ComponentConnector paintable = paintableMap.getConnector(widget);
  94. if (paintable == null) {
  95. continue;
  96. }
  97. String pid = paintableMap.getConnectorId(paintable);
  98. if (pid != null) {
  99. ServerConnector otherPaintable = paintableMap.getConnector(pid);
  100. if (otherPaintable == paintable) {
  101. return applicationConnection;
  102. }
  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().getWebkitVersion() > 0 || BrowserInfo.get()
  376. .getOperaVersion() >= 11) && getNativeScrollbarSize() > 0) {
  377. final String originalOverflow = elem.getStyle().getProperty(
  378. "overflow");
  379. if ("hidden".equals(originalOverflow)) {
  380. return;
  381. }
  382. // check the scrolltop value before hiding the element
  383. final int scrolltop = elem.getScrollTop();
  384. final int scrollleft = elem.getScrollLeft();
  385. elem.getStyle().setProperty("overflow", "hidden");
  386. Scheduler.get().scheduleDeferred(new Command() {
  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 getPaintableForElement(
  560. ApplicationConnection client, Widget parent, Element element) {
  561. Element rootElement = parent.getElement();
  562. while (element != null && element != rootElement) {
  563. ComponentConnector paintable = ConnectorMap.get(client)
  564. .getConnector(element);
  565. if (paintable == null) {
  566. String ownerPid = VCaption.getCaptionOwnerPid(element);
  567. if (ownerPid != null) {
  568. paintable = (ComponentConnector) ConnectorMap.get(client)
  569. .getConnector(ownerPid);
  570. }
  571. }
  572. if (paintable != null) {
  573. // check that inside the rootElement
  574. while (element != null && element != rootElement) {
  575. element = (Element) element.getParentElement();
  576. }
  577. if (element != rootElement) {
  578. return null;
  579. } else {
  580. return paintable;
  581. }
  582. }
  583. element = (Element) element.getParentElement();
  584. }
  585. return null;
  586. }
  587. /**
  588. * Will (attempt) to focus the given DOM Element.
  589. *
  590. * @param el
  591. * the element to focus
  592. */
  593. public static native void focus(Element el)
  594. /*-{
  595. try {
  596. el.focus();
  597. } catch (e) {
  598. }
  599. }-*/;
  600. /**
  601. * Helper method to find the nearest parent paintable instance by traversing
  602. * the DOM upwards from given element.
  603. *
  604. * @param element
  605. * the element to start from
  606. */
  607. public static ComponentConnector findPaintable(
  608. ApplicationConnection client, Element element) {
  609. Widget widget = Util.findWidget(element, null);
  610. ConnectorMap vPaintableMap = ConnectorMap.get(client);
  611. while (widget != null && !vPaintableMap.isConnector(widget)) {
  612. widget = widget.getParent();
  613. }
  614. return vPaintableMap.getConnector(widget);
  615. }
  616. /**
  617. * Helper method to find first instance of given Widget type found by
  618. * traversing DOM upwards from given element.
  619. *
  620. * @param element
  621. * the element where to start seeking of Widget
  622. * @param class1
  623. * the Widget type to seek for
  624. */
  625. public static <T> T findWidget(Element element,
  626. Class<? extends Widget> class1) {
  627. if (element != null) {
  628. /* First seek for the first EventListener (~Widget) from dom */
  629. EventListener eventListener = null;
  630. while (eventListener == null && element != null) {
  631. eventListener = Event.getEventListener(element);
  632. if (eventListener == null) {
  633. element = (Element) element.getParentElement();
  634. }
  635. }
  636. if (eventListener != null) {
  637. /*
  638. * Then find the first widget of type class1 from widget
  639. * hierarchy
  640. */
  641. Widget w = (Widget) eventListener;
  642. while (w != null) {
  643. if (class1 == null || w.getClass() == class1) {
  644. return (T) w;
  645. }
  646. w = w.getParent();
  647. }
  648. }
  649. }
  650. return null;
  651. }
  652. /**
  653. * Force webkit to redraw an element
  654. *
  655. * @param element
  656. * The element that should be redrawn
  657. */
  658. public static void forceWebkitRedraw(Element element) {
  659. Style style = element.getStyle();
  660. String s = style.getProperty("webkitTransform");
  661. if (s == null || s.length() == 0) {
  662. style.setProperty("webkitTransform", "scale(1)");
  663. } else {
  664. style.setProperty("webkitTransform", "");
  665. }
  666. }
  667. /**
  668. * Detaches and re-attaches the element from its parent. The element is
  669. * reattached at the same position in the DOM as it was before.
  670. *
  671. * Does nothing if the element is not attached to the DOM.
  672. *
  673. * @param element
  674. * The element to detach and re-attach
  675. */
  676. public static void detachAttach(Element element) {
  677. if (element == null) {
  678. return;
  679. }
  680. Node nextSibling = element.getNextSibling();
  681. Node parent = element.getParentNode();
  682. if (parent == null) {
  683. return;
  684. }
  685. parent.removeChild(element);
  686. if (nextSibling == null) {
  687. parent.appendChild(element);
  688. } else {
  689. parent.insertBefore(element, nextSibling);
  690. }
  691. }
  692. public static void sinkOnloadForImages(Element element) {
  693. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  694. .getElementsByTagName("img");
  695. for (int i = 0; i < imgElements.getLength(); i++) {
  696. DOM.sinkEvents((Element) imgElements.getItem(i), Event.ONLOAD);
  697. }
  698. }
  699. /**
  700. * Returns the index of the childElement within its parent.
  701. *
  702. * @param subElement
  703. * @return
  704. */
  705. public static int getChildElementIndex(Element childElement) {
  706. int idx = 0;
  707. Node n = childElement;
  708. while ((n = n.getPreviousSibling()) != null) {
  709. idx++;
  710. }
  711. return idx;
  712. }
  713. private static void printPaintablesInvocations(
  714. ArrayList<MethodInvocation> invocations, String id,
  715. ApplicationConnection c) {
  716. ComponentConnector paintable = (ComponentConnector) ConnectorMap.get(c)
  717. .getConnector(id);
  718. if (paintable != null) {
  719. VConsole.log("\t" + id + " (" + paintable.getClass() + ") :");
  720. for (MethodInvocation invocation : invocations) {
  721. Object[] parameters = invocation.getParameters();
  722. String formattedParams = null;
  723. if (ApplicationConnection.UPDATE_VARIABLE_METHOD
  724. .equals(invocation.getMethodName())
  725. && parameters.length == 2) {
  726. // name, value
  727. Object value = parameters[1];
  728. // TODO paintables inside lists/maps get rendered as
  729. // components in the debug console
  730. String formattedValue = value instanceof ServerConnector ? c
  731. .getConnectorMap()
  732. .getConnectorId((ServerConnector) value) : String
  733. .valueOf(value);
  734. formattedParams = parameters[0] + " : " + formattedValue;
  735. }
  736. if (null == formattedParams) {
  737. formattedParams = (null != parameters) ? Arrays
  738. .toString(parameters) : null;
  739. }
  740. VConsole.log("\t\t" + invocation.getInterfaceName() + "."
  741. + invocation.getMethodName() + "(" + formattedParams
  742. + ")");
  743. }
  744. } else {
  745. VConsole.log("\t" + id + ": Warning: no corresponding paintable!");
  746. }
  747. }
  748. static void logVariableBurst(ApplicationConnection c,
  749. ArrayList<MethodInvocation> loggedBurst) {
  750. try {
  751. VConsole.log("Variable burst to be sent to server:");
  752. String curId = null;
  753. ArrayList<MethodInvocation> invocations = new ArrayList<MethodInvocation>();
  754. for (int i = 0; i < loggedBurst.size(); i++) {
  755. String id = loggedBurst.get(i).getConnectorId();
  756. if (curId == null) {
  757. curId = id;
  758. } else if (!curId.equals(id)) {
  759. printPaintablesInvocations(invocations, curId, c);
  760. invocations.clear();
  761. curId = id;
  762. }
  763. invocations.add(loggedBurst.get(i));
  764. }
  765. if (!invocations.isEmpty()) {
  766. printPaintablesInvocations(invocations, curId, c);
  767. }
  768. } catch (Exception e) {
  769. VConsole.error(e);
  770. }
  771. }
  772. /**
  773. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  774. * resets it to its current value. Used mainly to work around rendering
  775. * issues in IE (and possibly in other browsers)
  776. *
  777. * @param element
  778. * The target element
  779. * @param styleProperty
  780. * The name of the property to set
  781. * @param tempValue
  782. * The temporary value
  783. */
  784. public static void setStyleTemporarily(Element element,
  785. final String styleProperty, String tempValue) {
  786. final Style style = element.getStyle();
  787. final String currentValue = style.getProperty(styleProperty);
  788. style.setProperty(styleProperty, tempValue);
  789. element.getOffsetWidth();
  790. style.setProperty(styleProperty, currentValue);
  791. }
  792. /**
  793. * A helper method to return the client position from an event. Returns
  794. * position from either first changed touch (if touch event) or from the
  795. * event itself.
  796. *
  797. * @param event
  798. * @return
  799. */
  800. public static int getTouchOrMouseClientX(Event event) {
  801. if (isTouchEvent(event)) {
  802. return event.getChangedTouches().get(0).getClientX();
  803. } else {
  804. return event.getClientX();
  805. }
  806. }
  807. /**
  808. * A helper method to return the client position from an event. Returns
  809. * position from either first changed touch (if touch event) or from the
  810. * event itself.
  811. *
  812. * @param event
  813. * @return
  814. */
  815. public static int getTouchOrMouseClientY(Event event) {
  816. if (isTouchEvent(event)) {
  817. return event.getChangedTouches().get(0).getClientY();
  818. } else {
  819. return event.getClientY();
  820. }
  821. }
  822. /**
  823. *
  824. * @see #getTouchOrMouseClientY(Event)
  825. * @param currentGwtEvent
  826. * @return
  827. */
  828. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  829. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  830. }
  831. /**
  832. * @see #getTouchOrMouseClientX(Event)
  833. *
  834. * @param event
  835. * @return
  836. */
  837. public static int getTouchOrMouseClientX(NativeEvent event) {
  838. return getTouchOrMouseClientX(Event.as(event));
  839. }
  840. public static boolean isTouchEvent(Event event) {
  841. return event.getType().contains("touch");
  842. }
  843. public static boolean isTouchEvent(NativeEvent event) {
  844. return isTouchEvent(Event.as(event));
  845. }
  846. public static void simulateClickFromTouchEvent(Event touchevent,
  847. Widget widget) {
  848. Touch touch = touchevent.getChangedTouches().get(0);
  849. final NativeEvent createMouseUpEvent = Document.get()
  850. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  851. touch.getClientX(), touch.getClientY(), false, false,
  852. false, false, NativeEvent.BUTTON_LEFT);
  853. final NativeEvent createMouseDownEvent = Document.get()
  854. .createMouseDownEvent(0, touch.getScreenX(),
  855. touch.getScreenY(), touch.getClientX(),
  856. touch.getClientY(), false, false, false, false,
  857. NativeEvent.BUTTON_LEFT);
  858. final NativeEvent createMouseClickEvent = Document.get()
  859. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  860. touch.getClientX(), touch.getClientY(), false, false,
  861. false, false);
  862. /*
  863. * Get target with element from point as we want the actual element, not
  864. * the one that sunk the event.
  865. */
  866. final Element target = getElementFromPoint(touch.getClientX(),
  867. touch.getClientY());
  868. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  869. public void execute() {
  870. try {
  871. target.dispatchEvent(createMouseDownEvent);
  872. target.dispatchEvent(createMouseUpEvent);
  873. target.dispatchEvent(createMouseClickEvent);
  874. } catch (Exception e) {
  875. }
  876. }
  877. });
  878. }
  879. /**
  880. * Gets the currently focused element for Internet Explorer.
  881. *
  882. * @return The currently focused element
  883. */
  884. public native static Element getIEFocusedElement()
  885. /*-{
  886. if ($wnd.document.activeElement) {
  887. return $wnd.document.activeElement;
  888. }
  889. return null;
  890. }-*/
  891. ;
  892. /**
  893. * Kind of stronger version of isAttached(). In addition to std isAttached,
  894. * this method checks that this widget nor any of its parents is hidden. Can
  895. * be e.g used to check whether component should react to some events or
  896. * not.
  897. *
  898. * @param widget
  899. * @return true if attached and displayed
  900. */
  901. public static boolean isAttachedAndDisplayed(Widget widget) {
  902. if (widget.isAttached()) {
  903. /*
  904. * Failfast using offset size, then by iterating the widget tree
  905. */
  906. boolean notZeroSized = widget.getOffsetHeight() > 0
  907. || widget.getOffsetWidth() > 0;
  908. return notZeroSized || checkVisibilityRecursively(widget);
  909. } else {
  910. return false;
  911. }
  912. }
  913. private static boolean checkVisibilityRecursively(Widget widget) {
  914. if (widget.isVisible()) {
  915. Widget parent = widget.getParent();
  916. if (parent == null) {
  917. return true; // root panel
  918. } else {
  919. return checkVisibilityRecursively(parent);
  920. }
  921. } else {
  922. return false;
  923. }
  924. }
  925. /**
  926. * Scrolls an element into view vertically only. Modified version of
  927. * Element.scrollIntoView.
  928. *
  929. * @param elem
  930. * The element to scroll into view
  931. */
  932. public static native void scrollIntoViewVertically(Element elem)
  933. /*-{
  934. var top = elem.offsetTop;
  935. var height = elem.offsetHeight;
  936. if (elem.parentNode != elem.offsetParent) {
  937. top -= elem.parentNode.offsetTop;
  938. }
  939. var cur = elem.parentNode;
  940. while (cur && (cur.nodeType == 1)) {
  941. if (top < cur.scrollTop) {
  942. cur.scrollTop = top;
  943. }
  944. if (top + height > cur.scrollTop + cur.clientHeight) {
  945. cur.scrollTop = (top + height) - cur.clientHeight;
  946. }
  947. var offsetTop = cur.offsetTop;
  948. if (cur.parentNode != cur.offsetParent) {
  949. offsetTop -= cur.parentNode.offsetTop;
  950. }
  951. top += offsetTop - cur.scrollTop;
  952. cur = cur.parentNode;
  953. }
  954. }-*/;
  955. /**
  956. * Checks if the given event is either a touch event or caused by the left
  957. * mouse button
  958. *
  959. * @param event
  960. * @return true if the event is a touch event or caused by the left mouse
  961. * button, false otherwise
  962. */
  963. public static boolean isTouchEventOrLeftMouseButton(Event event) {
  964. boolean touchEvent = Util.isTouchEvent(event);
  965. return touchEvent || event.getButton() == Event.BUTTON_LEFT;
  966. }
  967. /**
  968. * Performs a shallow comparison of the collections.
  969. *
  970. * @param collection1 The first collection
  971. * @param collection2 The second collection
  972. * @return true if the collections contain the same elements in the same
  973. * order, false otherwise
  974. */
  975. public static boolean collectionsEquals(Collection collection1, Collection collection2) {
  976. if (collection1 == null) {
  977. return collection2 == null;
  978. }
  979. if (collection2 == null) {
  980. return false;
  981. }
  982. Iterator<Object> collection1Iterator = collection1.iterator();
  983. Iterator<Object> collection2Iterator = collection2.iterator();
  984. while (collection1Iterator.hasNext()) {
  985. if (!collection2Iterator.hasNext()) {
  986. return false;
  987. }
  988. Object collection1Object = collection1Iterator.next();
  989. Object collection2Object = collection2Iterator.next();
  990. if (collection1Object != collection2Object) {
  991. return false;
  992. }
  993. }
  994. if (collection2Iterator.hasNext()) {
  995. return false;
  996. }
  997. return true;
  998. }
  999. }