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

VTree.java 77KB

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