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

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