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

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