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

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