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

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