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.

ComponentSizeValidator.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.server;
  5. import java.io.PrintStream;
  6. import java.io.PrintWriter;
  7. import java.io.Serializable;
  8. import java.util.HashMap;
  9. import java.util.Iterator;
  10. import java.util.LinkedList;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Stack;
  14. import java.util.Vector;
  15. import com.vaadin.terminal.Sizeable;
  16. import com.vaadin.ui.AbstractOrderedLayout;
  17. import com.vaadin.ui.Component;
  18. import com.vaadin.ui.ComponentContainer;
  19. import com.vaadin.ui.CustomComponent;
  20. import com.vaadin.ui.Form;
  21. import com.vaadin.ui.GridLayout;
  22. import com.vaadin.ui.GridLayout.Area;
  23. import com.vaadin.ui.Layout;
  24. import com.vaadin.ui.OrderedLayout;
  25. import com.vaadin.ui.Panel;
  26. import com.vaadin.ui.SplitPanel;
  27. import com.vaadin.ui.TabSheet;
  28. import com.vaadin.ui.VerticalLayout;
  29. import com.vaadin.ui.Window;
  30. @SuppressWarnings("serial")
  31. public class ComponentSizeValidator implements Serializable {
  32. private final static int LAYERS_SHOWN = 4;
  33. /**
  34. * Recursively checks given component and its subtree for invalid layout
  35. * setups. Prints errors to std err stream.
  36. *
  37. * @param component
  38. * component to check
  39. * @return set of first level errors found
  40. */
  41. public static List<InvalidLayout> validateComponentRelativeSizes(
  42. Component component, List<InvalidLayout> errors,
  43. InvalidLayout parent) {
  44. boolean invalidHeight = !checkHeights(component);
  45. boolean invalidWidth = !checkWidths(component);
  46. if (invalidHeight || invalidWidth) {
  47. InvalidLayout error = new InvalidLayout(component, invalidHeight,
  48. invalidWidth);
  49. if (parent != null) {
  50. parent.addError(error);
  51. } else {
  52. if (errors == null) {
  53. errors = new LinkedList<InvalidLayout>();
  54. }
  55. errors.add(error);
  56. }
  57. parent = error;
  58. }
  59. if (component instanceof Panel) {
  60. Panel panel = (Panel) component;
  61. errors = validateComponentRelativeSizes(panel.getContent(), errors,
  62. parent);
  63. } else if (component instanceof ComponentContainer) {
  64. ComponentContainer lo = (ComponentContainer) component;
  65. Iterator it = lo.getComponentIterator();
  66. while (it.hasNext()) {
  67. errors = validateComponentRelativeSizes((Component) it.next(),
  68. errors, parent);
  69. }
  70. } else if (component instanceof Form) {
  71. Form form = (Form) component;
  72. if (form.getLayout() != null) {
  73. errors = validateComponentRelativeSizes(form.getLayout(),
  74. errors, parent);
  75. }
  76. if (form.getFooter() != null) {
  77. errors = validateComponentRelativeSizes(form.getFooter(),
  78. errors, parent);
  79. }
  80. }
  81. return errors;
  82. }
  83. private static void printServerError(String msg,
  84. Stack<ComponentInfo> attributes, boolean widthError,
  85. PrintStream errorStream) {
  86. StringBuffer err = new StringBuffer();
  87. err.append("Vaadin DEBUG\n");
  88. StringBuilder indent = new StringBuilder("");
  89. ComponentInfo ci;
  90. if (attributes != null) {
  91. while (attributes.size() > LAYERS_SHOWN) {
  92. attributes.pop();
  93. }
  94. while (!attributes.empty()) {
  95. ci = attributes.pop();
  96. showComponent(ci.component, ci.info, err, indent, widthError);
  97. }
  98. }
  99. err.append("Layout problem detected: ");
  100. err.append(msg);
  101. err.append("\n");
  102. err.append("Relative sizes were replaced by undefined sizes, components may not render as expected.\n");
  103. errorStream.println(err);
  104. }
  105. public static boolean checkHeights(Component component) {
  106. try {
  107. if (!hasRelativeHeight(component)) {
  108. return true;
  109. }
  110. if (component instanceof Window) {
  111. return true;
  112. }
  113. if (component.getParent() == null) {
  114. return true;
  115. }
  116. return parentCanDefineHeight(component);
  117. } catch (Exception e) {
  118. e.printStackTrace();
  119. return true;
  120. }
  121. }
  122. public static boolean checkWidths(Component component) {
  123. try {
  124. if (!hasRelativeWidth(component)) {
  125. return true;
  126. }
  127. if (component instanceof Window) {
  128. return true;
  129. }
  130. if (component.getParent() == null) {
  131. return true;
  132. }
  133. return parentCanDefineWidth(component);
  134. } catch (Exception e) {
  135. e.printStackTrace();
  136. return true;
  137. }
  138. }
  139. public static class InvalidLayout implements Serializable {
  140. private Component component;
  141. private boolean invalidHeight;
  142. private boolean invalidWidth;
  143. private Vector<InvalidLayout> subErrors = new Vector<InvalidLayout>();
  144. public InvalidLayout(Component component, boolean height, boolean width) {
  145. this.component = component;
  146. invalidHeight = height;
  147. invalidWidth = width;
  148. }
  149. public void addError(InvalidLayout error) {
  150. subErrors.add(error);
  151. }
  152. @SuppressWarnings("deprecation")
  153. public void reportErrors(PrintWriter clientJSON,
  154. AbstractCommunicationManager communicationManager,
  155. PrintStream serverErrorStream) {
  156. clientJSON.write("{");
  157. Component parent = component.getParent();
  158. String paintableId = communicationManager.getPaintableId(component);
  159. clientJSON.print("id:\"" + paintableId + "\"");
  160. if (invalidHeight) {
  161. Stack<ComponentInfo> attributes = null;
  162. String msg = "";
  163. // set proper error messages
  164. if (parent instanceof AbstractOrderedLayout) {
  165. AbstractOrderedLayout ol = (AbstractOrderedLayout) parent;
  166. boolean vertical = false;
  167. if (ol instanceof OrderedLayout) {
  168. if (((OrderedLayout) ol).getOrientation() == OrderedLayout.ORIENTATION_VERTICAL) {
  169. vertical = true;
  170. }
  171. } else if (ol instanceof VerticalLayout) {
  172. vertical = true;
  173. }
  174. if (vertical) {
  175. msg = "Component with relative height inside a VerticalLayout with no height defined.";
  176. attributes = getHeightAttributes(component);
  177. } else {
  178. msg = "At least one of a HorizontalLayout's components must have non relative height if the height of the layout is not defined";
  179. attributes = getHeightAttributes(component);
  180. }
  181. } else if (parent instanceof GridLayout) {
  182. msg = "At least one of the GridLayout's components in each row should have non relative height if the height of the layout is not defined.";
  183. attributes = getHeightAttributes(component);
  184. } else {
  185. // default error for non sized parent issue
  186. msg = "A component with relative height needs a parent with defined height.";
  187. attributes = getHeightAttributes(component);
  188. }
  189. printServerError(msg, attributes, false, serverErrorStream);
  190. clientJSON.print(",\"heightMsg\":\"" + msg + "\"");
  191. }
  192. if (invalidWidth) {
  193. Stack<ComponentInfo> attributes = null;
  194. String msg = "";
  195. if (parent instanceof AbstractOrderedLayout) {
  196. AbstractOrderedLayout ol = (AbstractOrderedLayout) parent;
  197. boolean horizontal = true;
  198. if (ol instanceof OrderedLayout) {
  199. if (((OrderedLayout) ol).getOrientation() == OrderedLayout.ORIENTATION_VERTICAL) {
  200. horizontal = false;
  201. }
  202. } else if (ol instanceof VerticalLayout) {
  203. horizontal = false;
  204. }
  205. if (horizontal) {
  206. msg = "Component with relative width inside a HorizontalLayout with no width defined";
  207. attributes = getWidthAttributes(component);
  208. } else {
  209. msg = "At least one of a VerticalLayout's components must have non relative width if the width of the layout is not defined";
  210. attributes = getWidthAttributes(component);
  211. }
  212. } else if (parent instanceof GridLayout) {
  213. msg = "At least one of the GridLayout's components in each column should have non relative width if the width of the layout is not defined.";
  214. attributes = getWidthAttributes(component);
  215. } else {
  216. // default error for non sized parent issue
  217. msg = "A component with relative width needs a parent with defined width.";
  218. attributes = getWidthAttributes(component);
  219. }
  220. clientJSON.print(",\"widthMsg\":\"" + msg + "\"");
  221. printServerError(msg, attributes, true, serverErrorStream);
  222. }
  223. if (subErrors.size() > 0) {
  224. serverErrorStream.println("Sub errors >>");
  225. clientJSON.write(", \"subErrors\" : [");
  226. boolean first = true;
  227. for (InvalidLayout subError : subErrors) {
  228. if (!first) {
  229. clientJSON.print(",");
  230. } else {
  231. first = false;
  232. }
  233. subError.reportErrors(clientJSON, communicationManager,
  234. serverErrorStream);
  235. }
  236. clientJSON.write("]");
  237. serverErrorStream.println("<< Sub erros");
  238. }
  239. clientJSON.write("}");
  240. }
  241. }
  242. private static class ComponentInfo implements Serializable {
  243. Component component;
  244. String info;
  245. public ComponentInfo(Component component, String info) {
  246. this.component = component;
  247. this.info = info;
  248. }
  249. }
  250. private static Stack<ComponentInfo> getHeightAttributes(Component component) {
  251. Stack<ComponentInfo> attributes = new Stack<ComponentInfo>();
  252. attributes
  253. .add(new ComponentInfo(component, getHeightString(component)));
  254. Component parent = component.getParent();
  255. attributes.add(new ComponentInfo(parent, getHeightString(parent)));
  256. while ((parent = parent.getParent()) != null) {
  257. attributes.add(new ComponentInfo(parent, getHeightString(parent)));
  258. }
  259. return attributes;
  260. }
  261. private static Stack<ComponentInfo> getWidthAttributes(Component component) {
  262. Stack<ComponentInfo> attributes = new Stack<ComponentInfo>();
  263. attributes.add(new ComponentInfo(component, getWidthString(component)));
  264. Component parent = component.getParent();
  265. attributes.add(new ComponentInfo(parent, getWidthString(parent)));
  266. while ((parent = parent.getParent()) != null) {
  267. attributes.add(new ComponentInfo(parent, getWidthString(parent)));
  268. }
  269. return attributes;
  270. }
  271. private static String getWidthString(Component component) {
  272. String width = "width: ";
  273. if (hasRelativeWidth(component)) {
  274. width += "RELATIVE, " + component.getWidth() + " %";
  275. } else if (component instanceof Window && component.getParent() == null) {
  276. width += "MAIN WINDOW";
  277. } else if (component.getWidth() >= 0) {
  278. width += "ABSOLUTE, " + component.getWidth() + " "
  279. + Sizeable.UNIT_SYMBOLS[component.getWidthUnits()];
  280. } else {
  281. width += "UNDEFINED";
  282. }
  283. return width;
  284. }
  285. private static String getHeightString(Component component) {
  286. String height = "height: ";
  287. if (hasRelativeHeight(component)) {
  288. height += "RELATIVE, " + component.getHeight() + " %";
  289. } else if (component instanceof Window && component.getParent() == null) {
  290. height += "MAIN WINDOW";
  291. } else if (component.getHeight() > 0) {
  292. height += "ABSOLUTE, " + component.getHeight() + " "
  293. + Sizeable.UNIT_SYMBOLS[component.getHeightUnits()];
  294. } else {
  295. height += "UNDEFINED";
  296. }
  297. return height;
  298. }
  299. private static void showComponent(Component component, String attribute,
  300. StringBuffer err, StringBuilder indent, boolean widthError) {
  301. FileLocation createLoc = creationLocations.get(component);
  302. FileLocation sizeLoc;
  303. if (widthError) {
  304. sizeLoc = widthLocations.get(component);
  305. } else {
  306. sizeLoc = heightLocations.get(component);
  307. }
  308. err.append(indent);
  309. indent.append(" ");
  310. err.append("- ");
  311. err.append(component.getClass().getSimpleName());
  312. err.append("/").append(Integer.toHexString(component.hashCode()));
  313. if (component.getCaption() != null) {
  314. err.append(" \"");
  315. err.append(component.getCaption());
  316. err.append("\"");
  317. }
  318. if (component.getDebugId() != null) {
  319. err.append(" debugId: ");
  320. err.append(component.getDebugId());
  321. }
  322. if (createLoc != null) {
  323. err.append(", created at (" + createLoc.file + ":"
  324. + createLoc.lineNumber + ")");
  325. }
  326. if (attribute != null) {
  327. err.append(" (");
  328. err.append(attribute);
  329. if (sizeLoc != null) {
  330. err.append(", set at (" + sizeLoc.file + ":"
  331. + sizeLoc.lineNumber + ")");
  332. }
  333. err.append(")");
  334. }
  335. err.append("\n");
  336. }
  337. private static boolean hasNonRelativeHeightComponent(
  338. AbstractOrderedLayout ol) {
  339. Iterator it = ol.getComponentIterator();
  340. while (it.hasNext()) {
  341. if (!hasRelativeHeight((Component) it.next())) {
  342. return true;
  343. }
  344. }
  345. return false;
  346. }
  347. @SuppressWarnings("deprecation")
  348. public static boolean parentCanDefineHeight(Component component) {
  349. Component parent = component.getParent();
  350. if (parent == null) {
  351. // main window, valid situation
  352. return true;
  353. }
  354. if (parent.getHeight() < 0) {
  355. // Undefined height
  356. if (parent instanceof Window) {
  357. Window w = (Window) parent;
  358. if (w.getParent() == null) {
  359. // main window is considered to have size
  360. return true;
  361. }
  362. }
  363. if (parent instanceof AbstractOrderedLayout) {
  364. boolean horizontal = true;
  365. if (parent instanceof OrderedLayout) {
  366. horizontal = ((OrderedLayout) parent).getOrientation() == OrderedLayout.ORIENTATION_HORIZONTAL;
  367. } else if (parent instanceof VerticalLayout) {
  368. horizontal = false;
  369. }
  370. if (horizontal
  371. && hasNonRelativeHeightComponent((AbstractOrderedLayout) parent)) {
  372. return true;
  373. } else {
  374. return false;
  375. }
  376. } else if (parent instanceof GridLayout) {
  377. GridLayout gl = (GridLayout) parent;
  378. Area componentArea = gl.getComponentArea(component);
  379. boolean rowHasHeight = false;
  380. for (int row = componentArea.getRow1(); !rowHasHeight
  381. && row <= componentArea.getRow2(); row++) {
  382. for (int column = 0; !rowHasHeight
  383. && column < gl.getColumns(); column++) {
  384. Component c = gl.getComponent(column, row);
  385. if (c != null) {
  386. rowHasHeight = !hasRelativeHeight(c);
  387. }
  388. }
  389. }
  390. if (!rowHasHeight) {
  391. return false;
  392. } else {
  393. // Other components define row height
  394. return true;
  395. }
  396. }
  397. if (parent instanceof Panel || parent instanceof SplitPanel
  398. || parent instanceof TabSheet
  399. || parent instanceof CustomComponent) {
  400. // height undefined, we know how how component works and no
  401. // exceptions
  402. // TODO horiz SplitPanel ??
  403. return false;
  404. } else {
  405. // We cannot generally know if undefined component can serve
  406. // space for children (like CustomLayout or component built by
  407. // third party) so we assume they can
  408. return true;
  409. }
  410. } else if (hasRelativeHeight(parent)) {
  411. // Relative height
  412. if (parent.getParent() != null) {
  413. return parentCanDefineHeight(parent);
  414. } else {
  415. return true;
  416. }
  417. } else {
  418. // Absolute height
  419. return true;
  420. }
  421. }
  422. private static boolean hasRelativeHeight(Component component) {
  423. return (component.getHeightUnits() == Sizeable.UNITS_PERCENTAGE && component
  424. .getHeight() > 0);
  425. }
  426. private static boolean hasNonRelativeWidthComponent(AbstractOrderedLayout ol) {
  427. Iterator it = ol.getComponentIterator();
  428. while (it.hasNext()) {
  429. if (!hasRelativeWidth((Component) it.next())) {
  430. return true;
  431. }
  432. }
  433. return false;
  434. }
  435. private static boolean hasRelativeWidth(Component paintable) {
  436. return paintable.getWidth() > 0
  437. && paintable.getWidthUnits() == Sizeable.UNITS_PERCENTAGE;
  438. }
  439. @SuppressWarnings("deprecation")
  440. public static boolean parentCanDefineWidth(Component component) {
  441. Component parent = component.getParent();
  442. if (parent == null) {
  443. // main window, valid situation
  444. return true;
  445. }
  446. if (parent instanceof Window) {
  447. Window w = (Window) parent;
  448. if (w.getParent() == null) {
  449. // main window is considered to have size
  450. return true;
  451. }
  452. }
  453. if (parent.getWidth() < 0) {
  454. // Undefined width
  455. if (parent instanceof AbstractOrderedLayout) {
  456. AbstractOrderedLayout ol = (AbstractOrderedLayout) parent;
  457. boolean horizontal = true;
  458. if (ol instanceof OrderedLayout) {
  459. if (((OrderedLayout) ol).getOrientation() == OrderedLayout.ORIENTATION_VERTICAL) {
  460. horizontal = false;
  461. }
  462. } else if (ol instanceof VerticalLayout) {
  463. horizontal = false;
  464. }
  465. if (!horizontal && hasNonRelativeWidthComponent(ol)) {
  466. // valid situation, other components defined width
  467. return true;
  468. } else {
  469. return false;
  470. }
  471. } else if (parent instanceof GridLayout) {
  472. GridLayout gl = (GridLayout) parent;
  473. Area componentArea = gl.getComponentArea(component);
  474. boolean columnHasWidth = false;
  475. for (int col = componentArea.getColumn1(); !columnHasWidth
  476. && col <= componentArea.getColumn2(); col++) {
  477. for (int row = 0; !columnHasWidth && row < gl.getRows(); row++) {
  478. Component c = gl.getComponent(col, row);
  479. if (c != null) {
  480. columnHasWidth = !hasRelativeWidth(c);
  481. }
  482. }
  483. }
  484. if (!columnHasWidth) {
  485. return false;
  486. } else {
  487. // Other components define column width
  488. return true;
  489. }
  490. } else if (parent instanceof Form) {
  491. /*
  492. * If some other part of the form is not relative it determines
  493. * the component width
  494. */
  495. return hasNonRelativeWidthComponent((Form) parent);
  496. } else if (parent instanceof SplitPanel
  497. || parent instanceof TabSheet
  498. || parent instanceof CustomComponent) {
  499. // FIXME Could we use com.vaadin package name here and
  500. // fail for all component containers?
  501. // FIXME Actually this should be moved to containers so it can
  502. // be implemented for custom containers
  503. // TODO vertical splitpanel with another non relative component?
  504. return false;
  505. } else if (parent instanceof Window) {
  506. // Sub window can define width based on caption
  507. if (parent.getCaption() != null
  508. && !parent.getCaption().equals("")) {
  509. return true;
  510. } else {
  511. return false;
  512. }
  513. } else if (parent instanceof Panel) {
  514. // TODO Panel should be able to define width based on caption
  515. return false;
  516. } else {
  517. return true;
  518. }
  519. } else if (hasRelativeWidth(parent)) {
  520. // Relative width
  521. if (parent.getParent() == null) {
  522. return true;
  523. }
  524. return parentCanDefineWidth(parent);
  525. } else {
  526. return true;
  527. }
  528. }
  529. private static boolean hasNonRelativeWidthComponent(Form form) {
  530. Layout layout = form.getLayout();
  531. Layout footer = form.getFooter();
  532. if (layout != null && !hasRelativeWidth(layout)) {
  533. return true;
  534. }
  535. if (footer != null && !hasRelativeWidth(footer)) {
  536. return true;
  537. }
  538. return false;
  539. }
  540. private static Map<Object, FileLocation> creationLocations = new HashMap<Object, FileLocation>();
  541. private static Map<Object, FileLocation> widthLocations = new HashMap<Object, FileLocation>();
  542. private static Map<Object, FileLocation> heightLocations = new HashMap<Object, FileLocation>();
  543. public static class FileLocation implements Serializable {
  544. public String method;
  545. public String file;
  546. public String className;
  547. public String classNameSimple;
  548. public int lineNumber;
  549. public FileLocation(StackTraceElement traceElement) {
  550. file = traceElement.getFileName();
  551. className = traceElement.getClassName();
  552. classNameSimple = className
  553. .substring(className.lastIndexOf('.') + 1);
  554. lineNumber = traceElement.getLineNumber();
  555. method = traceElement.getMethodName();
  556. }
  557. }
  558. public static void setCreationLocation(Object object) {
  559. setLocation(creationLocations, object);
  560. }
  561. public static void setWidthLocation(Object object) {
  562. setLocation(widthLocations, object);
  563. }
  564. public static void setHeightLocation(Object object) {
  565. setLocation(heightLocations, object);
  566. }
  567. private static void setLocation(Map<Object, FileLocation> map, Object object) {
  568. StackTraceElement[] traceLines = Thread.currentThread().getStackTrace();
  569. for (StackTraceElement traceElement : traceLines) {
  570. Class cls;
  571. try {
  572. String className = traceElement.getClassName();
  573. if (className.startsWith("java.")
  574. || className.startsWith("sun.")) {
  575. continue;
  576. }
  577. cls = Class.forName(className);
  578. if (cls == ComponentSizeValidator.class || cls == Thread.class) {
  579. continue;
  580. }
  581. if (Component.class.isAssignableFrom(cls)
  582. && !CustomComponent.class.isAssignableFrom(cls)) {
  583. continue;
  584. }
  585. FileLocation cl = new FileLocation(traceElement);
  586. map.put(object, cl);
  587. return;
  588. } catch (Exception e) {
  589. // TODO Auto-generated catch block
  590. e.printStackTrace();
  591. }
  592. }
  593. }
  594. }