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

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