You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Util.java 41KB

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