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 77KB

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