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.

WidgetUtil.java 58KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client;
  17. import java.io.Serializable;
  18. import java.util.HashMap;
  19. import java.util.Map;
  20. import java.util.logging.Logger;
  21. import com.google.gwt.core.client.JavaScriptObject;
  22. import com.google.gwt.core.client.Scheduler;
  23. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  24. import com.google.gwt.dom.client.AnchorElement;
  25. import com.google.gwt.dom.client.DivElement;
  26. import com.google.gwt.dom.client.Document;
  27. import com.google.gwt.dom.client.Element;
  28. import com.google.gwt.dom.client.NativeEvent;
  29. import com.google.gwt.dom.client.Node;
  30. import com.google.gwt.dom.client.NodeList;
  31. import com.google.gwt.dom.client.Style;
  32. import com.google.gwt.dom.client.Style.Unit;
  33. import com.google.gwt.dom.client.Touch;
  34. import com.google.gwt.event.dom.client.KeyEvent;
  35. import com.google.gwt.regexp.shared.MatchResult;
  36. import com.google.gwt.regexp.shared.RegExp;
  37. import com.google.gwt.user.client.Command;
  38. import com.google.gwt.user.client.DOM;
  39. import com.google.gwt.user.client.Event;
  40. import com.google.gwt.user.client.EventListener;
  41. import com.google.gwt.user.client.Window;
  42. import com.google.gwt.user.client.ui.RootPanel;
  43. import com.google.gwt.user.client.ui.Widget;
  44. import com.vaadin.shared.util.SharedUtil;
  45. /**
  46. * Utility methods which are related to client side code only
  47. */
  48. public class WidgetUtil {
  49. /**
  50. * Helper method for debugging purposes.
  51. *
  52. * Stops execution on firefox browsers on a breakpoint.
  53. *
  54. */
  55. public static native void browserDebugger()
  56. /*-{
  57. if($wnd.console)
  58. debugger;
  59. }-*/;
  60. /**
  61. * Redirects the browser to the given url or refreshes the page if url is
  62. * null
  63. *
  64. * @since 7.6
  65. * @param url
  66. * The url to redirect to or null to refresh
  67. */
  68. public static native void redirect(String url)
  69. /*-{
  70. if (url) {
  71. $wnd.location = url;
  72. } else {
  73. $wnd.location.reload(false);
  74. }
  75. }-*/;
  76. /**
  77. * Helper method for a bug fix #14041. For mozilla getKeyCode return 0 for
  78. * space bar (because space is considered as char). If return 0 use
  79. * getCharCode.
  80. *
  81. * @param event
  82. * @return return key code
  83. * @since 7.2.4
  84. */
  85. public static int getKeyCode(KeyEvent<?> event) {
  86. int keyCode = event.getNativeEvent().getKeyCode();
  87. if (keyCode == 0) {
  88. keyCode = event.getNativeEvent().getCharCode();
  89. }
  90. return keyCode;
  91. }
  92. /**
  93. *
  94. * Returns the topmost element of from given coordinates.
  95. *
  96. * TODO fix crossplat issues clientX vs pageX. See quircksmode. Not critical
  97. * for vaadin as we scroll div istead of page.
  98. *
  99. * @param x
  100. * @param y
  101. * @return the element at given coordinates
  102. */
  103. public static native Element getElementFromPoint(int clientX, int clientY)
  104. /*-{
  105. var el = $wnd.document.elementFromPoint(clientX, clientY);
  106. if(el != null && el.nodeType == 3) {
  107. el = el.parentNode;
  108. }
  109. return el;
  110. }-*/;
  111. public static float parseRelativeSize(String size) {
  112. if (size == null || !size.endsWith("%")) {
  113. return -1;
  114. }
  115. try {
  116. return Float.parseFloat(size.substring(0, size.length() - 1));
  117. } catch (Exception e) {
  118. getLogger().warning("Unable to parse relative size");
  119. return -1;
  120. }
  121. }
  122. private static final Element escapeHtmlHelper = DOM.createDiv();
  123. /**
  124. * Converts html entities to text.
  125. *
  126. * @param html
  127. * @return escaped string presentation of given html
  128. */
  129. public static String escapeHTML(String html) {
  130. DOM.setInnerText(escapeHtmlHelper, html);
  131. String escapedText = DOM.getInnerHTML(escapeHtmlHelper);
  132. return escapedText;
  133. }
  134. /**
  135. * Escapes the string so it is safe to write inside an HTML attribute.
  136. *
  137. * @param attribute
  138. * The string to escape
  139. * @return An escaped version of <literal>attribute</literal>.
  140. */
  141. public static String escapeAttribute(String attribute) {
  142. if (attribute == null) {
  143. return "";
  144. }
  145. attribute = attribute.replace("\"", "&quot;");
  146. attribute = attribute.replace("'", "&#39;");
  147. attribute = attribute.replace(">", "&gt;");
  148. attribute = attribute.replace("<", "&lt;");
  149. attribute = attribute.replace("&", "&amp;");
  150. return attribute;
  151. }
  152. /**
  153. * Clones given element as in JavaScript.
  154. *
  155. * Deprecate this if there appears similar method into GWT someday.
  156. *
  157. * @param element
  158. * @param deep
  159. * clone child tree also
  160. * @return
  161. */
  162. public static native Element cloneNode(Element element, boolean deep)
  163. /*-{
  164. return element.cloneNode(deep);
  165. }-*/;
  166. public static int measureHorizontalPaddingAndBorder(Element element,
  167. int paddingGuess) {
  168. String originalWidth = DOM.getStyleAttribute(element, "width");
  169. int originalOffsetWidth = element.getOffsetWidth();
  170. int widthGuess = (originalOffsetWidth - paddingGuess);
  171. if (widthGuess < 1) {
  172. widthGuess = 1;
  173. }
  174. element.getStyle().setWidth(widthGuess, Unit.PX);
  175. int padding = element.getOffsetWidth() - widthGuess;
  176. element.getStyle().setProperty("width", originalWidth);
  177. return padding;
  178. }
  179. public static int measureVerticalPaddingAndBorder(Element element,
  180. int paddingGuess) {
  181. String originalHeight = DOM.getStyleAttribute(element, "height");
  182. int originalOffsetHeight = element.getOffsetHeight();
  183. int widthGuess = (originalOffsetHeight - paddingGuess);
  184. if (widthGuess < 1) {
  185. widthGuess = 1;
  186. }
  187. element.getStyle().setHeight(widthGuess, Unit.PX);
  188. int padding = element.getOffsetHeight() - widthGuess;
  189. element.getStyle().setProperty("height", originalHeight);
  190. return padding;
  191. }
  192. public static int measureHorizontalBorder(Element element) {
  193. int borders;
  194. if (BrowserInfo.get().isIE()) {
  195. String width = element.getStyle().getProperty("width");
  196. String height = element.getStyle().getProperty("height");
  197. int offsetWidth = element.getOffsetWidth();
  198. int offsetHeight = element.getOffsetHeight();
  199. if (offsetHeight < 1) {
  200. offsetHeight = 1;
  201. }
  202. if (offsetWidth < 1) {
  203. offsetWidth = 10;
  204. }
  205. element.getStyle().setPropertyPx("height", offsetHeight);
  206. element.getStyle().setPropertyPx("width", offsetWidth);
  207. borders = element.getOffsetWidth() - element.getClientWidth();
  208. element.getStyle().setProperty("width", width);
  209. element.getStyle().setProperty("height", height);
  210. } else {
  211. borders = element.getOffsetWidth()
  212. - element.getPropertyInt("clientWidth");
  213. }
  214. assert borders >= 0;
  215. return borders;
  216. }
  217. public static int measureVerticalBorder(Element element) {
  218. int borders;
  219. if (BrowserInfo.get().isIE()) {
  220. String width = element.getStyle().getProperty("width");
  221. String height = element.getStyle().getProperty("height");
  222. int offsetWidth = element.getOffsetWidth();
  223. int offsetHeight = element.getOffsetHeight();
  224. if (offsetHeight < 1) {
  225. offsetHeight = 1;
  226. }
  227. if (offsetWidth < 1) {
  228. offsetWidth = 10;
  229. }
  230. element.getStyle().setPropertyPx("width", offsetWidth);
  231. element.getStyle().setPropertyPx("height", offsetHeight);
  232. borders = element.getOffsetHeight()
  233. - element.getPropertyInt("clientHeight");
  234. element.getStyle().setProperty("height", height);
  235. element.getStyle().setProperty("width", width);
  236. } else {
  237. borders = element.getOffsetHeight()
  238. - element.getPropertyInt("clientHeight");
  239. }
  240. assert borders >= 0;
  241. return borders;
  242. }
  243. public static int measureMarginLeft(Element element) {
  244. return element.getAbsoluteLeft()
  245. - element.getParentElement().getAbsoluteLeft();
  246. }
  247. public static int setHeightExcludingPaddingAndBorder(Widget widget,
  248. String height, int paddingBorderGuess) {
  249. if (height.equals("")) {
  250. setHeight(widget, "");
  251. return paddingBorderGuess;
  252. } else if (height.endsWith("px")) {
  253. int pixelHeight = Integer
  254. .parseInt(height.substring(0, height.length() - 2));
  255. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  256. pixelHeight, paddingBorderGuess, false);
  257. } else {
  258. // Set the height in unknown units
  259. setHeight(widget, height);
  260. // Use the offsetWidth
  261. return setHeightExcludingPaddingAndBorder(widget.getElement(),
  262. widget.getOffsetHeight(), paddingBorderGuess, true);
  263. }
  264. }
  265. private static void setWidth(Widget widget, String width) {
  266. widget.getElement().getStyle().setProperty("width", width);
  267. }
  268. private static void setHeight(Widget widget, String height) {
  269. widget.getElement().getStyle().setProperty("height", height);
  270. }
  271. public static int setWidthExcludingPaddingAndBorder(Widget widget,
  272. String width, int paddingBorderGuess) {
  273. if (width.equals("")) {
  274. setWidth(widget, "");
  275. return paddingBorderGuess;
  276. } else if (width.endsWith("px")) {
  277. int pixelWidth = Integer
  278. .parseInt(width.substring(0, width.length() - 2));
  279. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  280. pixelWidth, paddingBorderGuess, false);
  281. } else {
  282. setWidth(widget, width);
  283. return setWidthExcludingPaddingAndBorder(widget.getElement(),
  284. widget.getOffsetWidth(), paddingBorderGuess, true);
  285. }
  286. }
  287. public static int setWidthExcludingPaddingAndBorder(Element element,
  288. int requestedWidth, int horizontalPaddingBorderGuess,
  289. boolean requestedWidthIncludesPaddingBorder) {
  290. int widthGuess = requestedWidth - horizontalPaddingBorderGuess;
  291. if (widthGuess < 0) {
  292. widthGuess = 0;
  293. }
  294. element.getStyle().setWidth(widthGuess, Unit.PX);
  295. int captionOffsetWidth = DOM.getElementPropertyInt(element,
  296. "offsetWidth");
  297. int actualPadding = captionOffsetWidth - widthGuess;
  298. if (requestedWidthIncludesPaddingBorder) {
  299. actualPadding += actualPadding;
  300. }
  301. if (actualPadding != horizontalPaddingBorderGuess) {
  302. int w = requestedWidth - actualPadding;
  303. if (w < 0) {
  304. // Cannot set negative width even if we would want to
  305. w = 0;
  306. }
  307. element.getStyle().setWidth(w, Unit.PX);
  308. }
  309. return actualPadding;
  310. }
  311. public static int setHeightExcludingPaddingAndBorder(Element element,
  312. int requestedHeight, int verticalPaddingBorderGuess,
  313. boolean requestedHeightIncludesPaddingBorder) {
  314. int heightGuess = requestedHeight - verticalPaddingBorderGuess;
  315. if (heightGuess < 0) {
  316. heightGuess = 0;
  317. }
  318. element.getStyle().setHeight(heightGuess, Unit.PX);
  319. int captionOffsetHeight = DOM.getElementPropertyInt(element,
  320. "offsetHeight");
  321. int actualPadding = captionOffsetHeight - heightGuess;
  322. if (requestedHeightIncludesPaddingBorder) {
  323. actualPadding += actualPadding;
  324. }
  325. if (actualPadding != verticalPaddingBorderGuess) {
  326. int h = requestedHeight - actualPadding;
  327. if (h < 0) {
  328. // Cannot set negative height even if we would want to
  329. h = 0;
  330. }
  331. element.getStyle().setHeight(h, Unit.PX);
  332. }
  333. return actualPadding;
  334. }
  335. public static void setFloat(Element element, String value) {
  336. if (BrowserInfo.get().isIE()) {
  337. element.getStyle().setProperty("styleFloat", value);
  338. } else {
  339. element.getStyle().setProperty("cssFloat", value);
  340. }
  341. }
  342. private static int detectedScrollbarSize = -1;
  343. private static int detectedSubPixelRoundingFactor = -1;
  344. public static int getNativeScrollbarSize() {
  345. if (detectedScrollbarSize < 0) {
  346. Element scroller = DOM.createDiv();
  347. scroller.getStyle().setProperty("width", "50px");
  348. scroller.getStyle().setProperty("height", "50px");
  349. scroller.getStyle().setProperty("overflow", "scroll");
  350. scroller.getStyle().setProperty("position", "absolute");
  351. scroller.getStyle().setProperty("marginLeft", "-5000px");
  352. RootPanel.getBodyElement().appendChild(scroller);
  353. detectedScrollbarSize = scroller.getOffsetWidth()
  354. - scroller.getPropertyInt("clientWidth");
  355. RootPanel.getBodyElement().removeChild(scroller);
  356. }
  357. return detectedScrollbarSize;
  358. }
  359. /**
  360. * Defers the execution of {@link #runWebkitOverflowAutoFix(Element)}
  361. *
  362. * @since 7.2.6
  363. * @param elem
  364. * with overflow auto
  365. */
  366. public static void runWebkitOverflowAutoFixDeferred(final Element elem) {
  367. Scheduler.get().scheduleDeferred(new Command() {
  368. @Override
  369. public void execute() {
  370. WidgetUtil.runWebkitOverflowAutoFix(elem);
  371. }
  372. });
  373. }
  374. /**
  375. * Run workaround for webkits overflow auto issue.
  376. *
  377. * See: our bug #2138 and https://bugs.webkit.org/show_bug.cgi?id=21462
  378. *
  379. * @param elem
  380. * with overflow auto
  381. */
  382. public static void runWebkitOverflowAutoFix(final Element elem) {
  383. // Add max version if fix lands sometime to Webkit
  384. // Starting from Opera 11.00, also a problem in Opera
  385. if (BrowserInfo.get().requiresOverflowAutoFix()) {
  386. final String originalOverflow = elem.getStyle()
  387. .getProperty("overflow");
  388. final String originalOverflowX = elem.getStyle()
  389. .getProperty("overflowX");
  390. final String originalOverflowY = elem.getStyle()
  391. .getProperty("overflowY");
  392. if ("hidden".equals(originalOverflow)
  393. || "hidden".equals(originalOverflowX)
  394. || "hidden".equals(originalOverflowY)) {
  395. return;
  396. }
  397. // check the scrolltop value before hiding the element
  398. final int scrolltop = elem.getScrollTop();
  399. final int scrollleft = elem.getScrollLeft();
  400. elem.getStyle().setProperty("overflow", "hidden");
  401. Scheduler.get().scheduleDeferred(new Command() {
  402. @Override
  403. public void execute() {
  404. // Dough, Safari scroll auto means actually just a moped
  405. elem.getStyle().setProperty("overflow", originalOverflow);
  406. if (!originalOverflowX.isEmpty()) {
  407. elem.getStyle().setProperty("overflowX",
  408. originalOverflowX);
  409. }
  410. if (!originalOverflowY.isEmpty()) {
  411. elem.getStyle().setProperty("overflowY",
  412. originalOverflowY);
  413. }
  414. if (scrolltop > 0 || elem.getScrollTop() > 0) {
  415. int scrollvalue = scrolltop;
  416. if (scrollvalue == 0) {
  417. // mysterious are the ways of webkits scrollbar
  418. // handling. In some cases webkit reports bad (0)
  419. // scrolltop before hiding the element temporary,
  420. // sometimes after.
  421. scrollvalue = elem.getScrollTop();
  422. }
  423. // fix another bug where scrollbar remains in wrong
  424. // position
  425. elem.setScrollTop(scrollvalue - 1);
  426. elem.setScrollTop(scrollvalue);
  427. }
  428. // fix for #6940 : Table horizontal scroll sometimes not
  429. // updated when collapsing/expanding columns
  430. // Also appeared in Safari 5.1 with webkit 534 (#7667)
  431. if ((BrowserInfo.get().isChrome() || (BrowserInfo.get()
  432. .isSafari()
  433. && BrowserInfo.get().getWebkitVersion() >= 534))
  434. && (scrollleft > 0 || elem.getScrollLeft() > 0)) {
  435. int scrollvalue = scrollleft;
  436. if (scrollvalue == 0) {
  437. // mysterious are the ways of webkits scrollbar
  438. // handling. In some cases webkit may report a bad
  439. // (0) scrollleft before hiding the element
  440. // temporary, sometimes after.
  441. scrollvalue = elem.getScrollLeft();
  442. }
  443. // fix another bug where scrollbar remains in wrong
  444. // position
  445. elem.setScrollLeft(scrollvalue - 1);
  446. elem.setScrollLeft(scrollvalue);
  447. }
  448. }
  449. });
  450. }
  451. }
  452. public static void alert(String string) {
  453. if (true) {
  454. Window.alert(string);
  455. }
  456. }
  457. /**
  458. * Gets the border-box width for the given element, i.e. element width +
  459. * border + padding. Always rounds up to nearest integer.
  460. *
  461. * @param element
  462. * The element to check
  463. * @return The border-box width for the element
  464. */
  465. public static int getRequiredWidth(
  466. com.google.gwt.dom.client.Element element) {
  467. int reqWidth = getRequiredWidthBoundingClientRect(element);
  468. if (BrowserInfo.get().isIE()) {
  469. int csSize = getRequiredWidthComputedStyle(element);
  470. if (csSize == reqWidth + 1) {
  471. // If computed style reports one pixel larger than requiredWidth
  472. // we would be rounding in the wrong direction in IE9. Round up
  473. // instead.
  474. // We do not always use csSize as it e.g. for 100% wide Labels
  475. // in GridLayouts produces senseless values (see e.g.
  476. // ThemeTestUI with Runo).
  477. return csSize;
  478. }
  479. }
  480. return reqWidth;
  481. }
  482. /**
  483. * Gets the border-box width for the given element, i.e. element width +
  484. * border + padding.
  485. *
  486. * @since 7.5.1
  487. * @param element
  488. * The element to check
  489. * @return The border-box width for the element
  490. */
  491. public static double getRequiredWidthDouble(
  492. com.google.gwt.dom.client.Element element) {
  493. double reqWidth = getRequiredWidthBoundingClientRectDouble(element);
  494. if (BrowserInfo.get().isIE()) {
  495. double csWidth = getRequiredWidthComputedStyleDouble(element);
  496. if (csWidth > reqWidth && csWidth <= (reqWidth + 1)) {
  497. // IE9 rounds reqHeight to integers BUT sometimes reports wrong
  498. // csHeight it seems, so we only use csHeight if it is within a
  499. // rounding error
  500. return csWidth;
  501. }
  502. }
  503. return reqWidth;
  504. }
  505. /**
  506. * Gets the border-box height for the given element, i.e. element height +
  507. * border + padding. Always rounds up to nearest integer.
  508. *
  509. * @param element
  510. * The element to check
  511. * @return The border-box height for the element
  512. */
  513. public static int getRequiredHeight(
  514. com.google.gwt.dom.client.Element element) {
  515. int reqHeight = getRequiredHeightBoundingClientRect(element);
  516. if (BrowserInfo.get().isIE()) {
  517. int csSize = getRequiredHeightComputedStyle(element);
  518. if (csSize == reqHeight + 1) {
  519. // If computed style reports one pixel larger than
  520. // requiredHeight we would be rounding in the wrong direction in
  521. // IE9. Round up instead.
  522. // We do not always use csSize as it e.g. for 100% wide Labels
  523. // in GridLayouts produces senseless values (see e.g.
  524. // ThemeTestUI with Runo).
  525. return csSize;
  526. }
  527. }
  528. return reqHeight;
  529. }
  530. /**
  531. * Gets the border-box height for the given element, i.e. element height +
  532. * border + padding.
  533. *
  534. * @since 7.5.1
  535. * @param element
  536. * The element to check
  537. * @return The border-box height for the element
  538. */
  539. public static double getRequiredHeightDouble(
  540. com.google.gwt.dom.client.Element element) {
  541. double reqHeight = getRequiredHeightBoundingClientRectDouble(element);
  542. if (BrowserInfo.get().isIE()) {
  543. double csHeight = getRequiredHeightComputedStyleDouble(element);
  544. if (csHeight > reqHeight && csHeight <= (reqHeight + 1)) {
  545. // IE9 rounds reqHeight to integers BUT sometimes reports wrong
  546. // csHeight it seems, so we only use csHeight if it is within a
  547. // rounding error
  548. // Although sometimes it also happens that IE9 returns an
  549. // incorrectly rounded down requiredHeight and a computed height
  550. // which is exactly one larger, hence the "<="...
  551. return csHeight;
  552. }
  553. }
  554. return reqHeight;
  555. }
  556. /**
  557. * Calculates the width of the element's bounding rectangle.
  558. * <p>
  559. * In case the browser doesn't support bounding rectangles, the returned
  560. * value is the offset width.
  561. *
  562. * @param element
  563. * the element of which to calculate the width
  564. * @return the width of the element
  565. */
  566. public static int getRequiredWidthBoundingClientRect(
  567. com.google.gwt.dom.client.Element element) {
  568. return (int) Math
  569. .ceil(getRequiredWidthBoundingClientRectDouble(element));
  570. }
  571. /**
  572. * Calculates the width of the element's bounding rectangle to subpixel
  573. * precision.
  574. * <p>
  575. * In case the browser doesn't support bounding rectangles, the returned
  576. * value is the offset width.
  577. *
  578. * @param element
  579. * the element of which to calculate the width
  580. * @return the subpixel-accurate width of the element
  581. * @since 7.4
  582. */
  583. public static native double getRequiredWidthBoundingClientRectDouble(
  584. com.google.gwt.dom.client.Element element)
  585. /*-{
  586. if (element.getBoundingClientRect) {
  587. var rect = element.getBoundingClientRect();
  588. return rect.right - rect.left;
  589. } else {
  590. return element.offsetWidth;
  591. }
  592. }-*/;
  593. public static int getRequiredHeightComputedStyle(
  594. com.google.gwt.dom.client.Element element) {
  595. return (int) Math.ceil(getRequiredHeightComputedStyleDouble(element));
  596. }
  597. public static native double getRequiredHeightComputedStyleDouble(
  598. com.google.gwt.dom.client.Element element)
  599. /*-{
  600. var cs = element.ownerDocument.defaultView.getComputedStyle(element);
  601. var heightPx = cs.height;
  602. if(heightPx == 'auto'){
  603. // Fallback for inline elements
  604. return @com.vaadin.client.WidgetUtil::getRequiredHeightBoundingClientRectDouble(Lcom/google/gwt/dom/client/Element;)(element);
  605. }
  606. var height = parseFloat(heightPx); // Will automatically skip "px" suffix
  607. var border = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth); // Will automatically skip "px" suffix
  608. var padding = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom); // Will automatically skip "px" suffix
  609. return height+border+padding;
  610. }-*/;
  611. public static int getRequiredWidthComputedStyle(
  612. com.google.gwt.dom.client.Element element) {
  613. return (int) Math.ceil(getRequiredWidthComputedStyleDouble(element));
  614. }
  615. public static native int getRequiredWidthComputedStyleDouble(
  616. com.google.gwt.dom.client.Element element)
  617. /*-{
  618. var cs = element.ownerDocument.defaultView.getComputedStyle(element);
  619. var widthPx = cs.width;
  620. if(widthPx == 'auto'){
  621. // Fallback for inline elements
  622. return @com.vaadin.client.WidgetUtil::getRequiredWidthBoundingClientRectDouble(Lcom/google/gwt/dom/client/Element;)(element);
  623. }
  624. var width = parseFloat(widthPx); // Will automatically skip "px" suffix
  625. var border = parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth); // Will automatically skip "px" suffix
  626. var padding = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight); // Will automatically skip "px" suffix
  627. return width+border+padding;
  628. }-*/;
  629. /**
  630. * Calculates the height of the element's bounding rectangle.
  631. * <p>
  632. * In case the browser doesn't support bounding rectangles, the returned
  633. * value is the offset height.
  634. *
  635. * @param element
  636. * the element of which to calculate the height
  637. * @return the height of the element
  638. */
  639. public static int getRequiredHeightBoundingClientRect(
  640. com.google.gwt.dom.client.Element element) {
  641. return (int) Math
  642. .ceil(getRequiredHeightBoundingClientRectDouble(element));
  643. }
  644. /**
  645. * Calculates the height of the element's bounding rectangle to subpixel
  646. * precision.
  647. * <p>
  648. * In case the browser doesn't support bounding rectangles, the returned
  649. * value is the offset height.
  650. *
  651. * @param element
  652. * the element of which to calculate the height
  653. * @return the subpixel-accurate height of the element
  654. * @since 7.4
  655. */
  656. public static native double getRequiredHeightBoundingClientRectDouble(
  657. com.google.gwt.dom.client.Element element)
  658. /*-{
  659. var height;
  660. if (element.getBoundingClientRect != null) {
  661. var rect = element.getBoundingClientRect();
  662. height = rect.bottom - rect.top;
  663. } else {
  664. height = element.offsetHeight;
  665. }
  666. return height;
  667. }-*/;
  668. public static int getRequiredWidth(Widget widget) {
  669. return getRequiredWidth(widget.getElement());
  670. }
  671. public static int getRequiredHeight(Widget widget) {
  672. return getRequiredHeight(widget.getElement());
  673. }
  674. /**
  675. * Detects what is currently the overflow style attribute in given element.
  676. *
  677. * @param pe
  678. * the element to detect
  679. * @return true if auto or scroll
  680. */
  681. public static boolean mayHaveScrollBars(
  682. com.google.gwt.dom.client.Element pe) {
  683. String overflow = getComputedStyle(pe, "overflow");
  684. if (overflow != null) {
  685. if (overflow.equals("auto") || overflow.equals("scroll")) {
  686. return true;
  687. } else {
  688. return false;
  689. }
  690. } else {
  691. return false;
  692. }
  693. }
  694. /**
  695. * A simple helper method to detect "computed style" (aka style sheets +
  696. * element styles). Values returned differ a lot depending on browsers.
  697. * Always be very careful when using this.
  698. *
  699. * @param el
  700. * the element from which the style property is detected
  701. * @param p
  702. * the property to detect
  703. * @return String value of style property
  704. */
  705. private static native String getComputedStyle(
  706. com.google.gwt.dom.client.Element el, String p)
  707. /*-{
  708. try {
  709. if (el.currentStyle) {
  710. // IE
  711. return el.currentStyle[p];
  712. } else if (window.getComputedStyle) {
  713. // Sa, FF, Opera
  714. var view = el.ownerDocument.defaultView;
  715. return view.getComputedStyle(el,null).getPropertyValue(p);
  716. } else {
  717. // fall back for non IE, Sa, FF, Opera
  718. return "";
  719. }
  720. } catch (e) {
  721. return "";
  722. }
  723. }-*/;
  724. /**
  725. * Will (attempt) to focus the given DOM Element.
  726. *
  727. * @param el
  728. * the element to focus
  729. */
  730. public static native void focus(Element el)
  731. /*-{
  732. try {
  733. el.focus();
  734. } catch (e) {
  735. }
  736. }-*/;
  737. /**
  738. * Helper method to find first instance of given Widget type found by
  739. * traversing DOM upwards from given element.
  740. * <p>
  741. * <strong>Note:</strong> If {@code element} is inside some widget {@code W}
  742. * , <em>and</em> {@code W} in turn is wrapped in a {@link Composite}
  743. * {@code C}, this method will not find {@code W}. It returns either
  744. * {@code C} or null, depending on whether the class parameter matches. This
  745. * may also be the case with other Composite-like classes that hijack the
  746. * event handling of their child widget(s).
  747. *
  748. * @param element
  749. * the element where to start seeking of Widget
  750. * @param class1
  751. * the Widget type to seek for
  752. */
  753. @SuppressWarnings("unchecked")
  754. public static <T> T findWidget(Element element,
  755. Class<? extends Widget> class1) {
  756. if (element != null) {
  757. /* First seek for the first EventListener (~Widget) from dom */
  758. EventListener eventListener = null;
  759. while (eventListener == null && element != null) {
  760. eventListener = Event.getEventListener(element);
  761. if (eventListener == null) {
  762. element = element.getParentElement();
  763. }
  764. }
  765. if (eventListener instanceof Widget) {
  766. /*
  767. * Then find the first widget of type class1 from widget
  768. * hierarchy
  769. */
  770. Widget w = (Widget) eventListener;
  771. while (w != null) {
  772. if (class1 == null || w.getClass() == class1) {
  773. return (T) w;
  774. }
  775. w = w.getParent();
  776. }
  777. }
  778. }
  779. return null;
  780. }
  781. /**
  782. * Force webkit to redraw an element
  783. *
  784. * @param element
  785. * The element that should be redrawn
  786. */
  787. public static void forceWebkitRedraw(Element element) {
  788. Style style = element.getStyle();
  789. String s = style.getProperty("webkitTransform");
  790. if (s == null || s.length() == 0) {
  791. style.setProperty("webkitTransform", "scale(1)");
  792. } else {
  793. style.setProperty("webkitTransform", "");
  794. }
  795. }
  796. /**
  797. * Performs a hack to trigger a re-layout in the IE browser. This is usually
  798. * necessary in cases where IE "forgets" to update child elements when they
  799. * resize.
  800. *
  801. * @since 7.3
  802. * @param e
  803. * The element to perform the hack on
  804. */
  805. public static void forceIERedraw(Element e) {
  806. if (BrowserInfo.get().isIE()) {
  807. setStyleTemporarily(e, "zoom", "1");
  808. }
  809. }
  810. /**
  811. * Detaches and re-attaches the element from its parent. The element is
  812. * reattached at the same position in the DOM as it was before.
  813. *
  814. * Does nothing if the element is not attached to the DOM.
  815. *
  816. * @param element
  817. * The element to detach and re-attach
  818. */
  819. public static void detachAttach(Element element) {
  820. if (element == null) {
  821. return;
  822. }
  823. Node nextSibling = element.getNextSibling();
  824. Node parent = element.getParentNode();
  825. if (parent == null) {
  826. return;
  827. }
  828. parent.removeChild(element);
  829. if (nextSibling == null) {
  830. parent.appendChild(element);
  831. } else {
  832. parent.insertBefore(element, nextSibling);
  833. }
  834. }
  835. public static void sinkOnloadForImages(Element element) {
  836. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  837. .getElementsByTagName("img");
  838. for (int i = 0; i < imgElements.getLength(); i++) {
  839. DOM.sinkEvents(imgElements.getItem(i), Event.ONLOAD);
  840. }
  841. }
  842. /**
  843. * Returns the index of the childElement within its parent.
  844. *
  845. * @param subElement
  846. * @return
  847. */
  848. public static int getChildElementIndex(Element childElement) {
  849. int idx = 0;
  850. Node n = childElement;
  851. while ((n = n.getPreviousSibling()) != null) {
  852. idx++;
  853. }
  854. return idx;
  855. }
  856. /**
  857. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  858. * resets it to its current value. Used mainly to work around rendering
  859. * issues in IE (and possibly in other browsers)
  860. *
  861. * @param element
  862. * The target element
  863. * @param styleProperty
  864. * The name of the property to set
  865. * @param tempValue
  866. * The temporary value
  867. */
  868. public static void setStyleTemporarily(Element element,
  869. final String styleProperty, String tempValue) {
  870. final Style style = element.getStyle();
  871. final String currentValue = style.getProperty(styleProperty);
  872. style.setProperty(styleProperty, tempValue);
  873. // Read a style-based property to force the browser to recalculate the
  874. // element's dimensions with the temporary style.
  875. element.getOffsetWidth();
  876. style.setProperty(styleProperty, currentValue);
  877. }
  878. /**
  879. * A helper method to return the client position from an event. Returns
  880. * position from either first changed touch (if touch event) or from the
  881. * event itself.
  882. *
  883. * @param event
  884. * @return
  885. */
  886. public static int getTouchOrMouseClientX(Event event) {
  887. if (isTouchEvent(event)) {
  888. return event.getChangedTouches().get(0).getClientX();
  889. } else {
  890. return event.getClientX();
  891. }
  892. }
  893. /**
  894. * Find the element corresponding to the coordinates in the passed mouse
  895. * event. Please note that this is not always the same as the target of the
  896. * event e.g. if event capture is used.
  897. *
  898. * @param event
  899. * the mouse event to get coordinates from
  900. * @return the element at the coordinates of the event
  901. */
  902. public static Element getElementUnderMouse(NativeEvent event) {
  903. int pageX = getTouchOrMouseClientX(event);
  904. int pageY = getTouchOrMouseClientY(event);
  905. return getElementFromPoint(pageX, pageY);
  906. }
  907. /**
  908. * A helper method to return the client position from an event. Returns
  909. * position from either first changed touch (if touch event) or from the
  910. * event itself.
  911. *
  912. * @param event
  913. * @return
  914. */
  915. public static int getTouchOrMouseClientY(Event event) {
  916. if (isTouchEvent(event)) {
  917. return event.getChangedTouches().get(0).getClientY();
  918. } else {
  919. return event.getClientY();
  920. }
  921. }
  922. /**
  923. *
  924. * @see #getTouchOrMouseClientY(Event)
  925. * @param currentGwtEvent
  926. * @return
  927. */
  928. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  929. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  930. }
  931. /**
  932. * @see #getTouchOrMouseClientX(Event)
  933. *
  934. * @param event
  935. * @return
  936. */
  937. public static int getTouchOrMouseClientX(NativeEvent event) {
  938. return getTouchOrMouseClientX(Event.as(event));
  939. }
  940. public static boolean isTouchEvent(Event event) {
  941. return event.getType().contains("touch");
  942. }
  943. public static boolean isTouchEvent(NativeEvent event) {
  944. return isTouchEvent(Event.as(event));
  945. }
  946. public static void simulateClickFromTouchEvent(Event touchevent,
  947. Widget widget) {
  948. Touch touch = touchevent.getChangedTouches().get(0);
  949. final NativeEvent createMouseUpEvent = Document.get()
  950. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  951. touch.getClientX(), touch.getClientY(), false, false,
  952. false, false, NativeEvent.BUTTON_LEFT);
  953. final NativeEvent createMouseDownEvent = Document.get()
  954. .createMouseDownEvent(0, touch.getScreenX(), touch.getScreenY(),
  955. touch.getClientX(), touch.getClientY(), false, false,
  956. false, false, NativeEvent.BUTTON_LEFT);
  957. final NativeEvent createMouseClickEvent = Document.get()
  958. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  959. touch.getClientX(), touch.getClientY(), false, false,
  960. false, false);
  961. /*
  962. * Get target with element from point as we want the actual element, not
  963. * the one that sunk the event.
  964. */
  965. final Element target = getElementFromPoint(touch.getClientX(),
  966. touch.getClientY());
  967. /*
  968. * Fixes infocusable form fields in Safari of iOS 5.x and some Android
  969. * browsers.
  970. */
  971. Widget targetWidget = findWidget(target, null);
  972. if (targetWidget instanceof com.google.gwt.user.client.ui.Focusable) {
  973. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) targetWidget;
  974. toBeFocusedWidget.setFocus(true);
  975. } else if (targetWidget instanceof Focusable) {
  976. ((Focusable) targetWidget).focus();
  977. }
  978. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  979. @Override
  980. public void execute() {
  981. try {
  982. target.dispatchEvent(createMouseDownEvent);
  983. target.dispatchEvent(createMouseUpEvent);
  984. target.dispatchEvent(createMouseClickEvent);
  985. } catch (Exception e) {
  986. }
  987. }
  988. });
  989. }
  990. /**
  991. * Gets the currently focused element.
  992. *
  993. * @return The active element or null if no active element could be found.
  994. */
  995. public native static Element getFocusedElement()
  996. /*-{
  997. if ($wnd.document.activeElement) {
  998. return $wnd.document.activeElement;
  999. }
  1000. return null;
  1001. }-*/;
  1002. /**
  1003. * Gets currently focused element and checks if it's editable
  1004. *
  1005. * @since 7.4
  1006. *
  1007. * @return true if focused element is editable
  1008. */
  1009. public static boolean isFocusedElementEditable() {
  1010. Element focusedElement = WidgetUtil.getFocusedElement();
  1011. if (focusedElement != null) {
  1012. String tagName = focusedElement.getTagName();
  1013. String contenteditable = focusedElement
  1014. .getAttribute("contenteditable");
  1015. return "textarea".equalsIgnoreCase(tagName)
  1016. || "input".equalsIgnoreCase(tagName)
  1017. || "true".equalsIgnoreCase(contenteditable);
  1018. }
  1019. return false;
  1020. }
  1021. /**
  1022. * Kind of stronger version of isAttached(). In addition to std isAttached,
  1023. * this method checks that this widget nor any of its parents is hidden. Can
  1024. * be e.g used to check whether component should react to some events or
  1025. * not.
  1026. *
  1027. * @param widget
  1028. * @return true if attached and displayed
  1029. */
  1030. public static boolean isAttachedAndDisplayed(Widget widget) {
  1031. if (widget.isAttached()) {
  1032. /*
  1033. * Failfast using offset size, then by iterating the widget tree
  1034. */
  1035. boolean notZeroSized = widget.getOffsetHeight() > 0
  1036. || widget.getOffsetWidth() > 0;
  1037. return notZeroSized || checkVisibilityRecursively(widget);
  1038. } else {
  1039. return false;
  1040. }
  1041. }
  1042. private static boolean checkVisibilityRecursively(Widget widget) {
  1043. if (widget.isVisible()) {
  1044. Widget parent = widget.getParent();
  1045. if (parent == null) {
  1046. return true; // root panel
  1047. } else {
  1048. return checkVisibilityRecursively(parent);
  1049. }
  1050. } else {
  1051. return false;
  1052. }
  1053. }
  1054. /**
  1055. * Scrolls an element into view vertically only. Modified version of
  1056. * Element.scrollIntoView.
  1057. *
  1058. * @param elem
  1059. * The element to scroll into view
  1060. */
  1061. public static native void scrollIntoViewVertically(Element elem)
  1062. /*-{
  1063. var top = elem.offsetTop;
  1064. var height = elem.offsetHeight;
  1065. if (elem.parentNode != elem.offsetParent) {
  1066. top -= elem.parentNode.offsetTop;
  1067. }
  1068. var cur = elem.parentNode;
  1069. while (cur && (cur.nodeType == 1)) {
  1070. if (top < cur.scrollTop) {
  1071. cur.scrollTop = top;
  1072. }
  1073. if (top + height > cur.scrollTop + cur.clientHeight) {
  1074. cur.scrollTop = (top + height) - cur.clientHeight;
  1075. }
  1076. var offsetTop = cur.offsetTop;
  1077. if (cur.parentNode != cur.offsetParent) {
  1078. offsetTop -= cur.parentNode.offsetTop;
  1079. }
  1080. top += offsetTop - cur.scrollTop;
  1081. cur = cur.parentNode;
  1082. }
  1083. }-*/;
  1084. /**
  1085. * Checks if the given event is either a touch event or caused by the left
  1086. * mouse button
  1087. *
  1088. * @param event
  1089. * @return true if the event is a touch event or caused by the left mouse
  1090. * button, false otherwise
  1091. */
  1092. public static boolean isTouchEventOrLeftMouseButton(Event event) {
  1093. boolean touchEvent = WidgetUtil.isTouchEvent(event);
  1094. return touchEvent || event.getButton() == Event.BUTTON_LEFT;
  1095. }
  1096. /**
  1097. * Resolve a relative URL to an absolute URL based on the current document's
  1098. * location.
  1099. *
  1100. * @param url
  1101. * a string with the relative URL to resolve
  1102. * @return the corresponding absolute URL as a string
  1103. */
  1104. public static String getAbsoluteUrl(String url) {
  1105. AnchorElement a = Document.get().createAnchorElement();
  1106. a.setHref(url);
  1107. return a.getHref();
  1108. }
  1109. /**
  1110. * Sets the selection range of an input element.
  1111. *
  1112. * We need this JSNI function to set selection range so that we can use the
  1113. * optional direction attribute to set the anchor to the end and the focus
  1114. * to the start. This makes Firefox work the same way as other browsers
  1115. * (#13477)
  1116. *
  1117. * @param elem
  1118. * the html input element.
  1119. * @param pos
  1120. * the index of the first selected character.
  1121. * @param length
  1122. * the selection length.
  1123. * @param direction
  1124. * a string indicating the direction in which the selection was
  1125. * performed. This may be "forward" or "backward", or "none" if
  1126. * the direction is unknown or irrelevant.
  1127. *
  1128. * @since 7.3
  1129. */
  1130. public native static void setSelectionRange(Element elem, int pos,
  1131. int length, String direction)
  1132. /*-{
  1133. try {
  1134. elem.setSelectionRange(pos, pos + length, direction);
  1135. } catch (e) {
  1136. // Firefox throws exception if TextBox is not visible, even if attached
  1137. }
  1138. }-*/;
  1139. /**
  1140. * JavaScript hack to prevent text selection in various browsers.
  1141. *
  1142. * @since 7.6
  1143. * @param e
  1144. * element for enabling or disabling text selection
  1145. * @param enable
  1146. * <code>true</code> if selection is enabled; </code>false</code>
  1147. * if not
  1148. */
  1149. public native static void setTextSelectionEnabled(Element e, boolean enable)
  1150. /*-{
  1151. if (!enable) {
  1152. e.ondrag = function () { return false; };
  1153. e.onselectstart = function () { return false; };
  1154. e.style.webkitUserSelect = "none";
  1155. } else {
  1156. e.ondrag = null;
  1157. e.onselectstart = null;
  1158. e.style.webkitUserSelect = "text";
  1159. }
  1160. }-*/;
  1161. /**
  1162. * JavaScript hack to clear text selection in various browsers.
  1163. *
  1164. * @since 7.6
  1165. */
  1166. public native static void clearTextSelection()
  1167. /*-{
  1168. if ($wnd.getSelection) {
  1169. $wnd.getSelection().removeAllRanges();
  1170. }
  1171. }-*/;
  1172. /**
  1173. * The allowed value inaccuracy when comparing two double-typed pixel
  1174. * values.
  1175. * <p>
  1176. * Since we're comparing pixels on a screen, epsilon must be less than 1.
  1177. * 0.49 was deemed a perfectly fine and beautifully round number.
  1178. */
  1179. public static final double PIXEL_EPSILON = 0.49d;
  1180. /**
  1181. * Compares two double values with the error margin of
  1182. * {@link #PIXEL_EPSILON} (i.e. {@value #PIXEL_EPSILON})
  1183. *
  1184. * @param num1
  1185. * the first value for which to compare equality
  1186. * @param num2
  1187. * the second value for which to compare equality
  1188. * @since 7.4
  1189. *
  1190. * @return true if the values are considered equals; false otherwise
  1191. */
  1192. public static boolean pixelValuesEqual(final double num1,
  1193. final double num2) {
  1194. return Math.abs(num1 - num2) <= PIXEL_EPSILON;
  1195. }
  1196. public static native TextRectangle getBoundingClientRect(Element e)
  1197. /*-{
  1198. return e.getBoundingClientRect();
  1199. }-*/;
  1200. public static final class TextRectangle extends JavaScriptObject {
  1201. protected TextRectangle() {
  1202. }
  1203. public native double getBottom()
  1204. /*-{
  1205. return this.bottom;
  1206. }-*/;
  1207. public native double getHeight()
  1208. /*-{
  1209. return this.height;
  1210. }-*/;
  1211. public native double getLeft()
  1212. /*-{
  1213. return this.left;
  1214. }-*/;
  1215. public native double getRight()
  1216. /*-{
  1217. return this.right;
  1218. }-*/;
  1219. public native double getTop()
  1220. /*-{
  1221. return this.top;
  1222. }-*/;
  1223. public native double getWidth()
  1224. /*-{
  1225. return this.width;
  1226. }-*/;
  1227. }
  1228. /**
  1229. * Wrap a css size value and its unit and translate back and forth to the
  1230. * string representation.<br/>
  1231. * Eg. 50%, 123px, ...
  1232. *
  1233. * @since 7.2.6
  1234. * @author Vaadin Ltd
  1235. */
  1236. @SuppressWarnings("serial")
  1237. public static class CssSize implements Serializable {
  1238. /*
  1239. * Map the size units with their type.
  1240. */
  1241. private static Map<String, Unit> type2Unit = new HashMap<>();
  1242. static {
  1243. for (Unit unit : Unit.values()) {
  1244. type2Unit.put(unit.getType(), unit);
  1245. }
  1246. }
  1247. /**
  1248. * Gets the unit value by its type.
  1249. *
  1250. * @param type
  1251. * the type of the unit as found in the style.
  1252. * @return the unit value.
  1253. */
  1254. public static Unit unitByType(String type) {
  1255. return type2Unit.get(type);
  1256. }
  1257. /*
  1258. * Regex to parse the size.
  1259. */
  1260. private static final RegExp sizePattern = RegExp
  1261. .compile(SharedUtil.SIZE_PATTERN);
  1262. /**
  1263. * Parse the size from string format to {@link CssSize}.
  1264. *
  1265. * @param s
  1266. * the size as string.
  1267. * @return a {@link CssSize} object.
  1268. */
  1269. public static CssSize fromString(String s) {
  1270. if (s == null) {
  1271. return null;
  1272. }
  1273. s = s.trim();
  1274. if ("".equals(s)) {
  1275. return null;
  1276. }
  1277. float size = 0;
  1278. Unit unit = null;
  1279. MatchResult matcher = sizePattern.exec(s);
  1280. if (matcher.getGroupCount() > 1) {
  1281. size = Float.parseFloat(matcher.getGroup(1));
  1282. if (size < 0) {
  1283. size = -1;
  1284. unit = Unit.PX;
  1285. } else {
  1286. String symbol = matcher.getGroup(2);
  1287. unit = unitByType(symbol);
  1288. }
  1289. } else {
  1290. throw new IllegalArgumentException(
  1291. "Invalid size argument: \"" + s + "\" (should match "
  1292. + sizePattern.getSource() + ")");
  1293. }
  1294. return new CssSize(size, unit);
  1295. }
  1296. /**
  1297. * Creates a {@link CssSize} using a value and its measurement unit.
  1298. *
  1299. * @param value
  1300. * the value.
  1301. * @param unit
  1302. * the unit.
  1303. * @return the {@link CssSize} object.
  1304. */
  1305. public static CssSize fromValueUnit(float value, Unit unit) {
  1306. return new CssSize(value, unit);
  1307. }
  1308. /*
  1309. * The value.
  1310. */
  1311. private final float value;
  1312. /*
  1313. * The measure unit.
  1314. */
  1315. private final Unit unit;
  1316. private CssSize(float value, Unit unit) {
  1317. this.value = value;
  1318. this.unit = unit;
  1319. }
  1320. /**
  1321. * Gets the value for this css size.
  1322. *
  1323. * @return the value.
  1324. */
  1325. public float getValue() {
  1326. return value;
  1327. }
  1328. /**
  1329. * Gets the measurement unit for this css size.
  1330. *
  1331. * @return the unit.
  1332. */
  1333. public Unit getUnit() {
  1334. return unit;
  1335. }
  1336. @Override
  1337. public String toString() {
  1338. return value + unit.getType();
  1339. }
  1340. @Override
  1341. public boolean equals(Object obj) {
  1342. if (obj instanceof CssSize) {
  1343. CssSize size = (CssSize) obj;
  1344. return size.value == value && size.unit == unit;
  1345. }
  1346. return false;
  1347. }
  1348. /**
  1349. * Check whether the two sizes are equals.
  1350. *
  1351. * @param cssSize1
  1352. * the first size to compare.
  1353. * @param cssSize2
  1354. * the other size to compare with the first one.
  1355. * @return true if the two sizes are equals, otherwise false.
  1356. */
  1357. public static boolean equals(String cssSize1, String cssSize2) {
  1358. return CssSize.fromString(cssSize1)
  1359. .equals(CssSize.fromString(cssSize2));
  1360. }
  1361. }
  1362. private static Logger getLogger() {
  1363. return Logger.getLogger(WidgetUtil.class.getName());
  1364. }
  1365. /**
  1366. * Returns the thickness of the given element's top border.
  1367. * <p>
  1368. * The value is determined using computed style when available and
  1369. * calculated otherwise.
  1370. *
  1371. * @since 7.5.0
  1372. * @param element
  1373. * the element to measure
  1374. * @return the top border thickness
  1375. */
  1376. public static double getBorderTopThickness(Element element) {
  1377. return getBorderThickness(element, new String[] { "borderTopWidth" });
  1378. }
  1379. /**
  1380. * Returns the thickness of the given element's bottom border.
  1381. * <p>
  1382. * The value is determined using computed style when available and
  1383. * calculated otherwise.
  1384. *
  1385. * @since 7.5.0
  1386. * @param element
  1387. * the element to measure
  1388. * @return the bottom border thickness
  1389. */
  1390. public static double getBorderBottomThickness(Element element) {
  1391. return getBorderThickness(element,
  1392. new String[] { "borderBottomWidth" });
  1393. }
  1394. /**
  1395. * Returns the combined thickness of the given element's top and bottom
  1396. * borders.
  1397. * <p>
  1398. * The value is determined using computed style when available and
  1399. * calculated otherwise.
  1400. *
  1401. * @since 7.5.0
  1402. * @param element
  1403. * the element to measure
  1404. * @return the top and bottom border thickness
  1405. */
  1406. public static double getBorderTopAndBottomThickness(Element element) {
  1407. return getBorderThickness(element,
  1408. new String[] { "borderTopWidth", "borderBottomWidth" });
  1409. }
  1410. /**
  1411. * Returns the thickness of the given element's left border.
  1412. * <p>
  1413. * The value is determined using computed style when available and
  1414. * calculated otherwise.
  1415. *
  1416. * @since 7.5.0
  1417. * @param element
  1418. * the element to measure
  1419. * @return the left border thickness
  1420. */
  1421. public static double getBorderLeftThickness(Element element) {
  1422. return getBorderThickness(element, new String[] { "borderLeftWidth" });
  1423. }
  1424. /**
  1425. * Returns the thickness of the given element's right border.
  1426. * <p>
  1427. * The value is determined using computed style when available and
  1428. * calculated otherwise.
  1429. *
  1430. * @since 7.5.0
  1431. * @param element
  1432. * the element to measure
  1433. * @return the right border thickness
  1434. */
  1435. public static double getBorderRightThickness(Element element) {
  1436. return getBorderThickness(element, new String[] { "borderRightWidth" });
  1437. }
  1438. /**
  1439. * Returns the thickness of the given element's left and right borders.
  1440. * <p>
  1441. * The value is determined using computed style when available and
  1442. * calculated otherwise.
  1443. *
  1444. * @since 7.5.0
  1445. * @param element
  1446. * the element to measure
  1447. * @return the top border thickness
  1448. */
  1449. public static double getBorderLeftAndRightThickness(Element element) {
  1450. return getBorderThickness(element,
  1451. new String[] { "borderLeftWidth", "borderRightWidth" });
  1452. }
  1453. private static native double getBorderThickness(
  1454. com.google.gwt.dom.client.Element element, String[] borderNames)
  1455. /*-{
  1456. if (typeof $wnd.getComputedStyle === 'function') {
  1457. var computedStyle = $wnd.getComputedStyle(element);
  1458. var width = 0;
  1459. for (i=0; i< borderNames.length; i++) {
  1460. var borderWidth = computedStyle[borderNames[i]];
  1461. width += parseFloat(borderWidth);
  1462. }
  1463. return width;
  1464. } else {
  1465. var parentElement = element.offsetParent;
  1466. var cloneElement = element.cloneNode(false);
  1467. cloneElement.style.boxSizing ="content-box";
  1468. parentElement.appendChild(cloneElement);
  1469. var heightWithBorder = cloneElement.offsetHeight;
  1470. for (i=0; i< borderNames.length; i++) {
  1471. cloneElement.style[borderNames[i]] = "0";
  1472. }
  1473. var heightWithoutBorder = cloneElement.offsetHeight;
  1474. parentElement.removeChild(cloneElement);
  1475. return heightWithBorder - heightWithoutBorder;
  1476. }
  1477. }-*/;
  1478. /**
  1479. * Rounds the given size up to a value which the browser will accept.
  1480. *
  1481. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1482. * (http://trac.webkit.org/wiki/LayoutUnit).
  1483. *
  1484. * Firefox uses 1/60th of a pixel because it is divisible by three
  1485. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1486. *
  1487. * @since 7.5.1
  1488. * @param size
  1489. * the value to round
  1490. * @return the rounded value
  1491. */
  1492. public static double roundSizeUp(double size) {
  1493. return roundSize(size, true);
  1494. }
  1495. /**
  1496. * Rounds the given size down to a value which the browser will accept.
  1497. *
  1498. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1499. * (http://trac.webkit.org/wiki/LayoutUnit).
  1500. *
  1501. * Firefox uses 1/60th of a pixel because it is divisible by three
  1502. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1503. *
  1504. * IE9+ uses 1/100th of a pixel
  1505. *
  1506. * @since 7.5.1
  1507. * @param size
  1508. * the value to round
  1509. * @return the rounded value
  1510. */
  1511. public static double roundSizeDown(double size) {
  1512. return roundSize(size, false);
  1513. }
  1514. private static double roundSize(double size, boolean roundUp) {
  1515. double factor = getSubPixelRoundingFactor();
  1516. if (factor < 0 || size < 0) {
  1517. return size;
  1518. }
  1519. if (roundUp) {
  1520. return roundSizeUp(size, factor);
  1521. } else {
  1522. return roundSizeDown(size, factor);
  1523. }
  1524. }
  1525. /**
  1526. * Returns the factor used by browsers to round subpixel values
  1527. *
  1528. * @since 7.5.1
  1529. * @return the factor N used by the browser when storing subpixels as X+Y/N
  1530. */
  1531. private static double getSubPixelRoundingFactor() {
  1532. // Detects how the browser does subpixel rounding
  1533. // Currently Firefox uses 1/60th pixels
  1534. // and Safari uses 1/64th pixels
  1535. // IE 1/100th pixels
  1536. if (detectedSubPixelRoundingFactor != -1) {
  1537. return detectedSubPixelRoundingFactor;
  1538. }
  1539. double probeSize = 0.999999;
  1540. DivElement div = Document.get().createDivElement();
  1541. Document.get().getBody().appendChild(div);
  1542. div.getStyle().setHeight(probeSize, Unit.PX);
  1543. ComputedStyle computedStyle = new ComputedStyle(div);
  1544. double computedHeight = computedStyle.getHeight();
  1545. if (computedHeight < probeSize) {
  1546. // Rounded down by browser, all browsers but Firefox do this
  1547. // today
  1548. detectedSubPixelRoundingFactor = (int) Math
  1549. .round(1.0 / (1.0 - computedHeight));
  1550. } else {
  1551. // Rounded up / to nearest by browser
  1552. probeSize = 1;
  1553. while (computedStyle.getHeight() != 0.0) {
  1554. computedHeight = computedStyle.getHeight();
  1555. probeSize /= 2.0;
  1556. div.getStyle().setHeight(probeSize, Unit.PX);
  1557. }
  1558. detectedSubPixelRoundingFactor = (int) Math
  1559. .round(1.0 / computedHeight);
  1560. }
  1561. div.removeFromParent();
  1562. return detectedSubPixelRoundingFactor;
  1563. }
  1564. private static double roundSizeUp(double size, double divisor) {
  1565. // In: 12.51, 60.0
  1566. // 12
  1567. double integerPart = (int) size;
  1568. // (12.51 - 12) * 60 = 30.6
  1569. double nrFractions = (size - integerPart) * divisor;
  1570. // 12 + ceil(30.6) / 60 = 12 + 31/60 = 12.51666
  1571. return integerPart + (Math.ceil(nrFractions)) / divisor;
  1572. }
  1573. private static double roundSizeDown(double size, double divisor) {
  1574. // In: 12.51, 60.0
  1575. // 12
  1576. double integerPart = (int) size;
  1577. // (12.51 - 12) * 60 = 30.6
  1578. double nrFractions = (size - integerPart) * divisor;
  1579. // 12 + int(30.6) / 60 = 12 + 30/60 = 12.5
  1580. return integerPart + ((int) nrFractions) / divisor;
  1581. }
  1582. }