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

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