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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. /*
  2. * Copyright 2000-2014 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.parseInt(height.substring(0,
  263. 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.parseInt(width.substring(0,
  287. 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().getProperty(
  396. "overflow");
  397. final String originalOverflowX = elem.getStyle().getProperty(
  398. "overflowX");
  399. final String originalOverflowY = elem.getStyle().getProperty(
  400. "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() && BrowserInfo.get().getWebkitVersion() >= 534))
  442. && (scrollleft > 0 || elem.getScrollLeft() > 0)) {
  443. int scrollvalue = scrollleft;
  444. if (scrollvalue == 0) {
  445. // mysterious are the ways of webkits scrollbar
  446. // handling. In some cases webkit may report a bad
  447. // (0) scrollleft before hiding the element
  448. // temporary, sometimes after.
  449. scrollvalue = elem.getScrollLeft();
  450. }
  451. // fix another bug where scrollbar remains in wrong
  452. // position
  453. elem.setScrollLeft(scrollvalue - 1);
  454. elem.setScrollLeft(scrollvalue);
  455. }
  456. }
  457. });
  458. }
  459. }
  460. public static void alert(String string) {
  461. if (true) {
  462. Window.alert(string);
  463. }
  464. }
  465. /**
  466. * Gets the border-box width for the given element, i.e. element width +
  467. * border + padding. Always rounds up to nearest integer.
  468. *
  469. * @param element
  470. * The element to check
  471. * @return The border-box width for the element
  472. */
  473. public static int getRequiredWidth(com.google.gwt.dom.client.Element element) {
  474. int reqWidth = getRequiredWidthBoundingClientRect(element);
  475. if (BrowserInfo.get().isIE() && !BrowserInfo.get().isIE8()) {
  476. int csSize = getRequiredWidthComputedStyle(element);
  477. if (csSize == reqWidth + 1) {
  478. // If computed style reports one pixel larger than requiredWidth
  479. // we would be rounding in the wrong direction in IE9. Round up
  480. // instead.
  481. // We do not always use csSize as it e.g. for 100% wide Labels
  482. // in GridLayouts produces senseless values (see e.g.
  483. // ThemeTestUI with Runo).
  484. return csSize;
  485. }
  486. }
  487. return reqWidth;
  488. }
  489. /**
  490. * Gets the border-box width for the given element, i.e. element width +
  491. * border + padding.
  492. *
  493. * @since 7.5.1
  494. * @param element
  495. * The element to check
  496. * @return The border-box width for the element
  497. */
  498. public static double getRequiredWidthDouble(
  499. com.google.gwt.dom.client.Element element) {
  500. double reqWidth = getRequiredWidthBoundingClientRectDouble(element);
  501. if (BrowserInfo.get().isIE() && !BrowserInfo.get().isIE8()) {
  502. double csWidth = getRequiredWidthComputedStyleDouble(element);
  503. if (csWidth > reqWidth && csWidth <= (reqWidth + 1)) {
  504. // IE9 rounds reqHeight to integers BUT sometimes reports wrong
  505. // csHeight it seems, so we only use csHeight if it is within a
  506. // rounding error
  507. return csWidth;
  508. }
  509. }
  510. return reqWidth;
  511. }
  512. /**
  513. * Gets the border-box height for the given element, i.e. element height +
  514. * border + padding. Always rounds up to nearest integer.
  515. *
  516. * @param element
  517. * The element to check
  518. * @return The border-box height for the element
  519. */
  520. public static int getRequiredHeight(
  521. com.google.gwt.dom.client.Element element) {
  522. int reqHeight = getRequiredHeightBoundingClientRect(element);
  523. if (BrowserInfo.get().isIE() && !BrowserInfo.get().isIE8()) {
  524. int csSize = getRequiredHeightComputedStyle(element);
  525. if (csSize == reqHeight + 1) {
  526. // If computed style reports one pixel larger than
  527. // requiredHeight we would be rounding in the wrong direction in
  528. // IE9. Round up instead.
  529. // We do not always use csSize as it e.g. for 100% wide Labels
  530. // in GridLayouts produces senseless values (see e.g.
  531. // ThemeTestUI with Runo).
  532. return csSize;
  533. }
  534. }
  535. return reqHeight;
  536. }
  537. /**
  538. * Gets the border-box height for the given element, i.e. element height +
  539. * border + padding.
  540. *
  541. * @since 7.5.1
  542. * @param element
  543. * The element to check
  544. * @return The border-box height for the element
  545. */
  546. public static double getRequiredHeightDouble(
  547. com.google.gwt.dom.client.Element element) {
  548. double reqHeight = getRequiredHeightBoundingClientRectDouble(element);
  549. if (BrowserInfo.get().isIE() && !BrowserInfo.get().isIE8()) {
  550. double csHeight = getRequiredHeightComputedStyleDouble(element);
  551. if (csHeight > reqHeight && csHeight <= (reqHeight + 1)) {
  552. // IE9 rounds reqHeight to integers BUT sometimes reports wrong
  553. // csHeight it seems, so we only use csHeight if it is within a
  554. // rounding error
  555. // Although sometimes it also happens that IE9 returns an
  556. // incorrectly rounded down requiredHeight and a computed height
  557. // which is exactly one larger, hence the "<="...
  558. return csHeight;
  559. }
  560. }
  561. return reqHeight;
  562. }
  563. /**
  564. * Calculates the width of the element's bounding rectangle.
  565. * <p>
  566. * In case the browser doesn't support bounding rectangles, the returned
  567. * value is the offset width.
  568. *
  569. * @param element
  570. * the element of which to calculate the width
  571. * @return the width of the element
  572. */
  573. public static int getRequiredWidthBoundingClientRect(
  574. com.google.gwt.dom.client.Element element) {
  575. return (int) Math
  576. .ceil(getRequiredWidthBoundingClientRectDouble(element));
  577. }
  578. /**
  579. * Calculates the width of the element's bounding rectangle to subpixel
  580. * precision.
  581. * <p>
  582. * In case the browser doesn't support bounding rectangles, the returned
  583. * value is the offset width.
  584. *
  585. * @param element
  586. * the element of which to calculate the width
  587. * @return the subpixel-accurate width of the element
  588. * @since 7.4
  589. */
  590. public static native double getRequiredWidthBoundingClientRectDouble(
  591. com.google.gwt.dom.client.Element element)
  592. /*-{
  593. if (element.getBoundingClientRect) {
  594. var rect = element.getBoundingClientRect();
  595. return rect.right - rect.left;
  596. } else {
  597. return element.offsetWidth;
  598. }
  599. }-*/;
  600. public static int getRequiredHeightComputedStyle(
  601. com.google.gwt.dom.client.Element element) {
  602. return (int) Math.ceil(getRequiredHeightComputedStyleDouble(element));
  603. }
  604. public static native double getRequiredHeightComputedStyleDouble(
  605. com.google.gwt.dom.client.Element element)
  606. /*-{
  607. var cs = element.ownerDocument.defaultView.getComputedStyle(element);
  608. var heightPx = cs.height;
  609. if(heightPx == 'auto'){
  610. // Fallback for inline elements
  611. return @com.vaadin.client.WidgetUtil::getRequiredHeightBoundingClientRectDouble(Lcom/google/gwt/dom/client/Element;)(element);
  612. }
  613. var height = parseFloat(heightPx); // Will automatically skip "px" suffix
  614. var border = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth); // Will automatically skip "px" suffix
  615. var padding = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom); // Will automatically skip "px" suffix
  616. return height+border+padding;
  617. }-*/;
  618. public static int getRequiredWidthComputedStyle(
  619. com.google.gwt.dom.client.Element element) {
  620. return (int) Math.ceil(getRequiredWidthComputedStyleDouble(element));
  621. }
  622. public static native int getRequiredWidthComputedStyleDouble(
  623. com.google.gwt.dom.client.Element element)
  624. /*-{
  625. var cs = element.ownerDocument.defaultView.getComputedStyle(element);
  626. var widthPx = cs.width;
  627. if(widthPx == 'auto'){
  628. // Fallback for inline elements
  629. return @com.vaadin.client.WidgetUtil::getRequiredWidthBoundingClientRectDouble(Lcom/google/gwt/dom/client/Element;)(element);
  630. }
  631. var width = parseFloat(widthPx); // Will automatically skip "px" suffix
  632. var border = parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth); // Will automatically skip "px" suffix
  633. var padding = parseFloat(cs.paddingLeft) + parseFloat(cs.paddingRight); // Will automatically skip "px" suffix
  634. return width+border+padding;
  635. }-*/;
  636. /**
  637. * Calculates the height of the element's bounding rectangle.
  638. * <p>
  639. * In case the browser doesn't support bounding rectangles, the returned
  640. * value is the offset height.
  641. *
  642. * @param element
  643. * the element of which to calculate the height
  644. * @return the height of the element
  645. */
  646. public static int getRequiredHeightBoundingClientRect(
  647. com.google.gwt.dom.client.Element element) {
  648. return (int) Math
  649. .ceil(getRequiredHeightBoundingClientRectDouble(element));
  650. }
  651. /**
  652. * Calculates the height of the element's bounding rectangle to subpixel
  653. * precision.
  654. * <p>
  655. * In case the browser doesn't support bounding rectangles, the returned
  656. * value is the offset height.
  657. *
  658. * @param element
  659. * the element of which to calculate the height
  660. * @return the subpixel-accurate height of the element
  661. * @since 7.4
  662. */
  663. public static native double getRequiredHeightBoundingClientRectDouble(
  664. com.google.gwt.dom.client.Element element)
  665. /*-{
  666. var height;
  667. if (element.getBoundingClientRect != null) {
  668. var rect = element.getBoundingClientRect();
  669. height = rect.bottom - rect.top;
  670. } else {
  671. height = element.offsetHeight;
  672. }
  673. return height;
  674. }-*/;
  675. public static int getRequiredWidth(Widget widget) {
  676. return getRequiredWidth(widget.getElement());
  677. }
  678. public static int getRequiredHeight(Widget widget) {
  679. return getRequiredHeight(widget.getElement());
  680. }
  681. /**
  682. * Detects what is currently the overflow style attribute in given element.
  683. *
  684. * @param pe
  685. * the element to detect
  686. * @return true if auto or scroll
  687. */
  688. public static boolean mayHaveScrollBars(com.google.gwt.dom.client.Element pe) {
  689. String overflow = getComputedStyle(pe, "overflow");
  690. if (overflow != null) {
  691. if (overflow.equals("auto") || overflow.equals("scroll")) {
  692. return true;
  693. } else {
  694. return false;
  695. }
  696. } else {
  697. return false;
  698. }
  699. }
  700. /**
  701. * A simple helper method to detect "computed style" (aka style sheets +
  702. * element styles). Values returned differ a lot depending on browsers.
  703. * Always be very careful when using this.
  704. *
  705. * @param el
  706. * the element from which the style property is detected
  707. * @param p
  708. * the property to detect
  709. * @return String value of style property
  710. */
  711. private static native String getComputedStyle(
  712. com.google.gwt.dom.client.Element el, String p)
  713. /*-{
  714. try {
  715. if (el.currentStyle) {
  716. // IE
  717. return el.currentStyle[p];
  718. } else if (window.getComputedStyle) {
  719. // Sa, FF, Opera
  720. var view = el.ownerDocument.defaultView;
  721. return view.getComputedStyle(el,null).getPropertyValue(p);
  722. } else {
  723. // fall back for non IE, Sa, FF, Opera
  724. return "";
  725. }
  726. } catch (e) {
  727. return "";
  728. }
  729. }-*/;
  730. /**
  731. * Will (attempt) to focus the given DOM Element.
  732. *
  733. * @param el
  734. * the element to focus
  735. */
  736. public static native void focus(Element el)
  737. /*-{
  738. try {
  739. el.focus();
  740. } catch (e) {
  741. }
  742. }-*/;
  743. /**
  744. * Helper method to find first instance of given Widget type found by
  745. * traversing DOM upwards from given element.
  746. * <p>
  747. * <strong>Note:</strong> If {@code element} is inside some widget {@code W}
  748. * , <em>and</em> {@code W} in turn is wrapped in a {@link Composite}
  749. * {@code C}, this method will not find {@code W}. It returns either
  750. * {@code C} or null, depending on whether the class parameter matches. This
  751. * may also be the case with other Composite-like classes that hijack the
  752. * event handling of their child widget(s).
  753. *
  754. * @param element
  755. * the element where to start seeking of Widget
  756. * @param class1
  757. * the Widget type to seek for
  758. */
  759. @SuppressWarnings("unchecked")
  760. public static <T> T findWidget(Element element,
  761. Class<? extends Widget> class1) {
  762. if (element != null) {
  763. /* First seek for the first EventListener (~Widget) from dom */
  764. EventListener eventListener = null;
  765. while (eventListener == null && element != null) {
  766. eventListener = Event.getEventListener(element);
  767. if (eventListener == null) {
  768. element = element.getParentElement();
  769. }
  770. }
  771. if (eventListener instanceof Widget) {
  772. /*
  773. * Then find the first widget of type class1 from widget
  774. * hierarchy
  775. */
  776. Widget w = (Widget) eventListener;
  777. while (w != null) {
  778. if (class1 == null || w.getClass() == class1) {
  779. return (T) w;
  780. }
  781. w = w.getParent();
  782. }
  783. }
  784. }
  785. return null;
  786. }
  787. /**
  788. * Force webkit to redraw an element
  789. *
  790. * @param element
  791. * The element that should be redrawn
  792. */
  793. public static void forceWebkitRedraw(Element element) {
  794. Style style = element.getStyle();
  795. String s = style.getProperty("webkitTransform");
  796. if (s == null || s.length() == 0) {
  797. style.setProperty("webkitTransform", "scale(1)");
  798. } else {
  799. style.setProperty("webkitTransform", "");
  800. }
  801. }
  802. /**
  803. * Performs a hack to trigger a re-layout in the IE8. This is usually
  804. * necessary in cases where IE8 "forgets" to update child elements when they
  805. * resize.
  806. *
  807. * @param e
  808. * The element to perform the hack on
  809. */
  810. public static final void forceIE8Redraw(Element e) {
  811. if (BrowserInfo.get().isIE8()) {
  812. forceIERedraw(e);
  813. }
  814. }
  815. /**
  816. * Performs a hack to trigger a re-layout in the IE browser. This is usually
  817. * necessary in cases where IE "forgets" to update child elements when they
  818. * resize.
  819. *
  820. * @since 7.3
  821. * @param e
  822. * The element to perform the hack on
  823. */
  824. public static void forceIERedraw(Element e) {
  825. if (BrowserInfo.get().isIE()) {
  826. setStyleTemporarily(e, "zoom", "1");
  827. }
  828. }
  829. /**
  830. * Detaches and re-attaches the element from its parent. The element is
  831. * reattached at the same position in the DOM as it was before.
  832. *
  833. * Does nothing if the element is not attached to the DOM.
  834. *
  835. * @param element
  836. * The element to detach and re-attach
  837. */
  838. public static void detachAttach(Element element) {
  839. if (element == null) {
  840. return;
  841. }
  842. Node nextSibling = element.getNextSibling();
  843. Node parent = element.getParentNode();
  844. if (parent == null) {
  845. return;
  846. }
  847. parent.removeChild(element);
  848. if (nextSibling == null) {
  849. parent.appendChild(element);
  850. } else {
  851. parent.insertBefore(element, nextSibling);
  852. }
  853. }
  854. public static void sinkOnloadForImages(Element element) {
  855. NodeList<com.google.gwt.dom.client.Element> imgElements = element
  856. .getElementsByTagName("img");
  857. for (int i = 0; i < imgElements.getLength(); i++) {
  858. DOM.sinkEvents(imgElements.getItem(i), Event.ONLOAD);
  859. }
  860. }
  861. /**
  862. * Returns the index of the childElement within its parent.
  863. *
  864. * @param subElement
  865. * @return
  866. */
  867. public static int getChildElementIndex(Element childElement) {
  868. int idx = 0;
  869. Node n = childElement;
  870. while ((n = n.getPreviousSibling()) != null) {
  871. idx++;
  872. }
  873. return idx;
  874. }
  875. /**
  876. * Temporarily sets the {@code styleProperty} to {@code tempValue} and then
  877. * resets it to its current value. Used mainly to work around rendering
  878. * issues in IE (and possibly in other browsers)
  879. *
  880. * @param element
  881. * The target element
  882. * @param styleProperty
  883. * The name of the property to set
  884. * @param tempValue
  885. * The temporary value
  886. */
  887. public static void setStyleTemporarily(Element element,
  888. final String styleProperty, String tempValue) {
  889. final Style style = element.getStyle();
  890. final String currentValue = style.getProperty(styleProperty);
  891. style.setProperty(styleProperty, tempValue);
  892. // Read a style-based property to force the browser to recalculate the
  893. // element's dimensions with the temporary style.
  894. element.getOffsetWidth();
  895. style.setProperty(styleProperty, currentValue);
  896. }
  897. /**
  898. * A helper method to return the client position from an event. Returns
  899. * position from either first changed touch (if touch event) or from the
  900. * event itself.
  901. *
  902. * @param event
  903. * @return
  904. */
  905. public static int getTouchOrMouseClientX(Event event) {
  906. if (isTouchEvent(event)) {
  907. return event.getChangedTouches().get(0).getClientX();
  908. } else {
  909. return event.getClientX();
  910. }
  911. }
  912. /**
  913. * Find the element corresponding to the coordinates in the passed mouse
  914. * event. Please note that this is not always the same as the target of the
  915. * event e.g. if event capture is used.
  916. *
  917. * @param event
  918. * the mouse event to get coordinates from
  919. * @return the element at the coordinates of the event
  920. */
  921. public static Element getElementUnderMouse(NativeEvent event) {
  922. int pageX = getTouchOrMouseClientX(event);
  923. int pageY = getTouchOrMouseClientY(event);
  924. return getElementFromPoint(pageX, pageY);
  925. }
  926. /**
  927. * A helper method to return the client position from an event. Returns
  928. * position from either first changed touch (if touch event) or from the
  929. * event itself.
  930. *
  931. * @param event
  932. * @return
  933. */
  934. public static int getTouchOrMouseClientY(Event event) {
  935. if (isTouchEvent(event)) {
  936. return event.getChangedTouches().get(0).getClientY();
  937. } else {
  938. return event.getClientY();
  939. }
  940. }
  941. /**
  942. *
  943. * @see #getTouchOrMouseClientY(Event)
  944. * @param currentGwtEvent
  945. * @return
  946. */
  947. public static int getTouchOrMouseClientY(NativeEvent currentGwtEvent) {
  948. return getTouchOrMouseClientY(Event.as(currentGwtEvent));
  949. }
  950. /**
  951. * @see #getTouchOrMouseClientX(Event)
  952. *
  953. * @param event
  954. * @return
  955. */
  956. public static int getTouchOrMouseClientX(NativeEvent event) {
  957. return getTouchOrMouseClientX(Event.as(event));
  958. }
  959. public static boolean isTouchEvent(Event event) {
  960. return event.getType().contains("touch");
  961. }
  962. public static boolean isTouchEvent(NativeEvent event) {
  963. return isTouchEvent(Event.as(event));
  964. }
  965. public static void simulateClickFromTouchEvent(Event touchevent,
  966. Widget widget) {
  967. Touch touch = touchevent.getChangedTouches().get(0);
  968. final NativeEvent createMouseUpEvent = Document.get()
  969. .createMouseUpEvent(0, touch.getScreenX(), touch.getScreenY(),
  970. touch.getClientX(), touch.getClientY(), false, false,
  971. false, false, NativeEvent.BUTTON_LEFT);
  972. final NativeEvent createMouseDownEvent = Document.get()
  973. .createMouseDownEvent(0, touch.getScreenX(),
  974. touch.getScreenY(), touch.getClientX(),
  975. touch.getClientY(), false, false, false, false,
  976. NativeEvent.BUTTON_LEFT);
  977. final NativeEvent createMouseClickEvent = Document.get()
  978. .createClickEvent(0, touch.getScreenX(), touch.getScreenY(),
  979. touch.getClientX(), touch.getClientY(), false, false,
  980. false, false);
  981. /*
  982. * Get target with element from point as we want the actual element, not
  983. * the one that sunk the event.
  984. */
  985. final Element target = getElementFromPoint(touch.getClientX(),
  986. touch.getClientY());
  987. /*
  988. * Fixes infocusable form fields in Safari of iOS 5.x and some Android
  989. * browsers.
  990. */
  991. Widget targetWidget = findWidget(target, null);
  992. if (targetWidget instanceof com.google.gwt.user.client.ui.Focusable) {
  993. final com.google.gwt.user.client.ui.Focusable toBeFocusedWidget = (com.google.gwt.user.client.ui.Focusable) targetWidget;
  994. toBeFocusedWidget.setFocus(true);
  995. } else if (targetWidget instanceof Focusable) {
  996. ((Focusable) targetWidget).focus();
  997. }
  998. Scheduler.get().scheduleDeferred(new ScheduledCommand() {
  999. @Override
  1000. public void execute() {
  1001. try {
  1002. target.dispatchEvent(createMouseDownEvent);
  1003. target.dispatchEvent(createMouseUpEvent);
  1004. target.dispatchEvent(createMouseClickEvent);
  1005. } catch (Exception e) {
  1006. }
  1007. }
  1008. });
  1009. }
  1010. /**
  1011. * Gets the currently focused element.
  1012. *
  1013. * @return The active element or null if no active element could be found.
  1014. */
  1015. public native static Element getFocusedElement()
  1016. /*-{
  1017. if ($wnd.document.activeElement) {
  1018. return $wnd.document.activeElement;
  1019. }
  1020. return null;
  1021. }-*/;
  1022. /**
  1023. * Gets currently focused element and checks if it's editable
  1024. *
  1025. * @since 7.4
  1026. *
  1027. * @return true if focused element is editable
  1028. */
  1029. public static boolean isFocusedElementEditable() {
  1030. Element focusedElement = WidgetUtil.getFocusedElement();
  1031. if (focusedElement != null) {
  1032. String tagName = focusedElement.getTagName();
  1033. String contenteditable = focusedElement
  1034. .getAttribute("contenteditable");
  1035. return "textarea".equalsIgnoreCase(tagName)
  1036. || "input".equalsIgnoreCase(tagName)
  1037. || "true".equalsIgnoreCase(contenteditable);
  1038. }
  1039. return false;
  1040. }
  1041. /**
  1042. * Kind of stronger version of isAttached(). In addition to std isAttached,
  1043. * this method checks that this widget nor any of its parents is hidden. Can
  1044. * be e.g used to check whether component should react to some events or
  1045. * not.
  1046. *
  1047. * @param widget
  1048. * @return true if attached and displayed
  1049. */
  1050. public static boolean isAttachedAndDisplayed(Widget widget) {
  1051. if (widget.isAttached()) {
  1052. /*
  1053. * Failfast using offset size, then by iterating the widget tree
  1054. */
  1055. boolean notZeroSized = widget.getOffsetHeight() > 0
  1056. || widget.getOffsetWidth() > 0;
  1057. return notZeroSized || checkVisibilityRecursively(widget);
  1058. } else {
  1059. return false;
  1060. }
  1061. }
  1062. private static boolean checkVisibilityRecursively(Widget widget) {
  1063. if (widget.isVisible()) {
  1064. Widget parent = widget.getParent();
  1065. if (parent == null) {
  1066. return true; // root panel
  1067. } else {
  1068. return checkVisibilityRecursively(parent);
  1069. }
  1070. } else {
  1071. return false;
  1072. }
  1073. }
  1074. /**
  1075. * Scrolls an element into view vertically only. Modified version of
  1076. * Element.scrollIntoView.
  1077. *
  1078. * @param elem
  1079. * The element to scroll into view
  1080. */
  1081. public static native void scrollIntoViewVertically(Element elem)
  1082. /*-{
  1083. var top = elem.offsetTop;
  1084. var height = elem.offsetHeight;
  1085. if (elem.parentNode != elem.offsetParent) {
  1086. top -= elem.parentNode.offsetTop;
  1087. }
  1088. var cur = elem.parentNode;
  1089. while (cur && (cur.nodeType == 1)) {
  1090. if (top < cur.scrollTop) {
  1091. cur.scrollTop = top;
  1092. }
  1093. if (top + height > cur.scrollTop + cur.clientHeight) {
  1094. cur.scrollTop = (top + height) - cur.clientHeight;
  1095. }
  1096. var offsetTop = cur.offsetTop;
  1097. if (cur.parentNode != cur.offsetParent) {
  1098. offsetTop -= cur.parentNode.offsetTop;
  1099. }
  1100. top += offsetTop - cur.scrollTop;
  1101. cur = cur.parentNode;
  1102. }
  1103. }-*/;
  1104. /**
  1105. * Checks if the given event is either a touch event or caused by the left
  1106. * mouse button
  1107. *
  1108. * @param event
  1109. * @return true if the event is a touch event or caused by the left mouse
  1110. * button, false otherwise
  1111. */
  1112. public static boolean isTouchEventOrLeftMouseButton(Event event) {
  1113. boolean touchEvent = WidgetUtil.isTouchEvent(event);
  1114. return touchEvent || event.getButton() == Event.BUTTON_LEFT;
  1115. }
  1116. /**
  1117. * Resolve a relative URL to an absolute URL based on the current document's
  1118. * location.
  1119. *
  1120. * @param url
  1121. * a string with the relative URL to resolve
  1122. * @return the corresponding absolute URL as a string
  1123. */
  1124. public static String getAbsoluteUrl(String url) {
  1125. if (BrowserInfo.get().isIE8()) {
  1126. // The hard way - must use innerHTML and attach to DOM in IE8
  1127. DivElement divElement = Document.get().createDivElement();
  1128. divElement.getStyle().setDisplay(Display.NONE);
  1129. RootPanel.getBodyElement().appendChild(divElement);
  1130. divElement.setInnerHTML("<a href='" + escapeAttribute(url)
  1131. + "' ></a>");
  1132. AnchorElement a = divElement.getChild(0).cast();
  1133. String href = a.getHref();
  1134. RootPanel.getBodyElement().removeChild(divElement);
  1135. return href;
  1136. } else {
  1137. AnchorElement a = Document.get().createAnchorElement();
  1138. a.setHref(url);
  1139. return a.getHref();
  1140. }
  1141. }
  1142. /**
  1143. * Sets the selection range of an input element.
  1144. *
  1145. * We need this JSNI function to set selection range so that we can use the
  1146. * optional direction attribute to set the anchor to the end and the focus
  1147. * to the start. This makes Firefox work the same way as other browsers
  1148. * (#13477)
  1149. *
  1150. * @param elem
  1151. * the html input element.
  1152. * @param pos
  1153. * the index of the first selected character.
  1154. * @param length
  1155. * the selection length.
  1156. * @param direction
  1157. * a string indicating the direction in which the selection was
  1158. * performed. This may be "forward" or "backward", or "none" if
  1159. * the direction is unknown or irrelevant.
  1160. *
  1161. * @since 7.3
  1162. */
  1163. public native static void setSelectionRange(Element elem, int pos,
  1164. int length, String direction)
  1165. /*-{
  1166. try {
  1167. elem.setSelectionRange(pos, pos + length, direction);
  1168. } catch (e) {
  1169. // Firefox throws exception if TextBox is not visible, even if attached
  1170. }
  1171. }-*/;
  1172. /**
  1173. * JavaScript hack to prevent text selection in various browsers.
  1174. *
  1175. * @since 7.6
  1176. * @param e
  1177. * element for enabling or disabling text selection
  1178. * @param enable
  1179. * <code>true</code> if selection is enabled; </code>false</code>
  1180. * if not
  1181. */
  1182. public native static void setTextSelectionEnabled(Element e, boolean enable)
  1183. /*-{
  1184. if (!enable) {
  1185. e.ondrag = function () { return false; };
  1186. e.onselectstart = function () { return false; };
  1187. e.style.webkitUserSelect = "none";
  1188. } else {
  1189. e.ondrag = null;
  1190. e.onselectstart = null;
  1191. e.style.webkitUserSelect = "text";
  1192. }
  1193. }-*/;
  1194. /**
  1195. * The allowed value inaccuracy when comparing two double-typed pixel
  1196. * values.
  1197. * <p>
  1198. * Since we're comparing pixels on a screen, epsilon must be less than 1.
  1199. * 0.49 was deemed a perfectly fine and beautifully round number.
  1200. */
  1201. public static final double PIXEL_EPSILON = 0.49d;
  1202. /**
  1203. * Compares two double values with the error margin of
  1204. * {@link #PIXEL_EPSILON} (i.e. {@value #PIXEL_EPSILON})
  1205. *
  1206. * @param num1
  1207. * the first value for which to compare equality
  1208. * @param num2
  1209. * the second value for which to compare equality
  1210. * @since 7.4
  1211. *
  1212. * @return true if the values are considered equals; false otherwise
  1213. */
  1214. public static boolean pixelValuesEqual(final double num1, final double num2) {
  1215. return Math.abs(num1 - num2) <= PIXEL_EPSILON;
  1216. }
  1217. public static native TextRectangle getBoundingClientRect(Element e)
  1218. /*-{
  1219. return e.getBoundingClientRect();
  1220. }-*/;
  1221. public static final class TextRectangle extends JavaScriptObject {
  1222. protected TextRectangle() {
  1223. }
  1224. public native double getBottom()
  1225. /*-{
  1226. return this.bottom;
  1227. }-*/;
  1228. public native double getHeight()
  1229. /*-{
  1230. return this.height;
  1231. }-*/;
  1232. public native double getLeft()
  1233. /*-{
  1234. return this.left;
  1235. }-*/;
  1236. public native double getRight()
  1237. /*-{
  1238. return this.right;
  1239. }-*/;
  1240. public native double getTop()
  1241. /*-{
  1242. return this.top;
  1243. }-*/;
  1244. public native double getWidth()
  1245. /*-{
  1246. return this.width;
  1247. }-*/;
  1248. }
  1249. /**
  1250. * Wrap a css size value and its unit and translate back and forth to the
  1251. * string representation.<br/>
  1252. * Eg. 50%, 123px, ...
  1253. *
  1254. * @since 7.2.6
  1255. * @author Vaadin Ltd
  1256. */
  1257. @SuppressWarnings("serial")
  1258. public static class CssSize implements Serializable {
  1259. /*
  1260. * Map the size units with their type.
  1261. */
  1262. private static Map<String, Unit> type2Unit = new HashMap<String, Style.Unit>();
  1263. static {
  1264. for (Unit unit : Unit.values()) {
  1265. type2Unit.put(unit.getType(), unit);
  1266. }
  1267. }
  1268. /**
  1269. * Gets the unit value by its type.
  1270. *
  1271. * @param type
  1272. * the type of the unit as found in the style.
  1273. * @return the unit value.
  1274. */
  1275. public static Unit unitByType(String type) {
  1276. return type2Unit.get(type);
  1277. }
  1278. /*
  1279. * Regex to parse the size.
  1280. */
  1281. private static final RegExp sizePattern = RegExp
  1282. .compile(SharedUtil.SIZE_PATTERN);
  1283. /**
  1284. * Parse the size from string format to {@link CssSize}.
  1285. *
  1286. * @param s
  1287. * the size as string.
  1288. * @return a {@link CssSize} object.
  1289. */
  1290. public static CssSize fromString(String s) {
  1291. if (s == null) {
  1292. return null;
  1293. }
  1294. s = s.trim();
  1295. if ("".equals(s)) {
  1296. return null;
  1297. }
  1298. float size = 0;
  1299. Unit unit = null;
  1300. MatchResult matcher = sizePattern.exec(s);
  1301. if (matcher.getGroupCount() > 1) {
  1302. size = Float.parseFloat(matcher.getGroup(1));
  1303. if (size < 0) {
  1304. size = -1;
  1305. unit = Unit.PX;
  1306. } else {
  1307. String symbol = matcher.getGroup(2);
  1308. unit = unitByType(symbol);
  1309. }
  1310. } else {
  1311. throw new IllegalArgumentException("Invalid size argument: \""
  1312. + s + "\" (should match " + sizePattern.getSource()
  1313. + ")");
  1314. }
  1315. return new CssSize(size, unit);
  1316. }
  1317. /**
  1318. * Creates a {@link CssSize} using a value and its measurement unit.
  1319. *
  1320. * @param value
  1321. * the value.
  1322. * @param unit
  1323. * the unit.
  1324. * @return the {@link CssSize} object.
  1325. */
  1326. public static CssSize fromValueUnit(float value, Unit unit) {
  1327. return new CssSize(value, unit);
  1328. }
  1329. /*
  1330. * The value.
  1331. */
  1332. private final float value;
  1333. /*
  1334. * The measure unit.
  1335. */
  1336. private final Unit unit;
  1337. private CssSize(float value, Unit unit) {
  1338. this.value = value;
  1339. this.unit = unit;
  1340. }
  1341. /**
  1342. * Gets the value for this css size.
  1343. *
  1344. * @return the value.
  1345. */
  1346. public float getValue() {
  1347. return value;
  1348. }
  1349. /**
  1350. * Gets the measurement unit for this css size.
  1351. *
  1352. * @return the unit.
  1353. */
  1354. public Unit getUnit() {
  1355. return unit;
  1356. }
  1357. @Override
  1358. public String toString() {
  1359. return value + unit.getType();
  1360. }
  1361. @Override
  1362. public boolean equals(Object obj) {
  1363. if (obj instanceof CssSize) {
  1364. CssSize size = (CssSize) obj;
  1365. return size.value == value && size.unit == unit;
  1366. }
  1367. return false;
  1368. }
  1369. /**
  1370. * Check whether the two sizes are equals.
  1371. *
  1372. * @param cssSize1
  1373. * the first size to compare.
  1374. * @param cssSize2
  1375. * the other size to compare with the first one.
  1376. * @return true if the two sizes are equals, otherwise false.
  1377. */
  1378. public static boolean equals(String cssSize1, String cssSize2) {
  1379. return CssSize.fromString(cssSize1).equals(
  1380. CssSize.fromString(cssSize2));
  1381. }
  1382. }
  1383. private static Logger getLogger() {
  1384. return Logger.getLogger(WidgetUtil.class.getName());
  1385. }
  1386. /**
  1387. * Returns the thickness of the given element's top border.
  1388. * <p>
  1389. * The value is determined using computed style when available and
  1390. * calculated otherwise.
  1391. *
  1392. * @since 7.5.0
  1393. * @param element
  1394. * the element to measure
  1395. * @return the top border thickness
  1396. */
  1397. public static double getBorderTopThickness(Element element) {
  1398. return getBorderThickness(element, new String[] { "borderTopWidth" });
  1399. }
  1400. /**
  1401. * Returns the thickness of the given element's bottom 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 bottom border thickness
  1410. */
  1411. public static double getBorderBottomThickness(Element element) {
  1412. return getBorderThickness(element, new String[] { "borderBottomWidth" });
  1413. }
  1414. /**
  1415. * Returns the combined thickness of the given element's top and bottom
  1416. * borders.
  1417. * <p>
  1418. * The value is determined using computed style when available and
  1419. * calculated otherwise.
  1420. *
  1421. * @since 7.5.0
  1422. * @param element
  1423. * the element to measure
  1424. * @return the top and bottom border thickness
  1425. */
  1426. public static double getBorderTopAndBottomThickness(Element element) {
  1427. return getBorderThickness(element, new String[] { "borderTopWidth",
  1428. "borderBottomWidth" });
  1429. }
  1430. /**
  1431. * Returns the thickness of the given element's left border.
  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 left border thickness
  1440. */
  1441. public static double getBorderLeftThickness(Element element) {
  1442. return getBorderThickness(element, new String[] { "borderLeftWidth" });
  1443. }
  1444. /**
  1445. * Returns the thickness of the given element's right border.
  1446. * <p>
  1447. * The value is determined using computed style when available and
  1448. * calculated otherwise.
  1449. *
  1450. * @since 7.5.0
  1451. * @param element
  1452. * the element to measure
  1453. * @return the right border thickness
  1454. */
  1455. public static double getBorderRightThickness(Element element) {
  1456. return getBorderThickness(element, new String[] { "borderRightWidth" });
  1457. }
  1458. /**
  1459. * Returns the thickness of the given element's left and right borders.
  1460. * <p>
  1461. * The value is determined using computed style when available and
  1462. * calculated otherwise.
  1463. *
  1464. * @since 7.5.0
  1465. * @param element
  1466. * the element to measure
  1467. * @return the top border thickness
  1468. */
  1469. public static double getBorderLeftAndRightThickness(Element element) {
  1470. return getBorderThickness(element, new String[] { "borderLeftWidth",
  1471. "borderRightWidth" });
  1472. }
  1473. private static native double getBorderThickness(
  1474. com.google.gwt.dom.client.Element element, String[] borderNames)
  1475. /*-{
  1476. if (typeof $wnd.getComputedStyle === 'function') {
  1477. var computedStyle = $wnd.getComputedStyle(element);
  1478. var width = 0;
  1479. for (i=0; i< borderNames.length; i++) {
  1480. var borderWidth = computedStyle[borderNames[i]];
  1481. width += parseFloat(borderWidth);
  1482. }
  1483. return width;
  1484. } else {
  1485. var parentElement = element.offsetParent;
  1486. var cloneElement = element.cloneNode(false);
  1487. cloneElement.style.boxSizing ="content-box";
  1488. parentElement.appendChild(cloneElement);
  1489. cloneElement.style.height = "10px"; // IE8 wants the height to be set to something...
  1490. var heightWithBorder = cloneElement.offsetHeight;
  1491. for (i=0; i< borderNames.length; i++) {
  1492. cloneElement.style[borderNames[i]] = "0";
  1493. }
  1494. var heightWithoutBorder = cloneElement.offsetHeight;
  1495. parentElement.removeChild(cloneElement);
  1496. return heightWithBorder - heightWithoutBorder;
  1497. }
  1498. }-*/;
  1499. /**
  1500. * Rounds the given size up to a value which the browser will accept.
  1501. *
  1502. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1503. * (http://trac.webkit.org/wiki/LayoutUnit).
  1504. *
  1505. * Firefox uses 1/60th of a pixel because it is divisible by three
  1506. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1507. *
  1508. * @since 7.5.1
  1509. * @param size
  1510. * the value to round
  1511. * @return the rounded value
  1512. */
  1513. public static double roundSizeUp(double size) {
  1514. return roundSize(size, true);
  1515. }
  1516. /**
  1517. * Rounds the given size down to a value which the browser will accept.
  1518. *
  1519. * Safari/WebKit uses 1/64th of a pixel to enable using integer math
  1520. * (http://trac.webkit.org/wiki/LayoutUnit).
  1521. *
  1522. * Firefox uses 1/60th of a pixel because it is divisible by three
  1523. * (https://bugzilla.mozilla.org/show_bug.cgi?id=1070940)
  1524. *
  1525. * IE9+ uses 1/100th of a pixel
  1526. *
  1527. * @since 7.5.1
  1528. * @param size
  1529. * the value to round
  1530. * @return the rounded value
  1531. */
  1532. public static double roundSizeDown(double size) {
  1533. return roundSize(size, false);
  1534. }
  1535. private static double roundSize(double size, boolean roundUp) {
  1536. if (BrowserInfo.get().isIE8()) {
  1537. if (roundUp) {
  1538. return Math.ceil(size);
  1539. } else {
  1540. return (int) size;
  1541. }
  1542. }
  1543. double factor = getSubPixelRoundingFactor();
  1544. if (factor < 0 || size < 0) {
  1545. return size;
  1546. }
  1547. if (roundUp) {
  1548. return roundSizeUp(size, factor);
  1549. } else {
  1550. return roundSizeDown(size, factor);
  1551. }
  1552. }
  1553. /**
  1554. * Returns the factor used by browsers to round subpixel values
  1555. *
  1556. * @since 7.5.1
  1557. * @return the factor N used by the browser when storing subpixels as X+Y/N
  1558. */
  1559. private static double getSubPixelRoundingFactor() {
  1560. // Detects how the browser does subpixel rounding
  1561. // Currently Firefox uses 1/60th pixels
  1562. // and Safari uses 1/64th pixels
  1563. // IE 1/100th pixels
  1564. if (detectedSubPixelRoundingFactor != -1) {
  1565. return detectedSubPixelRoundingFactor;
  1566. }
  1567. double probeSize = 0.999999;
  1568. DivElement div = Document.get().createDivElement();
  1569. Document.get().getBody().appendChild(div);
  1570. div.getStyle().setHeight(probeSize, Unit.PX);
  1571. ComputedStyle computedStyle = new ComputedStyle(div);
  1572. double computedHeight = computedStyle.getHeight();
  1573. if (computedHeight < probeSize) {
  1574. // Rounded down by browser, all browsers but Firefox do this
  1575. // today
  1576. detectedSubPixelRoundingFactor = (int) Math
  1577. .round(1.0 / (1.0 - computedHeight));
  1578. } else {
  1579. // Rounded up / to nearest by browser
  1580. probeSize = 1;
  1581. while (computedStyle.getHeight() != 0.0) {
  1582. computedHeight = computedStyle.getHeight();
  1583. probeSize /= 2.0;
  1584. div.getStyle().setHeight(probeSize, Unit.PX);
  1585. }
  1586. detectedSubPixelRoundingFactor = (int) Math
  1587. .round(1.0 / computedHeight);
  1588. }
  1589. div.removeFromParent();
  1590. return detectedSubPixelRoundingFactor;
  1591. }
  1592. private static double roundSizeUp(double size, double divisor) {
  1593. // In: 12.51, 60.0
  1594. // 12
  1595. double integerPart = (int) size;
  1596. // (12.51 - 12) * 60 = 30.6
  1597. double nrFractions = (size - integerPart) * divisor;
  1598. // 12 + ceil(30.6) / 60 = 12 + 31/60 = 12.51666
  1599. return integerPart + (Math.ceil(nrFractions)) / divisor;
  1600. }
  1601. private static double roundSizeDown(double size, double divisor) {
  1602. // In: 12.51, 60.0
  1603. // 12
  1604. double integerPart = (int) size;
  1605. // (12.51 - 12) * 60 = 30.6
  1606. double nrFractions = (size - integerPart) * divisor;
  1607. // 12 + int(30.6) / 60 = 12 + 30/60 = 12.5
  1608. return integerPart + ((int) nrFractions) / divisor;
  1609. }
  1610. }