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

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