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
  91. .getConnectorMap();
  92. ComponentConnector paintable = paintableMap.getConnector(widget);
  93. if (paintable == null) {
  94. continue;
  95. }
  96. String pid = paintableMap.getConnectorId(paintable);
  97. if (pid != null) {
  98. Connector otherPaintable = paintableMap.getConnector(pid);
  99. if (otherPaintable == paintable) {
  100. return applicationConnection;
  101. }
  102. }
  103. }
  104. return null;
  105. }
  106. public static float parseRelativeSize(String size) {
  107. if (size == null || !size.endsWith("%")) {
  108. return -1;
  109. }
  110. try {
  111. return Float.parseFloat(size.substring(0, size.length() - 1));
  112. } catch (Exception e) {
  113. VConsole.log("Unable to parse relative size");
  114. return -1;
  115. }
  116. }
  117. private static final Element escapeHtmlHelper = DOM.createDiv();
  118. /**
  119. * Converts html entities to text.
  120. *
  121. * @param html
  122. * @return escaped string presentation of given html
  123. */
  124. public static String escapeHTML(String html) {
  125. DOM.setInnerText(escapeHtmlHelper, html);
  126. String escapedText = DOM.getInnerHTML(escapeHtmlHelper);
  127. if (BrowserInfo.get().isIE8()) {
  128. // #7478 IE8 "incorrectly" returns "<br>" for newlines set using
  129. // setInnerText. The same for " " which is converted to "&nbsp;"
  130. escapedText = escapedText.replaceAll("<(BR|br)>", "\n");
  131. escapedText = escapedText.replaceAll("&nbsp;", " ");
  132. }
  133. return escapedText;
  134. }
  135. /**
  136. * Escapes the string so it is safe to write inside an HTML attribute.
  137. *
  138. * @param attribute
  139. * The string to escape
  140. * @return An escaped version of <literal>attribute</literal>.
  141. */
  142. public static String escapeAttribute(String attribute) {
  143. attribute = attribute.replace("\"", "&quot;");
  144. attribute = attribute.replace("'", "&#39;");
  145. attribute = attribute.replace(">", "&gt;");
  146. attribute = attribute.replace("<", "&lt;");
  147. attribute = attribute.replace("&", "&amp;");
  148. return attribute;
  149. }
  150. /**
  151. * Clones given element as in JavaScript.
  152. *
  153. * Deprecate this if there appears similar method into GWT someday.
  154. *
  155. * @param element
  156. * @param deep
  157. * clone child tree also
  158. * @return
  159. */
  160. public static native Element cloneNode(Element element, boolean deep)
  161. /*-{
  162. return element.cloneNode(deep);
  163. }-*/;
  164. public static int measureHorizontalPaddingAndBorder(Element element,
  165. int paddingGuess) {
  166. String originalWidth = DOM.getStyleAttribute(element, "width");
  167. int originalOffsetWidth = element.getOffsetWidth();
  168. int widthGuess = (originalOffsetWidth - paddingGuess);
  169. if (widthGuess < 1) {
  170. widthGuess = 1;
  171. }
  172. DOM.setStyleAttribute(element, "width", widthGuess + "px");
  173. int padding = element.getOffsetWidth() - widthGuess;
  174. DOM.setStyleAttribute(element, "width", originalWidth);
  175. return padding;
  176. }
  177. public static int measureVerticalPaddingAndBorder(Element element,
  178. int paddingGuess) {
  179. String originalHeight = DOM.getStyleAttribute(element, "height");
  180. int originalOffsetHeight = element.getOffsetHeight();
  181. int widthGuess = (originalOffsetHeight - paddingGuess);
  182. if (widthGuess < 1) {
  183. widthGuess = 1;
  184. }
  185. DOM.setStyleAttribute(element, "height", widthGuess + "px");
  186. int padding = element.getOffsetHeight() - widthGuess;
  187. DOM.setStyleAttribute(element, "height", originalHeight);
  188. return padding;
  189. }
  190. public static int measureHorizontalBorder(Element element) {
  191. int borders;
  192. if (BrowserInfo.get().isIE()) {
  193. String width = element.getStyle().getProperty("width");
  194. String height = element.getStyle().getProperty("height");
  195. int offsetWidth = element.getOffsetWidth();
  196. int offsetHeight = element.getOffsetHeight();
  197. if (offsetHeight < 1) {
  198. offsetHeight = 1;
  199. }
  200. if (offsetWidth < 1) {
  201. offsetWidth = 10;
  202. }
  203. element.getStyle().setPropertyPx("height", offsetHeight);
  204. element.getStyle().setPropertyPx("width", offsetWidth);
  205. borders = element.getOffsetWidth() - element.getClientWidth();
  206. element.getStyle().setProperty("width", width);
  207. element.getStyle().setProperty("height", height);
  208. } else {
  209. borders = element.getOffsetWidth()
  210. - element.getPropertyInt("clientWidth");
  211. }
  212. assert borders >= 0;
  213. return borders;
  214. }
  215. public static int measureVerticalBorder(Element element) {
  216. int borders;
  217. if (BrowserInfo.get().isIE()) {
  218. String width = element.getStyle().getProperty("width");
  219. String height = element.getStyle().getProperty("height");
  220. int offsetWidth = element.getOffsetWidth();
  221. int offsetHeight = element.getOffsetHeight();
  222. if (offsetHeight < 1) {
  223. offsetHeight = 1;
  224. }
  225. if (offsetWidth < 1) {
  226. offsetWidth = 10;
  227. }
  228. element.getStyle().setPropertyPx("width", offsetWidth);
  229. element.getStyle().setPropertyPx("height", offsetHeight);
  230. borders = element.getOffsetHeight()
  231. - element.getPropertyInt("clientHeight");
  232. element.getStyle().setProperty("height", height);
  233. element.getStyle().setProperty("width", width);
  234. } else {
  235. borders = element.getOffsetHeight()
  236. - element.getPropertyInt("clientHeight");
  237. }
  238. assert borders >= 0;
  239. return borders;
  240. }
  241. public static int measureMarginLeft(Element element) {
  242. return element.getAbsoluteLeft()
  243. - element.getParentElement().getAbsoluteLeft();
  244. }
  245. public static int setHeightExcludingPaddingAndBorder(Widget widget,
  246. String height, int paddingBorderGuess) {
  247. if (height.equals("")) {
  248. setHeight(widget, "");
  249. return paddingBorderGuess;
  250. } else if (height.endsWith("px")) {
  251. int pixelHeight = Integer.parseInt(height.substring(0,
  252. height.length() - 2));
  253. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  254. pixelHeight, paddingBorderGuess, false);
  255. } else {
  256. // Set the height in unknown units
  257. setHeight(widget, height);
  258. // Use the offsetWidth
  259. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  260. widget.getOffsetHeight(), paddingBorderGuess, true);
  261. }
  262. }
  263. private static void setWidth(Widget widget, String width) {
  264. DOM.setStyleAttribute(widget.getElement(), "width", width);
  265. }
  266. private static void setHeight(Widget widget, String height) {
  267. DOM.setStyleAttribute(widget.getElement(), "height", height);
  268. }
  269. public static int setWidthExcludingPaddingAndBorder(Widget widget,
  270. String width, int paddingBorderGuess) {
  271. if (width.equals("")) {
  272. setWidth(widget, "");
  273. return paddingBorderGuess;
  274. } else if (width.endsWith("px")) {
  275. int pixelWidth = Integer.parseInt(width.substring(0,
  276. width.length() - 2));
  277. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  278. pixelWidth, paddingBorderGuess, false);
  279. } else {
  280. setWidth(widget, width);
  281. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  282. widget.getOffsetWidth(), paddingBorderGuess, true);
  283. }
  284. }
  285. public static int setWidthExcludingPaddingAndBorder(Element element,
  286. int requestedWidth, int horizontalPaddingBorderGuess,
  287. boolean requestedWidthIncludesPaddingBorder) {
  288. int widthGuess = requestedWidth - horizontalPaddingBorderGuess;
  289. if (widthGuess < 0) {
  290. widthGuess = 0;
  291. }
  292. DOM.setStyleAttribute(element, "width", widthGuess + "px");
  293. int captionOffsetWidth = DOM.getElementPropertyInt(element,
  294. "offsetWidth");
  295. int actualPadding = captionOffsetWidth - widthGuess;
  296. if (requestedWidthIncludesPaddingBorder) {
  297. actualPadding += actualPadding;
  298. }
  299. if (actualPadding != horizontalPaddingBorderGuess) {
  300. int w = requestedWidth - actualPadding;
  301. if (w < 0) {
  302. // Cannot set negative width even if we would want to
  303. w = 0;
  304. }
  305. DOM.setStyleAttribute(element, "width", w + "px");
  306. }
  307. return actualPadding;
  308. }
  309. public static int setHeightExcludingPaddingAndBorder(Element element,
  310. int requestedHeight, int verticalPaddingBorderGuess,
  311. boolean requestedHeightIncludesPaddingBorder) {
  312. int heightGuess = requestedHeight - verticalPaddingBorderGuess;
  313. if (heightGuess < 0) {
  314. heightGuess = 0;
  315. }
  316. DOM.setStyleAttribute(element, "height", heightGuess + "px");
  317. int captionOffsetHeight = DOM.getElementPropertyInt(element,
  318. "offsetHeight");
  319. int actualPadding = captionOffsetHeight - heightGuess;
  320. if (requestedHeightIncludesPaddingBorder) {
  321. actualPadding += actualPadding;
  322. }
  323. if (actualPadding != verticalPaddingBorderGuess) {
  324. int h = requestedHeight - actualPadding;
  325. if (h < 0) {
  326. // Cannot set negative height even if we would want to
  327. h = 0;
  328. }
  329. DOM.setStyleAttribute(element, "height", h + "px");
  330. }
  331. return actualPadding;
  332. }
  333. public static String getSimpleName(Object widget) {
  334. if (widget == null) {
  335. return "(null)";
  336. }
  337. String name = widget.getClass().getName();
  338. return name.substring(name.lastIndexOf('.') + 1);
  339. }
  340. public static void setFloat(Element element, String value) {
  341. if (BrowserInfo.get().isIE()) {
  342. DOM.setStyleAttribute(element, "styleFloat", value);
  343. } else {
  344. DOM.setStyleAttribute(element, "cssFloat", value);
  345. }
  346. }
  347. private static int detectedScrollbarSize = -1;
  348. public static int getNativeScrollbarSize() {
  349. if (detectedScrollbarSize < 0) {
  350. Element scroller = DOM.createDiv();
  351. scroller.getStyle().setProperty("width", "50px");
  352. scroller.getStyle().setProperty("height", "50px");
  353. scroller.getStyle().setProperty("overflow", "scroll");
  354. scroller.getStyle().setProperty("position", "absolute");
  355. scroller.getStyle().setProperty("marginLeft", "-5000px");
  356. RootPanel.getBodyElement().appendChild(scroller);
  357. detectedScrollbarSize = scroller.getOffsetWidth()
  358. - scroller.getPropertyInt("clientWidth");
  359. RootPanel.getBodyElement().removeChild(scroller);
  360. }
  361. return detectedScrollbarSize;
  362. }
  363. /**
  364. * Run workaround for webkits overflow auto issue.
  365. *
  366. * See: our bug #2138 and https://bugs.webkit.org/show_bug.cgi?id=21462
  367. *
  368. * @param elem
  369. * with overflow auto
  370. */
  371. public static void runWebkitOverflowAutoFix(final Element elem) {
  372. // Add max version if fix lands sometime to Webkit
  373. // Starting from Opera 11.00, also a problem in Opera
  374. if ((BrowserInfo.get().getWebkitVersion() > 0 || BrowserInfo.get()
  375. .getOperaVersion() >= 11) && getNativeScrollbarSize() > 0) {
  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. public void execute() {
  387. // Dough, Safari scroll auto means actually just a moped
  388. elem.getStyle().setProperty("overflow", originalOverflow);
  389. if (scrolltop > 0 || elem.getScrollTop() > 0) {
  390. int scrollvalue = scrolltop;
  391. if (scrollvalue == 0) {
  392. // mysterious are the ways of webkits scrollbar
  393. // handling. In some cases webkit reports bad (0)
  394. // scrolltop before hiding the element temporary,
  395. // sometimes after.
  396. scrollvalue = elem.getScrollTop();
  397. }
  398. // fix another bug where scrollbar remains in wrong
  399. // position
  400. elem.setScrollTop(scrollvalue - 1);
  401. elem.setScrollTop(scrollvalue);
  402. }
  403. // fix for #6940 : Table horizontal scroll sometimes not
  404. // updated when collapsing/expanding columns
  405. // Also appeared in Safari 5.1 with webkit 534 (#7667)
  406. if ((BrowserInfo.get().isChrome() || (BrowserInfo.get()
  407. .isSafari() && BrowserInfo.get().getWebkitVersion() >= 534))
  408. && (scrollleft > 0 || elem.getScrollLeft() > 0)) {
  409. int scrollvalue = scrollleft;
  410. if (scrollvalue == 0) {
  411. // mysterious are the ways of webkits scrollbar
  412. // handling. In some cases webkit may report a bad
  413. // (0) scrollleft before hiding the element
  414. // temporary, sometimes after.
  415. scrollvalue = elem.getScrollLeft();
  416. }
  417. // fix another bug where scrollbar remains in wrong
  418. // position
  419. elem.setScrollLeft(scrollvalue - 1);
  420. elem.setScrollLeft(scrollvalue);
  421. }
  422. }
  423. });
  424. }
  425. }
  426. /**
  427. * Parses shared state and fetches the relative size of the component. If a
  428. * dimension is not specified as relative it will return -1. If the shared
  429. * state does not contain width or height specifications this will return
  430. * null.
  431. *
  432. * @param state
  433. * @return
  434. */
  435. public static FloatSize parseRelativeSize(ComponentState state) {
  436. if (state.isUndefinedHeight() && state.isUndefinedWidth()) {
  437. return null;
  438. }
  439. float relativeWidth = Util.parseRelativeSize(state.getWidth());
  440. float relativeHeight = Util.parseRelativeSize(state.getHeight());
  441. FloatSize relativeSize = new FloatSize(relativeWidth, relativeHeight);
  442. return relativeSize;
  443. }
  444. @Deprecated
  445. public static boolean isCached(UIDL uidl) {
  446. return uidl.getBooleanAttribute("cached");
  447. }
  448. public static void alert(String string) {
  449. if (true) {
  450. Window.alert(string);
  451. }
  452. }
  453. public static boolean equals(Object a, Object b) {
  454. if (a == null) {
  455. return b == null;
  456. }
  457. return a.equals(b);
  458. }
  459. public static void updateRelativeChildrenAndSendSizeUpdateEvent(
  460. ApplicationConnection client, HasWidgets container, Widget widget) {
  461. notifyParentOfSizeChange(widget, false);
  462. }
  463. public static native int getRequiredWidth(
  464. com.google.gwt.dom.client.Element element)
  465. /*-{
  466. if (element.getBoundingClientRect) {
  467. var rect = element.getBoundingClientRect();
  468. return Math.ceil(rect.right - rect.left);
  469. } else {
  470. return element.offsetWidth;
  471. }
  472. }-*/;
  473. public static native int getRequiredHeight(
  474. com.google.gwt.dom.client.Element element)
  475. /*-{
  476. var height;
  477. if (element.getBoundingClientRect != null) {
  478. var rect = element.getBoundingClientRect();
  479. height = Math.ceil(rect.bottom - rect.top);
  480. } else {
  481. height = element.offsetHeight;
  482. }
  483. return height;
  484. }-*/;
  485. public static int getRequiredWidth(Widget widget) {
  486. return getRequiredWidth(widget.getElement());
  487. }
  488. public static int getRequiredHeight(Widget widget) {
  489. return getRequiredHeight(widget.getElement());
  490. }
  491. /**
  492. * Detects what is currently the overflow style attribute in given element.
  493. *
  494. * @param pe
  495. * the element to detect
  496. * @return true if auto or scroll
  497. */
  498. public static boolean mayHaveScrollBars(com.google.gwt.dom.client.Element pe) {
  499. String overflow = getComputedStyle(pe, "overflow");
  500. if (overflow != null) {
  501. if (overflow.equals("auto") || overflow.equals("scroll")) {
  502. return true;
  503. } else {
  504. return false;
  505. }
  506. } else {
  507. return false;
  508. }
  509. }
  510. /**
  511. * A simple helper method to detect "computed style" (aka style sheets +
  512. * element styles). Values returned differ a lot depending on browsers.
  513. * Always be very careful when using this.
  514. *
  515. * @param el
  516. * the element from which the style property is detected
  517. * @param p
  518. * the property to detect
  519. * @return String value of style property
  520. */
  521. private static native String getComputedStyle(
  522. com.google.gwt.dom.client.Element el, String p)
  523. /*-{
  524. try {
  525. if (el.currentStyle) {
  526. // IE
  527. return el.currentStyle[p];
  528. } else if (window.getComputedStyle) {
  529. // Sa, FF, Opera
  530. var view = el.ownerDocument.defaultView;
  531. return view.getComputedStyle(el,null).getPropertyValue(p);
  532. } else {
  533. // fall back for non IE, Sa, FF, Opera
  534. return "";
  535. }
  536. } catch (e) {
  537. return "";
  538. }
  539. }-*/;
  540. /**
  541. * Locates the nested child component of <literal>parent</literal> which
  542. * contains the element <literal>element</literal>. The child component is
  543. * also returned if "element" is part of its caption. If
  544. * <literal>element</literal> is not part of any child component, null is
  545. * returned.
  546. *
  547. * This method returns the deepest nested VPaintableWidget.
  548. *
  549. * @param client
  550. * A reference to ApplicationConnection
  551. * @param parent
  552. * The widget that contains <literal>element</literal>.
  553. * @param element
  554. * An element that is a sub element of the parent
  555. * @return The VPaintableWidget which the element is a part of. Null if the
  556. * element does not belong to a child.
  557. */
  558. public static ComponentConnector getPaintableForElement(
  559. ApplicationConnection client, Widget parent, Element element) {
  560. Element rootElement = parent.getElement();
  561. while (element != null && element != rootElement) {
  562. ComponentConnector paintable = ConnectorMap.get(client)
  563. .getConnector(element);
  564. if (paintable == null) {
  565. String ownerPid = VCaption.getCaptionOwnerPid(element);
  566. if (ownerPid != null) {
  567. paintable = (ComponentConnector) ConnectorMap.get(client)
  568. .getConnector(ownerPid);
  569. }
  570. }
  571. if (paintable != null) {
  572. // check that inside the rootElement
  573. while (element != null && element != rootElement) {
  574. element = (Element) element.getParentElement();
  575. }
  576. if (element != rootElement) {
  577. return null;
  578. } else {
  579. return paintable;
  580. }
  581. }
  582. element = (Element) element.getParentElement();
  583. }
  584. return null;
  585. }
  586. /**
  587. * Will (attempt) to focus the given DOM Element.
  588. *
  589. * @param el
  590. * the element to focus
  591. */
  592. public static native void focus(Element el)
  593. /*-{
  594. try {
  595. el.focus();
  596. } catch (e) {
  597. }
  598. }-*/;
  599. /**
  600. * Helper method to find the nearest parent paintable instance by traversing
  601. * the DOM upwards from given element.
  602. *
  603. * @param element
  604. * the element to start from
  605. */
  606. public static ComponentConnector findPaintable(ApplicationConnection client,
  607. Element element) {
  608. Widget widget = Util.findWidget(element, null);
  609. ConnectorMap vPaintableMap = ConnectorMap.get(client);
  610. while (widget != null && !vPaintableMap.isConnector(widget)) {
  611. widget = widget.getParent();
  612. }
  613. return vPaintableMap.getConnector(widget);
  614. }
  615. /**
  616. * Helper method to find first instance of given Widget type found by
  617. * traversing DOM upwards from given element.
  618. *
  619. * @param element
  620. * the element where to start seeking of Widget
  621. * @param class1
  622. * the Widget type to seek for
  623. */
  624. public static <T> T findWidget(Element element,
  625. Class<? extends Widget> class1) {
  626. if (element != null) {
  627. /* First seek for the first EventListener (~Widget) from dom */
  628. EventListener eventListener = null;
  629. while (eventListener == null && element != null) {
  630. eventListener = Event.getEventListener(element);
  631. if (eventListener == null) {
  632. element = (Element) element.getParentElement();
  633. }
  634. }
  635. if (eventListener != null) {
  636. /*
  637. * Then find the first widget of type class1 from widget
  638. * hierarchy
  639. */
  640. Widget w = (Widget) eventListener;
  641. while (w != null) {
  642. if (class1 == null || w.getClass() == class1) {
  643. return (T) w;
  644. }
  645. w = w.getParent();
  646. }
  647. }
  648. }
  649. return null;
  650. }
  651. /**
  652. * Force webkit to redraw an element
  653. *
  654. * @param element
  655. * The element that should be redrawn
  656. */
  657. public static void forceWebkitRedraw(Element element) {
  658. Style style = element.getStyle();
  659. String s = style.getProperty("webkitTransform");
  660. if (s == null || s.length() == 0) {
  661. style.setProperty("webkitTransform", "scale(1)");
  662. } else {
  663. style.setProperty("webkitTransform", "");
  664. }
  665. }
  666. /**
  667. * Detaches and re-attaches the element from its parent. The element is
  668. * reattached at the same position in the DOM as it was before.
  669. *
  670. * Does nothing if the element is not attached to the DOM.
  671. *
  672. * @param element
  673. * The element to detach and re-attach
  674. */
  675. public static void detachAttach(Element element) {
  676. if (element == null) {
  677. return;
  678. }
  679. Node nextSibling = element.getNextSibling();
  680. Node parent = element.getParentNode();
  681. if (parent == null) {
  682. return;
  683. }
  684. parent.removeChild(element);
  685. if (nextSibling == null) {
  686. parent.appendChild(element);
  687. } else {
  688. parent.insertBefore(element, nextSibling);
  689. }
  690. }
  691. public static void sinkOnloadForImages(Element element) {
  692. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  693. .getElementsByTagName("img");
  694. for (int i = 0; i < imgElements.getLength(); i++) {
  695. DOM.sinkEvents((Element) imgElements.getItem(i), Event.ONLOAD);
  696. }
  697. }
  698. /**
  699. * Returns the index of the childElement within its parent.
  700. *
  701. * @param subElement
  702. * @return
  703. */
  704. public static int getChildElementIndex(Element childElement) {
  705. int idx = 0;
  706. Node n = childElement;
  707. while ((n = n.getPreviousSibling()) != null) {
  708. idx++;
  709. }
  710. return idx;
  711. }
  712. private static void printPaintablesInvocations(
  713. ArrayList<MethodInvocation> invocations, String id,
  714. ApplicationConnection c) {
  715. ComponentConnector paintable = (ComponentConnector) ConnectorMap.get(c)
  716. .getConnector(id);
  717. if (paintable != null) {
  718. VConsole.log("\t" + id + " (" + paintable.getClass() + ") :");
  719. for (MethodInvocation invocation : invocations) {
  720. Object[] parameters = invocation.getParameters();
  721. String formattedParams = null;
  722. if (ApplicationConnection.UPDATE_VARIABLE_METHOD
  723. .equals(invocation.getMethodName())
  724. && parameters.length == 2) {
  725. // name, value
  726. Object value = parameters[1];
  727. // TODO paintables inside lists/maps get rendered as
  728. // components in the debug console
  729. String formattedValue = value instanceof Connector ? c
  730. .getConnectorMap().getConnectorId((Connector) value)
  731. : String.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. }