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.

Util.java 56KB

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