Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

VTree.java 77KB

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