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

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