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

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