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

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