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

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