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

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