You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WidgetUtil.java 65KB

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