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.

ComponentLocator.java 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*
  2. * Copyright 2011 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.terminal.gwt.client;
  17. import java.util.ArrayList;
  18. import java.util.Iterator;
  19. import java.util.List;
  20. import com.google.gwt.user.client.DOM;
  21. import com.google.gwt.user.client.Element;
  22. import com.google.gwt.user.client.ui.HasWidgets;
  23. import com.google.gwt.user.client.ui.RootPanel;
  24. import com.google.gwt.user.client.ui.Widget;
  25. import com.vaadin.shared.ComponentState;
  26. import com.vaadin.shared.Connector;
  27. import com.vaadin.shared.communication.SharedState;
  28. import com.vaadin.terminal.gwt.client.ui.SubPartAware;
  29. import com.vaadin.terminal.gwt.client.ui.gridlayout.VGridLayout;
  30. import com.vaadin.terminal.gwt.client.ui.orderedlayout.VMeasuringOrderedLayout;
  31. import com.vaadin.terminal.gwt.client.ui.root.VRoot;
  32. import com.vaadin.terminal.gwt.client.ui.tabsheet.VTabsheetPanel;
  33. import com.vaadin.terminal.gwt.client.ui.window.VWindow;
  34. import com.vaadin.terminal.gwt.client.ui.window.WindowConnector;
  35. /**
  36. * ComponentLocator provides methods for generating a String locator for a given
  37. * DOM element and for locating a DOM element using a String locator.
  38. */
  39. public class ComponentLocator {
  40. /**
  41. * Separator used in the String locator between a parent and a child widget.
  42. */
  43. private static final String PARENTCHILD_SEPARATOR = "/";
  44. /**
  45. * Separator used in the String locator between the part identifying the
  46. * containing widget and the part identifying the target element within the
  47. * widget.
  48. */
  49. private static final String SUBPART_SEPARATOR = "#";
  50. /**
  51. * String that identifies the root panel when appearing first in the String
  52. * locator.
  53. */
  54. private static final String ROOT_ID = "Root";
  55. /**
  56. * Reference to ApplicationConnection instance.
  57. */
  58. private ApplicationConnection client;
  59. /**
  60. * Construct a ComponentLocator for the given ApplicationConnection.
  61. *
  62. * @param client
  63. * ApplicationConnection instance for the application.
  64. */
  65. public ComponentLocator(ApplicationConnection client) {
  66. this.client = client;
  67. }
  68. /**
  69. * Generates a String locator which uniquely identifies the target element.
  70. * The {@link #getElementByPath(String)} method can be used for the inverse
  71. * operation, i.e. locating an element based on the return value from this
  72. * method.
  73. * <p>
  74. * Note that getElementByPath(getPathForElement(element)) == element is not
  75. * always true as {@link #getPathForElement(Element)} can return a path to
  76. * another element if the widget determines an action on the other element
  77. * will give the same result as the action on the target element.
  78. * </p>
  79. *
  80. * @since 5.4
  81. * @param targetElement
  82. * The element to generate a path for.
  83. * @return A String locator that identifies the target element or null if a
  84. * String locator could not be created.
  85. */
  86. public String getPathForElement(Element targetElement) {
  87. String pid = null;
  88. Element e = targetElement;
  89. while (true) {
  90. pid = ConnectorMap.get(client).getConnectorId(e);
  91. if (pid != null) {
  92. break;
  93. }
  94. e = DOM.getParent(e);
  95. if (e == null) {
  96. break;
  97. }
  98. }
  99. Widget w = null;
  100. if (pid != null) {
  101. // If we found a Paintable then we use that as reference. We should
  102. // find the Paintable for all but very special cases (like
  103. // overlays).
  104. w = ((ComponentConnector) ConnectorMap.get(client)
  105. .getConnector(pid)).getWidget();
  106. /*
  107. * Still if the Paintable contains a widget that implements
  108. * SubPartAware, we want to use that as a reference
  109. */
  110. Widget targetParent = findParentWidget(targetElement, w);
  111. while (targetParent != w && targetParent != null) {
  112. if (targetParent instanceof SubPartAware) {
  113. /*
  114. * The targetParent widget is a child of the Paintable and
  115. * the first parent (of the targetElement) that implements
  116. * SubPartAware
  117. */
  118. w = targetParent;
  119. break;
  120. }
  121. targetParent = targetParent.getParent();
  122. }
  123. }
  124. if (w == null) {
  125. // Check if the element is part of a widget that is attached
  126. // directly to the root panel
  127. RootPanel rootPanel = RootPanel.get();
  128. int rootWidgetCount = rootPanel.getWidgetCount();
  129. for (int i = 0; i < rootWidgetCount; i++) {
  130. Widget rootWidget = rootPanel.getWidget(i);
  131. if (rootWidget.getElement().isOrHasChild(targetElement)) {
  132. // The target element is contained by this root widget
  133. w = findParentWidget(targetElement, rootWidget);
  134. break;
  135. }
  136. }
  137. if (w != null) {
  138. // We found a widget but we should still see if we find a
  139. // SubPartAware implementor (we cannot find the Paintable as
  140. // there is no link from VOverlay to its paintable/owner).
  141. Widget subPartAwareWidget = findSubPartAwareParentWidget(w);
  142. if (subPartAwareWidget != null) {
  143. w = subPartAwareWidget;
  144. }
  145. }
  146. }
  147. if (w == null) {
  148. // Containing widget not found
  149. return null;
  150. }
  151. // Determine the path for the target widget
  152. String path = getPathForWidget(w);
  153. if (path == null) {
  154. /*
  155. * No path could be determined for the target widget. Cannot create
  156. * a locator string.
  157. */
  158. return null;
  159. }
  160. if (w.getElement() == targetElement) {
  161. /*
  162. * We are done if the target element is the root of the target
  163. * widget.
  164. */
  165. return path;
  166. } else if (w instanceof SubPartAware) {
  167. /*
  168. * If the widget can provide an identifier for the targetElement we
  169. * let it do that
  170. */
  171. String elementLocator = ((SubPartAware) w)
  172. .getSubPartName(targetElement);
  173. if (elementLocator != null) {
  174. return path + SUBPART_SEPARATOR + elementLocator;
  175. }
  176. }
  177. /*
  178. * If everything else fails we use the DOM path to identify the target
  179. * element
  180. */
  181. return path + getDOMPathForElement(targetElement, w.getElement());
  182. }
  183. /**
  184. * Finds the first widget in the hierarchy (moving upwards) that implements
  185. * SubPartAware. Returns the SubPartAware implementor or null if none is
  186. * found.
  187. *
  188. * @param w
  189. * The widget to start from. This is returned if it implements
  190. * SubPartAware.
  191. * @return The first widget (upwards in hierarchy) that implements
  192. * SubPartAware or null
  193. */
  194. private Widget findSubPartAwareParentWidget(Widget w) {
  195. while (w != null) {
  196. if (w instanceof SubPartAware) {
  197. return w;
  198. }
  199. w = w.getParent();
  200. }
  201. return null;
  202. }
  203. /**
  204. * Returns the first widget found when going from {@code targetElement}
  205. * upwards in the DOM hierarchy, assuming that {@code ancestorWidget} is a
  206. * parent of {@code targetElement}.
  207. *
  208. * @param targetElement
  209. * @param ancestorWidget
  210. * @return The widget whose root element is a parent of
  211. * {@code targetElement}.
  212. */
  213. private Widget findParentWidget(Element targetElement, Widget ancestorWidget) {
  214. /*
  215. * As we cannot resolve Widgets from the element we start from the
  216. * widget and move downwards to the correct child widget, as long as we
  217. * find one.
  218. */
  219. if (ancestorWidget instanceof HasWidgets) {
  220. for (Widget w : ((HasWidgets) ancestorWidget)) {
  221. if (w.getElement().isOrHasChild(targetElement)) {
  222. return findParentWidget(targetElement, w);
  223. }
  224. }
  225. }
  226. // No children found, this is it
  227. return ancestorWidget;
  228. }
  229. /**
  230. * Locates an element based on a DOM path and a base element.
  231. *
  232. * @param baseElement
  233. * The base element which the path is relative to
  234. * @param path
  235. * String locator (consisting of domChild[x] parts) that
  236. * identifies the element
  237. * @return The element identified by path, relative to baseElement or null
  238. * if the element could not be found.
  239. */
  240. private Element getElementByDOMPath(Element baseElement, String path) {
  241. String parts[] = path.split(PARENTCHILD_SEPARATOR);
  242. Element element = baseElement;
  243. for (String part : parts) {
  244. if (part.startsWith("domChild[")) {
  245. String childIndexString = part.substring("domChild[".length(),
  246. part.length() - 1);
  247. try {
  248. int childIndex = Integer.parseInt(childIndexString);
  249. element = DOM.getChild(element, childIndex);
  250. } catch (Exception e) {
  251. return null;
  252. }
  253. }
  254. }
  255. return element;
  256. }
  257. /**
  258. * Generates a String locator using domChild[x] parts for the element
  259. * relative to the baseElement.
  260. *
  261. * @param element
  262. * The target element
  263. * @param baseElement
  264. * The starting point for the locator. The generated path is
  265. * relative to this element.
  266. * @return A String locator that can be used to locate the target element
  267. * using {@link #getElementByDOMPath(Element, String)} or null if
  268. * the locator String cannot be created.
  269. */
  270. private String getDOMPathForElement(Element element, Element baseElement) {
  271. Element e = element;
  272. String path = "";
  273. while (true) {
  274. Element parent = DOM.getParent(e);
  275. if (parent == null) {
  276. return null;
  277. }
  278. int childIndex = -1;
  279. int childCount = DOM.getChildCount(parent);
  280. for (int i = 0; i < childCount; i++) {
  281. if (e == DOM.getChild(parent, i)) {
  282. childIndex = i;
  283. break;
  284. }
  285. }
  286. if (childIndex == -1) {
  287. return null;
  288. }
  289. path = PARENTCHILD_SEPARATOR + "domChild[" + childIndex + "]"
  290. + path;
  291. if (parent == baseElement) {
  292. break;
  293. }
  294. e = parent;
  295. }
  296. return path;
  297. }
  298. /**
  299. * Locates an element using a String locator (path) which identifies a DOM
  300. * element. The {@link #getPathForElement(Element)} method can be used for
  301. * the inverse operation, i.e. generating a string expression for a DOM
  302. * element.
  303. *
  304. * @since 5.4
  305. * @param path
  306. * The String locater which identifies the target element.
  307. * @return The DOM element identified by {@code path} or null if the element
  308. * could not be located.
  309. */
  310. public Element getElementByPath(String path) {
  311. /*
  312. * Path is of type "targetWidgetPath#componentPart" or
  313. * "targetWidgetPath".
  314. */
  315. String parts[] = path.split(SUBPART_SEPARATOR, 2);
  316. String widgetPath = parts[0];
  317. Widget w = getWidgetFromPath(widgetPath);
  318. if (w == null || !Util.isAttachedAndDisplayed(w)) {
  319. return null;
  320. }
  321. if (parts.length == 1) {
  322. int pos = widgetPath.indexOf("domChild");
  323. if (pos == -1) {
  324. return w.getElement();
  325. }
  326. // Contains dom reference to a sub element of the widget
  327. String subPath = widgetPath.substring(pos);
  328. return getElementByDOMPath(w.getElement(), subPath);
  329. } else if (parts.length == 2) {
  330. if (w instanceof SubPartAware) {
  331. return ((SubPartAware) w).getSubPartElement(parts[1]);
  332. }
  333. }
  334. return null;
  335. }
  336. /**
  337. * Creates a locator String for the given widget. The path can be used to
  338. * locate the widget using {@link #getWidgetFromPath(String)}.
  339. *
  340. * Returns null if no path can be determined for the widget or if the widget
  341. * is null.
  342. *
  343. * @param w
  344. * The target widget
  345. * @return A String locator for the widget
  346. */
  347. private String getPathForWidget(Widget w) {
  348. if (w == null) {
  349. return null;
  350. }
  351. if (w instanceof VRoot) {
  352. return "";
  353. } else if (w instanceof VWindow) {
  354. Connector windowConnector = ConnectorMap.get(client)
  355. .getConnector(w);
  356. List<WindowConnector> subWindowList = client.getRootConnector()
  357. .getSubWindows();
  358. int indexOfSubWindow = subWindowList.indexOf(windowConnector);
  359. return PARENTCHILD_SEPARATOR + "VWindow[" + indexOfSubWindow + "]";
  360. } else if (w instanceof RootPanel) {
  361. return ROOT_ID;
  362. }
  363. Widget parent = w.getParent();
  364. String basePath = getPathForWidget(parent);
  365. if (basePath == null) {
  366. return null;
  367. }
  368. String simpleName = Util.getSimpleName(w);
  369. /*
  370. * Check if the parent implements Iterable. At least VPopupView does not
  371. * implement HasWdgets so we cannot check for that.
  372. */
  373. if (!(parent instanceof Iterable<?>)) {
  374. // Parent does not implement Iterable so we cannot find out which
  375. // child this is
  376. return null;
  377. }
  378. Iterator<?> i = ((Iterable<?>) parent).iterator();
  379. int pos = 0;
  380. while (i.hasNext()) {
  381. Object child = i.next();
  382. if (child == w) {
  383. return basePath + PARENTCHILD_SEPARATOR + simpleName + "["
  384. + pos + "]";
  385. }
  386. String simpleName2 = Util.getSimpleName(child);
  387. if (simpleName.equals(simpleName2)) {
  388. pos++;
  389. }
  390. }
  391. return null;
  392. }
  393. /**
  394. * Locates the widget based on a String locator.
  395. *
  396. * @param path
  397. * The String locator that identifies the widget.
  398. * @return The Widget identified by the String locator or null if the widget
  399. * could not be identified.
  400. */
  401. private Widget getWidgetFromPath(String path) {
  402. Widget w = null;
  403. String parts[] = path.split(PARENTCHILD_SEPARATOR);
  404. for (int i = 0; i < parts.length; i++) {
  405. String part = parts[i];
  406. if (part.equals(ROOT_ID)) {
  407. w = RootPanel.get();
  408. } else if (part.equals("")) {
  409. w = client.getRootConnector().getWidget();
  410. } else if (w == null) {
  411. String id = part;
  412. // Must be old static pid (PID_S*)
  413. ServerConnector connector = ConnectorMap.get(client)
  414. .getConnector(id);
  415. if (connector == null) {
  416. // Lookup by debugId
  417. // TODO Optimize this
  418. connector = findConnectorById(client.getRootConnector(),
  419. id.substring(5));
  420. }
  421. if (connector instanceof ComponentConnector) {
  422. w = ((ComponentConnector) connector).getWidget();
  423. } else {
  424. // Not found
  425. return null;
  426. }
  427. } else if (part.startsWith("domChild[")) {
  428. // The target widget has been found and the rest identifies the
  429. // element
  430. break;
  431. } else if (w instanceof Iterable) {
  432. // W identifies a widget that contains other widgets, as it
  433. // should. Try to locate the child
  434. Iterable<?> parent = (Iterable<?>) w;
  435. // Part is of type "VVerticalLayout[0]", split this into
  436. // VVerticalLayout and 0
  437. String[] split = part.split("\\[", 2);
  438. String widgetClassName = split[0];
  439. String indexString = split[1];
  440. int widgetPosition = Integer.parseInt(indexString.substring(0,
  441. indexString.length() - 1));
  442. // AbsolutePanel in GridLayout has been removed -> skip it
  443. if (w instanceof VGridLayout
  444. && "AbsolutePanel".equals(widgetClassName)) {
  445. continue;
  446. }
  447. if (w instanceof VTabsheetPanel && widgetPosition != 0) {
  448. // TabSheetPanel now only contains 1 connector => the index
  449. // is always 0 which indicates the widget in the active tab
  450. widgetPosition = 0;
  451. }
  452. /*
  453. * The new grid and ordered layotus do not contain
  454. * ChildComponentContainer widgets. This is instead simulated by
  455. * constructing a path step that would find the desired widget
  456. * from the layout and injecting it as the next search step
  457. * (which would originally have found the widget inside the
  458. * ChildComponentContainer)
  459. */
  460. if ((w instanceof VMeasuringOrderedLayout || w instanceof VGridLayout)
  461. && "ChildComponentContainer".equals(widgetClassName)
  462. && i + 1 < parts.length) {
  463. HasWidgets layout = (HasWidgets) w;
  464. String nextPart = parts[i + 1];
  465. String[] nextSplit = nextPart.split("\\[", 2);
  466. String nextWidgetClassName = nextSplit[0];
  467. // Find the n:th child and count the number of children with
  468. // the same type before it
  469. int nextIndex = 0;
  470. for (Widget child : layout) {
  471. boolean matchingType = nextWidgetClassName.equals(Util
  472. .getSimpleName(child));
  473. if (matchingType && widgetPosition == 0) {
  474. // This is the n:th child that we looked for
  475. break;
  476. } else if (widgetPosition < 0) {
  477. // Error if we're past the desired position without
  478. // a match
  479. return null;
  480. } else if (matchingType) {
  481. // If this was another child of the expected type,
  482. // increase the count for the next step
  483. nextIndex++;
  484. }
  485. // Don't count captions
  486. if (!(child instanceof VCaption)) {
  487. widgetPosition--;
  488. }
  489. }
  490. // Advance to the next step, this time checking for the
  491. // actual child widget
  492. parts[i + 1] = nextWidgetClassName + '[' + nextIndex + ']';
  493. continue;
  494. }
  495. // Locate the child
  496. Iterator<? extends Widget> iterator;
  497. /*
  498. * VWindow and VContextMenu workarounds for backwards
  499. * compatibility
  500. */
  501. if (widgetClassName.equals("VWindow")) {
  502. List<WindowConnector> windows = client.getRootConnector()
  503. .getSubWindows();
  504. List<VWindow> windowWidgets = new ArrayList<VWindow>(
  505. windows.size());
  506. for (WindowConnector wc : windows) {
  507. windowWidgets.add(wc.getWidget());
  508. }
  509. iterator = windowWidgets.iterator();
  510. } else if (widgetClassName.equals("VContextMenu")) {
  511. return client.getContextMenu();
  512. } else {
  513. iterator = (Iterator<? extends Widget>) parent.iterator();
  514. }
  515. boolean ok = false;
  516. // Find the widgetPosition:th child of type "widgetClassName"
  517. while (iterator.hasNext()) {
  518. Widget child = iterator.next();
  519. String simpleName2 = Util.getSimpleName(child);
  520. if (widgetClassName.equals(simpleName2)) {
  521. if (widgetPosition == 0) {
  522. w = child;
  523. ok = true;
  524. break;
  525. }
  526. widgetPosition--;
  527. }
  528. }
  529. if (!ok) {
  530. // Did not find the child
  531. return null;
  532. }
  533. } else {
  534. // W identifies something that is not a "HasWidgets". This
  535. // should not happen as all widget containers should implement
  536. // HasWidgets.
  537. return null;
  538. }
  539. }
  540. return w;
  541. }
  542. private ServerConnector findConnectorById(ServerConnector root, String id) {
  543. SharedState state = root.getState();
  544. if (state instanceof ComponentState
  545. && id.equals(((ComponentState) state).getDebugId())) {
  546. return root;
  547. }
  548. for (ServerConnector child : root.getChildren()) {
  549. ServerConnector found = findConnectorById(child, id);
  550. if (found != null) {
  551. return found;
  552. }
  553. }
  554. return null;
  555. }
  556. }