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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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
  740. * {@link com.google.gwt.user.client.ui.Composite Composite} {@code C}, this
  741. * method will not find {@code W} but returns {@code C}. This may also be
  742. * the case with other Composite-like classes that hijack the event handling
  743. * of their child widget(s).
  744. *
  745. * @param element
  746. * the element where to start seeking of Widget
  747. * @since 8.1
  748. */
  749. @SuppressWarnings("unchecked")
  750. public static <T> T findWidget(Element element) {
  751. return findWidget(element, null);
  752. }
  753. /**
  754. * Helper method to find first instance of given Widget type found by
  755. * traversing DOM upwards from given element.
  756. * <p>
  757. * <strong>Note:</strong> If {@code element} is inside some widget {@code W}
  758. * , <em>and</em> {@code W} in turn is wrapped in a
  759. * {@link com.google.gwt.user.client.ui.Composite Composite} {@code C}, this
  760. * method will not find {@code W}. It returns either {@code C} or null,
  761. * depending on whether the class parameter matches. This may also be the
  762. * case with other Composite-like classes that hijack the event handling of
  763. * their child widget(s).
  764. * <p>
  765. * Only accepts the exact class {@code class1} if not null.
  766. *
  767. * @param element
  768. * the element where to start seeking of Widget
  769. * @param class1
  770. * the Widget type to seek for, null for any
  771. */
  772. @SuppressWarnings("unchecked")
  773. public static <T> T findWidget(Element element,
  774. Class<? extends Widget> class1) {
  775. return findWidget(element, class1, true);
  776. }
  777. /**
  778. * Helper method to find first instance of given Widget type found by
  779. * traversing DOM upwards from given element.
  780. * <p>
  781. * <strong>Note:</strong> If {@code element} is inside some widget {@code W}
  782. * , <em>and</em> {@code W} in turn is wrapped in a
  783. * {@link com.google.gwt.user.client.ui.Composite Composite} {@code C}, this
  784. * method will not find {@code W}. It returns either {@code C} or null,
  785. * depending on whether the class parameter matches. This may also be the
  786. * case with other Composite-like classes that hijack the event handling of
  787. * their child widget(s).
  788. *
  789. * @param element
  790. * the element where to start seeking of Widget
  791. * @param class1
  792. * the Widget type to seek for
  793. * @param exactMatch
  794. * true to only accept class1, false to also accept its
  795. * superclasses
  796. * @since 8.1
  797. */
  798. @SuppressWarnings("unchecked")
  799. public static <T> T findWidget(Element element,
  800. Class<? extends Widget> class1, boolean exactMatch) {
  801. if (element != null) {
  802. /* First seek for the first EventListener (~Widget) from dom */
  803. EventListener eventListener = null;
  804. while (eventListener == null && element != null) {
  805. eventListener = Event.getEventListener(element);
  806. if (eventListener == null) {
  807. element = element.getParentElement();
  808. }
  809. }
  810. if (eventListener instanceof Widget) {
  811. /*
  812. * Then find the first widget of type class1 from widget
  813. * hierarchy
  814. */
  815. Widget w = (Widget) eventListener;
  816. if (class1 == null && w != null) {
  817. return (T) w;
  818. }
  819. while (w != null) {
  820. Class<?> widgetClass = w.getClass();
  821. while (widgetClass != null) {
  822. if (widgetClass == class1) {
  823. return (T) w;
  824. }
  825. // terminate after first check if looking for exact
  826. // match
  827. widgetClass = exactMatch ? null
  828. : widgetClass.getSuperclass();
  829. }
  830. w = w.getParent();
  831. }
  832. }
  833. }
  834. return null;
  835. }
  836. /**
  837. * Force webkit to redraw an element.
  838. *
  839. * @param element
  840. * The element that should be redrawn
  841. */
  842. public static void forceWebkitRedraw(Element element) {
  843. Style style = element.getStyle();
  844. String s = style.getProperty("webkitTransform");
  845. if (s == null || s.isEmpty()) {
  846. style.setProperty("webkitTransform", "scale(1)");
  847. } else {
  848. style.setProperty("webkitTransform", "");
  849. }
  850. }
  851. /**
  852. * Performs a hack to trigger a re-layout in the IE browser. This is usually
  853. * necessary in cases where IE "forgets" to update child elements when they
  854. * resize.
  855. *
  856. * @since 7.3
  857. * @param e
  858. * The element to perform the hack on
  859. */
  860. public static void forceIERedraw(Element e) {
  861. if (BrowserInfo.get().isIE()) {
  862. setStyleTemporarily(e, "zoom", "1");
  863. }
  864. }
  865. /**
  866. * Detaches and re-attaches the element from its parent. The element is
  867. * reattached at the same position in the DOM as it was before.
  868. *
  869. * Does nothing if the element is not attached to the DOM.
  870. *
  871. * @param element
  872. * The element to detach and re-attach
  873. */
  874. public static void detachAttach(Element element) {
  875. if (element == null) {
  876. return;
  877. }
  878. Node nextSibling = element.getNextSibling();
  879. Node parent = element.getParentNode();
  880. if (parent == null) {
  881. return;
  882. }
  883. parent.removeChild(element);
  884. if (nextSibling == null) {
  885. parent.appendChild(element);
  886. } else {
  887. parent.insertBefore(element, nextSibling);
  888. }
  889. }
  890. public static void sinkOnloadForImages(Element element) {
  891. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  892. .getElementsByTagName("img");
  893. for (int i = 0; i < imgElements.getLength(); i++) {
  894. DOM.sinkEvents(imgElements.getItem(i), Event.ONLOAD);
  895. }
  896. }
  897. /**
  898. * Returns the index of the childElement within its parent.
  899. *
  900. * @param subElement
  901. * @return
  902. */
  903. public static int getChildElementIndex(Element childElement) {
  904. int idx = 0;
  905. Node n = childElement;
  906. while ((n = n.getPreviousSibling()) != null) {
  907. idx++;
  908. }
  909. return idx;
  910. }
  911. /**
  912. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  913. * resets it to its current value. Used mainly to work around rendering
  914. * issues in IE (and possibly in other browsers)
  915. *
  916. * @param element
  917. * The target element
  918. * @param styleProperty
  919. * The name of the property to set
  920. * @param tempValue
  921. * The temporary value
  922. */
  923. public static void setStyleTemporarily(Element element,
  924. final String styleProperty, String tempValue) {
  925. final Style style = element.getStyle();
  926. final String currentValue = style.getProperty(styleProperty);
  927. style.setProperty(styleProperty, tempValue);
  928. // Read a style-based property to force the browser to recalculate the
  929. // element's dimensions with the temporary style.
  930. element.getOffsetWidth();
  931. style.setProperty(styleProperty, currentValue);
  932. }
  933. /**
  934. * A helper method to return the client position from an event. Returns
  935. * position from either first changed touch (if touch event) or from the
  936. * event itself.
  937. *
  938. * @param event
  939. * @return
  940. */
  941. public static int getTouchOrMouseClientX(Event event) {
  942. if (isTouchEvent(event)) {
  943. return event.getChangedTouches().get(0).getClientX();
  944. } else {
  945. return event.getClientX();
  946. }
  947. }
  948. /**
  949. * Find the element corresponding to the coordinates in the passed mouse
  950. * event. Please note that this is not always the same as the target of the
  951. * event e.g. if event capture is used.
  952. *
  953. * @param event
  954. * the mouse event to get coordinates from
  955. * @return the element at the coordinates of the event
  956. */
  957. public static Element getElementUnderMouse(NativeEvent event) {
  958. int pageX = getTouchOrMouseClientX(event);
  959. int pageY = getTouchOrMouseClientY(event);
  960. return getElementFromPoint(pageX, pageY);
  961. }
  962. /**
  963. * A helper method to return the client position from an event. Returns
  964. * position from either first changed touch (if touch event) or from the
  965. * event itself.
  966. *
  967. * @param event
  968. * @return
  969. */
  970. public static int getTouchOrMouseClientY(Event event) {
  971. if (isTouchEvent(event)) {
  972. return event.getChangedTouches().get(0).getClientY();
  973. } else {
  974. return event.getClientY();
  975. }
  976. }
  977. /**
  978. *
  979. * @see #getTouchOrMouseClientY(Event)
  980. * @param currentGwtEvent
  981. * @return
  982. */
  983. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  984. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  985. }
  986. /**
  987. * @see #getTouchOrMouseClientX(Event)
  988. *
  989. * @param event
  990. * @return
  991. */
  992. public static int getTouchOrMouseClientX(NativeEvent event) {
  993. return getTouchOrMouseClientX(Event.as(event));
  994. }
  995. public static boolean isTouchEvent(Event event) {
  996. return event.getType().contains("touch");
  997. }
  998. public static boolean isTouchEvent(NativeEvent event) {
  999. return isTouchEvent(Event.as(event));
  1000. }
  1001. public static void simulateClickFromTouchEvent(Event touchevent,
  1002. Widget widget) {
  1003. Touch touch = touchevent.getChangedTouches().get(0);
  1004. final NativeEvent createMouseUpEvent = Document.get()
  1005. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  1006. touch.getClientX(), touch.getClientY(), false, false,
  1007. false, false, NativeEvent.BUTTON_LEFT);
  1008. final NativeEvent createMouseDownEvent = Document.get()
  1009. .createMouseDownEvent(0, touch.getScreenX(), touch.getScreenY(),
  1010. touch.getClientX(), touch.getClientY(), false, false,
  1011. false, false, NativeEvent.BUTTON_LEFT);
  1012. final NativeEvent createMouseClickEvent = Document.get()
  1013. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  1014. touch.getClientX(), touch.getClientY(), false, false,
  1015. false, false);
  1016. /*
  1017. * Get target with element from point as we want the actual element, not
  1018. * the one that sunk the event.
  1019. */
  1020. final Element target = getElementFromPoint(touch.getClientX(),
  1021. touch.getClientY());
  1022. /*
  1023. * Fixes infocusable form fields in Safari of iOS 5.x and some Android
  1024. * browsers.
  1025. */
  1026. Widget targetWidget = findWidget(target);
  1027. if (targetWidget instanceof com.google.gwt.user.client.ui.Focusable) {
  1028. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) targetWidget;
  1029. toBeFocusedWidget.setFocus(true);
  1030. } else if (targetWidget instanceof Focusable) {
  1031. ((Focusable) targetWidget).focus();
  1032. }
  1033. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  1034. @Override
  1035. public void execute() {
  1036. try {
  1037. target.dispatchEvent(createMouseDownEvent);
  1038. target.dispatchEvent(createMouseUpEvent);
  1039. target.dispatchEvent(createMouseClickEvent);
  1040. } catch (Exception e) {
  1041. }
  1042. }
  1043. });
  1044. }
  1045. /**
  1046. * Gets the currently focused element.
  1047. *
  1048. * @return The active element or null if no active element could be found.
  1049. */
  1050. public static native Element getFocusedElement()
  1051. /*-{
  1052. if ($wnd.document.activeElement) {
  1053. return $wnd.document.activeElement;
  1054. }
  1055. return null;
  1056. }-*/;
  1057. /**
  1058. * Gets currently focused element and checks if it's editable.
  1059. *
  1060. * @since 7.4
  1061. *
  1062. * @return true if focused element is editable
  1063. */
  1064. public static boolean isFocusedElementEditable() {
  1065. Element focusedElement = WidgetUtil.getFocusedElement();
  1066. if (focusedElement != null) {
  1067. String tagName = focusedElement.getTagName();
  1068. String contenteditable = focusedElement
  1069. .getAttribute("contenteditable");
  1070. return "textarea".equalsIgnoreCase(tagName)
  1071. || "input".equalsIgnoreCase(tagName)
  1072. || "true".equalsIgnoreCase(contenteditable);
  1073. }
  1074. return false;
  1075. }
  1076. /**
  1077. * Kind of stronger version of isAttached(). In addition to std isAttached,
  1078. * this method checks that this widget nor any of its parents is hidden. Can
  1079. * be e.g used to check whether component should react to some events or
  1080. * not.
  1081. *
  1082. * @param widget
  1083. * @return true if attached and displayed
  1084. */
  1085. public static boolean isAttachedAndDisplayed(Widget widget) {
  1086. if (widget.isAttached()) {
  1087. /*
  1088. * Failfast using offset size, then by iterating the widget tree
  1089. */
  1090. boolean notZeroSized = widget.getOffsetHeight() > 0
  1091. || widget.getOffsetWidth() > 0;
  1092. return notZeroSized || checkVisibilityRecursively(widget);
  1093. } else {
  1094. return false;
  1095. }
  1096. }
  1097. private static boolean checkVisibilityRecursively(Widget widget) {
  1098. if (widget.isVisible()) {
  1099. Widget parent = widget.getParent();
  1100. if (parent == null) {
  1101. return true; // root panel
  1102. } else {
  1103. return checkVisibilityRecursively(parent);
  1104. }
  1105. } else {
  1106. return false;
  1107. }
  1108. }
  1109. /**
  1110. * Scrolls an element into view vertically only. Modified version of
  1111. * Element.scrollIntoView.
  1112. *
  1113. * @param elem
  1114. * The element to scroll into view
  1115. */
  1116. public static native void scrollIntoViewVertically(Element elem)
  1117. /*-{
  1118. var top = elem.offsetTop;
  1119. var height = elem.offsetHeight;
  1120. if (elem.parentNode != elem.offsetParent) {
  1121. top -= elem.parentNode.offsetTop;
  1122. }
  1123. var cur = elem.parentNode;
  1124. while (cur && (cur.nodeType == 1)) {
  1125. if (top < cur.scrollTop) {
  1126. cur.scrollTop = top;
  1127. }
  1128. if (top + height > cur.scrollTop + cur.clientHeight) {
  1129. cur.scrollTop = (top + height) - cur.clientHeight;
  1130. }
  1131. var offsetTop = cur.offsetTop;
  1132. if (cur.parentNode != cur.offsetParent) {
  1133. offsetTop -= cur.parentNode.offsetTop;
  1134. }
  1135. top += offsetTop - cur.scrollTop;
  1136. cur = cur.parentNode;
  1137. }
  1138. }-*/;
  1139. /**
  1140. * Checks if the given event is either a touch event or caused by the left
  1141. * mouse button.
  1142. *
  1143. * @param event
  1144. * @return true if the event is a touch event or caused by the left mouse
  1145. * button, false otherwise
  1146. */
  1147. public static boolean isTouchEventOrLeftMouseButton(Event event) {
  1148. boolean touchEvent = WidgetUtil.isTouchEvent(event);
  1149. return touchEvent || event.getButton() == Event.BUTTON_LEFT;
  1150. }
  1151. /**
  1152. * Resolve a relative URL to an absolute URL based on the current document's
  1153. * location.
  1154. *
  1155. * @param url
  1156. * a string with the relative URL to resolve
  1157. * @return the corresponding absolute URL as a string
  1158. */
  1159. public static String getAbsoluteUrl(String url) {
  1160. AnchorElement a = Document.get().createAnchorElement();
  1161. a.setHref(url);
  1162. return a.getHref();
  1163. }
  1164. /**
  1165. * Sets the selection range of an input element.
  1166. *
  1167. * We need this JSNI function to set selection range so that we can use the
  1168. * optional direction attribute to set the anchor to the end and the focus
  1169. * to the start. This makes Firefox work the same way as other browsers
  1170. * (#13477)
  1171. *
  1172. * @param elem
  1173. * the html input element.
  1174. * @param pos
  1175. * the index of the first selected character.
  1176. * @param length
  1177. * the selection length.
  1178. * @param direction
  1179. * a string indicating the direction in which the selection was
  1180. * performed. This may be "forward" or "backward", or "none" if
  1181. * the direction is unknown or irrelevant.
  1182. *
  1183. * @since 7.3
  1184. */
  1185. public static native void setSelectionRange(Element elem, int pos,
  1186. int length, String direction)
  1187. /*-{
  1188. try {
  1189. elem.setSelectionRange(pos, pos + length, direction);
  1190. } catch (e) {
  1191. // Firefox throws exception if TextBox is not visible, even if attached
  1192. }
  1193. }-*/;
  1194. /**
  1195. * JavaScript hack to prevent text selection in various browsers.
  1196. *
  1197. * @since 7.6
  1198. * @param e
  1199. * element for enabling or disabling text selection
  1200. * @param enable
  1201. * <code>true</code> if selection is enabled; <code>false</code>
  1202. * if not
  1203. */
  1204. public static native void setTextSelectionEnabled(Element e, boolean enable)
  1205. /*-{
  1206. if (!enable) {
  1207. e.ondrag = function () { return false; };
  1208. e.onselectstart = function () { return false; };
  1209. e.style.webkitUserSelect = "none";
  1210. } else {
  1211. e.ondrag = null;
  1212. e.onselectstart = null;
  1213. e.style.webkitUserSelect = "text";
  1214. }
  1215. }-*/;
  1216. /**
  1217. * JavaScript hack to clear text selection in various browsers.
  1218. *
  1219. * @since 7.6
  1220. */
  1221. public static native void clearTextSelection()
  1222. /*-{
  1223. if ($wnd.getSelection) {
  1224. $wnd.getSelection().removeAllRanges();
  1225. }
  1226. }-*/;
  1227. /**
  1228. * The allowed value inaccuracy when comparing two double-typed pixel
  1229. * values.
  1230. * <p>
  1231. * Since we're comparing pixels on a screen, epsilon must be less than 1.
  1232. * 0.49 was deemed a perfectly fine and beautifully round number.
  1233. */
  1234. public static final double PIXEL_EPSILON = 0.49d;
  1235. /**
  1236. * Compares two double values with the error margin of
  1237. * {@link #PIXEL_EPSILON} (i.e. {@value #PIXEL_EPSILON})
  1238. *
  1239. * @param num1
  1240. * the first value for which to compare equality
  1241. * @param num2
  1242. * the second value for which to compare equality
  1243. * @since 7.4
  1244. *
  1245. * @return true if the values are considered equals; false otherwise
  1246. */
  1247. public static boolean pixelValuesEqual(final double num1,
  1248. final double num2) {
  1249. return Math.abs(num1 - num2) <= PIXEL_EPSILON;
  1250. }
  1251. public static native TextRectangle getBoundingClientRect(Element e)
  1252. /*-{
  1253. return e.getBoundingClientRect();
  1254. }-*/;
  1255. public static final class TextRectangle extends JavaScriptObject {
  1256. protected TextRectangle() {
  1257. }
  1258. public native double getBottom()
  1259. /*-{
  1260. return this.bottom;
  1261. }-*/;
  1262. public native double getHeight()
  1263. /*-{
  1264. return this.height;
  1265. }-*/;
  1266. public native double getLeft()
  1267. /*-{
  1268. return this.left;
  1269. }-*/;
  1270. public native double getRight()
  1271. /*-{
  1272. return this.right;
  1273. }-*/;
  1274. public native double getTop()
  1275. /*-{
  1276. return this.top;
  1277. }-*/;
  1278. public native double getWidth()
  1279. /*-{
  1280. return this.width;
  1281. }-*/;
  1282. }
  1283. /**
  1284. * Wrap a css size value and its unit and translate back and forth to the
  1285. * string representation.<br/>
  1286. * Eg. 50%, 123px, ...
  1287. *
  1288. * @since 7.2.6
  1289. * @author Vaadin Ltd
  1290. */
  1291. @SuppressWarnings("serial")
  1292. public static class CssSize implements Serializable {
  1293. /*
  1294. * Map the size units with their type.
  1295. */
  1296. private static Map<String, Unit> type2Unit = new HashMap<>();
  1297. static {
  1298. for (Unit unit : Unit.values()) {
  1299. type2Unit.put(unit.getType(), unit);
  1300. }
  1301. }
  1302. /**
  1303. * Gets the unit value by its type.
  1304. *
  1305. * @param type
  1306. * the type of the unit as found in the style.
  1307. * @return the unit value.
  1308. */
  1309. public static Unit unitByType(String type) {
  1310. return type2Unit.get(type);
  1311. }
  1312. /*
  1313. * Regex to parse the size.
  1314. */
  1315. private static final RegExp sizePattern = RegExp
  1316. .compile(SharedUtil.SIZE_PATTERN);
  1317. /**
  1318. * Parse the size from string format to {@link CssSize}.
  1319. *
  1320. * @param s
  1321. * the size as string.
  1322. * @return a {@link CssSize} object.
  1323. */
  1324. public static CssSize fromString(String s) {
  1325. if (s == null) {
  1326. return null;
  1327. }
  1328. s = s.trim();
  1329. if (s.isEmpty()) {
  1330. return null;
  1331. }
  1332. float size = 0;
  1333. Unit unit = null;
  1334. MatchResult matcher = sizePattern.exec(s);
  1335. if (matcher.getGroupCount() > 1) {
  1336. size = Float.parseFloat(matcher.getGroup(1));
  1337. if (size < 0) {
  1338. size = -1;
  1339. unit = Unit.PX;
  1340. } else {
  1341. String symbol = matcher.getGroup(2);
  1342. unit = unitByType(symbol);
  1343. }
  1344. } else {
  1345. throw new IllegalArgumentException(
  1346. "Invalid size argument: \"" + s + "\" (should match "
  1347. + sizePattern.getSource() + ")");
  1348. }
  1349. return new CssSize(size, unit);
  1350. }
  1351. /**
  1352. * Creates a {@link CssSize} using a value and its measurement unit.
  1353. *
  1354. * @param value
  1355. * the value.
  1356. * @param unit
  1357. * the unit.
  1358. * @return the {@link CssSize} object.
  1359. */
  1360. public static CssSize fromValueUnit(float value, Unit unit) {
  1361. return new CssSize(value, unit);
  1362. }
  1363. /*
  1364. * The value.
  1365. */
  1366. private final float value;
  1367. /*
  1368. * The measure unit.
  1369. */
  1370. private final Unit unit;
  1371. private CssSize(float value, Unit unit) {
  1372. this.value = value;
  1373. this.unit = unit;
  1374. }
  1375. /**
  1376. * Gets the value for this css size.
  1377. *
  1378. * @return the value.
  1379. */
  1380. public float getValue() {
  1381. return value;
  1382. }
  1383. /**
  1384. * Gets the measurement unit for this css size.
  1385. *
  1386. * @return the unit.
  1387. */
  1388. public Unit getUnit() {
  1389. return unit;
  1390. }
  1391. @Override
  1392. public String toString() {
  1393. return value + unit.getType();
  1394. }
  1395. @Override
  1396. public boolean equals(Object obj) {
  1397. if (obj instanceof CssSize) {
  1398. CssSize size = (CssSize) obj;
  1399. return size.value == value && size.unit == unit;
  1400. }
  1401. return false;
  1402. }
  1403. @Override
  1404. public int hashCode() {
  1405. final int prime = 31;
  1406. int result = 1;
  1407. result = prime * result + (int) value;
  1408. result = prime * result + ((unit == null) ? 0 : unit.hashCode());
  1409. return result;
  1410. }
  1411. /**
  1412. * Check whether the two sizes are equals.
  1413. *
  1414. * @param cssSize1
  1415. * the first size to compare.
  1416. * @param cssSize2
  1417. * the other size to compare with the first one.
  1418. * @return true if the two sizes are equals, otherwise false.
  1419. */
  1420. public static boolean equals(String cssSize1, String cssSize2) {
  1421. return CssSize.fromString(cssSize1)
  1422. .equals(CssSize.fromString(cssSize2));
  1423. }
  1424. }
  1425. private static Logger getLogger() {
  1426. return Logger.getLogger(WidgetUtil.class.getName());
  1427. }
  1428. /**
  1429. * Returns the thickness of the given element's top border.
  1430. * <p>
  1431. * The value is determined using computed style when available and
  1432. * calculated otherwise.
  1433. *
  1434. * @since 7.5.0
  1435. * @param element
  1436. * the element to measure
  1437. * @return the top border thickness
  1438. */
  1439. public static double getBorderTopThickness(Element element) {
  1440. return getBorderThickness(element, new String[] { "borderTopWidth" });
  1441. }
  1442. /**
  1443. * Returns the thickness of the given element's bottom border.
  1444. * <p>
  1445. * The value is determined using computed style when available and
  1446. * calculated otherwise.
  1447. *
  1448. * @since 7.5.0
  1449. * @param element
  1450. * the element to measure
  1451. * @return the bottom border thickness
  1452. */
  1453. public static double getBorderBottomThickness(Element element) {
  1454. return getBorderThickness(element,
  1455. new String[] { "borderBottomWidth" });
  1456. }
  1457. /**
  1458. * Returns the combined thickness of the given element's top and bottom
  1459. * borders.
  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 top and bottom border thickness
  1468. */
  1469. public static double getBorderTopAndBottomThickness(Element element) {
  1470. return getBorderThickness(element,
  1471. new String[] { "borderTopWidth", "borderBottomWidth" });
  1472. }
  1473. /**
  1474. * Returns the thickness of the given element's left border.
  1475. * <p>
  1476. * The value is determined using computed style when available and
  1477. * calculated otherwise.
  1478. *
  1479. * @since 7.5.0
  1480. * @param element
  1481. * the element to measure
  1482. * @return the left border thickness
  1483. */
  1484. public static double getBorderLeftThickness(Element element) {
  1485. return getBorderThickness(element, new String[] { "borderLeftWidth" });
  1486. }
  1487. /**
  1488. * Returns the thickness of the given element's right border.
  1489. * <p>
  1490. * The value is determined using computed style when available and
  1491. * calculated otherwise.
  1492. *
  1493. * @since 7.5.0
  1494. * @param element
  1495. * the element to measure
  1496. * @return the right border thickness
  1497. */
  1498. public static double getBorderRightThickness(Element element) {
  1499. return getBorderThickness(element, new String[] { "borderRightWidth" });
  1500. }
  1501. /**
  1502. * Returns the thickness of the given element's left and right borders.
  1503. * <p>
  1504. * The value is determined using computed style when available and
  1505. * calculated otherwise.
  1506. *
  1507. * @since 7.5.0
  1508. * @param element
  1509. * the element to measure
  1510. * @return the top border thickness
  1511. */
  1512. public static double getBorderLeftAndRightThickness(Element element) {
  1513. return getBorderThickness(element,
  1514. new String[] { "borderLeftWidth", "borderRightWidth" });
  1515. }
  1516. private static native double getBorderThickness(
  1517. com.google.gwt.dom.client.Element element, String[] borderNames)
  1518. /*-{
  1519. if (typeof $wnd.getComputedStyle === 'function') {
  1520. var computedStyle = $wnd.getComputedStyle(element);
  1521. var width = 0;
  1522. for (i=0; i< borderNames.length; i++) {
  1523. var borderWidth = computedStyle[borderNames[i]];
  1524. width += parseFloat(borderWidth);
  1525. }
  1526. return width;
  1527. } else {
  1528. var parentElement = element.offsetParent;
  1529. var cloneElement = element.cloneNode(false);
  1530. cloneElement.style.boxSizing ="content-box";
  1531. parentElement.appendChild(cloneElement);
  1532. var heightWithBorder = cloneElement.offsetHeight;
  1533. for (i=0; i< borderNames.length; i++) {
  1534. cloneElement.style[borderNames[i]] = "0";
  1535. }
  1536. var heightWithoutBorder = cloneElement.offsetHeight;
  1537. parentElement.removeChild(cloneElement);
  1538. return heightWithBorder - heightWithoutBorder;
  1539. }
  1540. }-*/;
  1541. /**
  1542. * Rounds the given size up to a value which the browser will accept.
  1543. *
  1544. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1545. * (http://trac.webkit.org/wiki/LayoutUnit).
  1546. *
  1547. * Firefox uses 1/60th of a pixel because it is divisible by three
  1548. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1549. *
  1550. * @since 7.5.1
  1551. * @param size
  1552. * the value to round
  1553. * @return the rounded value
  1554. */
  1555. public static double roundSizeUp(double size) {
  1556. return roundSize(size, true);
  1557. }
  1558. /**
  1559. * Rounds the given size down to a value which the browser will accept.
  1560. *
  1561. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1562. * (http://trac.webkit.org/wiki/LayoutUnit).
  1563. *
  1564. * Firefox uses 1/60th of a pixel because it is divisible by three
  1565. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1566. *
  1567. * IE9+ uses 1/100th of a pixel
  1568. *
  1569. * @since 7.5.1
  1570. * @param size
  1571. * the value to round
  1572. * @return the rounded value
  1573. */
  1574. public static double roundSizeDown(double size) {
  1575. return roundSize(size, false);
  1576. }
  1577. private static double roundSize(double size, boolean roundUp) {
  1578. double factor = getSubPixelRoundingFactor();
  1579. if (factor < 0 || size < 0) {
  1580. return size;
  1581. }
  1582. if (roundUp) {
  1583. return roundSizeUp(size, factor);
  1584. } else {
  1585. return roundSizeDown(size, factor);
  1586. }
  1587. }
  1588. /**
  1589. * Returns the factor used by browsers to round subpixel values
  1590. *
  1591. * @since 7.5.1
  1592. * @return the factor N used by the browser when storing subpixels as X+Y/N
  1593. */
  1594. private static double getSubPixelRoundingFactor() {
  1595. // Detects how the browser does subpixel rounding
  1596. // Currently Firefox uses 1/60th pixels
  1597. // and Safari uses 1/64th pixels
  1598. // IE 1/100th pixels
  1599. if (detectedSubPixelRoundingFactor != -1) {
  1600. return detectedSubPixelRoundingFactor;
  1601. }
  1602. double probeSize = 0.999999;
  1603. DivElement div = Document.get().createDivElement();
  1604. Document.get().getBody().appendChild(div);
  1605. div.getStyle().setHeight(probeSize, Unit.PX);
  1606. ComputedStyle computedStyle = new ComputedStyle(div);
  1607. double computedHeight = computedStyle.getHeight();
  1608. if (computedHeight < probeSize) {
  1609. // Rounded down by browser, all browsers but Firefox do this
  1610. // today
  1611. detectedSubPixelRoundingFactor = (int) Math
  1612. .round(1.0 / (1.0 - computedHeight));
  1613. } else {
  1614. // Rounded up / to nearest by browser
  1615. probeSize = 1;
  1616. while (computedStyle.getHeight() != 0.0) {
  1617. computedHeight = computedStyle.getHeight();
  1618. probeSize /= 2.0;
  1619. div.getStyle().setHeight(probeSize, Unit.PX);
  1620. }
  1621. detectedSubPixelRoundingFactor = (int) Math
  1622. .round(1.0 / computedHeight);
  1623. }
  1624. div.removeFromParent();
  1625. return detectedSubPixelRoundingFactor;
  1626. }
  1627. private static double roundSizeUp(double size, double divisor) {
  1628. // In: 12.51, 60.0
  1629. // 12
  1630. double integerPart = (int) size;
  1631. // (12.51 - 12) * 60 = 30.6
  1632. double nrFractions = (size - integerPart) * divisor;
  1633. // 12 + ceil(30.6) / 60 = 12 + 31/60 = 12.51666
  1634. return integerPart + (Math.ceil(nrFractions)) / divisor;
  1635. }
  1636. private static double roundSizeDown(double size, double divisor) {
  1637. // In: 12.51, 60.0
  1638. // 12
  1639. double integerPart = (int) size;
  1640. // (12.51 - 12) * 60 = 30.6
  1641. double nrFractions = (size - integerPart) * divisor;
  1642. // 12 + int(30.6) / 60 = 12 + 30/60 = 12.5
  1643. return integerPart + ((int) nrFractions) / divisor;
  1644. }
  1645. /**
  1646. * Returns the X coordinate of an event relative to an element.
  1647. *
  1648. * @param element
  1649. * base element of the relative coordinates
  1650. * @param event
  1651. * with touch or mouse coordinates
  1652. * @return relative X coordinate
  1653. * @since 8.1
  1654. */
  1655. public static int getRelativeX(Element element, NativeEvent event) {
  1656. int relativeLeft = element.getAbsoluteLeft() - Window.getScrollLeft();
  1657. return WidgetUtil.getTouchOrMouseClientX(event) - relativeLeft;
  1658. }
  1659. /**
  1660. * Returns the Y coordinate of an event relative to an element.
  1661. *
  1662. * @param element
  1663. * base element of the relative coordinates
  1664. * @param event
  1665. * with touch or mouse coordinates
  1666. * @return relative Y coordinate
  1667. * @since 8.1
  1668. */
  1669. public static int getRelativeY(Element element, NativeEvent event) {
  1670. int relativeTop = element.getAbsoluteTop() - Window.getScrollTop();
  1671. return WidgetUtil.getTouchOrMouseClientY(event) - relativeTop;
  1672. }
  1673. /**
  1674. * Utility methods for displaying error message on components.
  1675. *
  1676. * @since 8.2
  1677. */
  1678. public static class ErrorUtil {
  1679. /**
  1680. * Sets the error level style name for the given element and removes all
  1681. * previously applied error level style names. The style name has the
  1682. * {@code prefix-errorLevel} format.
  1683. *
  1684. * @param element
  1685. * element to apply the style name to
  1686. * @param prefix
  1687. * part of the style name before the error level string
  1688. * @param errorLevel
  1689. * error level for which the style will be applied
  1690. */
  1691. public static void setErrorLevelStyle(Element element, String prefix,
  1692. ErrorLevel errorLevel) {
  1693. for (ErrorLevel errorLevelValue : ErrorLevel.values()) {
  1694. String className = prefix + "-"
  1695. + errorLevelValue.toString().toLowerCase();
  1696. if (errorLevel == errorLevelValue) {
  1697. element.addClassName(className);
  1698. } else {
  1699. element.removeClassName(className);
  1700. }
  1701. }
  1702. }
  1703. /**
  1704. * Creates an element to use by widgets as an error indicator.
  1705. *
  1706. * @return the error indicator element
  1707. */
  1708. public static Element createErrorIndicatorElement() {
  1709. Element indicator = DOM.createSpan();
  1710. indicator.setClassName(StyleConstants.STYLE_NAME_ERROR_INDICATOR);
  1711. return indicator;
  1712. }
  1713. }
  1714. }