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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  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.dom.client.AnchorElement;
  24. import com.google.gwt.dom.client.DivElement;
  25. import com.google.gwt.dom.client.Document;
  26. import com.google.gwt.dom.client.Element;
  27. import com.google.gwt.dom.client.NativeEvent;
  28. import com.google.gwt.dom.client.Node;
  29. import com.google.gwt.dom.client.NodeList;
  30. import com.google.gwt.dom.client.Style;
  31. import com.google.gwt.dom.client.Style.Unit;
  32. import com.google.gwt.dom.client.Touch;
  33. import com.google.gwt.event.dom.client.KeyEvent;
  34. import com.google.gwt.regexp.shared.MatchResult;
  35. import com.google.gwt.regexp.shared.RegExp;
  36. import com.google.gwt.user.client.Command;
  37. import com.google.gwt.user.client.DOM;
  38. import com.google.gwt.user.client.Event;
  39. import com.google.gwt.user.client.EventListener;
  40. import com.google.gwt.user.client.Window;
  41. import com.google.gwt.user.client.ui.RootPanel;
  42. import com.google.gwt.user.client.ui.Widget;
  43. import com.vaadin.shared.ui.ErrorLevel;
  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.isEmpty()) {
  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.isEmpty()) {
  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
  739. * {@link com.google.gwt.user.client.ui.Composite Composite} {@code C}, this
  740. * method will not find {@code W} but returns {@code C}. This may also be
  741. * the case with other Composite-like classes that hijack the event handling
  742. * of their child widget(s).
  743. *
  744. * @param element
  745. * the element where to start seeking of Widget
  746. * @since 8.1
  747. */
  748. @SuppressWarnings("unchecked")
  749. public static <T> T findWidget(Element element) {
  750. return findWidget(element, null);
  751. }
  752. /**
  753. * Helper method to find first instance of given Widget type found by
  754. * traversing DOM upwards from given element.
  755. * <p>
  756. * <strong>Note:</strong> If {@code element} is inside some widget {@code W}
  757. * , <em>and</em> {@code W} in turn is wrapped in a
  758. * {@link com.google.gwt.user.client.ui.Composite Composite} {@code C}, this
  759. * method will not find {@code W}. It returns either {@code C} or null,
  760. * depending on whether the class parameter matches. This may also be the
  761. * case with other Composite-like classes that hijack the event handling of
  762. * their child widget(s).
  763. * <p>
  764. * Only accepts the exact class {@code class1} if not null.
  765. *
  766. * @param element
  767. * the element where to start seeking of Widget
  768. * @param class1
  769. * the Widget type to seek for, null for any
  770. */
  771. @SuppressWarnings("unchecked")
  772. public static <T> T findWidget(Element element,
  773. Class<? extends Widget> class1) {
  774. return findWidget(element, class1, true);
  775. }
  776. /**
  777. * Helper method to find first instance of given Widget type found by
  778. * traversing DOM upwards from given element.
  779. * <p>
  780. * <strong>Note:</strong> If {@code element} is inside some widget {@code W}
  781. * , <em>and</em> {@code W} in turn is wrapped in a
  782. * {@link com.google.gwt.user.client.ui.Composite Composite} {@code C}, this
  783. * method will not find {@code W}. It returns either {@code C} or null,
  784. * depending on whether the class parameter matches. This may also be the
  785. * case with other Composite-like classes that hijack the event handling of
  786. * their child widget(s).
  787. *
  788. * @param element
  789. * the element where to start seeking of Widget
  790. * @param class1
  791. * the Widget type to seek for
  792. * @param exactMatch
  793. * true to only accept class1, false to also accept its
  794. * superclasses
  795. * @since 8.1
  796. */
  797. @SuppressWarnings("unchecked")
  798. public static <T> T findWidget(Element element,
  799. Class<? extends Widget> class1, boolean exactMatch) {
  800. if (element != null) {
  801. /* First seek for the first EventListener (~Widget) from dom */
  802. EventListener eventListener = null;
  803. while (eventListener == null && element != null) {
  804. eventListener = Event.getEventListener(element);
  805. if (eventListener == null) {
  806. element = element.getParentElement();
  807. }
  808. }
  809. if (eventListener instanceof Widget) {
  810. /*
  811. * Then find the first widget of type class1 from widget
  812. * hierarchy
  813. */
  814. Widget w = (Widget) eventListener;
  815. if (class1 == null && w != null) {
  816. return (T) w;
  817. }
  818. while (w != null) {
  819. Class<?> widgetClass = w.getClass();
  820. while (widgetClass != null) {
  821. if (widgetClass == class1) {
  822. return (T) w;
  823. }
  824. // terminate after first check if looking for exact
  825. // match
  826. widgetClass = exactMatch ? null
  827. : widgetClass.getSuperclass();
  828. }
  829. w = w.getParent();
  830. }
  831. }
  832. }
  833. return null;
  834. }
  835. /**
  836. * Force webkit to redraw an element.
  837. *
  838. * @param element
  839. * The element that should be redrawn
  840. */
  841. public static void forceWebkitRedraw(Element element) {
  842. Style style = element.getStyle();
  843. String s = style.getProperty("webkitTransform");
  844. if (s == null || s.isEmpty()) {
  845. style.setProperty("webkitTransform", "scale(1)");
  846. } else {
  847. style.setProperty("webkitTransform", "");
  848. }
  849. }
  850. /**
  851. * Performs a hack to trigger a re-layout in the IE browser. This is usually
  852. * necessary in cases where IE "forgets" to update child elements when they
  853. * resize.
  854. *
  855. * @since 7.3
  856. * @param e
  857. * The element to perform the hack on
  858. */
  859. public static void forceIERedraw(Element e) {
  860. if (BrowserInfo.get().isIE()) {
  861. setStyleTemporarily(e, "zoom", "1");
  862. }
  863. }
  864. /**
  865. * Detaches and re-attaches the element from its parent. The element is
  866. * reattached at the same position in the DOM as it was before.
  867. *
  868. * Does nothing if the element is not attached to the DOM.
  869. *
  870. * @param element
  871. * The element to detach and re-attach
  872. */
  873. public static void detachAttach(Element element) {
  874. if (element == null) {
  875. return;
  876. }
  877. Node nextSibling = element.getNextSibling();
  878. Node parent = element.getParentNode();
  879. if (parent == null) {
  880. return;
  881. }
  882. parent.removeChild(element);
  883. if (nextSibling == null) {
  884. parent.appendChild(element);
  885. } else {
  886. parent.insertBefore(element, nextSibling);
  887. }
  888. }
  889. public static void sinkOnloadForImages(Element element) {
  890. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  891. .getElementsByTagName("img");
  892. for (int i = 0; i < imgElements.getLength(); i++) {
  893. DOM.sinkEvents(imgElements.getItem(i), Event.ONLOAD);
  894. }
  895. }
  896. /**
  897. * Returns the index of the childElement within its parent.
  898. *
  899. * @param subElement
  900. * @return
  901. */
  902. public static int getChildElementIndex(Element childElement) {
  903. int idx = 0;
  904. Node n = childElement;
  905. while ((n = n.getPreviousSibling()) != null) {
  906. idx++;
  907. }
  908. return idx;
  909. }
  910. /**
  911. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  912. * resets it to its current value. Used mainly to work around rendering
  913. * issues in IE (and possibly in other browsers)
  914. *
  915. * @param element
  916. * The target element
  917. * @param styleProperty
  918. * The name of the property to set
  919. * @param tempValue
  920. * The temporary value
  921. */
  922. public static void setStyleTemporarily(Element element,
  923. final String styleProperty, String tempValue) {
  924. final Style style = element.getStyle();
  925. final String currentValue = style.getProperty(styleProperty);
  926. style.setProperty(styleProperty, tempValue);
  927. // Read a style-based property to force the browser to recalculate the
  928. // element's dimensions with the temporary style.
  929. element.getOffsetWidth();
  930. style.setProperty(styleProperty, currentValue);
  931. }
  932. /**
  933. * A helper method to return the client position from an event. Returns
  934. * position from either first changed touch (if touch event) or from the
  935. * event itself.
  936. *
  937. * @param event
  938. * @return
  939. */
  940. public static int getTouchOrMouseClientX(Event event) {
  941. if (isTouchEvent(event)) {
  942. return event.getChangedTouches().get(0).getClientX();
  943. } else {
  944. return event.getClientX();
  945. }
  946. }
  947. /**
  948. * Find the element corresponding to the coordinates in the passed mouse
  949. * event. Please note that this is not always the same as the target of the
  950. * event e.g. if event capture is used.
  951. *
  952. * @param event
  953. * the mouse event to get coordinates from
  954. * @return the element at the coordinates of the event
  955. */
  956. public static Element getElementUnderMouse(NativeEvent event) {
  957. int pageX = getTouchOrMouseClientX(event);
  958. int pageY = getTouchOrMouseClientY(event);
  959. return getElementFromPoint(pageX, pageY);
  960. }
  961. /**
  962. * A helper method to return the client position from an event. Returns
  963. * position from either first changed touch (if touch event) or from the
  964. * event itself.
  965. *
  966. * @param event
  967. * @return
  968. */
  969. public static int getTouchOrMouseClientY(Event event) {
  970. if (isTouchEvent(event)) {
  971. return event.getChangedTouches().get(0).getClientY();
  972. } else {
  973. return event.getClientY();
  974. }
  975. }
  976. /**
  977. *
  978. * @see #getTouchOrMouseClientY(Event)
  979. * @param currentGwtEvent
  980. * @return
  981. */
  982. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  983. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  984. }
  985. /**
  986. * @see #getTouchOrMouseClientX(Event)
  987. *
  988. * @param event
  989. * @return
  990. */
  991. public static int getTouchOrMouseClientX(NativeEvent event) {
  992. return getTouchOrMouseClientX(Event.as(event));
  993. }
  994. public static boolean isTouchEvent(Event event) {
  995. return event.getType().contains("touch");
  996. }
  997. public static boolean isTouchEvent(NativeEvent event) {
  998. return isTouchEvent(Event.as(event));
  999. }
  1000. public static void simulateClickFromTouchEvent(Event touchevent,
  1001. Widget widget) {
  1002. Touch touch = touchevent.getChangedTouches().get(0);
  1003. final NativeEvent createMouseUpEvent = Document.get()
  1004. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  1005. touch.getClientX(), touch.getClientY(), false, false,
  1006. false, false, NativeEvent.BUTTON_LEFT);
  1007. final NativeEvent createMouseDownEvent = Document.get()
  1008. .createMouseDownEvent(0, touch.getScreenX(), touch.getScreenY(),
  1009. touch.getClientX(), touch.getClientY(), false, false,
  1010. false, false, NativeEvent.BUTTON_LEFT);
  1011. final NativeEvent createMouseClickEvent = Document.get()
  1012. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  1013. touch.getClientX(), touch.getClientY(), false, false,
  1014. false, false);
  1015. /*
  1016. * Get target with element from point as we want the actual element, not
  1017. * the one that sunk the event.
  1018. */
  1019. final Element target = getElementFromPoint(touch.getClientX(),
  1020. touch.getClientY());
  1021. /*
  1022. * Fixes infocusable form fields in Safari of iOS 5.x and some Android
  1023. * browsers.
  1024. */
  1025. Widget targetWidget = findWidget(target);
  1026. if (targetWidget instanceof com.google.gwt.user.client.ui.Focusable) {
  1027. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) targetWidget;
  1028. toBeFocusedWidget.setFocus(true);
  1029. } else if (targetWidget instanceof Focusable) {
  1030. ((Focusable) targetWidget).focus();
  1031. }
  1032. Scheduler.get().scheduleDeferred(() -> {
  1033. try {
  1034. target.dispatchEvent(createMouseDownEvent);
  1035. target.dispatchEvent(createMouseUpEvent);
  1036. target.dispatchEvent(createMouseClickEvent);
  1037. } catch (Exception e) {
  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 static native 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 static native 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 static native 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 static native 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 (s.isEmpty()) {
  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. @Override
  1400. public int hashCode() {
  1401. final int prime = 31;
  1402. int result = 1;
  1403. result = prime * result + (int) value;
  1404. result = prime * result + ((unit == null) ? 0 : unit.hashCode());
  1405. return result;
  1406. }
  1407. /**
  1408. * Check whether the two sizes are equals.
  1409. *
  1410. * @param cssSize1
  1411. * the first size to compare.
  1412. * @param cssSize2
  1413. * the other size to compare with the first one.
  1414. * @return true if the two sizes are equals, otherwise false.
  1415. */
  1416. public static boolean equals(String cssSize1, String cssSize2) {
  1417. return CssSize.fromString(cssSize1)
  1418. .equals(CssSize.fromString(cssSize2));
  1419. }
  1420. }
  1421. private static Logger getLogger() {
  1422. return Logger.getLogger(WidgetUtil.class.getName());
  1423. }
  1424. /**
  1425. * Returns the thickness of the given element's top border.
  1426. * <p>
  1427. * The value is determined using computed style when available and
  1428. * calculated otherwise.
  1429. *
  1430. * @since 7.5.0
  1431. * @param element
  1432. * the element to measure
  1433. * @return the top border thickness
  1434. */
  1435. public static double getBorderTopThickness(Element element) {
  1436. return getBorderThickness(element, new String[] { "borderTopWidth" });
  1437. }
  1438. /**
  1439. * Returns the thickness of the given element's bottom border.
  1440. * <p>
  1441. * The value is determined using computed style when available and
  1442. * calculated otherwise.
  1443. *
  1444. * @since 7.5.0
  1445. * @param element
  1446. * the element to measure
  1447. * @return the bottom border thickness
  1448. */
  1449. public static double getBorderBottomThickness(Element element) {
  1450. return getBorderThickness(element,
  1451. new String[] { "borderBottomWidth" });
  1452. }
  1453. /**
  1454. * Returns the combined thickness of the given element's top and bottom
  1455. * borders.
  1456. * <p>
  1457. * The value is determined using computed style when available and
  1458. * calculated otherwise.
  1459. *
  1460. * @since 7.5.0
  1461. * @param element
  1462. * the element to measure
  1463. * @return the top and bottom border thickness
  1464. */
  1465. public static double getBorderTopAndBottomThickness(Element element) {
  1466. return getBorderThickness(element,
  1467. new String[] { "borderTopWidth", "borderBottomWidth" });
  1468. }
  1469. /**
  1470. * Returns the thickness of the given element's left border.
  1471. * <p>
  1472. * The value is determined using computed style when available and
  1473. * calculated otherwise.
  1474. *
  1475. * @since 7.5.0
  1476. * @param element
  1477. * the element to measure
  1478. * @return the left border thickness
  1479. */
  1480. public static double getBorderLeftThickness(Element element) {
  1481. return getBorderThickness(element, new String[] { "borderLeftWidth" });
  1482. }
  1483. /**
  1484. * Returns the thickness of the given element's right border.
  1485. * <p>
  1486. * The value is determined using computed style when available and
  1487. * calculated otherwise.
  1488. *
  1489. * @since 7.5.0
  1490. * @param element
  1491. * the element to measure
  1492. * @return the right border thickness
  1493. */
  1494. public static double getBorderRightThickness(Element element) {
  1495. return getBorderThickness(element, new String[] { "borderRightWidth" });
  1496. }
  1497. /**
  1498. * Returns the thickness of the given element's left and right borders.
  1499. * <p>
  1500. * The value is determined using computed style when available and
  1501. * calculated otherwise.
  1502. *
  1503. * @since 7.5.0
  1504. * @param element
  1505. * the element to measure
  1506. * @return the top border thickness
  1507. */
  1508. public static double getBorderLeftAndRightThickness(Element element) {
  1509. return getBorderThickness(element,
  1510. new String[] { "borderLeftWidth", "borderRightWidth" });
  1511. }
  1512. private static native double getBorderThickness(
  1513. com.google.gwt.dom.client.Element element, String[] borderNames)
  1514. /*-{
  1515. if (typeof $wnd.getComputedStyle === 'function') {
  1516. var computedStyle = $wnd.getComputedStyle(element);
  1517. var width = 0;
  1518. for (i=0; i< borderNames.length; i++) {
  1519. var borderWidth = computedStyle[borderNames[i]];
  1520. width += parseFloat(borderWidth);
  1521. }
  1522. return width;
  1523. } else {
  1524. var parentElement = element.offsetParent;
  1525. var cloneElement = element.cloneNode(false);
  1526. cloneElement.style.boxSizing ="content-box";
  1527. parentElement.appendChild(cloneElement);
  1528. var heightWithBorder = cloneElement.offsetHeight;
  1529. for (i=0; i< borderNames.length; i++) {
  1530. cloneElement.style[borderNames[i]] = "0";
  1531. }
  1532. var heightWithoutBorder = cloneElement.offsetHeight;
  1533. parentElement.removeChild(cloneElement);
  1534. return heightWithBorder - heightWithoutBorder;
  1535. }
  1536. }-*/;
  1537. /**
  1538. * Rounds the given size up to a value which the browser will accept.
  1539. *
  1540. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1541. * (http://trac.webkit.org/wiki/LayoutUnit).
  1542. *
  1543. * Firefox uses 1/60th of a pixel because it is divisible by three
  1544. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1545. *
  1546. * @since 7.5.1
  1547. * @param size
  1548. * the value to round
  1549. * @return the rounded value
  1550. */
  1551. public static double roundSizeUp(double size) {
  1552. return roundSize(size, true);
  1553. }
  1554. /**
  1555. * Rounds the given size down to a value which the browser will accept.
  1556. *
  1557. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1558. * (http://trac.webkit.org/wiki/LayoutUnit).
  1559. *
  1560. * Firefox uses 1/60th of a pixel because it is divisible by three
  1561. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1562. *
  1563. * IE9+ uses 1/100th of a pixel
  1564. *
  1565. * @since 7.5.1
  1566. * @param size
  1567. * the value to round
  1568. * @return the rounded value
  1569. */
  1570. public static double roundSizeDown(double size) {
  1571. return roundSize(size, false);
  1572. }
  1573. private static double roundSize(double size, boolean roundUp) {
  1574. double factor = getSubPixelRoundingFactor();
  1575. if (factor < 0 || size < 0) {
  1576. return size;
  1577. }
  1578. if (roundUp) {
  1579. return roundSizeUp(size, factor);
  1580. } else {
  1581. return roundSizeDown(size, factor);
  1582. }
  1583. }
  1584. /**
  1585. * Returns the factor used by browsers to round subpixel values
  1586. *
  1587. * @since 7.5.1
  1588. * @return the factor N used by the browser when storing subpixels as X+Y/N
  1589. */
  1590. private static double getSubPixelRoundingFactor() {
  1591. // Detects how the browser does subpixel rounding
  1592. // Currently Firefox uses 1/60th pixels
  1593. // and Safari uses 1/64th pixels
  1594. // IE 1/100th pixels
  1595. if (detectedSubPixelRoundingFactor != -1) {
  1596. return detectedSubPixelRoundingFactor;
  1597. }
  1598. double probeSize = 0.999999;
  1599. DivElement div = Document.get().createDivElement();
  1600. Document.get().getBody().appendChild(div);
  1601. div.getStyle().setHeight(probeSize, Unit.PX);
  1602. ComputedStyle computedStyle = new ComputedStyle(div);
  1603. double computedHeight = computedStyle.getHeight();
  1604. if (computedHeight < probeSize) {
  1605. // Rounded down by browser, all browsers but Firefox do this
  1606. // today
  1607. detectedSubPixelRoundingFactor = (int) Math
  1608. .round(1.0 / (1.0 - computedHeight));
  1609. } else {
  1610. // Rounded up / to nearest by browser
  1611. probeSize = 1;
  1612. while (computedStyle.getHeight() != 0.0) {
  1613. computedHeight = computedStyle.getHeight();
  1614. probeSize /= 2.0;
  1615. div.getStyle().setHeight(probeSize, Unit.PX);
  1616. }
  1617. detectedSubPixelRoundingFactor = (int) Math
  1618. .round(1.0 / computedHeight);
  1619. }
  1620. div.removeFromParent();
  1621. return detectedSubPixelRoundingFactor;
  1622. }
  1623. private static double roundSizeUp(double size, double divisor) {
  1624. // In: 12.51, 60.0
  1625. // 12
  1626. double integerPart = (int) size;
  1627. // (12.51 - 12) * 60 = 30.6
  1628. double nrFractions = (size - integerPart) * divisor;
  1629. // 12 + ceil(30.6) / 60 = 12 + 31/60 = 12.51666
  1630. return integerPart + (Math.ceil(nrFractions)) / divisor;
  1631. }
  1632. private static double roundSizeDown(double size, double divisor) {
  1633. // In: 12.51, 60.0
  1634. // 12
  1635. double integerPart = (int) size;
  1636. // (12.51 - 12) * 60 = 30.6
  1637. double nrFractions = (size - integerPart) * divisor;
  1638. // 12 + int(30.6) / 60 = 12 + 30/60 = 12.5
  1639. return integerPart + ((int) nrFractions) / divisor;
  1640. }
  1641. /**
  1642. * Returns the X coordinate of an event relative to an element.
  1643. *
  1644. * @param element
  1645. * base element of the relative coordinates
  1646. * @param event
  1647. * with touch or mouse coordinates
  1648. * @return relative X coordinate
  1649. * @since 8.1
  1650. */
  1651. public static int getRelativeX(Element element, NativeEvent event) {
  1652. int relativeLeft = element.getAbsoluteLeft() - Window.getScrollLeft();
  1653. return WidgetUtil.getTouchOrMouseClientX(event) - relativeLeft;
  1654. }
  1655. /**
  1656. * Returns the Y coordinate of an event relative to an element.
  1657. *
  1658. * @param element
  1659. * base element of the relative coordinates
  1660. * @param event
  1661. * with touch or mouse coordinates
  1662. * @return relative Y coordinate
  1663. * @since 8.1
  1664. */
  1665. public static int getRelativeY(Element element, NativeEvent event) {
  1666. int relativeTop = element.getAbsoluteTop() - Window.getScrollTop();
  1667. return WidgetUtil.getTouchOrMouseClientY(event) - relativeTop;
  1668. }
  1669. /**
  1670. * Utility methods for displaying error message on components.
  1671. *
  1672. * @since 8.2
  1673. */
  1674. public static class ErrorUtil {
  1675. /**
  1676. * Sets the error level style name for the given element and removes all
  1677. * previously applied error level style names. The style name has the
  1678. * {@code prefix-errorLevel} format.
  1679. *
  1680. * @param element
  1681. * element to apply the style name to
  1682. * @param prefix
  1683. * part of the style name before the error level string
  1684. * @param errorLevel
  1685. * error level for which the style will be applied
  1686. */
  1687. public static void setErrorLevelStyle(Element element, String prefix,
  1688. ErrorLevel errorLevel) {
  1689. for (ErrorLevel errorLevelValue : ErrorLevel.values()) {
  1690. String className = prefix + "-"
  1691. + errorLevelValue.toString().toLowerCase();
  1692. if (errorLevel == errorLevelValue) {
  1693. element.addClassName(className);
  1694. } else {
  1695. element.removeClassName(className);
  1696. }
  1697. }
  1698. }
  1699. /**
  1700. * Creates an element to use by widgets as an error indicator.
  1701. *
  1702. * @return the error indicator element
  1703. */
  1704. public static Element createErrorIndicatorElement() {
  1705. Element indicator = DOM.createSpan();
  1706. indicator.setClassName(StyleConstants.STYLE_NAME_ERROR_INDICATOR);
  1707. return indicator;
  1708. }
  1709. }
  1710. }