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

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