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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  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. String escapedText = DOM.getInnerHTML(escapeHtmlHelper);
  225. if (BrowserInfo.get().isIE() && BrowserInfo.get().getIEVersion() < 9) {
  226. // #7478 IE6-IE8 "incorrectly" returns "<br>" for newlines set using
  227. // setInnerText. The same for " " which is converted to "&nbsp;"
  228. escapedText = escapedText.replaceAll("<(BR|br)>", "\n");
  229. escapedText = escapedText.replaceAll("&nbsp;", " ");
  230. }
  231. return escapedText;
  232. }
  233. /**
  234. * Escapes the string so it is safe to write inside an HTML attribute.
  235. *
  236. * @param attribute
  237. * The string to escape
  238. * @return An escaped version of <literal>attribute</literal>.
  239. */
  240. public static String escapeAttribute(String attribute) {
  241. attribute = attribute.replace("\"", "&quot;");
  242. attribute = attribute.replace("'", "&#39;");
  243. attribute = attribute.replace(">", "&gt;");
  244. attribute = attribute.replace("<", "&lt;");
  245. attribute = attribute.replace("&", "&amp;");
  246. return attribute;
  247. }
  248. /**
  249. * Adds transparent PNG fix to image element; only use for IE6.
  250. *
  251. * @param el
  252. * IMG element
  253. */
  254. public native static void addPngFix(Element el)
  255. /*-{
  256. el.attachEvent("onload", $entry(function() {
  257. @com.vaadin.terminal.gwt.client.Util::doIE6PngFix(Lcom/google/gwt/user/client/Element;)(el);
  258. }),false);
  259. }-*/;
  260. private native static void doPngFix(Element el, String blankImageUrl)
  261. /*-{
  262. var src = el.src;
  263. if (src.indexOf(".png") < 1) return;
  264. var w = el.width || 16;
  265. var h = el.height || 16;
  266. if(h==30 || w==28) {
  267. setTimeout(function(){
  268. el.style.height = el.height + "px";
  269. el.style.width = el.width + "px";
  270. el.src = blankImageUrl;
  271. },10);
  272. } else {
  273. el.src = blankImageUrl;
  274. el.style.height = h + "px";
  275. el.style.width = w + "px";
  276. }
  277. el.style.padding = "0";
  278. el.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='crop')";
  279. }-*/;
  280. public static void doIE6PngFix(Element el) {
  281. String blankImageUrl = GWT.getModuleBaseURL() + "ie6pngfix/blank.gif";
  282. String src = el.getAttribute("src");
  283. if (src != null && !src.equals(blankImageUrl)) {
  284. doPngFix(el, blankImageUrl);
  285. }
  286. }
  287. /**
  288. * Clones given element as in JavaScript.
  289. *
  290. * Deprecate this if there appears similar method into GWT someday.
  291. *
  292. * @param element
  293. * @param deep
  294. * clone child tree also
  295. * @return
  296. */
  297. public static native Element cloneNode(Element element, boolean deep)
  298. /*-{
  299. return element.cloneNode(deep);
  300. }-*/;
  301. public static int measureHorizontalPaddingAndBorder(Element element,
  302. int paddingGuess) {
  303. String originalWidth = DOM.getStyleAttribute(element, "width");
  304. String originalOverflow = "";
  305. if (BrowserInfo.get().isIE6()) {
  306. originalOverflow = DOM.getStyleAttribute(element, "overflow");
  307. DOM.setStyleAttribute(element, "overflow", "hidden");
  308. }
  309. int originalOffsetWidth = element.getOffsetWidth();
  310. int widthGuess = (originalOffsetWidth - paddingGuess);
  311. if (widthGuess < 1) {
  312. widthGuess = 1;
  313. }
  314. DOM.setStyleAttribute(element, "width", widthGuess + "px");
  315. int padding = element.getOffsetWidth() - widthGuess;
  316. DOM.setStyleAttribute(element, "width", originalWidth);
  317. if (BrowserInfo.get().isIE6()) {
  318. DOM.setStyleAttribute(element, "overflow", originalOverflow);
  319. }
  320. return padding;
  321. }
  322. public static int measureVerticalPaddingAndBorder(Element element,
  323. int paddingGuess) {
  324. String originalHeight = DOM.getStyleAttribute(element, "height");
  325. int originalOffsetHeight = element.getOffsetHeight();
  326. int widthGuess = (originalOffsetHeight - paddingGuess);
  327. if (widthGuess < 1) {
  328. widthGuess = 1;
  329. }
  330. DOM.setStyleAttribute(element, "height", widthGuess + "px");
  331. int padding = element.getOffsetHeight() - widthGuess;
  332. DOM.setStyleAttribute(element, "height", originalHeight);
  333. return padding;
  334. }
  335. public static int measureHorizontalBorder(Element element) {
  336. int borders;
  337. if (BrowserInfo.get().isIE()) {
  338. String width = element.getStyle().getProperty("width");
  339. String height = element.getStyle().getProperty("height");
  340. int offsetWidth = element.getOffsetWidth();
  341. int offsetHeight = element.getOffsetHeight();
  342. if (!BrowserInfo.get().isIE7()) {
  343. if (offsetHeight < 1) {
  344. offsetHeight = 1;
  345. }
  346. if (offsetWidth < 1) {
  347. offsetWidth = 10;
  348. }
  349. element.getStyle().setPropertyPx("height", offsetHeight);
  350. }
  351. element.getStyle().setPropertyPx("width", offsetWidth);
  352. borders = element.getOffsetWidth() - element.getClientWidth();
  353. element.getStyle().setProperty("width", width);
  354. if (!BrowserInfo.get().isIE7()) {
  355. element.getStyle().setProperty("height", height);
  356. }
  357. } else {
  358. borders = element.getOffsetWidth()
  359. - element.getPropertyInt("clientWidth");
  360. }
  361. assert borders >= 0;
  362. return borders;
  363. }
  364. public static int measureVerticalBorder(Element element) {
  365. int borders;
  366. if (BrowserInfo.get().isIE()) {
  367. String width = element.getStyle().getProperty("width");
  368. String height = element.getStyle().getProperty("height");
  369. int offsetWidth = element.getOffsetWidth();
  370. int offsetHeight = element.getOffsetHeight();
  371. // if (BrowserInfo.get().isIE6()) {
  372. if (offsetHeight < 1) {
  373. offsetHeight = 1;
  374. }
  375. if (offsetWidth < 1) {
  376. offsetWidth = 10;
  377. }
  378. element.getStyle().setPropertyPx("width", offsetWidth);
  379. // }
  380. element.getStyle().setPropertyPx("height", offsetHeight);
  381. borders = element.getOffsetHeight()
  382. - element.getPropertyInt("clientHeight");
  383. element.getStyle().setProperty("height", height);
  384. // if (BrowserInfo.get().isIE6()) {
  385. element.getStyle().setProperty("width", width);
  386. // }
  387. } else {
  388. borders = element.getOffsetHeight()
  389. - element.getPropertyInt("clientHeight");
  390. }
  391. assert borders >= 0;
  392. return borders;
  393. }
  394. public static int measureMarginLeft(Element element) {
  395. return element.getAbsoluteLeft()
  396. - element.getParentElement().getAbsoluteLeft();
  397. }
  398. public static int setHeightExcludingPaddingAndBorder(Widget widget,
  399. String height, int paddingBorderGuess) {
  400. if (height.equals("")) {
  401. setHeight(widget, "");
  402. return paddingBorderGuess;
  403. } else if (height.endsWith("px")) {
  404. int pixelHeight = Integer.parseInt(height.substring(0,
  405. height.length() - 2));
  406. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  407. pixelHeight, paddingBorderGuess, false);
  408. } else {
  409. // Set the height in unknown units
  410. setHeight(widget, height);
  411. // Use the offsetWidth
  412. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  413. widget.getOffsetHeight(), paddingBorderGuess, true);
  414. }
  415. }
  416. private static void setWidth(Widget widget, String width) {
  417. DOM.setStyleAttribute(widget.getElement(), "width", width);
  418. }
  419. private static void setHeight(Widget widget, String height) {
  420. DOM.setStyleAttribute(widget.getElement(), "height", height);
  421. }
  422. public static int setWidthExcludingPaddingAndBorder(Widget widget,
  423. String width, int paddingBorderGuess) {
  424. if (width.equals("")) {
  425. setWidth(widget, "");
  426. return paddingBorderGuess;
  427. } else if (width.endsWith("px")) {
  428. int pixelWidth = Integer.parseInt(width.substring(0,
  429. width.length() - 2));
  430. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  431. pixelWidth, paddingBorderGuess, false);
  432. } else {
  433. setWidth(widget, width);
  434. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  435. widget.getOffsetWidth(), paddingBorderGuess, true);
  436. }
  437. }
  438. public static int setWidthExcludingPaddingAndBorder(Element element,
  439. int requestedWidth, int horizontalPaddingBorderGuess,
  440. boolean requestedWidthIncludesPaddingBorder) {
  441. int widthGuess = requestedWidth - horizontalPaddingBorderGuess;
  442. if (widthGuess < 0) {
  443. widthGuess = 0;
  444. }
  445. DOM.setStyleAttribute(element, "width", widthGuess + "px");
  446. int captionOffsetWidth = DOM.getElementPropertyInt(element,
  447. "offsetWidth");
  448. int actualPadding = captionOffsetWidth - widthGuess;
  449. if (requestedWidthIncludesPaddingBorder) {
  450. actualPadding += actualPadding;
  451. }
  452. if (actualPadding != horizontalPaddingBorderGuess) {
  453. int w = requestedWidth - actualPadding;
  454. if (w < 0) {
  455. // Cannot set negative width even if we would want to
  456. w = 0;
  457. }
  458. DOM.setStyleAttribute(element, "width", w + "px");
  459. }
  460. return actualPadding;
  461. }
  462. public static int setHeightExcludingPaddingAndBorder(Element element,
  463. int requestedHeight, int verticalPaddingBorderGuess,
  464. boolean requestedHeightIncludesPaddingBorder) {
  465. int heightGuess = requestedHeight - verticalPaddingBorderGuess;
  466. if (heightGuess < 0) {
  467. heightGuess = 0;
  468. }
  469. DOM.setStyleAttribute(element, "height", heightGuess + "px");
  470. int captionOffsetHeight = DOM.getElementPropertyInt(element,
  471. "offsetHeight");
  472. int actualPadding = captionOffsetHeight - heightGuess;
  473. if (requestedHeightIncludesPaddingBorder) {
  474. actualPadding += actualPadding;
  475. }
  476. if (actualPadding != verticalPaddingBorderGuess) {
  477. int h = requestedHeight - actualPadding;
  478. if (h < 0) {
  479. // Cannot set negative height even if we would want to
  480. h = 0;
  481. }
  482. DOM.setStyleAttribute(element, "height", h + "px");
  483. }
  484. return actualPadding;
  485. }
  486. public static String getSimpleName(Object widget) {
  487. if (widget == null) {
  488. return "(null)";
  489. }
  490. String name = widget.getClass().getName();
  491. return name.substring(name.lastIndexOf('.') + 1);
  492. }
  493. public static void setFloat(Element element, String value) {
  494. if (BrowserInfo.get().isIE()) {
  495. DOM.setStyleAttribute(element, "styleFloat", value);
  496. } else {
  497. DOM.setStyleAttribute(element, "cssFloat", value);
  498. }
  499. }
  500. private static int detectedScrollbarSize = -1;
  501. public static int getNativeScrollbarSize() {
  502. if (detectedScrollbarSize < 0) {
  503. Element scroller = DOM.createDiv();
  504. scroller.getStyle().setProperty("width", "50px");
  505. scroller.getStyle().setProperty("height", "50px");
  506. scroller.getStyle().setProperty("overflow", "scroll");
  507. scroller.getStyle().setProperty("position", "absolute");
  508. scroller.getStyle().setProperty("marginLeft", "-5000px");
  509. RootPanel.getBodyElement().appendChild(scroller);
  510. detectedScrollbarSize = scroller.getOffsetWidth()
  511. - scroller.getPropertyInt("clientWidth");
  512. RootPanel.getBodyElement().removeChild(scroller);
  513. }
  514. return detectedScrollbarSize;
  515. }
  516. /**
  517. * Run workaround for webkits overflow auto issue.
  518. *
  519. * See: our bug #2138 and https://bugs.webkit.org/show_bug.cgi?id=21462
  520. *
  521. * @param elem
  522. * with overflow auto
  523. */
  524. public static void runWebkitOverflowAutoFix(final Element elem) {
  525. // Add max version if fix lands sometime to Webkit
  526. // Starting from Opera 11.00, also a problem in Opera
  527. if ((BrowserInfo.get().getWebkitVersion() > 0 || BrowserInfo.get()
  528. .getOperaVersion() >= 11) && getNativeScrollbarSize() > 0) {
  529. final String originalOverflow = elem.getStyle().getProperty(
  530. "overflow");
  531. if ("hidden".equals(originalOverflow)) {
  532. return;
  533. }
  534. // check the scrolltop value before hiding the element
  535. final int scrolltop = elem.getScrollTop();
  536. final int scrollleft = elem.getScrollLeft();
  537. elem.getStyle().setProperty("overflow", "hidden");
  538. Scheduler.get().scheduleDeferred(new Command() {
  539. public void execute() {
  540. // Dough, Safari scroll auto means actually just a moped
  541. elem.getStyle().setProperty("overflow", originalOverflow);
  542. if (scrolltop > 0 || elem.getScrollTop() > 0) {
  543. int scrollvalue = scrolltop;
  544. if (scrollvalue == 0) {
  545. // mysterious are the ways of webkits scrollbar
  546. // handling. In some cases webkit reports bad (0)
  547. // scrolltop before hiding the element temporary,
  548. // sometimes after.
  549. scrollvalue = elem.getScrollTop();
  550. }
  551. // fix another bug where scrollbar remains in wrong
  552. // position
  553. elem.setScrollTop(scrollvalue - 1);
  554. elem.setScrollTop(scrollvalue);
  555. }
  556. // fix for #6940 : Table horizontal scroll sometimes not
  557. // updated when collapsing/expanding columns
  558. // Also appeared in Safari 5.1 with webkit 534 (#7667)
  559. if ((BrowserInfo.get().isChrome() || (BrowserInfo.get()
  560. .isSafari() && BrowserInfo.get().getWebkitVersion() >= 534))
  561. && (scrollleft > 0 || elem.getScrollLeft() > 0)) {
  562. int scrollvalue = scrollleft;
  563. if (scrollvalue == 0) {
  564. // mysterious are the ways of webkits scrollbar
  565. // handling. In some cases webkit may report a bad
  566. // (0) scrollleft before hiding the element
  567. // temporary, sometimes after.
  568. scrollvalue = elem.getScrollLeft();
  569. }
  570. // fix another bug where scrollbar remains in wrong
  571. // position
  572. elem.setScrollLeft(scrollvalue - 1);
  573. elem.setScrollLeft(scrollvalue);
  574. }
  575. }
  576. });
  577. }
  578. }
  579. /**
  580. * Parses the UIDL parameter and fetches the relative size of the component.
  581. * If a dimension is not specified as relative it will return -1. If the
  582. * UIDL does not contain width or height specifications this will return
  583. * null.
  584. *
  585. * @param uidl
  586. * @return
  587. */
  588. public static FloatSize parseRelativeSize(UIDL uidl) {
  589. boolean hasAttribute = false;
  590. String w = "";
  591. String h = "";
  592. if (uidl.hasAttribute("width")) {
  593. hasAttribute = true;
  594. w = uidl.getStringAttribute("width");
  595. }
  596. if (uidl.hasAttribute("height")) {
  597. hasAttribute = true;
  598. h = uidl.getStringAttribute("height");
  599. }
  600. if (!hasAttribute) {
  601. return null;
  602. }
  603. float relativeWidth = Util.parseRelativeSize(w);
  604. float relativeHeight = Util.parseRelativeSize(h);
  605. FloatSize relativeSize = new FloatSize(relativeWidth, relativeHeight);
  606. return relativeSize;
  607. }
  608. public static boolean isCached(UIDL uidl) {
  609. return uidl.getBooleanAttribute("cached");
  610. }
  611. public static void alert(String string) {
  612. if (true) {
  613. Window.alert(string);
  614. }
  615. }
  616. public static boolean equals(Object a, Object b) {
  617. if (a == null) {
  618. return b == null;
  619. }
  620. return a.equals(b);
  621. }
  622. public static void updateRelativeChildrenAndSendSizeUpdateEvent(
  623. ApplicationConnection client, HasWidgets container) {
  624. updateRelativeChildrenAndSendSizeUpdateEvent(client, container,
  625. (Paintable) container);
  626. }
  627. public static void updateRelativeChildrenAndSendSizeUpdateEvent(
  628. ApplicationConnection client, HasWidgets container, Paintable widget) {
  629. /*
  630. * Relative sized children must be updated first so the component has
  631. * the correct outer dimensions when signaling a size change to the
  632. * parent.
  633. */
  634. Iterator<Widget> childIterator = container.iterator();
  635. while (childIterator.hasNext()) {
  636. Widget w = childIterator.next();
  637. client.handleComponentRelativeSize(w);
  638. }
  639. HashSet<Paintable> widgets = new HashSet<Paintable>();
  640. widgets.add(widget);
  641. Util.componentSizeUpdated(widgets);
  642. }
  643. public static native int getRequiredWidth(
  644. com.google.gwt.dom.client.Element element)
  645. /*-{
  646. if (element.getBoundingClientRect) {
  647. var rect = element.getBoundingClientRect();
  648. return Math.ceil(rect.right - rect.left);
  649. } else {
  650. return element.offsetWidth;
  651. }
  652. }-*/;
  653. public static native int getRequiredHeight(
  654. com.google.gwt.dom.client.Element element)
  655. /*-{
  656. var height;
  657. if (element.getBoundingClientRect != null) {
  658. var rect = element.getBoundingClientRect();
  659. height = Math.ceil(rect.bottom - rect.top);
  660. } else {
  661. height = element.offsetHeight;
  662. }
  663. return height;
  664. }-*/;
  665. public static int getRequiredWidth(Widget widget) {
  666. return getRequiredWidth(widget.getElement());
  667. }
  668. public static int getRequiredHeight(Widget widget) {
  669. return getRequiredHeight(widget.getElement());
  670. }
  671. /**
  672. * Detects what is currently the overflow style attribute in given element.
  673. *
  674. * @param pe
  675. * the element to detect
  676. * @return true if auto or scroll
  677. */
  678. public static boolean mayHaveScrollBars(com.google.gwt.dom.client.Element pe) {
  679. String overflow = getComputedStyle(pe, "overflow");
  680. if (overflow != null) {
  681. if (overflow.equals("auto") || overflow.equals("scroll")) {
  682. return true;
  683. } else {
  684. return false;
  685. }
  686. } else {
  687. return false;
  688. }
  689. }
  690. /**
  691. * A simple helper method to detect "computed style" (aka style sheets +
  692. * element styles). Values returned differ a lot depending on browsers.
  693. * Always be very careful when using this.
  694. *
  695. * @param el
  696. * the element from which the style property is detected
  697. * @param p
  698. * the property to detect
  699. * @return String value of style property
  700. */
  701. private static native String getComputedStyle(
  702. com.google.gwt.dom.client.Element el, String p)
  703. /*-{
  704. try {
  705. if (el.currentStyle) {
  706. // IE
  707. return el.currentStyle[p];
  708. } else if (window.getComputedStyle) {
  709. // Sa, FF, Opera
  710. var view = el.ownerDocument.defaultView;
  711. return view.getComputedStyle(el,null).getPropertyValue(p);
  712. } else {
  713. // fall back for non IE, Sa, FF, Opera
  714. return "";
  715. }
  716. } catch (e) {
  717. return "";
  718. }
  719. }-*/;
  720. /**
  721. * IE7 sometimes "forgets" to render content. This function runs a hack to
  722. * workaround the bug if needed. This happens easily in framset. See #3295.
  723. */
  724. public static void runIE7ZeroSizedBodyFix() {
  725. if (BrowserInfo.get().isIE7()) {
  726. int offsetWidth = RootPanel.getBodyElement().getOffsetWidth();
  727. if (offsetWidth == 0) {
  728. shakeBodyElement();
  729. }
  730. }
  731. }
  732. /**
  733. * Does some very small adjustments to body element. We need this just to
  734. * overcome some IE bugs.
  735. */
  736. public static void shakeBodyElement() {
  737. final DivElement shaker = Document.get().createDivElement();
  738. RootPanel.getBodyElement().insertBefore(shaker,
  739. RootPanel.getBodyElement().getFirstChildElement());
  740. shaker.getStyle().setPropertyPx("height", 0);
  741. shaker.setInnerHTML("&nbsp;");
  742. RootPanel.getBodyElement().removeChild(shaker);
  743. }
  744. /**
  745. * Locates the child component of <literal>parent</literal> which contains
  746. * the element <literal>element</literal>. The child component is also
  747. * returned if "element" is part of its caption. If
  748. * <literal>element</literal> is not part of any child component, null is
  749. * returned.
  750. *
  751. * This method returns the immediate child of the parent that contains the
  752. * element. See
  753. * {@link #getPaintableForElement(ApplicationConnection, Container, Element)}
  754. * for the deepest nested paintable of parent that contains the element.
  755. *
  756. * @param client
  757. * A reference to ApplicationConnection
  758. * @param parent
  759. * The widget that contains <literal>element</literal>.
  760. * @param element
  761. * An element that is a sub element of the parent
  762. * @return The Paintable which the element is a part of. Null if the element
  763. * does not belong to a child.
  764. */
  765. public static Paintable getChildPaintableForElement(
  766. ApplicationConnection client, Container parent, Element element) {
  767. Element rootElement = ((Widget) parent).getElement();
  768. while (element != null && element != rootElement) {
  769. Paintable paintable = client.getPaintable(element);
  770. if (paintable == null) {
  771. String ownerPid = VCaption.getCaptionOwnerPid(element);
  772. if (ownerPid != null) {
  773. paintable = client.getPaintable(ownerPid);
  774. }
  775. }
  776. if (paintable != null) {
  777. try {
  778. if (parent.hasChildComponent((Widget) paintable)) {
  779. return paintable;
  780. }
  781. } catch (ClassCastException e) {
  782. // We assume everything is a widget however there is no need
  783. // to crash everything if there is a paintable that is not.
  784. }
  785. }
  786. element = (Element) element.getParentElement();
  787. }
  788. return null;
  789. }
  790. /**
  791. * Locates the nested child component of <literal>parent</literal> which
  792. * contains the element <literal>element</literal>. The child component is
  793. * also returned if "element" is part of its caption. If
  794. * <literal>element</literal> is not part of any child component, null is
  795. * returned.
  796. *
  797. * This method returns the deepest nested Paintable. See
  798. * {@link #getChildPaintableForElement(ApplicationConnection, Container, Element)}
  799. * for the immediate child component of parent that contains the element.
  800. *
  801. * @param client
  802. * A reference to ApplicationConnection
  803. * @param parent
  804. * The widget that contains <literal>element</literal>.
  805. * @param element
  806. * An element that is a sub element of the parent
  807. * @return The Paintable which the element is a part of. Null if the element
  808. * does not belong to a child.
  809. */
  810. public static Paintable getPaintableForElement(
  811. ApplicationConnection client, Widget parent, Element element) {
  812. Element rootElement = parent.getElement();
  813. while (element != null && element != rootElement) {
  814. Paintable paintable = client.getPaintable(element);
  815. if (paintable == null) {
  816. String ownerPid = VCaption.getCaptionOwnerPid(element);
  817. if (ownerPid != null) {
  818. paintable = client.getPaintable(ownerPid);
  819. }
  820. }
  821. if (paintable != null) {
  822. // check that inside the rootElement
  823. while (element != null && element != rootElement) {
  824. element = (Element) element.getParentElement();
  825. }
  826. if (element != rootElement) {
  827. return null;
  828. } else {
  829. return paintable;
  830. }
  831. }
  832. element = (Element) element.getParentElement();
  833. }
  834. return null;
  835. }
  836. /**
  837. * Will (attempt) to focus the given DOM Element.
  838. *
  839. * @param el
  840. * the element to focus
  841. */
  842. public static native void focus(Element el)
  843. /*-{
  844. try {
  845. el.focus();
  846. } catch (e) {
  847. }
  848. }-*/;
  849. /**
  850. * Helper method to find first instance of given Widget type found by
  851. * traversing DOM upwards from given element.
  852. *
  853. * @param element
  854. * the element where to start seeking of Widget
  855. * @param class1
  856. * the Widget type to seek for
  857. */
  858. public static <T> T findWidget(Element element,
  859. Class<? extends Widget> class1) {
  860. if (element != null) {
  861. /* First seek for the first EventListener (~Widget) from dom */
  862. EventListener eventListener = null;
  863. while (eventListener == null && element != null) {
  864. eventListener = Event.getEventListener(element);
  865. if (eventListener == null) {
  866. element = (Element) element.getParentElement();
  867. }
  868. }
  869. if (eventListener != null) {
  870. /*
  871. * Then find the first widget of type class1 from widget
  872. * hierarchy
  873. */
  874. Widget w = (Widget) eventListener;
  875. while (w != null) {
  876. if (class1 == null || w.getClass() == class1) {
  877. return (T) w;
  878. }
  879. w = w.getParent();
  880. }
  881. }
  882. }
  883. return null;
  884. }
  885. /**
  886. * Force webkit to redraw an element
  887. *
  888. * @param element
  889. * The element that should be redrawn
  890. */
  891. public static void forceWebkitRedraw(Element element) {
  892. Style style = element.getStyle();
  893. String s = style.getProperty("webkitTransform");
  894. if (s == null || s.length() == 0) {
  895. style.setProperty("webkitTransform", "scale(1)");
  896. } else {
  897. style.setProperty("webkitTransform", "");
  898. }
  899. }
  900. /**
  901. * Detaches and re-attaches the element from its parent. The element is
  902. * reattached at the same position in the DOM as it was before.
  903. *
  904. * Does nothing if the element is not attached to the DOM.
  905. *
  906. * @param element
  907. * The element to detach and re-attach
  908. */
  909. public static void detachAttach(Element element) {
  910. if (element == null) {
  911. return;
  912. }
  913. Node nextSibling = element.getNextSibling();
  914. Node parent = element.getParentNode();
  915. if (parent == null) {
  916. return;
  917. }
  918. parent.removeChild(element);
  919. if (nextSibling == null) {
  920. parent.appendChild(element);
  921. } else {
  922. parent.insertBefore(element, nextSibling);
  923. }
  924. }
  925. public static void sinkOnloadForImages(Element element) {
  926. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  927. .getElementsByTagName("img");
  928. for (int i = 0; i < imgElements.getLength(); i++) {
  929. DOM.sinkEvents((Element) imgElements.getItem(i), Event.ONLOAD);
  930. }
  931. }
  932. /**
  933. * Returns the index of the childElement within its parent.
  934. *
  935. * @param subElement
  936. * @return
  937. */
  938. public static int getChildElementIndex(Element childElement) {
  939. int idx = 0;
  940. Node n = childElement;
  941. while ((n = n.getPreviousSibling()) != null) {
  942. idx++;
  943. }
  944. return idx;
  945. }
  946. private static void printPaintablesVariables(ArrayList<String[]> vars,
  947. String id, ApplicationConnection c) {
  948. Paintable paintable = c.getPaintable(id);
  949. if (paintable != null) {
  950. VConsole.log("\t" + id + " (" + paintable.getClass() + ") :");
  951. for (String[] var : vars) {
  952. VConsole.log("\t\t" + var[1] + " (" + var[2] + ")" + " : "
  953. + var[0]);
  954. }
  955. } else {
  956. VConsole.log("\t" + id + ": Warning: no corresponding paintable!");
  957. }
  958. }
  959. static void logVariableBurst(ApplicationConnection c,
  960. ArrayList<String> loggedBurst) {
  961. try {
  962. VConsole.log("Variable burst to be sent to server:");
  963. String curId = null;
  964. ArrayList<String[]> vars = new ArrayList<String[]>();
  965. for (int i = 0; i < loggedBurst.size(); i++) {
  966. String value = loggedBurst.get(i++);
  967. String[] split = loggedBurst
  968. .get(i)
  969. .split(String
  970. .valueOf(ApplicationConnection.VAR_FIELD_SEPARATOR));
  971. String id = split[0];
  972. if (curId == null) {
  973. curId = id;
  974. } else if (!curId.equals(id)) {
  975. printPaintablesVariables(vars, curId, c);
  976. vars.clear();
  977. curId = id;
  978. }
  979. split[0] = value;
  980. vars.add(split);
  981. }
  982. if (!vars.isEmpty()) {
  983. printPaintablesVariables(vars, curId, c);
  984. }
  985. } catch (Exception e) {
  986. VConsole.error(e);
  987. }
  988. }
  989. /**
  990. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  991. * resets it to its current value. Used mainly to work around rendering
  992. * issues in IE (and possibly in other browsers)
  993. *
  994. * @param element
  995. * The target element
  996. * @param styleProperty
  997. * The name of the property to set
  998. * @param tempValue
  999. * The temporary value
  1000. */
  1001. public static void setStyleTemporarily(Element element,
  1002. final String styleProperty, String tempValue) {
  1003. final Style style = element.getStyle();
  1004. final String currentValue = style.getProperty(styleProperty);
  1005. style.setProperty(styleProperty, tempValue);
  1006. element.getOffsetWidth();
  1007. style.setProperty(styleProperty, currentValue);
  1008. }
  1009. /**
  1010. * A helper method to return the client position from an event. Returns
  1011. * position from either first changed touch (if touch event) or from the
  1012. * event itself.
  1013. *
  1014. * @param event
  1015. * @return
  1016. */
  1017. public static int getTouchOrMouseClientX(Event event) {
  1018. if (isTouchEvent(event)) {
  1019. return event.getChangedTouches().get(0).getClientX();
  1020. } else {
  1021. return event.getClientX();
  1022. }
  1023. }
  1024. /**
  1025. * Find the element corresponding to the coordinates in the passed mouse
  1026. * event. Please note that this is not always the same as the target of the
  1027. * event e.g. if event capture is used.
  1028. *
  1029. * @param event
  1030. * the mouse event to get coordinates from
  1031. * @return the element at the coordinates of the event
  1032. */
  1033. public static Element getElementUnderMouse(NativeEvent event) {
  1034. int pageX = getTouchOrMouseClientX(event);
  1035. int pageY = getTouchOrMouseClientY(event);
  1036. return getElementFromPoint(pageX, pageY);
  1037. }
  1038. /**
  1039. * A helper method to return the client position from an event. Returns
  1040. * position from either first changed touch (if touch event) or from the
  1041. * event itself.
  1042. *
  1043. * @param event
  1044. * @return
  1045. */
  1046. public static int getTouchOrMouseClientY(Event event) {
  1047. if (isTouchEvent(event)) {
  1048. return event.getChangedTouches().get(0).getClientY();
  1049. } else {
  1050. return event.getClientY();
  1051. }
  1052. }
  1053. /**
  1054. *
  1055. * @see #getTouchOrMouseClientY(Event)
  1056. * @param currentGwtEvent
  1057. * @return
  1058. */
  1059. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  1060. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  1061. }
  1062. /**
  1063. * @see #getTouchOrMouseClientX(Event)
  1064. *
  1065. * @param event
  1066. * @return
  1067. */
  1068. public static int getTouchOrMouseClientX(NativeEvent event) {
  1069. return getTouchOrMouseClientX(Event.as(event));
  1070. }
  1071. public static boolean isTouchEvent(Event event) {
  1072. return event.getType().contains("touch");
  1073. }
  1074. public static boolean isTouchEvent(NativeEvent event) {
  1075. return isTouchEvent(Event.as(event));
  1076. }
  1077. public static void simulateClickFromTouchEvent(Event touchevent,
  1078. Widget widget) {
  1079. Touch touch = touchevent.getChangedTouches().get(0);
  1080. final NativeEvent createMouseUpEvent = Document.get()
  1081. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  1082. touch.getClientX(), touch.getClientY(), false, false,
  1083. false, false, NativeEvent.BUTTON_LEFT);
  1084. final NativeEvent createMouseDownEvent = Document.get()
  1085. .createMouseDownEvent(0, touch.getScreenX(),
  1086. touch.getScreenY(), touch.getClientX(),
  1087. touch.getClientY(), false, false, false, false,
  1088. NativeEvent.BUTTON_LEFT);
  1089. final NativeEvent createMouseClickEvent = Document.get()
  1090. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  1091. touch.getClientX(), touch.getClientY(), false, false,
  1092. false, false);
  1093. /*
  1094. * Get target with element from point as we want the actual element, not
  1095. * the one that sunk the event.
  1096. */
  1097. final Element target = getElementFromPoint(touch.getClientX(),
  1098. touch.getClientY());
  1099. /*
  1100. * Fixes infocusable form fields in Safari of iOS 5.x and some Android
  1101. * browsers.
  1102. */
  1103. Widget targetWidget = findWidget(target, null);
  1104. if (targetWidget instanceof com.google.gwt.user.client.ui.Focusable) {
  1105. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) targetWidget;
  1106. toBeFocusedWidget.setFocus(true);
  1107. } else if (targetWidget instanceof Focusable) {
  1108. ((Focusable) targetWidget).focus();
  1109. }
  1110. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  1111. public void execute() {
  1112. try {
  1113. target.dispatchEvent(createMouseDownEvent);
  1114. target.dispatchEvent(createMouseUpEvent);
  1115. target.dispatchEvent(createMouseClickEvent);
  1116. } catch (Exception e) {
  1117. }
  1118. }
  1119. });
  1120. }
  1121. /**
  1122. * Gets the currently focused element for Internet Explorer.
  1123. *
  1124. * @return The currently focused element
  1125. */
  1126. public native static Element getIEFocusedElement()
  1127. /*-{
  1128. if ($wnd.document.activeElement) {
  1129. return $wnd.document.activeElement;
  1130. }
  1131. return null;
  1132. }-*/
  1133. ;
  1134. /**
  1135. * Kind of stronger version of isAttached(). In addition to std isAttached,
  1136. * this method checks that this widget nor any of its parents is hidden. Can
  1137. * be e.g used to check whether component should react to some events or
  1138. * not.
  1139. *
  1140. * @param widget
  1141. * @return true if attached and displayed
  1142. */
  1143. public static boolean isAttachedAndDisplayed(Widget widget) {
  1144. if (widget.isAttached()) {
  1145. /*
  1146. * Failfast using offset size, then by iterating the widget tree
  1147. */
  1148. boolean notZeroSized = widget.getOffsetHeight() > 0
  1149. || widget.getOffsetWidth() > 0;
  1150. return notZeroSized || checkVisibilityRecursively(widget);
  1151. } else {
  1152. return false;
  1153. }
  1154. }
  1155. private static boolean checkVisibilityRecursively(Widget widget) {
  1156. if (widget.isVisible()) {
  1157. Widget parent = widget.getParent();
  1158. if (parent == null) {
  1159. return true; // root panel
  1160. } else {
  1161. return checkVisibilityRecursively(parent);
  1162. }
  1163. } else {
  1164. return false;
  1165. }
  1166. }
  1167. /**
  1168. * Scrolls an element into view vertically only. Modified version of
  1169. * Element.scrollIntoView.
  1170. *
  1171. * @param elem
  1172. * The element to scroll into view
  1173. */
  1174. public static native void scrollIntoViewVertically(Element elem)
  1175. /*-{
  1176. var top = elem.offsetTop;
  1177. var height = elem.offsetHeight;
  1178. if (elem.parentNode != elem.offsetParent) {
  1179. top -= elem.parentNode.offsetTop;
  1180. }
  1181. var cur = elem.parentNode;
  1182. while (cur && (cur.nodeType == 1)) {
  1183. if (top < cur.scrollTop) {
  1184. cur.scrollTop = top;
  1185. }
  1186. if (top + height > cur.scrollTop + cur.clientHeight) {
  1187. cur.scrollTop = (top + height) - cur.clientHeight;
  1188. }
  1189. var offsetTop = cur.offsetTop;
  1190. if (cur.parentNode != cur.offsetParent) {
  1191. offsetTop -= cur.parentNode.offsetTop;
  1192. }
  1193. top += offsetTop - cur.scrollTop;
  1194. cur = cur.parentNode;
  1195. }
  1196. }-*/;
  1197. /**
  1198. * Checks if the given event is either a touch event or caused by the left
  1199. * mouse button
  1200. *
  1201. * @param event
  1202. * @return true if the event is a touch event or caused by the left mouse
  1203. * button, false otherwise
  1204. */
  1205. public static boolean isTouchEventOrLeftMouseButton(Event event) {
  1206. boolean touchEvent = Util.isTouchEvent(event);
  1207. return touchEvent || event.getButton() == Event.BUTTON_LEFT;
  1208. }
  1209. }