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

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