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.

VTree.java 75KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  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.ui;
  17. import java.util.ArrayList;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.Iterator;
  21. import java.util.LinkedList;
  22. import java.util.List;
  23. import java.util.Set;
  24. import com.google.gwt.aria.client.ExpandedValue;
  25. import com.google.gwt.aria.client.Id;
  26. import com.google.gwt.aria.client.Roles;
  27. import com.google.gwt.aria.client.SelectedValue;
  28. import com.google.gwt.core.client.JavaScriptObject;
  29. import com.google.gwt.core.client.Scheduler;
  30. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  31. import com.google.gwt.dom.client.Element;
  32. import com.google.gwt.dom.client.NativeEvent;
  33. import com.google.gwt.dom.client.Node;
  34. import com.google.gwt.event.dom.client.BlurEvent;
  35. import com.google.gwt.event.dom.client.BlurHandler;
  36. import com.google.gwt.event.dom.client.ContextMenuEvent;
  37. import com.google.gwt.event.dom.client.ContextMenuHandler;
  38. import com.google.gwt.event.dom.client.FocusEvent;
  39. import com.google.gwt.event.dom.client.FocusHandler;
  40. import com.google.gwt.event.dom.client.KeyCodes;
  41. import com.google.gwt.event.dom.client.KeyDownEvent;
  42. import com.google.gwt.event.dom.client.KeyDownHandler;
  43. import com.google.gwt.event.dom.client.KeyPressEvent;
  44. import com.google.gwt.event.dom.client.KeyPressHandler;
  45. import com.google.gwt.user.client.Command;
  46. import com.google.gwt.user.client.DOM;
  47. import com.google.gwt.user.client.Event;
  48. import com.google.gwt.user.client.Window;
  49. import com.google.gwt.user.client.ui.FlowPanel;
  50. import com.google.gwt.user.client.ui.SimplePanel;
  51. import com.google.gwt.user.client.ui.UIObject;
  52. import com.google.gwt.user.client.ui.Widget;
  53. import com.vaadin.client.ApplicationConnection;
  54. import com.vaadin.client.BrowserInfo;
  55. import com.vaadin.client.ComponentConnector;
  56. import com.vaadin.client.ConnectorMap;
  57. import com.vaadin.client.MouseEventDetailsBuilder;
  58. import com.vaadin.client.UIDL;
  59. import com.vaadin.client.Util;
  60. import com.vaadin.client.ui.aria.AriaHelper;
  61. import com.vaadin.client.ui.aria.HandlesAriaCaption;
  62. import com.vaadin.client.ui.dd.DDUtil;
  63. import com.vaadin.client.ui.dd.VAbstractDropHandler;
  64. import com.vaadin.client.ui.dd.VAcceptCallback;
  65. import com.vaadin.client.ui.dd.VDragAndDropManager;
  66. import com.vaadin.client.ui.dd.VDragEvent;
  67. import com.vaadin.client.ui.dd.VDropHandler;
  68. import com.vaadin.client.ui.dd.VHasDropHandler;
  69. import com.vaadin.client.ui.dd.VTransferable;
  70. import com.vaadin.client.ui.tree.TreeConnector;
  71. import com.vaadin.shared.MouseEventDetails;
  72. import com.vaadin.shared.MouseEventDetails.MouseButton;
  73. import com.vaadin.shared.ui.MultiSelectMode;
  74. import com.vaadin.shared.ui.dd.VerticalDropLocation;
  75. import com.vaadin.shared.ui.tree.TreeConstants;
  76. /**
  77. *
  78. */
  79. public class VTree extends FocusElementPanel implements VHasDropHandler,
  80. FocusHandler, BlurHandler, KeyPressHandler, KeyDownHandler,
  81. SubPartAware, ActionOwner, HandlesAriaCaption {
  82. private String lastNodeKey = "";
  83. public static final String CLASSNAME = "v-tree";
  84. /**
  85. * @deprecated As of 7.0, use {@link MultiSelectMode#DEFAULT} instead.
  86. */
  87. @Deprecated
  88. public static final MultiSelectMode MULTISELECT_MODE_DEFAULT = MultiSelectMode.DEFAULT;
  89. /**
  90. * @deprecated As of 7.0, use {@link MultiSelectMode#SIMPLE} instead.
  91. */
  92. @Deprecated
  93. public static final MultiSelectMode MULTISELECT_MODE_SIMPLE = MultiSelectMode.SIMPLE;
  94. private static final int CHARCODE_SPACE = 32;
  95. /** For internal use only. May be removed or replaced in the future. */
  96. public final FlowPanel body = new FlowPanel();
  97. /** For internal use only. May be removed or replaced in the future. */
  98. public Set<String> selectedIds = new HashSet<String>();
  99. /** For internal use only. May be removed or replaced in the future. */
  100. public ApplicationConnection client;
  101. /** For internal use only. May be removed or replaced in the future. */
  102. public String paintableId;
  103. /** For internal use only. May be removed or replaced in the future. */
  104. public boolean selectable;
  105. /** For internal use only. May be removed or replaced in the future. */
  106. public boolean isMultiselect;
  107. private String currentMouseOverKey;
  108. /** For internal use only. May be removed or replaced in the future. */
  109. public TreeNode lastSelection;
  110. /** For internal use only. May be removed or replaced in the future. */
  111. public TreeNode focusedNode;
  112. /** For internal use only. May be removed or replaced in the future. */
  113. public MultiSelectMode multiSelectMode = MultiSelectMode.DEFAULT;
  114. private final HashMap<String, TreeNode> keyToNode = new HashMap<String, TreeNode>();
  115. /**
  116. * This map contains captions and icon urls for actions like: * "33_c" ->
  117. * "Edit" * "33_i" -> "http://dom.com/edit.png"
  118. */
  119. private final HashMap<String, String> actionMap = new HashMap<String, String>();
  120. /** For internal use only. May be removed or replaced in the future. */
  121. public boolean immediate;
  122. /** For internal use only. May be removed or replaced in the future. */
  123. public boolean isNullSelectionAllowed = true;
  124. /** For internal use only. May be removed or replaced in the future. */
  125. public boolean disabled = false;
  126. /** For internal use only. May be removed or replaced in the future. */
  127. public boolean readonly;
  128. /** For internal use only. May be removed or replaced in the future. */
  129. public boolean rendering;
  130. private VAbstractDropHandler dropHandler;
  131. /** For internal use only. May be removed or replaced in the future. */
  132. public int dragMode;
  133. private boolean selectionHasChanged = false;
  134. /** For internal use only. May be removed or replaced in the future. */
  135. public String[] bodyActionKeys;
  136. /** For internal use only. May be removed or replaced in the future. */
  137. public TreeConnector connector;
  138. public VLazyExecutor iconLoaded = new VLazyExecutor(50,
  139. new ScheduledCommand() {
  140. @Override
  141. public void execute() {
  142. Util.notifyParentOfSizeChange(VTree.this, true);
  143. }
  144. });
  145. public VTree() {
  146. super();
  147. setStyleName(CLASSNAME);
  148. Roles.getTreeRole().set(body.getElement());
  149. add(body);
  150. addFocusHandler(this);
  151. addBlurHandler(this);
  152. /*
  153. * Listen to context menu events on the empty space in the tree
  154. */
  155. sinkEvents(Event.ONCONTEXTMENU);
  156. addDomHandler(new ContextMenuHandler() {
  157. @Override
  158. public void onContextMenu(ContextMenuEvent event) {
  159. handleBodyContextMenu(event);
  160. }
  161. }, ContextMenuEvent.getType());
  162. /*
  163. * Firefox auto-repeat works correctly only if we use a key press
  164. * handler, other browsers handle it correctly when using a key down
  165. * handler
  166. */
  167. if (BrowserInfo.get().isGecko()) {
  168. addKeyPressHandler(this);
  169. } else {
  170. addKeyDownHandler(this);
  171. }
  172. /*
  173. * We need to use the sinkEvents method to catch the keyUp events so we
  174. * can cache a single shift. KeyUpHandler cannot do this. At the same
  175. * time we catch the mouse down and up events so we can apply the text
  176. * selection patch in IE
  177. */
  178. sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONKEYUP);
  179. /*
  180. * Re-set the tab index to make sure that the FocusElementPanel's
  181. * (super) focus element gets the tab index and not the element
  182. * containing the tree.
  183. */
  184. setTabIndex(0);
  185. }
  186. /*
  187. * (non-Javadoc)
  188. *
  189. * @see
  190. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user
  191. * .client.Event)
  192. */
  193. @Override
  194. public void onBrowserEvent(Event event) {
  195. super.onBrowserEvent(event);
  196. if (event.getTypeInt() == Event.ONMOUSEDOWN) {
  197. // Prevent default text selection in IE
  198. if (BrowserInfo.get().isIE()) {
  199. ((Element) event.getEventTarget().cast()).setPropertyJSO(
  200. "onselectstart", applyDisableTextSelectionIEHack());
  201. }
  202. } else if (event.getTypeInt() == Event.ONMOUSEUP) {
  203. // Remove IE text selection hack
  204. if (BrowserInfo.get().isIE()) {
  205. ((Element) event.getEventTarget().cast()).setPropertyJSO(
  206. "onselectstart", null);
  207. }
  208. } else if (event.getTypeInt() == Event.ONKEYUP) {
  209. if (selectionHasChanged) {
  210. if (event.getKeyCode() == getNavigationDownKey()
  211. && !event.getShiftKey()) {
  212. sendSelectionToServer();
  213. event.preventDefault();
  214. } else if (event.getKeyCode() == getNavigationUpKey()
  215. && !event.getShiftKey()) {
  216. sendSelectionToServer();
  217. event.preventDefault();
  218. } else if (event.getKeyCode() == KeyCodes.KEY_SHIFT) {
  219. sendSelectionToServer();
  220. event.preventDefault();
  221. } else if (event.getKeyCode() == getNavigationSelectKey()) {
  222. sendSelectionToServer();
  223. event.preventDefault();
  224. }
  225. }
  226. }
  227. }
  228. public String getActionCaption(String actionKey) {
  229. return actionMap.get(actionKey + "_c");
  230. }
  231. public String getActionIcon(String actionKey) {
  232. return actionMap.get(actionKey + "_i");
  233. }
  234. /**
  235. * Returns the first root node of the tree or null if there are no root
  236. * nodes.
  237. *
  238. * @return The first root {@link TreeNode}
  239. */
  240. protected TreeNode getFirstRootNode() {
  241. if (body.getWidgetCount() == 0) {
  242. return null;
  243. }
  244. return (TreeNode) body.getWidget(0);
  245. }
  246. /**
  247. * Returns the last root node of the tree or null if there are no root
  248. * nodes.
  249. *
  250. * @return The last root {@link TreeNode}
  251. */
  252. protected TreeNode getLastRootNode() {
  253. if (body.getWidgetCount() == 0) {
  254. return null;
  255. }
  256. return (TreeNode) body.getWidget(body.getWidgetCount() - 1);
  257. }
  258. /**
  259. * Returns a list of all root nodes in the Tree in the order they appear in
  260. * the tree.
  261. *
  262. * @return A list of all root {@link TreeNode}s.
  263. */
  264. protected List<TreeNode> getRootNodes() {
  265. ArrayList<TreeNode> rootNodes = new ArrayList<TreeNode>();
  266. for (int i = 0; i < body.getWidgetCount(); i++) {
  267. rootNodes.add((TreeNode) body.getWidget(i));
  268. }
  269. return rootNodes;
  270. }
  271. private void updateTreeRelatedDragData(VDragEvent drag) {
  272. currentMouseOverKey = findCurrentMouseOverKey(drag.getElementOver());
  273. drag.getDropDetails().put("itemIdOver", currentMouseOverKey);
  274. if (currentMouseOverKey != null) {
  275. TreeNode treeNode = getNodeByKey(currentMouseOverKey);
  276. VerticalDropLocation detail = treeNode.getDropDetail(drag
  277. .getCurrentGwtEvent());
  278. Boolean overTreeNode = null;
  279. if (treeNode != null && !treeNode.isLeaf()
  280. && detail == VerticalDropLocation.MIDDLE) {
  281. overTreeNode = true;
  282. }
  283. drag.getDropDetails().put("itemIdOverIsNode", overTreeNode);
  284. drag.getDropDetails().put("detail", detail);
  285. } else {
  286. drag.getDropDetails().put("itemIdOverIsNode", null);
  287. drag.getDropDetails().put("detail", null);
  288. }
  289. }
  290. private String findCurrentMouseOverKey(Element elementOver) {
  291. TreeNode treeNode = Util.findWidget(elementOver, TreeNode.class);
  292. return treeNode == null ? null : treeNode.key;
  293. }
  294. /** For internal use only. May be removed or replaced in the future. */
  295. public void updateDropHandler(UIDL childUidl) {
  296. if (dropHandler == null) {
  297. dropHandler = new VAbstractDropHandler() {
  298. @Override
  299. public void dragEnter(VDragEvent drag) {
  300. }
  301. @Override
  302. protected void dragAccepted(final VDragEvent drag) {
  303. }
  304. @Override
  305. public void dragOver(final VDragEvent currentDrag) {
  306. final Object oldIdOver = currentDrag.getDropDetails().get(
  307. "itemIdOver");
  308. final VerticalDropLocation oldDetail = (VerticalDropLocation) currentDrag
  309. .getDropDetails().get("detail");
  310. updateTreeRelatedDragData(currentDrag);
  311. final VerticalDropLocation detail = (VerticalDropLocation) currentDrag
  312. .getDropDetails().get("detail");
  313. boolean nodeHasChanged = (currentMouseOverKey != null && currentMouseOverKey != oldIdOver)
  314. || (currentMouseOverKey == null && oldIdOver != null);
  315. boolean detailHasChanded = (detail != null && detail != oldDetail)
  316. || (detail == null && oldDetail != null);
  317. if (nodeHasChanged || detailHasChanded) {
  318. final String newKey = currentMouseOverKey;
  319. TreeNode treeNode = keyToNode.get(oldIdOver);
  320. if (treeNode != null) {
  321. // clear old styles
  322. treeNode.emphasis(null);
  323. }
  324. if (newKey != null) {
  325. validate(new VAcceptCallback() {
  326. @Override
  327. public void accepted(VDragEvent event) {
  328. VerticalDropLocation curDetail = (VerticalDropLocation) event
  329. .getDropDetails().get("detail");
  330. if (curDetail == detail
  331. && newKey.equals(currentMouseOverKey)) {
  332. getNodeByKey(newKey).emphasis(detail);
  333. }
  334. /*
  335. * Else drag is already on a different
  336. * node-detail pair, new criteria check is
  337. * going on
  338. */
  339. }
  340. }, currentDrag);
  341. }
  342. }
  343. }
  344. @Override
  345. public void dragLeave(VDragEvent drag) {
  346. cleanUp();
  347. }
  348. private void cleanUp() {
  349. if (currentMouseOverKey != null) {
  350. getNodeByKey(currentMouseOverKey).emphasis(null);
  351. currentMouseOverKey = null;
  352. }
  353. }
  354. @Override
  355. public boolean drop(VDragEvent drag) {
  356. cleanUp();
  357. return super.drop(drag);
  358. }
  359. @Override
  360. public ComponentConnector getConnector() {
  361. return ConnectorMap.get(client).getConnector(VTree.this);
  362. }
  363. @Override
  364. public ApplicationConnection getApplicationConnection() {
  365. return client;
  366. }
  367. };
  368. }
  369. dropHandler.updateAcceptRules(childUidl);
  370. }
  371. public void setSelected(TreeNode treeNode, boolean selected) {
  372. if (selected) {
  373. if (!isMultiselect) {
  374. while (selectedIds.size() > 0) {
  375. final String id = selectedIds.iterator().next();
  376. final TreeNode oldSelection = getNodeByKey(id);
  377. if (oldSelection != null) {
  378. // can be null if the node is not visible (parent
  379. // collapsed)
  380. oldSelection.setSelected(false);
  381. }
  382. selectedIds.remove(id);
  383. }
  384. }
  385. treeNode.setSelected(true);
  386. selectedIds.add(treeNode.key);
  387. } else {
  388. if (!isNullSelectionAllowed) {
  389. if (!isMultiselect || selectedIds.size() == 1) {
  390. return;
  391. }
  392. }
  393. selectedIds.remove(treeNode.key);
  394. treeNode.setSelected(false);
  395. }
  396. sendSelectionToServer();
  397. }
  398. /**
  399. * Sends the selection to the server
  400. */
  401. private void sendSelectionToServer() {
  402. Command command = new Command() {
  403. @Override
  404. public void execute() {
  405. client.updateVariable(paintableId, "selected",
  406. selectedIds.toArray(new String[selectedIds.size()]),
  407. immediate);
  408. selectionHasChanged = false;
  409. }
  410. };
  411. /*
  412. * Delaying the sending of the selection in webkit to ensure the
  413. * selection is always sent when the tree has focus and after click
  414. * events have been processed. This is due to the focusing
  415. * implementation in FocusImplSafari which uses timeouts when focusing
  416. * and blurring.
  417. */
  418. if (BrowserInfo.get().isWebkit()) {
  419. Scheduler.get().scheduleDeferred(command);
  420. } else {
  421. command.execute();
  422. }
  423. }
  424. /**
  425. * Is a node selected in the tree
  426. *
  427. * @param treeNode
  428. * The node to check
  429. * @return
  430. */
  431. public boolean isSelected(TreeNode treeNode) {
  432. return selectedIds.contains(treeNode.key);
  433. }
  434. public class TreeNode extends SimplePanel implements ActionOwner {
  435. public static final String CLASSNAME = "v-tree-node";
  436. public static final String CLASSNAME_FOCUSED = CLASSNAME + "-focused";
  437. public String key;
  438. /** For internal use only. May be removed or replaced in the future. */
  439. public String[] actionKeys = null;
  440. /** For internal use only. May be removed or replaced in the future. */
  441. public boolean childrenLoaded;
  442. Element nodeCaptionDiv;
  443. protected Element nodeCaptionSpan;
  444. /** For internal use only. May be removed or replaced in the future. */
  445. public FlowPanel childNodeContainer;
  446. private boolean open;
  447. private Icon icon;
  448. private Event mouseDownEvent;
  449. private int cachedHeight = -1;
  450. private boolean focused = false;
  451. public TreeNode() {
  452. constructDom();
  453. sinkEvents(Event.ONCLICK | Event.ONDBLCLICK | Event.MOUSEEVENTS
  454. | Event.TOUCHEVENTS | Event.ONCONTEXTMENU);
  455. }
  456. public VerticalDropLocation getDropDetail(NativeEvent currentGwtEvent) {
  457. if (cachedHeight < 0) {
  458. /*
  459. * Height is cached to avoid flickering (drop hints may change
  460. * the reported offsetheight -> would change the drop detail)
  461. */
  462. cachedHeight = nodeCaptionDiv.getOffsetHeight();
  463. }
  464. VerticalDropLocation verticalDropLocation = DDUtil
  465. .getVerticalDropLocation(nodeCaptionDiv, cachedHeight,
  466. currentGwtEvent, 0.15);
  467. return verticalDropLocation;
  468. }
  469. protected void emphasis(VerticalDropLocation detail) {
  470. String base = "v-tree-node-drag-";
  471. UIObject.setStyleName(getElement(), base + "top",
  472. VerticalDropLocation.TOP == detail);
  473. UIObject.setStyleName(getElement(), base + "bottom",
  474. VerticalDropLocation.BOTTOM == detail);
  475. UIObject.setStyleName(getElement(), base + "center",
  476. VerticalDropLocation.MIDDLE == detail);
  477. base = "v-tree-node-caption-drag-";
  478. UIObject.setStyleName(nodeCaptionDiv, base + "top",
  479. VerticalDropLocation.TOP == detail);
  480. UIObject.setStyleName(nodeCaptionDiv, base + "bottom",
  481. VerticalDropLocation.BOTTOM == detail);
  482. UIObject.setStyleName(nodeCaptionDiv, base + "center",
  483. VerticalDropLocation.MIDDLE == detail);
  484. // also add classname to "folder node" into which the drag is
  485. // targeted
  486. TreeNode folder = null;
  487. /* Possible parent of this TreeNode will be stored here */
  488. TreeNode parentFolder = getParentNode();
  489. // TODO fix my bugs
  490. if (isLeaf()) {
  491. folder = parentFolder;
  492. // note, parent folder may be null if this is root node => no
  493. // folder target exists
  494. } else {
  495. if (detail == VerticalDropLocation.TOP) {
  496. folder = parentFolder;
  497. } else {
  498. folder = this;
  499. }
  500. // ensure we remove the dragfolder classname from the previous
  501. // folder node
  502. setDragFolderStyleName(this, false);
  503. setDragFolderStyleName(parentFolder, false);
  504. }
  505. if (folder != null) {
  506. setDragFolderStyleName(folder, detail != null);
  507. }
  508. }
  509. private TreeNode getParentNode() {
  510. Widget parent2 = getParent().getParent();
  511. if (parent2 instanceof TreeNode) {
  512. return (TreeNode) parent2;
  513. }
  514. return null;
  515. }
  516. private void setDragFolderStyleName(TreeNode folder, boolean add) {
  517. if (folder != null) {
  518. UIObject.setStyleName(folder.getElement(),
  519. "v-tree-node-dragfolder", add);
  520. UIObject.setStyleName(folder.nodeCaptionDiv,
  521. "v-tree-node-caption-dragfolder", add);
  522. }
  523. }
  524. /**
  525. * Handles mouse selection
  526. *
  527. * @param ctrl
  528. * Was the ctrl-key pressed
  529. * @param shift
  530. * Was the shift-key pressed
  531. * @return Returns true if event was handled, else false
  532. */
  533. private boolean handleClickSelection(final boolean ctrl,
  534. final boolean shift) {
  535. // always when clicking an item, focus it
  536. setFocusedNode(this, false);
  537. if (!BrowserInfo.get().isOpera()) {
  538. /*
  539. * Ensure that the tree's focus element also gains focus
  540. * (TreeNodes focus is faked using FocusElementPanel in browsers
  541. * other than Opera).
  542. */
  543. focus();
  544. }
  545. executeEventCommand(new ScheduledCommand() {
  546. @Override
  547. public void execute() {
  548. if (multiSelectMode == MultiSelectMode.SIMPLE
  549. || !isMultiselect) {
  550. toggleSelection();
  551. lastSelection = TreeNode.this;
  552. } else if (multiSelectMode == MultiSelectMode.DEFAULT) {
  553. // Handle ctrl+click
  554. if (isMultiselect && ctrl && !shift) {
  555. toggleSelection();
  556. lastSelection = TreeNode.this;
  557. // Handle shift+click
  558. } else if (isMultiselect && !ctrl && shift) {
  559. deselectAll();
  560. selectNodeRange(lastSelection.key, key);
  561. sendSelectionToServer();
  562. // Handle ctrl+shift click
  563. } else if (isMultiselect && ctrl && shift) {
  564. selectNodeRange(lastSelection.key, key);
  565. // Handle click
  566. } else {
  567. // TODO should happen only if this alone not yet
  568. // selected,
  569. // now sending excess server calls
  570. deselectAll();
  571. toggleSelection();
  572. lastSelection = TreeNode.this;
  573. }
  574. }
  575. }
  576. });
  577. return true;
  578. }
  579. /*
  580. * (non-Javadoc)
  581. *
  582. * @see
  583. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt
  584. * .user.client.Event)
  585. */
  586. @Override
  587. public void onBrowserEvent(Event event) {
  588. super.onBrowserEvent(event);
  589. final int type = DOM.eventGetType(event);
  590. final Element target = DOM.eventGetTarget(event);
  591. if (type == Event.ONLOAD && target == icon.getElement()) {
  592. iconLoaded.trigger();
  593. }
  594. if (disabled) {
  595. return;
  596. }
  597. final boolean inCaption = isCaptionElement(target);
  598. if (inCaption
  599. && client.hasEventListeners(VTree.this,
  600. TreeConstants.ITEM_CLICK_EVENT_ID)
  601. && (type == Event.ONDBLCLICK || type == Event.ONMOUSEUP)) {
  602. fireClick(event);
  603. }
  604. if (type == Event.ONCLICK) {
  605. if (getElement() == target) {
  606. // state change
  607. toggleState();
  608. } else if (!readonly && inCaption) {
  609. if (selectable) {
  610. // caption click = selection change && possible click
  611. // event
  612. if (handleClickSelection(
  613. event.getCtrlKey() || event.getMetaKey(),
  614. event.getShiftKey())) {
  615. event.preventDefault();
  616. }
  617. } else {
  618. // Not selectable, only focus the node.
  619. setFocusedNode(this);
  620. }
  621. }
  622. event.stopPropagation();
  623. } else if (type == Event.ONCONTEXTMENU) {
  624. showContextMenu(event);
  625. }
  626. if (dragMode != 0 || dropHandler != null) {
  627. if (type == Event.ONMOUSEDOWN || type == Event.ONTOUCHSTART) {
  628. if (nodeCaptionDiv.isOrHasChild((Node) event
  629. .getEventTarget().cast())) {
  630. if (dragMode > 0
  631. && (type == Event.ONTOUCHSTART || event
  632. .getButton() == NativeEvent.BUTTON_LEFT)) {
  633. mouseDownEvent = event; // save event for possible
  634. // dd operation
  635. if (type == Event.ONMOUSEDOWN) {
  636. event.preventDefault(); // prevent text
  637. // selection
  638. } else {
  639. /*
  640. * FIXME We prevent touch start event to be used
  641. * as a scroll start event. Note that we cannot
  642. * easily distinguish whether the user wants to
  643. * drag or scroll. The same issue is in table
  644. * that has scrollable area and has drag and
  645. * drop enable. Some kind of timer might be used
  646. * to resolve the issue.
  647. */
  648. event.stopPropagation();
  649. }
  650. }
  651. }
  652. } else if (type == Event.ONMOUSEMOVE
  653. || type == Event.ONMOUSEOUT
  654. || type == Event.ONTOUCHMOVE) {
  655. if (mouseDownEvent != null) {
  656. // start actual drag on slight move when mouse is down
  657. VTransferable t = new VTransferable();
  658. t.setDragSource(ConnectorMap.get(client).getConnector(
  659. VTree.this));
  660. t.setData("itemId", key);
  661. VDragEvent drag = VDragAndDropManager.get().startDrag(
  662. t, mouseDownEvent, true);
  663. drag.createDragImage(nodeCaptionDiv, true);
  664. event.stopPropagation();
  665. mouseDownEvent = null;
  666. }
  667. } else if (type == Event.ONMOUSEUP) {
  668. mouseDownEvent = null;
  669. }
  670. if (type == Event.ONMOUSEOVER) {
  671. mouseDownEvent = null;
  672. currentMouseOverKey = key;
  673. event.stopPropagation();
  674. }
  675. } else if (type == Event.ONMOUSEDOWN
  676. && event.getButton() == NativeEvent.BUTTON_LEFT) {
  677. event.preventDefault(); // text selection
  678. }
  679. }
  680. /**
  681. * Checks if the given element is the caption or the icon.
  682. *
  683. * @param target
  684. * The element to check
  685. * @return true if the element is the caption or the icon
  686. */
  687. public boolean isCaptionElement(com.google.gwt.dom.client.Element target) {
  688. return (target == nodeCaptionSpan || (icon != null && target == icon
  689. .getElement()));
  690. }
  691. private void fireClick(final Event evt) {
  692. /*
  693. * Ensure we have focus in tree before sending variables. Otherwise
  694. * previously modified field may contain dirty variables.
  695. */
  696. if (!treeHasFocus) {
  697. if (BrowserInfo.get().isOpera()) {
  698. if (focusedNode == null) {
  699. getNodeByKey(key).setFocused(true);
  700. } else {
  701. focusedNode.setFocused(true);
  702. }
  703. } else {
  704. focus();
  705. }
  706. }
  707. final MouseEventDetails details = MouseEventDetailsBuilder
  708. .buildMouseEventDetails(evt);
  709. executeEventCommand(new ScheduledCommand() {
  710. @Override
  711. public void execute() {
  712. // Determine if we should send the event immediately to the
  713. // server. We do not want to send the event if there is a
  714. // selection event happening after this. In all other cases
  715. // we want to send it immediately.
  716. boolean sendClickEventNow = true;
  717. if (details.getButton() == MouseButton.LEFT && immediate
  718. && selectable) {
  719. // Probably a selection that will cause a value change
  720. // event to be sent
  721. sendClickEventNow = false;
  722. // The exception is that user clicked on the
  723. // currently selected row and null selection is not
  724. // allowed == no selection event
  725. if (isSelected() && selectedIds.size() == 1
  726. && !isNullSelectionAllowed) {
  727. sendClickEventNow = true;
  728. }
  729. }
  730. client.updateVariable(paintableId, "clickedKey", key, false);
  731. client.updateVariable(paintableId, "clickEvent",
  732. details.toString(), sendClickEventNow);
  733. }
  734. });
  735. }
  736. /*
  737. * Must wait for Safari to focus before sending click and value change
  738. * events (see #6373, #6374)
  739. */
  740. private void executeEventCommand(ScheduledCommand command) {
  741. if (BrowserInfo.get().isWebkit() && !treeHasFocus) {
  742. Scheduler.get().scheduleDeferred(command);
  743. } else {
  744. command.execute();
  745. }
  746. }
  747. private void toggleSelection() {
  748. if (selectable) {
  749. VTree.this.setSelected(this, !isSelected());
  750. }
  751. }
  752. private void toggleState() {
  753. setState(!getState(), true);
  754. }
  755. protected void constructDom() {
  756. String labelId = DOM.createUniqueId();
  757. addStyleName(CLASSNAME);
  758. String treeItemId = DOM.createUniqueId();
  759. getElement().setId(treeItemId);
  760. Roles.getTreeitemRole().set(getElement());
  761. Roles.getTreeitemRole().setAriaSelectedState(getElement(),
  762. SelectedValue.FALSE);
  763. Roles.getTreeitemRole().setAriaLabelledbyProperty(getElement(),
  764. Id.of(labelId));
  765. nodeCaptionDiv = DOM.createDiv();
  766. DOM.setElementProperty(nodeCaptionDiv, "className", CLASSNAME
  767. + "-caption");
  768. Element wrapper = DOM.createDiv();
  769. wrapper.setId(labelId);
  770. wrapper.setAttribute("for", treeItemId);
  771. nodeCaptionSpan = DOM.createSpan();
  772. DOM.appendChild(getElement(), nodeCaptionDiv);
  773. DOM.appendChild(nodeCaptionDiv, wrapper);
  774. DOM.appendChild(wrapper, nodeCaptionSpan);
  775. if (BrowserInfo.get().isOpera()) {
  776. /*
  777. * Focus the caption div of the node to get keyboard navigation
  778. * to work without scrolling up or down when focusing a node.
  779. */
  780. nodeCaptionDiv.setTabIndex(-1);
  781. }
  782. childNodeContainer = new FlowPanel();
  783. childNodeContainer.setStyleName(CLASSNAME + "-children");
  784. Roles.getGroupRole().set(childNodeContainer.getElement());
  785. setWidget(childNodeContainer);
  786. }
  787. public boolean isLeaf() {
  788. String[] styleNames = getStyleName().split(" ");
  789. for (String styleName : styleNames) {
  790. if (styleName.equals(CLASSNAME + "-leaf")) {
  791. return true;
  792. }
  793. }
  794. return false;
  795. }
  796. /** For internal use only. May be removed or replaced in the future. */
  797. public void setState(boolean state, boolean notifyServer) {
  798. if (open == state) {
  799. return;
  800. }
  801. if (state) {
  802. if (!childrenLoaded && notifyServer) {
  803. client.updateVariable(paintableId, "requestChildTree",
  804. true, false);
  805. }
  806. if (notifyServer) {
  807. client.updateVariable(paintableId, "expand",
  808. new String[] { key }, true);
  809. }
  810. addStyleName(CLASSNAME + "-expanded");
  811. Roles.getTreeitemRole().setAriaExpandedState(getElement(),
  812. ExpandedValue.TRUE);
  813. childNodeContainer.setVisible(true);
  814. } else {
  815. removeStyleName(CLASSNAME + "-expanded");
  816. Roles.getTreeitemRole().setAriaExpandedState(getElement(),
  817. ExpandedValue.FALSE);
  818. childNodeContainer.setVisible(false);
  819. if (notifyServer) {
  820. client.updateVariable(paintableId, "collapse",
  821. new String[] { key }, true);
  822. }
  823. }
  824. open = state;
  825. if (!rendering) {
  826. Util.notifyParentOfSizeChange(VTree.this, false);
  827. }
  828. }
  829. /** For internal use only. May be removed or replaced in the future. */
  830. public boolean getState() {
  831. return open;
  832. }
  833. /** For internal use only. May be removed or replaced in the future. */
  834. public void setText(String text) {
  835. DOM.setInnerText(nodeCaptionSpan, text);
  836. }
  837. public boolean isChildrenLoaded() {
  838. return childrenLoaded;
  839. }
  840. /**
  841. * Returns the children of the node
  842. *
  843. * @return A set of tree nodes
  844. */
  845. public List<TreeNode> getChildren() {
  846. List<TreeNode> nodes = new LinkedList<TreeNode>();
  847. if (!isLeaf() && isChildrenLoaded()) {
  848. Iterator<Widget> iter = childNodeContainer.iterator();
  849. while (iter.hasNext()) {
  850. TreeNode node = (TreeNode) iter.next();
  851. nodes.add(node);
  852. }
  853. }
  854. return nodes;
  855. }
  856. @Override
  857. public Action[] getActions() {
  858. if (actionKeys == null) {
  859. return new Action[] {};
  860. }
  861. final Action[] actions = new Action[actionKeys.length];
  862. for (int i = 0; i < actions.length; i++) {
  863. final String actionKey = actionKeys[i];
  864. final TreeAction a = new TreeAction(this, String.valueOf(key),
  865. actionKey);
  866. a.setCaption(getActionCaption(actionKey));
  867. a.setIconUrl(getActionIcon(actionKey));
  868. actions[i] = a;
  869. }
  870. return actions;
  871. }
  872. @Override
  873. public ApplicationConnection getClient() {
  874. return client;
  875. }
  876. @Override
  877. public String getPaintableId() {
  878. return paintableId;
  879. }
  880. /**
  881. * Adds/removes Vaadin specific style name.
  882. * <p>
  883. * For internal use only. May be removed or replaced in the future.
  884. *
  885. * @param selected
  886. */
  887. public void setSelected(boolean selected) {
  888. // add style name to caption dom structure only, not to subtree
  889. setStyleName(nodeCaptionDiv, "v-tree-node-selected", selected);
  890. }
  891. protected boolean isSelected() {
  892. return VTree.this.isSelected(this);
  893. }
  894. /**
  895. * Travels up the hierarchy looking for this node
  896. *
  897. * @param child
  898. * The child which grandparent this is or is not
  899. * @return True if this is a grandparent of the child node
  900. */
  901. public boolean isGrandParentOf(TreeNode child) {
  902. TreeNode currentNode = child;
  903. boolean isGrandParent = false;
  904. while (currentNode != null) {
  905. currentNode = currentNode.getParentNode();
  906. if (currentNode == this) {
  907. isGrandParent = true;
  908. break;
  909. }
  910. }
  911. return isGrandParent;
  912. }
  913. public boolean isSibling(TreeNode node) {
  914. return node.getParentNode() == getParentNode();
  915. }
  916. public void showContextMenu(Event event) {
  917. if (!readonly && !disabled) {
  918. if (actionKeys != null) {
  919. int left = event.getClientX();
  920. int top = event.getClientY();
  921. top += Window.getScrollTop();
  922. left += Window.getScrollLeft();
  923. client.getContextMenu().showAt(this, left, top);
  924. }
  925. event.stopPropagation();
  926. event.preventDefault();
  927. }
  928. }
  929. /*
  930. * (non-Javadoc)
  931. *
  932. * @see com.google.gwt.user.client.ui.Widget#onDetach()
  933. */
  934. @Override
  935. protected void onDetach() {
  936. super.onDetach();
  937. client.getContextMenu().ensureHidden(this);
  938. }
  939. /*
  940. * (non-Javadoc)
  941. *
  942. * @see com.google.gwt.user.client.ui.UIObject#toString()
  943. */
  944. @Override
  945. public String toString() {
  946. return nodeCaptionSpan.getInnerText();
  947. }
  948. /**
  949. * Is the node focused?
  950. *
  951. * @param focused
  952. * True if focused, false if not
  953. */
  954. public void setFocused(boolean focused) {
  955. if (!this.focused && focused) {
  956. nodeCaptionDiv.addClassName(CLASSNAME_FOCUSED);
  957. this.focused = focused;
  958. if (BrowserInfo.get().isOpera()) {
  959. nodeCaptionDiv.focus();
  960. }
  961. treeHasFocus = true;
  962. } else if (this.focused && !focused) {
  963. nodeCaptionDiv.removeClassName(CLASSNAME_FOCUSED);
  964. this.focused = focused;
  965. treeHasFocus = false;
  966. }
  967. }
  968. /**
  969. * Scrolls the caption into view
  970. */
  971. public void scrollIntoView() {
  972. Util.scrollIntoViewVertically(nodeCaptionDiv);
  973. }
  974. public void setIcon(String iconUrl, String altText) {
  975. if (icon != null) {
  976. DOM.getFirstChild(nodeCaptionDiv)
  977. .removeChild(icon.getElement());
  978. }
  979. icon = client.getIcon(iconUrl);
  980. if (icon != null) {
  981. DOM.insertBefore(DOM.getFirstChild(nodeCaptionDiv),
  982. icon.getElement(), nodeCaptionSpan);
  983. icon.setAlternateText(altText);
  984. }
  985. }
  986. public void setNodeStyleName(String styleName) {
  987. addStyleName(TreeNode.CLASSNAME + "-" + styleName);
  988. setStyleName(nodeCaptionDiv, TreeNode.CLASSNAME + "-caption-"
  989. + styleName, true);
  990. childNodeContainer.addStyleName(TreeNode.CLASSNAME + "-children-"
  991. + styleName);
  992. }
  993. }
  994. @Override
  995. public VDropHandler getDropHandler() {
  996. return dropHandler;
  997. }
  998. public TreeNode getNodeByKey(String key) {
  999. return keyToNode.get(key);
  1000. }
  1001. /**
  1002. * Deselects all items in the tree
  1003. */
  1004. public void deselectAll() {
  1005. for (String key : selectedIds) {
  1006. TreeNode node = keyToNode.get(key);
  1007. if (node != null) {
  1008. node.setSelected(false);
  1009. }
  1010. }
  1011. selectedIds.clear();
  1012. selectionHasChanged = true;
  1013. }
  1014. /**
  1015. * Selects a range of nodes
  1016. *
  1017. * @param startNodeKey
  1018. * The start node key
  1019. * @param endNodeKey
  1020. * The end node key
  1021. */
  1022. private void selectNodeRange(String startNodeKey, String endNodeKey) {
  1023. TreeNode startNode = keyToNode.get(startNodeKey);
  1024. TreeNode endNode = keyToNode.get(endNodeKey);
  1025. // The nodes have the same parent
  1026. if (startNode.getParent() == endNode.getParent()) {
  1027. doSiblingSelection(startNode, endNode);
  1028. // The start node is a grandparent of the end node
  1029. } else if (startNode.isGrandParentOf(endNode)) {
  1030. doRelationSelection(startNode, endNode);
  1031. // The end node is a grandparent of the start node
  1032. } else if (endNode.isGrandParentOf(startNode)) {
  1033. doRelationSelection(endNode, startNode);
  1034. } else {
  1035. doNoRelationSelection(startNode, endNode);
  1036. }
  1037. }
  1038. /**
  1039. * Selects a node and deselect all other nodes
  1040. *
  1041. * @param node
  1042. * The node to select
  1043. */
  1044. private void selectNode(TreeNode node, boolean deselectPrevious) {
  1045. if (deselectPrevious) {
  1046. deselectAll();
  1047. }
  1048. if (node != null) {
  1049. node.setSelected(true);
  1050. selectedIds.add(node.key);
  1051. lastSelection = node;
  1052. }
  1053. selectionHasChanged = true;
  1054. }
  1055. /**
  1056. * Deselects a node
  1057. *
  1058. * @param node
  1059. * The node to deselect
  1060. */
  1061. private void deselectNode(TreeNode node) {
  1062. node.setSelected(false);
  1063. selectedIds.remove(node.key);
  1064. selectionHasChanged = true;
  1065. }
  1066. /**
  1067. * Selects all the open children to a node
  1068. *
  1069. * @param node
  1070. * The parent node
  1071. */
  1072. private void selectAllChildren(TreeNode node, boolean includeRootNode) {
  1073. if (includeRootNode) {
  1074. node.setSelected(true);
  1075. selectedIds.add(node.key);
  1076. }
  1077. for (TreeNode child : node.getChildren()) {
  1078. if (!child.isLeaf() && child.getState()) {
  1079. selectAllChildren(child, true);
  1080. } else {
  1081. child.setSelected(true);
  1082. selectedIds.add(child.key);
  1083. }
  1084. }
  1085. selectionHasChanged = true;
  1086. }
  1087. /**
  1088. * Selects all children until a stop child is reached
  1089. *
  1090. * @param root
  1091. * The root not to start from
  1092. * @param stopNode
  1093. * The node to finish with
  1094. * @param includeRootNode
  1095. * Should the root node be selected
  1096. * @param includeStopNode
  1097. * Should the stop node be selected
  1098. *
  1099. * @return Returns false if the stop child was found, else true if all
  1100. * children was selected
  1101. */
  1102. private boolean selectAllChildrenUntil(TreeNode root, TreeNode stopNode,
  1103. boolean includeRootNode, boolean includeStopNode) {
  1104. if (includeRootNode) {
  1105. root.setSelected(true);
  1106. selectedIds.add(root.key);
  1107. }
  1108. if (root.getState() && root != stopNode) {
  1109. for (TreeNode child : root.getChildren()) {
  1110. if (!child.isLeaf() && child.getState() && child != stopNode) {
  1111. if (!selectAllChildrenUntil(child, stopNode, true,
  1112. includeStopNode)) {
  1113. return false;
  1114. }
  1115. } else if (child == stopNode) {
  1116. if (includeStopNode) {
  1117. child.setSelected(true);
  1118. selectedIds.add(child.key);
  1119. }
  1120. return false;
  1121. } else {
  1122. child.setSelected(true);
  1123. selectedIds.add(child.key);
  1124. }
  1125. }
  1126. }
  1127. selectionHasChanged = true;
  1128. return true;
  1129. }
  1130. /**
  1131. * Select a range between two nodes which have no relation to each other
  1132. *
  1133. * @param startNode
  1134. * The start node to start the selection from
  1135. * @param endNode
  1136. * The end node to end the selection to
  1137. */
  1138. private void doNoRelationSelection(TreeNode startNode, TreeNode endNode) {
  1139. TreeNode commonParent = getCommonGrandParent(startNode, endNode);
  1140. TreeNode startBranch = null, endBranch = null;
  1141. // Find the children of the common parent
  1142. List<TreeNode> children;
  1143. if (commonParent != null) {
  1144. children = commonParent.getChildren();
  1145. } else {
  1146. children = getRootNodes();
  1147. }
  1148. // Find the start and end branches
  1149. for (TreeNode node : children) {
  1150. if (nodeIsInBranch(startNode, node)) {
  1151. startBranch = node;
  1152. }
  1153. if (nodeIsInBranch(endNode, node)) {
  1154. endBranch = node;
  1155. }
  1156. }
  1157. // Swap nodes if necessary
  1158. if (children.indexOf(startBranch) > children.indexOf(endBranch)) {
  1159. TreeNode temp = startBranch;
  1160. startBranch = endBranch;
  1161. endBranch = temp;
  1162. temp = startNode;
  1163. startNode = endNode;
  1164. endNode = temp;
  1165. }
  1166. // Select all children under the start node
  1167. selectAllChildren(startNode, true);
  1168. TreeNode startParent = startNode.getParentNode();
  1169. TreeNode currentNode = startNode;
  1170. while (startParent != null && startParent != commonParent) {
  1171. List<TreeNode> startChildren = startParent.getChildren();
  1172. for (int i = startChildren.indexOf(currentNode) + 1; i < startChildren
  1173. .size(); i++) {
  1174. selectAllChildren(startChildren.get(i), true);
  1175. }
  1176. currentNode = startParent;
  1177. startParent = startParent.getParentNode();
  1178. }
  1179. // Select nodes until the end node is reached
  1180. for (int i = children.indexOf(startBranch) + 1; i <= children
  1181. .indexOf(endBranch); i++) {
  1182. selectAllChildrenUntil(children.get(i), endNode, true, true);
  1183. }
  1184. // Ensure end node was selected
  1185. endNode.setSelected(true);
  1186. selectedIds.add(endNode.key);
  1187. selectionHasChanged = true;
  1188. }
  1189. /**
  1190. * Examines the children of the branch node and returns true if a node is in
  1191. * that branch
  1192. *
  1193. * @param node
  1194. * The node to search for
  1195. * @param branch
  1196. * The branch to search in
  1197. * @return True if found, false if not found
  1198. */
  1199. private boolean nodeIsInBranch(TreeNode node, TreeNode branch) {
  1200. if (node == branch) {
  1201. return true;
  1202. }
  1203. for (TreeNode child : branch.getChildren()) {
  1204. if (child == node) {
  1205. return true;
  1206. }
  1207. if (!child.isLeaf() && child.getState()) {
  1208. if (nodeIsInBranch(node, child)) {
  1209. return true;
  1210. }
  1211. }
  1212. }
  1213. return false;
  1214. }
  1215. /**
  1216. * Selects a range of items which are in direct relation with each other.<br/>
  1217. * NOTE: The start node <b>MUST</b> be before the end node!
  1218. *
  1219. * @param startNode
  1220. *
  1221. * @param endNode
  1222. */
  1223. private void doRelationSelection(TreeNode startNode, TreeNode endNode) {
  1224. TreeNode currentNode = endNode;
  1225. while (currentNode != startNode) {
  1226. currentNode.setSelected(true);
  1227. selectedIds.add(currentNode.key);
  1228. // Traverse children above the selection
  1229. List<TreeNode> subChildren = currentNode.getParentNode()
  1230. .getChildren();
  1231. if (subChildren.size() > 1) {
  1232. selectNodeRange(subChildren.iterator().next().key,
  1233. currentNode.key);
  1234. } else if (subChildren.size() == 1) {
  1235. TreeNode n = subChildren.get(0);
  1236. n.setSelected(true);
  1237. selectedIds.add(n.key);
  1238. }
  1239. currentNode = currentNode.getParentNode();
  1240. }
  1241. startNode.setSelected(true);
  1242. selectedIds.add(startNode.key);
  1243. selectionHasChanged = true;
  1244. }
  1245. /**
  1246. * Selects a range of items which have the same parent.
  1247. *
  1248. * @param startNode
  1249. * The start node
  1250. * @param endNode
  1251. * The end node
  1252. */
  1253. private void doSiblingSelection(TreeNode startNode, TreeNode endNode) {
  1254. TreeNode parent = startNode.getParentNode();
  1255. List<TreeNode> children;
  1256. if (parent == null) {
  1257. // Topmost parent
  1258. children = getRootNodes();
  1259. } else {
  1260. children = parent.getChildren();
  1261. }
  1262. // Swap start and end point if needed
  1263. if (children.indexOf(startNode) > children.indexOf(endNode)) {
  1264. TreeNode temp = startNode;
  1265. startNode = endNode;
  1266. endNode = temp;
  1267. }
  1268. Iterator<TreeNode> childIter = children.iterator();
  1269. boolean startFound = false;
  1270. while (childIter.hasNext()) {
  1271. TreeNode node = childIter.next();
  1272. if (node == startNode) {
  1273. startFound = true;
  1274. }
  1275. if (startFound && node != endNode && node.getState()) {
  1276. selectAllChildren(node, true);
  1277. } else if (startFound && node != endNode) {
  1278. node.setSelected(true);
  1279. selectedIds.add(node.key);
  1280. }
  1281. if (node == endNode) {
  1282. node.setSelected(true);
  1283. selectedIds.add(node.key);
  1284. break;
  1285. }
  1286. }
  1287. selectionHasChanged = true;
  1288. }
  1289. /**
  1290. * Returns the first common parent of two nodes
  1291. *
  1292. * @param node1
  1293. * The first node
  1294. * @param node2
  1295. * The second node
  1296. * @return The common parent or null
  1297. */
  1298. public TreeNode getCommonGrandParent(TreeNode node1, TreeNode node2) {
  1299. // If either one does not have a grand parent then return null
  1300. if (node1.getParentNode() == null || node2.getParentNode() == null) {
  1301. return null;
  1302. }
  1303. // If the nodes are parents of each other then return null
  1304. if (node1.isGrandParentOf(node2) || node2.isGrandParentOf(node1)) {
  1305. return null;
  1306. }
  1307. // Get parents of node1
  1308. List<TreeNode> parents1 = new ArrayList<TreeNode>();
  1309. TreeNode parent1 = node1.getParentNode();
  1310. while (parent1 != null) {
  1311. parents1.add(parent1);
  1312. parent1 = parent1.getParentNode();
  1313. }
  1314. // Get parents of node2
  1315. List<TreeNode> parents2 = new ArrayList<TreeNode>();
  1316. TreeNode parent2 = node2.getParentNode();
  1317. while (parent2 != null) {
  1318. parents2.add(parent2);
  1319. parent2 = parent2.getParentNode();
  1320. }
  1321. // Search the parents for the first common parent
  1322. for (int i = 0; i < parents1.size(); i++) {
  1323. parent1 = parents1.get(i);
  1324. for (int j = 0; j < parents2.size(); j++) {
  1325. parent2 = parents2.get(j);
  1326. if (parent1 == parent2) {
  1327. return parent1;
  1328. }
  1329. }
  1330. }
  1331. return null;
  1332. }
  1333. /**
  1334. * Sets the node currently in focus
  1335. *
  1336. * @param node
  1337. * The node to focus or null to remove the focus completely
  1338. * @param scrollIntoView
  1339. * Scroll the node into view
  1340. */
  1341. public void setFocusedNode(TreeNode node, boolean scrollIntoView) {
  1342. // Unfocus previously focused node
  1343. if (focusedNode != null) {
  1344. focusedNode.setFocused(false);
  1345. Roles.getTreeRole().removeAriaActivedescendantProperty(
  1346. focusedNode.getElement());
  1347. }
  1348. if (node != null) {
  1349. node.setFocused(true);
  1350. Roles.getTreeitemRole().setAriaSelectedState(node.getElement(),
  1351. SelectedValue.TRUE);
  1352. /*
  1353. * FIXME: This code needs to be changed when the keyboard navigation
  1354. * doesn't immediately trigger a selection change anymore.
  1355. *
  1356. * Right now this function is called before and after the Tree is
  1357. * rebuilt when up/down arrow keys are pressed. This leads to the
  1358. * problem, that the newly selected item is announced too often with
  1359. * a screen reader.
  1360. *
  1361. * Behaviour is different when using the Tree with and without
  1362. * screen reader.
  1363. */
  1364. if (node.key.equals(lastNodeKey)) {
  1365. Roles.getTreeRole().setAriaActivedescendantProperty(
  1366. getFocusElement(), Id.of(node.getElement()));
  1367. } else {
  1368. lastNodeKey = node.key;
  1369. }
  1370. }
  1371. focusedNode = node;
  1372. if (node != null && scrollIntoView) {
  1373. /*
  1374. * Delay scrolling the focused node into view if we are still
  1375. * rendering. #5396
  1376. */
  1377. if (!rendering) {
  1378. node.scrollIntoView();
  1379. } else {
  1380. Scheduler.get().scheduleDeferred(new Command() {
  1381. @Override
  1382. public void execute() {
  1383. focusedNode.scrollIntoView();
  1384. }
  1385. });
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * Focuses a node and scrolls it into view
  1391. *
  1392. * @param node
  1393. * The node to focus
  1394. */
  1395. public void setFocusedNode(TreeNode node) {
  1396. setFocusedNode(node, true);
  1397. }
  1398. /*
  1399. * (non-Javadoc)
  1400. *
  1401. * @see
  1402. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1403. * .dom.client.FocusEvent)
  1404. */
  1405. @Override
  1406. public void onFocus(FocusEvent event) {
  1407. treeHasFocus = true;
  1408. // If no node has focus, focus the first item in the tree
  1409. if (focusedNode == null && lastSelection == null && selectable) {
  1410. setFocusedNode(getFirstRootNode(), false);
  1411. } else if (focusedNode != null && selectable) {
  1412. setFocusedNode(focusedNode, false);
  1413. } else if (lastSelection != null && selectable) {
  1414. setFocusedNode(lastSelection, false);
  1415. }
  1416. }
  1417. /*
  1418. * (non-Javadoc)
  1419. *
  1420. * @see
  1421. * com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
  1422. * .dom.client.BlurEvent)
  1423. */
  1424. @Override
  1425. public void onBlur(BlurEvent event) {
  1426. treeHasFocus = false;
  1427. if (focusedNode != null) {
  1428. focusedNode.setFocused(false);
  1429. }
  1430. }
  1431. /*
  1432. * (non-Javadoc)
  1433. *
  1434. * @see
  1435. * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
  1436. * .gwt.event.dom.client.KeyPressEvent)
  1437. */
  1438. @Override
  1439. public void onKeyPress(KeyPressEvent event) {
  1440. NativeEvent nativeEvent = event.getNativeEvent();
  1441. int keyCode = nativeEvent.getKeyCode();
  1442. if (keyCode == 0 && nativeEvent.getCharCode() == ' ') {
  1443. // Provide a keyCode for space to be compatible with FireFox
  1444. // keypress event
  1445. keyCode = CHARCODE_SPACE;
  1446. }
  1447. if (handleKeyNavigation(keyCode,
  1448. event.isControlKeyDown() || event.isMetaKeyDown(),
  1449. event.isShiftKeyDown())) {
  1450. event.preventDefault();
  1451. event.stopPropagation();
  1452. }
  1453. }
  1454. /*
  1455. * (non-Javadoc)
  1456. *
  1457. * @see
  1458. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1459. * .event.dom.client.KeyDownEvent)
  1460. */
  1461. @Override
  1462. public void onKeyDown(KeyDownEvent event) {
  1463. if (handleKeyNavigation(event.getNativeEvent().getKeyCode(),
  1464. event.isControlKeyDown() || event.isMetaKeyDown(),
  1465. event.isShiftKeyDown())) {
  1466. event.preventDefault();
  1467. event.stopPropagation();
  1468. }
  1469. }
  1470. /**
  1471. * Handles the keyboard navigation
  1472. *
  1473. * @param keycode
  1474. * The keycode of the pressed key
  1475. * @param ctrl
  1476. * Was ctrl pressed
  1477. * @param shift
  1478. * Was shift pressed
  1479. * @return Returns true if the key was handled, else false
  1480. */
  1481. protected boolean handleKeyNavigation(int keycode, boolean ctrl,
  1482. boolean shift) {
  1483. // Navigate down
  1484. if (keycode == getNavigationDownKey()) {
  1485. TreeNode node = null;
  1486. // If node is open and has children then move in to the children
  1487. if (!focusedNode.isLeaf() && focusedNode.getState()
  1488. && focusedNode.getChildren().size() > 0) {
  1489. node = focusedNode.getChildren().get(0);
  1490. }
  1491. // Else move down to the next sibling
  1492. else {
  1493. node = getNextSibling(focusedNode);
  1494. if (node == null) {
  1495. // Else jump to the parent and try to select the next
  1496. // sibling there
  1497. TreeNode current = focusedNode;
  1498. while (node == null && current.getParentNode() != null) {
  1499. node = getNextSibling(current.getParentNode());
  1500. current = current.getParentNode();
  1501. }
  1502. }
  1503. }
  1504. if (node != null) {
  1505. setFocusedNode(node);
  1506. if (selectable) {
  1507. if (!ctrl && !shift) {
  1508. selectNode(node, true);
  1509. } else if (shift && isMultiselect) {
  1510. deselectAll();
  1511. selectNodeRange(lastSelection.key, node.key);
  1512. } else if (shift) {
  1513. selectNode(node, true);
  1514. }
  1515. }
  1516. }
  1517. showTooltipForKeyboardNavigation(node);
  1518. return true;
  1519. }
  1520. // Navigate up
  1521. if (keycode == getNavigationUpKey()) {
  1522. TreeNode prev = getPreviousSibling(focusedNode);
  1523. TreeNode node = null;
  1524. if (prev != null) {
  1525. node = getLastVisibleChildInTree(prev);
  1526. } else if (focusedNode.getParentNode() != null) {
  1527. node = focusedNode.getParentNode();
  1528. }
  1529. if (node != null) {
  1530. setFocusedNode(node);
  1531. if (selectable) {
  1532. if (!ctrl && !shift) {
  1533. selectNode(node, true);
  1534. } else if (shift && isMultiselect) {
  1535. deselectAll();
  1536. selectNodeRange(lastSelection.key, node.key);
  1537. } else if (shift) {
  1538. selectNode(node, true);
  1539. }
  1540. }
  1541. }
  1542. showTooltipForKeyboardNavigation(node);
  1543. return true;
  1544. }
  1545. // Navigate left (close branch)
  1546. if (keycode == getNavigationLeftKey()) {
  1547. if (!focusedNode.isLeaf() && focusedNode.getState()) {
  1548. focusedNode.setState(false, true);
  1549. } else if (focusedNode.getParentNode() != null
  1550. && (focusedNode.isLeaf() || !focusedNode.getState())) {
  1551. if (ctrl || !selectable) {
  1552. setFocusedNode(focusedNode.getParentNode());
  1553. } else if (shift) {
  1554. doRelationSelection(focusedNode.getParentNode(),
  1555. focusedNode);
  1556. setFocusedNode(focusedNode.getParentNode());
  1557. } else {
  1558. focusAndSelectNode(focusedNode.getParentNode());
  1559. }
  1560. }
  1561. showTooltipForKeyboardNavigation(focusedNode);
  1562. return true;
  1563. }
  1564. // Navigate right (open branch)
  1565. if (keycode == getNavigationRightKey()) {
  1566. if (!focusedNode.isLeaf() && !focusedNode.getState()) {
  1567. focusedNode.setState(true, true);
  1568. } else if (!focusedNode.isLeaf()) {
  1569. if (ctrl || !selectable) {
  1570. setFocusedNode(focusedNode.getChildren().get(0));
  1571. } else if (shift) {
  1572. setSelected(focusedNode, true);
  1573. setFocusedNode(focusedNode.getChildren().get(0));
  1574. setSelected(focusedNode, true);
  1575. } else {
  1576. focusAndSelectNode(focusedNode.getChildren().get(0));
  1577. }
  1578. }
  1579. showTooltipForKeyboardNavigation(focusedNode);
  1580. return true;
  1581. }
  1582. // Selection
  1583. if (keycode == getNavigationSelectKey()) {
  1584. if (!focusedNode.isSelected()) {
  1585. selectNode(
  1586. focusedNode,
  1587. (!isMultiselect || multiSelectMode == MULTISELECT_MODE_SIMPLE)
  1588. && selectable);
  1589. } else {
  1590. deselectNode(focusedNode);
  1591. }
  1592. return true;
  1593. }
  1594. // Home selection
  1595. if (keycode == getNavigationStartKey()) {
  1596. TreeNode node = getFirstRootNode();
  1597. if (ctrl || !selectable) {
  1598. setFocusedNode(node);
  1599. } else if (shift) {
  1600. deselectAll();
  1601. selectNodeRange(focusedNode.key, node.key);
  1602. } else {
  1603. selectNode(node, true);
  1604. }
  1605. sendSelectionToServer();
  1606. showTooltipForKeyboardNavigation(node);
  1607. return true;
  1608. }
  1609. // End selection
  1610. if (keycode == getNavigationEndKey()) {
  1611. TreeNode lastNode = getLastRootNode();
  1612. TreeNode node = getLastVisibleChildInTree(lastNode);
  1613. if (ctrl || !selectable) {
  1614. setFocusedNode(node);
  1615. } else if (shift) {
  1616. deselectAll();
  1617. selectNodeRange(focusedNode.key, node.key);
  1618. } else {
  1619. selectNode(node, true);
  1620. }
  1621. sendSelectionToServer();
  1622. showTooltipForKeyboardNavigation(node);
  1623. return true;
  1624. }
  1625. return false;
  1626. }
  1627. private void showTooltipForKeyboardNavigation(TreeNode node) {
  1628. if (connector != null) {
  1629. getClient().getVTooltip().showAssistive(
  1630. connector.getTooltipInfo(node.nodeCaptionSpan));
  1631. }
  1632. }
  1633. private void focusAndSelectNode(TreeNode node) {
  1634. /*
  1635. * Keyboard navigation doesn't work reliably if the tree is in
  1636. * multiselect mode as well as isNullSelectionAllowed = false. It first
  1637. * tries to deselect the old focused node, which fails since there must
  1638. * be at least one selection. After this the newly focused node is
  1639. * selected and we've ended up with two selected nodes even though we
  1640. * only navigated with the arrow keys.
  1641. *
  1642. * Because of this, we first select the next node and later de-select
  1643. * the old one.
  1644. */
  1645. TreeNode oldFocusedNode = focusedNode;
  1646. setFocusedNode(node);
  1647. setSelected(focusedNode, true);
  1648. setSelected(oldFocusedNode, false);
  1649. }
  1650. /**
  1651. * Traverses the tree to the bottom most child
  1652. *
  1653. * @param root
  1654. * The root of the tree
  1655. * @return The bottom most child
  1656. */
  1657. private TreeNode getLastVisibleChildInTree(TreeNode root) {
  1658. if (root.isLeaf() || !root.getState() || root.getChildren().size() == 0) {
  1659. return root;
  1660. }
  1661. List<TreeNode> children = root.getChildren();
  1662. return getLastVisibleChildInTree(children.get(children.size() - 1));
  1663. }
  1664. /**
  1665. * Gets the next sibling in the tree
  1666. *
  1667. * @param node
  1668. * The node to get the sibling for
  1669. * @return The sibling node or null if the node is the last sibling
  1670. */
  1671. private TreeNode getNextSibling(TreeNode node) {
  1672. TreeNode parent = node.getParentNode();
  1673. List<TreeNode> children;
  1674. if (parent == null) {
  1675. children = getRootNodes();
  1676. } else {
  1677. children = parent.getChildren();
  1678. }
  1679. int idx = children.indexOf(node);
  1680. if (idx < children.size() - 1) {
  1681. return children.get(idx + 1);
  1682. }
  1683. return null;
  1684. }
  1685. /**
  1686. * Returns the previous sibling in the tree
  1687. *
  1688. * @param node
  1689. * The node to get the sibling for
  1690. * @return The sibling node or null if the node is the first sibling
  1691. */
  1692. private TreeNode getPreviousSibling(TreeNode node) {
  1693. TreeNode parent = node.getParentNode();
  1694. List<TreeNode> children;
  1695. if (parent == null) {
  1696. children = getRootNodes();
  1697. } else {
  1698. children = parent.getChildren();
  1699. }
  1700. int idx = children.indexOf(node);
  1701. if (idx > 0) {
  1702. return children.get(idx - 1);
  1703. }
  1704. return null;
  1705. }
  1706. /**
  1707. * Add this to the element mouse down event by using element.setPropertyJSO
  1708. * ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
  1709. * when the mouse is depressed in the mouse up event.
  1710. *
  1711. * @return Returns the JSO preventing text selection
  1712. */
  1713. private native JavaScriptObject applyDisableTextSelectionIEHack()
  1714. /*-{
  1715. return function(){ return false; };
  1716. }-*/;
  1717. /**
  1718. * Get the key that moves the selection head upwards. By default it is the
  1719. * up arrow key but by overriding this you can change the key to whatever
  1720. * you want.
  1721. *
  1722. * @return The keycode of the key
  1723. */
  1724. protected int getNavigationUpKey() {
  1725. return KeyCodes.KEY_UP;
  1726. }
  1727. /**
  1728. * Get the key that moves the selection head downwards. By default it is the
  1729. * down arrow key but by overriding this you can change the key to whatever
  1730. * you want.
  1731. *
  1732. * @return The keycode of the key
  1733. */
  1734. protected int getNavigationDownKey() {
  1735. return KeyCodes.KEY_DOWN;
  1736. }
  1737. /**
  1738. * Get the key that scrolls to the left in the table. By default it is the
  1739. * left arrow key but by overriding this you can change the key to whatever
  1740. * you want.
  1741. *
  1742. * @return The keycode of the key
  1743. */
  1744. protected int getNavigationLeftKey() {
  1745. return KeyCodes.KEY_LEFT;
  1746. }
  1747. /**
  1748. * Get the key that scroll to the right on the table. By default it is the
  1749. * right arrow key but by overriding this you can change the key to whatever
  1750. * you want.
  1751. *
  1752. * @return The keycode of the key
  1753. */
  1754. protected int getNavigationRightKey() {
  1755. return KeyCodes.KEY_RIGHT;
  1756. }
  1757. /**
  1758. * Get the key that selects an item in the table. By default it is the space
  1759. * bar key but by overriding this you can change the key to whatever you
  1760. * want.
  1761. *
  1762. * @return
  1763. */
  1764. protected int getNavigationSelectKey() {
  1765. return CHARCODE_SPACE;
  1766. }
  1767. /**
  1768. * Get the key the moves the selection one page up in the table. By default
  1769. * this is the Page Up key but by overriding this you can change the key to
  1770. * whatever you want.
  1771. *
  1772. * @return
  1773. */
  1774. protected int getNavigationPageUpKey() {
  1775. return KeyCodes.KEY_PAGEUP;
  1776. }
  1777. /**
  1778. * Get the key the moves the selection one page down in the table. By
  1779. * default this is the Page Down key but by overriding this you can change
  1780. * the key to whatever you want.
  1781. *
  1782. * @return
  1783. */
  1784. protected int getNavigationPageDownKey() {
  1785. return KeyCodes.KEY_PAGEDOWN;
  1786. }
  1787. /**
  1788. * Get the key the moves the selection to the beginning of the table. By
  1789. * default this is the Home key but by overriding this you can change the
  1790. * key to whatever you want.
  1791. *
  1792. * @return
  1793. */
  1794. protected int getNavigationStartKey() {
  1795. return KeyCodes.KEY_HOME;
  1796. }
  1797. /**
  1798. * Get the key the moves the selection to the end of the table. By default
  1799. * this is the End key but by overriding this you can change the key to
  1800. * whatever you want.
  1801. *
  1802. * @return
  1803. */
  1804. protected int getNavigationEndKey() {
  1805. return KeyCodes.KEY_END;
  1806. }
  1807. private final String SUBPART_NODE_PREFIX = "n";
  1808. private final String EXPAND_IDENTIFIER = "expand";
  1809. /*
  1810. * In webkit, focus may have been requested for this component but not yet
  1811. * gained. Use this to trac if tree has gained the focus on webkit. See
  1812. * FocusImplSafari and #6373
  1813. */
  1814. private boolean treeHasFocus;
  1815. /*
  1816. * (non-Javadoc)
  1817. *
  1818. * @see com.vaadin.client.ui.SubPartAware#getSubPartElement(java
  1819. * .lang.String)
  1820. */
  1821. @Override
  1822. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  1823. if ("fe".equals(subPart)) {
  1824. if (BrowserInfo.get().isOpera() && focusedNode != null) {
  1825. return focusedNode.getElement();
  1826. }
  1827. return getFocusElement();
  1828. }
  1829. if (subPart.startsWith(SUBPART_NODE_PREFIX + "[")) {
  1830. boolean expandCollapse = false;
  1831. // Node
  1832. String[] nodes = subPart.split("/");
  1833. TreeNode treeNode = null;
  1834. try {
  1835. for (String node : nodes) {
  1836. if (node.startsWith(SUBPART_NODE_PREFIX)) {
  1837. // skip SUBPART_NODE_PREFIX"["
  1838. node = node.substring(SUBPART_NODE_PREFIX.length() + 1);
  1839. // skip "]"
  1840. node = node.substring(0, node.length() - 1);
  1841. int position = Integer.parseInt(node);
  1842. if (treeNode == null) {
  1843. treeNode = getRootNodes().get(position);
  1844. } else {
  1845. treeNode = treeNode.getChildren().get(position);
  1846. }
  1847. } else if (node.startsWith(EXPAND_IDENTIFIER)) {
  1848. expandCollapse = true;
  1849. }
  1850. }
  1851. if (expandCollapse) {
  1852. return treeNode.getElement();
  1853. } else {
  1854. return DOM.asOld(treeNode.nodeCaptionSpan);
  1855. }
  1856. } catch (Exception e) {
  1857. // Invalid locator string or node could not be found
  1858. return null;
  1859. }
  1860. }
  1861. return null;
  1862. }
  1863. /*
  1864. * (non-Javadoc)
  1865. *
  1866. * @see com.vaadin.client.ui.SubPartAware#getSubPartName(com.google
  1867. * .gwt.user.client.Element)
  1868. */
  1869. @Override
  1870. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  1871. // Supported identifiers:
  1872. //
  1873. // n[index]/n[index]/n[index]{/expand}
  1874. //
  1875. // Ends with "/expand" if the target is expand/collapse indicator,
  1876. // otherwise ends with the node
  1877. boolean isExpandCollapse = false;
  1878. if (!getElement().isOrHasChild(subElement)) {
  1879. return null;
  1880. }
  1881. if (subElement == getFocusElement()) {
  1882. return "fe";
  1883. }
  1884. TreeNode treeNode = Util.findWidget(subElement, TreeNode.class);
  1885. if (treeNode == null) {
  1886. // Did not click on a node, let somebody else take care of the
  1887. // locator string
  1888. return null;
  1889. }
  1890. if (subElement == treeNode.getElement()) {
  1891. // Targets expand/collapse arrow
  1892. isExpandCollapse = true;
  1893. }
  1894. ArrayList<Integer> positions = new ArrayList<Integer>();
  1895. while (treeNode.getParentNode() != null) {
  1896. positions.add(0,
  1897. treeNode.getParentNode().getChildren().indexOf(treeNode));
  1898. treeNode = treeNode.getParentNode();
  1899. }
  1900. positions.add(0, getRootNodes().indexOf(treeNode));
  1901. String locator = "";
  1902. for (Integer i : positions) {
  1903. locator += SUBPART_NODE_PREFIX + "[" + i + "]/";
  1904. }
  1905. locator = locator.substring(0, locator.length() - 1);
  1906. if (isExpandCollapse) {
  1907. locator += "/" + EXPAND_IDENTIFIER;
  1908. }
  1909. return locator;
  1910. }
  1911. @Override
  1912. public Action[] getActions() {
  1913. if (bodyActionKeys == null) {
  1914. return new Action[] {};
  1915. }
  1916. final Action[] actions = new Action[bodyActionKeys.length];
  1917. for (int i = 0; i < actions.length; i++) {
  1918. final String actionKey = bodyActionKeys[i];
  1919. final TreeAction a = new TreeAction(this, null, actionKey);
  1920. a.setCaption(getActionCaption(actionKey));
  1921. a.setIconUrl(getActionIcon(actionKey));
  1922. actions[i] = a;
  1923. }
  1924. return actions;
  1925. }
  1926. @Override
  1927. public ApplicationConnection getClient() {
  1928. return client;
  1929. }
  1930. @Override
  1931. public String getPaintableId() {
  1932. return paintableId;
  1933. }
  1934. private void handleBodyContextMenu(ContextMenuEvent event) {
  1935. if (!readonly && !disabled) {
  1936. if (bodyActionKeys != null) {
  1937. int left = event.getNativeEvent().getClientX();
  1938. int top = event.getNativeEvent().getClientY();
  1939. top += Window.getScrollTop();
  1940. left += Window.getScrollLeft();
  1941. client.getContextMenu().showAt(this, left, top);
  1942. }
  1943. event.stopPropagation();
  1944. event.preventDefault();
  1945. }
  1946. }
  1947. public void registerAction(String key, String caption, String iconUrl) {
  1948. actionMap.put(key + "_c", caption);
  1949. if (iconUrl != null) {
  1950. actionMap.put(key + "_i", iconUrl);
  1951. } else {
  1952. actionMap.remove(key + "_i");
  1953. }
  1954. }
  1955. public void registerNode(TreeNode treeNode) {
  1956. keyToNode.put(treeNode.key, treeNode);
  1957. }
  1958. public void clearNodeToKeyMap() {
  1959. keyToNode.clear();
  1960. }
  1961. @Override
  1962. public void bindAriaCaption(
  1963. com.google.gwt.user.client.Element captionElement) {
  1964. AriaHelper.bindCaption(body, captionElement);
  1965. }
  1966. }