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.

VMenuBar.java 53KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import java.util.ArrayList;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import java.util.Queue;
  21. import com.google.gwt.core.client.GWT;
  22. import com.google.gwt.core.client.Scheduler;
  23. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  24. import com.google.gwt.dom.client.Element;
  25. import com.google.gwt.dom.client.Style;
  26. import com.google.gwt.dom.client.Style.Overflow;
  27. import com.google.gwt.dom.client.Style.Unit;
  28. import com.google.gwt.event.dom.client.FocusEvent;
  29. import com.google.gwt.event.dom.client.FocusHandler;
  30. import com.google.gwt.event.dom.client.KeyCodes;
  31. import com.google.gwt.event.dom.client.KeyDownEvent;
  32. import com.google.gwt.event.dom.client.KeyDownHandler;
  33. import com.google.gwt.event.dom.client.KeyPressEvent;
  34. import com.google.gwt.event.dom.client.KeyPressHandler;
  35. import com.google.gwt.event.logical.shared.CloseEvent;
  36. import com.google.gwt.event.logical.shared.CloseHandler;
  37. import com.google.gwt.user.client.Command;
  38. import com.google.gwt.user.client.DOM;
  39. import com.google.gwt.user.client.Event;
  40. import com.google.gwt.user.client.Timer;
  41. import com.google.gwt.user.client.ui.HasHTML;
  42. import com.google.gwt.user.client.ui.PopupPanel;
  43. import com.google.gwt.user.client.ui.RootPanel;
  44. import com.google.gwt.user.client.ui.Widget;
  45. import com.vaadin.client.ApplicationConnection;
  46. import com.vaadin.client.BrowserInfo;
  47. import com.vaadin.client.LayoutManager;
  48. import com.vaadin.client.TooltipInfo;
  49. import com.vaadin.client.UIDL;
  50. import com.vaadin.client.Util;
  51. import com.vaadin.client.WidgetUtil;
  52. import com.vaadin.shared.ui.menubar.MenuBarConstants;
  53. public class VMenuBar extends SimpleFocusablePanel implements
  54. CloseHandler<PopupPanel>, KeyPressHandler, KeyDownHandler,
  55. FocusHandler, SubPartAware {
  56. // The hierarchy of VMenuBar is a bit weird as VMenuBar is the Paintable,
  57. // used for the root menu but also used for the sub menus.
  58. /** Set the CSS class name to allow styling. */
  59. public static final String CLASSNAME = "v-menubar";
  60. public static final String SUBMENU_CLASSNAME_PREFIX = "-submenu";
  61. /**
  62. * For server connections.
  63. * <p>
  64. * For internal use only. May be removed or replaced in the future.
  65. */
  66. public String uidlId;
  67. /** For internal use only. May be removed or replaced in the future. */
  68. public ApplicationConnection client;
  69. /** For internal use only. May be removed or replaced in the future. */
  70. public final VMenuBar hostReference = this;
  71. /** For internal use only. May be removed or replaced in the future. */
  72. public CustomMenuItem moreItem = null;
  73. /** For internal use only. May be removed or replaced in the future. */
  74. public VMenuBar collapsedRootItems;
  75. /**
  76. * An empty command to be used when the item has no command associated
  77. * <p>
  78. * For internal use only. May be removed or replaced in the future.
  79. */
  80. public static final Command emptyCommand = null;
  81. /** Widget fields **/
  82. protected boolean subMenu;
  83. protected ArrayList<CustomMenuItem> items;
  84. protected Element containerElement;
  85. protected VOverlay popup;
  86. protected VMenuBar visibleChildMenu;
  87. protected boolean menuVisible = false;
  88. protected VMenuBar parentMenu;
  89. protected CustomMenuItem selected;
  90. /** For internal use only. May be removed or replaced in the future. */
  91. public boolean enabled = true;
  92. private VLazyExecutor iconLoadedExecutioner = new VLazyExecutor(100,
  93. new ScheduledCommand() {
  94. @Override
  95. public void execute() {
  96. iLayout(true);
  97. }
  98. });
  99. /** For internal use only. May be removed or replaced in the future. */
  100. public boolean openRootOnHover;
  101. /** For internal use only. May be removed or replaced in the future. */
  102. public boolean htmlContentAllowed;
  103. public VMenuBar() {
  104. // Create an empty horizontal menubar
  105. this(false, null);
  106. // Navigation is only handled by the root bar
  107. addFocusHandler(this);
  108. /*
  109. * Firefox auto-repeat works correctly only if we use a key press
  110. * handler, other browsers handle it correctly when using a key down
  111. * handler
  112. */
  113. if (BrowserInfo.get().isGecko()) {
  114. addKeyPressHandler(this);
  115. } else {
  116. addKeyDownHandler(this);
  117. }
  118. }
  119. public VMenuBar(boolean subMenu, VMenuBar parentMenu) {
  120. items = new ArrayList<CustomMenuItem>();
  121. popup = null;
  122. visibleChildMenu = null;
  123. this.subMenu = subMenu;
  124. containerElement = getElement();
  125. sinkEvents(Event.ONCLICK | Event.ONMOUSEOVER | Event.ONMOUSEOUT
  126. | Event.ONLOAD);
  127. if (parentMenu == null) {
  128. // Root menu
  129. setStyleName(CLASSNAME);
  130. } else {
  131. // Child menus inherits style name
  132. setStyleName(parentMenu.getStyleName());
  133. }
  134. }
  135. @Override
  136. public void setStyleName(String style) {
  137. super.setStyleName(style);
  138. updateStyleNames();
  139. }
  140. @Override
  141. public void setStylePrimaryName(String style) {
  142. super.setStylePrimaryName(style);
  143. updateStyleNames();
  144. }
  145. protected void updateStyleNames() {
  146. String primaryStyleName = getParentMenu() != null ? getParentMenu()
  147. .getStylePrimaryName() : getStylePrimaryName();
  148. // Reset the style name for all the items
  149. for (CustomMenuItem item : items) {
  150. item.setStyleName(primaryStyleName + "-menuitem");
  151. }
  152. if (subMenu
  153. && !getStylePrimaryName().endsWith(SUBMENU_CLASSNAME_PREFIX)) {
  154. /*
  155. * Sub-menus should get the sub-menu prefix
  156. */
  157. super.setStylePrimaryName(primaryStyleName
  158. + SUBMENU_CLASSNAME_PREFIX);
  159. }
  160. }
  161. @Override
  162. protected void onDetach() {
  163. super.onDetach();
  164. if (!subMenu) {
  165. setSelected(null);
  166. hideChildren();
  167. menuVisible = false;
  168. }
  169. }
  170. void updateSize() {
  171. // Take from setWidth
  172. if (!subMenu) {
  173. // Only needed for root level menu
  174. hideChildren();
  175. setSelected(null);
  176. menuVisible = false;
  177. }
  178. }
  179. /**
  180. * Build the HTML content for a menu item.
  181. * <p>
  182. * For internal use only. May be removed or replaced in the future.
  183. */
  184. public String buildItemHTML(UIDL item) {
  185. // Construct html from the text and the optional icon
  186. StringBuffer itemHTML = new StringBuffer();
  187. if (item.hasAttribute("separator")) {
  188. itemHTML.append("<span>---</span>");
  189. } else {
  190. // Add submenu indicator
  191. if (item.getChildCount() > 0) {
  192. String bgStyle = "";
  193. itemHTML.append("<span class=\"" + getStylePrimaryName()
  194. + "-submenu-indicator\"" + bgStyle + ">&#x25BA;</span>");
  195. }
  196. itemHTML.append("<span class=\"" + getStylePrimaryName()
  197. + "-menuitem-caption\">");
  198. Icon icon = client.getIcon(item.getStringAttribute("icon"));
  199. if (icon != null) {
  200. itemHTML.append(icon.getElement().getString());
  201. }
  202. String itemText = item.getStringAttribute("text");
  203. if (!htmlContentAllowed) {
  204. itemText = WidgetUtil.escapeHTML(itemText);
  205. }
  206. itemHTML.append(itemText);
  207. itemHTML.append("</span>");
  208. }
  209. return itemHTML.toString();
  210. }
  211. /**
  212. * This is called by the items in the menu and it communicates the
  213. * information to the server
  214. *
  215. * @param clickedItemId
  216. * id of the item that was clicked
  217. */
  218. public void onMenuClick(int clickedItemId) {
  219. // Updating the state to the server can not be done before
  220. // the server connection is known, i.e., before updateFromUIDL()
  221. // has been called.
  222. if (uidlId != null && client != null) {
  223. // Communicate the user interaction parameters to server. This call
  224. // will initiate an AJAX request to the server.
  225. client.updateVariable(uidlId, "clickedId", clickedItemId, true);
  226. }
  227. }
  228. /** Widget methods **/
  229. /**
  230. * Returns a list of items in this menu
  231. */
  232. public List<CustomMenuItem> getItems() {
  233. return items;
  234. }
  235. /**
  236. * Remove all the items in this menu
  237. */
  238. public void clearItems() {
  239. Element e = getContainerElement();
  240. while (DOM.getChildCount(e) > 0) {
  241. DOM.removeChild(e, DOM.getChild(e, 0));
  242. }
  243. items.clear();
  244. }
  245. /**
  246. * Returns the containing element of the menu
  247. *
  248. * @return
  249. */
  250. @Override
  251. public com.google.gwt.user.client.Element getContainerElement() {
  252. return DOM.asOld(containerElement);
  253. }
  254. /**
  255. * Add a new item to this menu
  256. *
  257. * @param html
  258. * items text
  259. * @param cmd
  260. * items command
  261. * @return the item created
  262. */
  263. public CustomMenuItem addItem(String html, Command cmd) {
  264. CustomMenuItem item = GWT.create(CustomMenuItem.class);
  265. item.setHTML(html);
  266. item.setCommand(cmd);
  267. addItem(item);
  268. return item;
  269. }
  270. /**
  271. * Add a new item to this menu
  272. *
  273. * @param item
  274. */
  275. public void addItem(CustomMenuItem item) {
  276. if (items.contains(item)) {
  277. return;
  278. }
  279. DOM.appendChild(getContainerElement(), item.getElement());
  280. item.setParentMenu(this);
  281. item.setSelected(false);
  282. items.add(item);
  283. }
  284. public void addItem(CustomMenuItem item, int index) {
  285. if (items.contains(item)) {
  286. return;
  287. }
  288. DOM.insertChild(getContainerElement(), item.getElement(), index);
  289. item.setParentMenu(this);
  290. item.setSelected(false);
  291. items.add(index, item);
  292. }
  293. /**
  294. * Remove the given item from this menu
  295. *
  296. * @param item
  297. */
  298. public void removeItem(CustomMenuItem item) {
  299. if (items.contains(item)) {
  300. int index = items.indexOf(item);
  301. DOM.removeChild(getContainerElement(),
  302. DOM.getChild(getContainerElement(), index));
  303. items.remove(index);
  304. }
  305. }
  306. /*
  307. * @see
  308. * com.google.gwt.user.client.ui.Widget#onBrowserEvent(com.google.gwt.user
  309. * .client.Event)
  310. */
  311. @Override
  312. public void onBrowserEvent(Event e) {
  313. super.onBrowserEvent(e);
  314. // Handle onload events (icon loaded, size changes)
  315. if (DOM.eventGetType(e) == Event.ONLOAD) {
  316. VMenuBar parent = getParentMenu();
  317. if (parent != null) {
  318. // The onload event for an image in a popup should be sent to
  319. // the parent, which owns the popup
  320. parent.iconLoaded();
  321. } else {
  322. // Onload events for images in the root menu are handled by the
  323. // root menu itself
  324. iconLoaded();
  325. }
  326. return;
  327. }
  328. Element targetElement = DOM.eventGetTarget(e);
  329. CustomMenuItem targetItem = null;
  330. for (int i = 0; i < items.size(); i++) {
  331. CustomMenuItem item = items.get(i);
  332. if (DOM.isOrHasChild(item.getElement(), targetElement)) {
  333. targetItem = item;
  334. }
  335. }
  336. if (targetItem != null) {
  337. switch (DOM.eventGetType(e)) {
  338. case Event.ONCLICK:
  339. if (isEnabled() && targetItem.isEnabled()) {
  340. itemClick(targetItem);
  341. }
  342. if (subMenu) {
  343. // Prevent moving keyboard focus to child menus
  344. VMenuBar parent = parentMenu;
  345. while (parent.getParentMenu() != null) {
  346. parent = parent.getParentMenu();
  347. }
  348. parent.setFocus(true);
  349. }
  350. break;
  351. case Event.ONMOUSEOVER:
  352. LazyCloser.cancelClosing();
  353. if (isEnabled() && targetItem.isEnabled()) {
  354. itemOver(targetItem);
  355. }
  356. break;
  357. case Event.ONMOUSEOUT:
  358. itemOut(targetItem);
  359. LazyCloser.schedule();
  360. break;
  361. }
  362. } else if (subMenu && DOM.eventGetType(e) == Event.ONCLICK && subMenu) {
  363. // Prevent moving keyboard focus to child menus
  364. VMenuBar parent = parentMenu;
  365. while (parent.getParentMenu() != null) {
  366. parent = parent.getParentMenu();
  367. }
  368. parent.setFocus(true);
  369. }
  370. }
  371. private boolean isEnabled() {
  372. return enabled;
  373. }
  374. private void iconLoaded() {
  375. iconLoadedExecutioner.trigger();
  376. }
  377. /**
  378. * When an item is clicked
  379. *
  380. * @param item
  381. */
  382. public void itemClick(CustomMenuItem item) {
  383. if (item.getCommand() != null) {
  384. setSelected(null);
  385. if (visibleChildMenu != null) {
  386. visibleChildMenu.hideChildren();
  387. }
  388. hideParents(true);
  389. menuVisible = false;
  390. Scheduler.get().scheduleDeferred(item.getCommand());
  391. } else {
  392. if (item.getSubMenu() != null
  393. && item.getSubMenu() != visibleChildMenu) {
  394. setSelected(item);
  395. showChildMenu(item);
  396. menuVisible = true;
  397. } else if (!subMenu) {
  398. setSelected(null);
  399. hideChildren();
  400. menuVisible = false;
  401. }
  402. }
  403. }
  404. /**
  405. * When the user hovers the mouse over the item
  406. *
  407. * @param item
  408. */
  409. public void itemOver(CustomMenuItem item) {
  410. if ((openRootOnHover || subMenu || menuVisible) && !item.isSeparator()) {
  411. setSelected(item);
  412. if (!subMenu && openRootOnHover && !menuVisible) {
  413. menuVisible = true; // start opening menus
  414. LazyCloser.prepare(this);
  415. }
  416. }
  417. if (menuVisible && visibleChildMenu != item.getSubMenu()
  418. && popup != null) {
  419. // #15255 - disable animation-in/out when hide in this case
  420. popup.hide(false, false, false);
  421. }
  422. if (menuVisible && item.getSubMenu() != null
  423. && visibleChildMenu != item.getSubMenu()) {
  424. showChildMenu(item);
  425. }
  426. }
  427. /**
  428. * When the mouse is moved away from an item
  429. *
  430. * @param item
  431. */
  432. public void itemOut(CustomMenuItem item) {
  433. if (visibleChildMenu != item.getSubMenu()) {
  434. hideChildMenu(item);
  435. setSelected(null);
  436. } else if (visibleChildMenu == null) {
  437. setSelected(null);
  438. }
  439. }
  440. /**
  441. * Used to autoclose submenus when they the menu is in a mode which opens
  442. * root menus on mouse hover.
  443. */
  444. private static class LazyCloser extends Timer {
  445. static LazyCloser INSTANCE;
  446. private VMenuBar activeRoot;
  447. @Override
  448. public void run() {
  449. activeRoot.hideChildren();
  450. activeRoot.setSelected(null);
  451. activeRoot.menuVisible = false;
  452. activeRoot = null;
  453. }
  454. public static void cancelClosing() {
  455. if (INSTANCE != null) {
  456. INSTANCE.cancel();
  457. }
  458. }
  459. public static void prepare(VMenuBar vMenuBar) {
  460. if (INSTANCE == null) {
  461. INSTANCE = new LazyCloser();
  462. }
  463. if (INSTANCE.activeRoot == vMenuBar) {
  464. INSTANCE.cancel();
  465. } else if (INSTANCE.activeRoot != null) {
  466. INSTANCE.cancel();
  467. INSTANCE.run();
  468. }
  469. INSTANCE.activeRoot = vMenuBar;
  470. }
  471. public static void schedule() {
  472. if (INSTANCE != null && INSTANCE.activeRoot != null) {
  473. INSTANCE.schedule(750);
  474. }
  475. }
  476. }
  477. /**
  478. * Shows the child menu of an item. The caller must ensure that the item has
  479. * a submenu.
  480. *
  481. * @param item
  482. */
  483. public void showChildMenu(CustomMenuItem item) {
  484. int left = 0;
  485. int top = 0;
  486. if (subMenu) {
  487. left = item.getParentMenu().getAbsoluteLeft()
  488. + item.getParentMenu().getOffsetWidth();
  489. top = item.getAbsoluteTop();
  490. } else {
  491. left = item.getAbsoluteLeft();
  492. top = item.getParentMenu().getAbsoluteTop()
  493. + item.getParentMenu().getOffsetHeight();
  494. }
  495. showChildMenuAt(item, top, left);
  496. }
  497. protected void showChildMenuAt(CustomMenuItem item, int top, int left) {
  498. final int shadowSpace = 10;
  499. popup = new VOverlay(true, false, true);
  500. popup.setOwner(this);
  501. /*
  502. * Use parents primary style name if possible and remove the submenu
  503. * prefix if needed
  504. */
  505. String primaryStyleName = parentMenu != null ? parentMenu
  506. .getStylePrimaryName() : getStylePrimaryName();
  507. if (subMenu) {
  508. primaryStyleName = primaryStyleName.replace(
  509. SUBMENU_CLASSNAME_PREFIX, "");
  510. }
  511. popup.setStyleName(primaryStyleName + "-popup");
  512. // Setting owner and handlers to support tooltips. Needed for tooltip
  513. // handling of overlay widgets (will direct queries to parent menu)
  514. if (parentMenu == null) {
  515. popup.setOwner(this);
  516. } else {
  517. VMenuBar parent = parentMenu;
  518. while (parent.getParentMenu() != null) {
  519. parent = parent.getParentMenu();
  520. }
  521. popup.setOwner(parent);
  522. }
  523. if (client != null) {
  524. client.getVTooltip().connectHandlersToWidget(popup);
  525. }
  526. popup.setWidget(item.getSubMenu());
  527. popup.addCloseHandler(this);
  528. popup.addAutoHidePartner(item.getElement());
  529. // at 0,0 because otherwise IE7 add extra scrollbars (#5547)
  530. popup.setPopupPosition(0, 0);
  531. item.getSubMenu().onShow();
  532. visibleChildMenu = item.getSubMenu();
  533. item.getSubMenu().setParentMenu(this);
  534. popup.show();
  535. if (left + popup.getOffsetWidth() >= RootPanel.getBodyElement()
  536. .getOffsetWidth() - shadowSpace) {
  537. if (subMenu) {
  538. left = item.getParentMenu().getAbsoluteLeft()
  539. - popup.getOffsetWidth() - shadowSpace;
  540. } else {
  541. left = RootPanel.getBodyElement().getOffsetWidth()
  542. - popup.getOffsetWidth() - shadowSpace;
  543. }
  544. // Accommodate space for shadow
  545. if (left < shadowSpace) {
  546. left = shadowSpace;
  547. }
  548. }
  549. top = adjustPopupHeight(top, shadowSpace);
  550. popup.setPopupPosition(left, top);
  551. }
  552. private int adjustPopupHeight(int top, final int shadowSpace) {
  553. // Check that the popup will fit the screen
  554. int availableHeight = RootPanel.getBodyElement().getOffsetHeight()
  555. - top - shadowSpace;
  556. int missingHeight = popup.getOffsetHeight() - availableHeight;
  557. if (missingHeight > 0) {
  558. // First move the top of the popup to get more space
  559. // Don't move above top of screen, don't move more than needed
  560. int moveUpBy = Math.min(top - shadowSpace, missingHeight);
  561. // Update state
  562. top -= moveUpBy;
  563. missingHeight -= moveUpBy;
  564. availableHeight += moveUpBy;
  565. if (missingHeight > 0) {
  566. int contentWidth = visibleChildMenu.getOffsetWidth();
  567. // If there's still not enough room, limit height to fit and add
  568. // a scroll bar
  569. Style style = popup.getElement().getStyle();
  570. style.setHeight(availableHeight, Unit.PX);
  571. style.setOverflowY(Overflow.SCROLL);
  572. // Make room for the scroll bar by adjusting the width of the
  573. // popup
  574. style.setWidth(
  575. contentWidth + WidgetUtil.getNativeScrollbarSize(),
  576. Unit.PX);
  577. popup.positionOrSizeUpdated();
  578. }
  579. }
  580. return top;
  581. }
  582. /**
  583. * Hides the submenu of an item
  584. *
  585. * @param item
  586. */
  587. public void hideChildMenu(CustomMenuItem item) {
  588. if (visibleChildMenu != null
  589. && !(visibleChildMenu == item.getSubMenu())) {
  590. popup.hide();
  591. }
  592. }
  593. /**
  594. * When the menu is shown.
  595. */
  596. public void onShow() {
  597. // remove possible previous selection
  598. if (selected != null) {
  599. selected.setSelected(false);
  600. selected = null;
  601. }
  602. menuVisible = true;
  603. }
  604. /**
  605. * Listener method, fired when this menu is closed
  606. */
  607. @Override
  608. public void onClose(CloseEvent<PopupPanel> event) {
  609. hideChildren();
  610. if (event.isAutoClosed()) {
  611. hideParents(true);
  612. menuVisible = false;
  613. }
  614. visibleChildMenu = null;
  615. popup = null;
  616. }
  617. /**
  618. * Recursively hide all child menus
  619. */
  620. public void hideChildren() {
  621. hideChildren(true, true);
  622. }
  623. /**
  624. *
  625. * Recursively hide all child menus
  626. *
  627. * @param animateIn
  628. * enable/disable animate-in animation when hide popup
  629. * @param animateOut
  630. * enable/disable animate-out animation when hide popup
  631. * @since 7.3.7
  632. */
  633. public void hideChildren(boolean animateIn, boolean animateOut) {
  634. if (visibleChildMenu != null) {
  635. visibleChildMenu.hideChildren(animateIn, animateOut);
  636. popup.hide(false, animateIn, animateOut);
  637. }
  638. }
  639. /**
  640. * Recursively hide all parent menus
  641. */
  642. public void hideParents(boolean autoClosed) {
  643. if (visibleChildMenu != null) {
  644. popup.hide();
  645. setSelected(null);
  646. menuVisible = !autoClosed;
  647. }
  648. if (getParentMenu() != null) {
  649. getParentMenu().hideParents(autoClosed);
  650. }
  651. }
  652. /**
  653. * Returns the parent menu of this menu, or null if this is the top-level
  654. * menu
  655. *
  656. * @return
  657. */
  658. public VMenuBar getParentMenu() {
  659. return parentMenu;
  660. }
  661. /**
  662. * Set the parent menu of this menu
  663. *
  664. * @param parent
  665. */
  666. public void setParentMenu(VMenuBar parent) {
  667. parentMenu = parent;
  668. }
  669. /**
  670. * Returns the currently selected item of this menu, or null if nothing is
  671. * selected
  672. *
  673. * @return
  674. */
  675. public CustomMenuItem getSelected() {
  676. return selected;
  677. }
  678. /**
  679. * Set the currently selected item of this menu
  680. *
  681. * @param item
  682. */
  683. public void setSelected(CustomMenuItem item) {
  684. // If we had something selected, unselect
  685. if (item != selected && selected != null) {
  686. selected.setSelected(false);
  687. }
  688. // If we have a valid selection, select it
  689. if (item != null) {
  690. item.setSelected(true);
  691. }
  692. selected = item;
  693. }
  694. /**
  695. *
  696. * A class to hold information on menu items
  697. *
  698. */
  699. public static class CustomMenuItem extends Widget implements HasHTML {
  700. protected String html = null;
  701. protected Command command = null;
  702. protected VMenuBar subMenu = null;
  703. protected VMenuBar parentMenu = null;
  704. protected boolean enabled = true;
  705. protected boolean isSeparator = false;
  706. protected boolean checkable = false;
  707. protected boolean checked = false;
  708. protected boolean selected = false;
  709. protected String description = null;
  710. private String styleName;
  711. /**
  712. * Default menu item {@link Widget} constructor for GWT.create().
  713. *
  714. * Use {@link #setHTML(String)} and {@link #setCommand(Command)} after
  715. * constructing a menu item.
  716. */
  717. public CustomMenuItem() {
  718. this("", null);
  719. }
  720. /**
  721. * Creates a menu item {@link Widget}.
  722. *
  723. * @param html
  724. * @param cmd
  725. * @deprecated use the default constructor and {@link #setHTML(String)}
  726. * and {@link #setCommand(Command)} instead
  727. */
  728. @Deprecated
  729. public CustomMenuItem(String html, Command cmd) {
  730. // We need spans to allow inline-block in IE
  731. setElement(DOM.createSpan());
  732. setHTML(html);
  733. setCommand(cmd);
  734. setSelected(false);
  735. }
  736. @Override
  737. public void setStyleName(String style) {
  738. super.setStyleName(style);
  739. updateStyleNames();
  740. // Pass stylename down to submenus
  741. if (getSubMenu() != null) {
  742. getSubMenu().setStyleName(style);
  743. }
  744. }
  745. public void setSelected(boolean selected) {
  746. this.selected = selected;
  747. updateStyleNames();
  748. }
  749. public void setChecked(boolean checked) {
  750. if (checkable && !isSeparator) {
  751. this.checked = checked;
  752. } else {
  753. this.checked = false;
  754. }
  755. updateStyleNames();
  756. }
  757. public boolean isChecked() {
  758. return checked;
  759. }
  760. public void setCheckable(boolean checkable) {
  761. if (checkable && !isSeparator) {
  762. this.checkable = true;
  763. } else {
  764. setChecked(false);
  765. this.checkable = false;
  766. }
  767. }
  768. public boolean isCheckable() {
  769. return checkable;
  770. }
  771. /*
  772. * setters and getters for the fields
  773. */
  774. public void setSubMenu(VMenuBar subMenu) {
  775. this.subMenu = subMenu;
  776. }
  777. public VMenuBar getSubMenu() {
  778. return subMenu;
  779. }
  780. public void setParentMenu(VMenuBar parentMenu) {
  781. this.parentMenu = parentMenu;
  782. updateStyleNames();
  783. }
  784. protected void updateStyleNames() {
  785. if (parentMenu == null) {
  786. // Style names depend on the parent menu's primary style name so
  787. // don't do updates until the item has a parent
  788. return;
  789. }
  790. String primaryStyleName = parentMenu.getStylePrimaryName();
  791. if (parentMenu.subMenu) {
  792. primaryStyleName = primaryStyleName.replace(
  793. SUBMENU_CLASSNAME_PREFIX, "");
  794. }
  795. if (isSeparator) {
  796. super.setStyleName(primaryStyleName + "-separator");
  797. } else {
  798. super.setStyleName(primaryStyleName + "-menuitem");
  799. }
  800. if (styleName != null) {
  801. addStyleDependentName(styleName);
  802. }
  803. if (enabled) {
  804. removeStyleDependentName("disabled");
  805. } else {
  806. addStyleDependentName("disabled");
  807. }
  808. if (selected && isSelectable()) {
  809. addStyleDependentName("selected");
  810. // needed for IE6 to have a single style name to match for an
  811. // element
  812. // TODO Can be optimized now that IE6 is not supported any more
  813. if (checkable) {
  814. if (checked) {
  815. removeStyleDependentName("selected-unchecked");
  816. addStyleDependentName("selected-checked");
  817. } else {
  818. removeStyleDependentName("selected-checked");
  819. addStyleDependentName("selected-unchecked");
  820. }
  821. }
  822. } else {
  823. removeStyleDependentName("selected");
  824. // needed for IE6 to have a single style name to match for an
  825. // element
  826. removeStyleDependentName("selected-checked");
  827. removeStyleDependentName("selected-unchecked");
  828. }
  829. if (checkable && !isSeparator) {
  830. if (checked) {
  831. addStyleDependentName("checked");
  832. removeStyleDependentName("unchecked");
  833. } else {
  834. addStyleDependentName("unchecked");
  835. removeStyleDependentName("checked");
  836. }
  837. }
  838. }
  839. public VMenuBar getParentMenu() {
  840. return parentMenu;
  841. }
  842. public void setCommand(Command command) {
  843. this.command = command;
  844. }
  845. public Command getCommand() {
  846. return command;
  847. }
  848. @Override
  849. public String getHTML() {
  850. return html;
  851. }
  852. @Override
  853. public void setHTML(String html) {
  854. this.html = html;
  855. DOM.setInnerHTML(getElement(), html);
  856. // Sink the onload event for any icons. The onload
  857. // events are handled by the parent VMenuBar.
  858. WidgetUtil.sinkOnloadForImages(getElement());
  859. }
  860. @Override
  861. public String getText() {
  862. return html;
  863. }
  864. @Override
  865. public void setText(String text) {
  866. setHTML(WidgetUtil.escapeHTML(text));
  867. }
  868. public void setEnabled(boolean enabled) {
  869. this.enabled = enabled;
  870. updateStyleNames();
  871. }
  872. public boolean isEnabled() {
  873. return enabled;
  874. }
  875. private void setSeparator(boolean separator) {
  876. isSeparator = separator;
  877. updateStyleNames();
  878. if (!separator) {
  879. setEnabled(enabled);
  880. }
  881. }
  882. public boolean isSeparator() {
  883. return isSeparator;
  884. }
  885. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  886. setSeparator(uidl.hasAttribute("separator"));
  887. setEnabled(!uidl
  888. .hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_DISABLED));
  889. if (!isSeparator()
  890. && uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_CHECKED)) {
  891. // if the selected attribute is present (either true or false),
  892. // the item is selectable
  893. setCheckable(true);
  894. setChecked(uidl
  895. .getBooleanAttribute(MenuBarConstants.ATTRIBUTE_CHECKED));
  896. } else {
  897. setCheckable(false);
  898. }
  899. if (uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_STYLE)) {
  900. styleName = uidl
  901. .getStringAttribute(MenuBarConstants.ATTRIBUTE_ITEM_STYLE);
  902. }
  903. if (uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION)) {
  904. description = uidl
  905. .getStringAttribute(MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION);
  906. }
  907. updateStyleNames();
  908. }
  909. public TooltipInfo getTooltip() {
  910. if (description == null) {
  911. return null;
  912. }
  913. return new TooltipInfo(description, null, this);
  914. }
  915. /**
  916. * Checks if the item can be selected.
  917. *
  918. * @return true if it is possible to select this item, false otherwise
  919. */
  920. public boolean isSelectable() {
  921. return !isSeparator() && isEnabled();
  922. }
  923. }
  924. /**
  925. * @author Jouni Koivuviita / Vaadin Ltd.
  926. */
  927. public void iLayout() {
  928. iLayout(false);
  929. updateSize();
  930. }
  931. public void iLayout(boolean iconLoadEvent) {
  932. // Only collapse if there is more than one item in the root menu and the
  933. // menu has an explicit size
  934. if ((getItems().size() > 1 || (collapsedRootItems != null && collapsedRootItems
  935. .getItems().size() > 0))
  936. && getElement().getStyle().getProperty("width") != null
  937. && moreItem != null) {
  938. // Measure the width of the "more" item
  939. final boolean morePresent = getItems().contains(moreItem);
  940. addItem(moreItem);
  941. final int moreItemWidth = moreItem.getOffsetWidth();
  942. if (!morePresent) {
  943. removeItem(moreItem);
  944. }
  945. int availableWidth = LayoutManager.get(client).getInnerWidth(
  946. getElement());
  947. // Used width includes the "more" item if present
  948. int usedWidth = getConsumedWidth();
  949. int diff = availableWidth - usedWidth;
  950. removeItem(moreItem);
  951. if (diff < 0) {
  952. // Too many items: collapse last items from root menu
  953. int widthNeeded = usedWidth - availableWidth;
  954. if (!morePresent) {
  955. widthNeeded += moreItemWidth;
  956. }
  957. int widthReduced = 0;
  958. while (widthReduced < widthNeeded && getItems().size() > 0) {
  959. // Move last root menu item to collapsed menu
  960. CustomMenuItem collapse = getItems().get(
  961. getItems().size() - 1);
  962. widthReduced += collapse.getOffsetWidth();
  963. removeItem(collapse);
  964. collapsedRootItems.addItem(collapse, 0);
  965. }
  966. } else if (collapsedRootItems.getItems().size() > 0) {
  967. // Space available for items: expand first items from collapsed
  968. // menu
  969. int widthAvailable = diff + moreItemWidth;
  970. int widthGrowth = 0;
  971. while (widthAvailable > widthGrowth
  972. && collapsedRootItems.getItems().size() > 0) {
  973. // Move first item from collapsed menu to the root menu
  974. CustomMenuItem expand = collapsedRootItems.getItems()
  975. .get(0);
  976. collapsedRootItems.removeItem(expand);
  977. addItem(expand);
  978. widthGrowth += expand.getOffsetWidth();
  979. if (collapsedRootItems.getItems().size() > 0) {
  980. widthAvailable -= moreItemWidth;
  981. }
  982. if (widthGrowth > widthAvailable) {
  983. removeItem(expand);
  984. collapsedRootItems.addItem(expand, 0);
  985. } else {
  986. widthAvailable = diff + moreItemWidth;
  987. }
  988. }
  989. }
  990. if (collapsedRootItems.getItems().size() > 0) {
  991. addItem(moreItem);
  992. }
  993. }
  994. // If a popup is open we might need to adjust the shadow as well if an
  995. // icon shown in that popup was loaded
  996. if (popup != null) {
  997. // Forces a recalculation of the shadow size
  998. popup.show();
  999. }
  1000. if (iconLoadEvent) {
  1001. // Size have changed if the width is undefined
  1002. Util.notifyParentOfSizeChange(this, false);
  1003. }
  1004. }
  1005. private int getConsumedWidth() {
  1006. int w = 0;
  1007. for (CustomMenuItem item : getItems()) {
  1008. if (!collapsedRootItems.getItems().contains(item)) {
  1009. w += item.getOffsetWidth();
  1010. }
  1011. }
  1012. return w;
  1013. }
  1014. /*
  1015. * (non-Javadoc)
  1016. *
  1017. * @see
  1018. * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
  1019. * .gwt.event.dom.client.KeyPressEvent)
  1020. */
  1021. @Override
  1022. public void onKeyPress(KeyPressEvent event) {
  1023. // A bug fix for #14041
  1024. // getKeyCode and getCharCode return different values for different
  1025. // browsers
  1026. int keyCode = event.getNativeEvent().getKeyCode();
  1027. if (keyCode == 0) {
  1028. keyCode = event.getNativeEvent().getCharCode();
  1029. }
  1030. if (handleNavigation(keyCode,
  1031. event.isControlKeyDown() || event.isMetaKeyDown(),
  1032. event.isShiftKeyDown())) {
  1033. event.preventDefault();
  1034. }
  1035. }
  1036. /*
  1037. * (non-Javadoc)
  1038. *
  1039. * @see
  1040. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1041. * .event.dom.client.KeyDownEvent)
  1042. */
  1043. @Override
  1044. public void onKeyDown(KeyDownEvent event) {
  1045. // A bug fix for #14041
  1046. // getKeyCode and getCharCode return different values for different
  1047. // browsers
  1048. int keyCode = event.getNativeEvent().getKeyCode();
  1049. if (keyCode == 0) {
  1050. keyCode = event.getNativeEvent().getCharCode();
  1051. }
  1052. if (handleNavigation(keyCode,
  1053. event.isControlKeyDown() || event.isMetaKeyDown(),
  1054. event.isShiftKeyDown())) {
  1055. event.preventDefault();
  1056. }
  1057. }
  1058. /**
  1059. * Get the key that moves the selection upwards. By default it is the up
  1060. * arrow key but by overriding this you can change the key to whatever you
  1061. * want.
  1062. *
  1063. * @return The keycode of the key
  1064. */
  1065. protected int getNavigationUpKey() {
  1066. return KeyCodes.KEY_UP;
  1067. }
  1068. /**
  1069. * Get the key that moves the selection downwards. By default it is the down
  1070. * arrow key but by overriding this you can change the key to whatever you
  1071. * want.
  1072. *
  1073. * @return The keycode of the key
  1074. */
  1075. protected int getNavigationDownKey() {
  1076. return KeyCodes.KEY_DOWN;
  1077. }
  1078. /**
  1079. * Get the key that moves the selection left. By default it is the left
  1080. * arrow key but by overriding this you can change the key to whatever you
  1081. * want.
  1082. *
  1083. * @return The keycode of the key
  1084. */
  1085. protected int getNavigationLeftKey() {
  1086. return KeyCodes.KEY_LEFT;
  1087. }
  1088. /**
  1089. * Get the key that moves the selection right. By default it is the right
  1090. * arrow key but by overriding this you can change the key to whatever you
  1091. * want.
  1092. *
  1093. * @return The keycode of the key
  1094. */
  1095. protected int getNavigationRightKey() {
  1096. return KeyCodes.KEY_RIGHT;
  1097. }
  1098. /**
  1099. * Get the key that selects a menu item. By default it is the Enter key but
  1100. * by overriding this you can change the key to whatever you want.
  1101. *
  1102. * @deprecated use {@link #isNavigationSelectKey(int)} instead
  1103. * @return
  1104. */
  1105. @Deprecated
  1106. protected int getNavigationSelectKey() {
  1107. return KeyCodes.KEY_ENTER;
  1108. }
  1109. /**
  1110. * Checks whether key code selects a menu item. By default it is the Enter
  1111. * and Space keys but by overriding this you can change the keys to whatever
  1112. * you want.
  1113. *
  1114. * @since 7.2
  1115. * @param keycode
  1116. * @return true if key selects menu item
  1117. */
  1118. protected boolean isNavigationSelectKey(int keycode) {
  1119. return keycode == getNavigationSelectKey()
  1120. || keycode == KeyCodes.KEY_SPACE;
  1121. }
  1122. /**
  1123. * Get the key that closes the menu. By default it is the escape key but by
  1124. * overriding this yoy can change the key to whatever you want.
  1125. *
  1126. * @return
  1127. */
  1128. protected int getCloseMenuKey() {
  1129. return KeyCodes.KEY_ESCAPE;
  1130. }
  1131. /**
  1132. * Handles the keyboard events handled by the MenuBar
  1133. *
  1134. * @param event
  1135. * The keyboard event received
  1136. * @return true iff the navigation event was handled
  1137. */
  1138. public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  1139. // If tab or shift+tab close menus
  1140. if (keycode == KeyCodes.KEY_TAB) {
  1141. setSelected(null);
  1142. hideChildren();
  1143. menuVisible = false;
  1144. return false;
  1145. }
  1146. if (ctrl || shift || !isEnabled()) {
  1147. // Do not handle tab key, nor ctrl keys
  1148. return false;
  1149. }
  1150. if (keycode == getNavigationLeftKey()) {
  1151. if (getSelected() == null) {
  1152. // If nothing is selected then select the last item
  1153. setSelected(items.get(items.size() - 1));
  1154. if (!getSelected().isSelectable()) {
  1155. handleNavigation(keycode, ctrl, shift);
  1156. }
  1157. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1158. // If this is the root menu then move to the left
  1159. int idx = items.indexOf(getSelected());
  1160. if (idx > 0) {
  1161. setSelected(items.get(idx - 1));
  1162. } else {
  1163. setSelected(items.get(items.size() - 1));
  1164. }
  1165. if (!getSelected().isSelectable()) {
  1166. handleNavigation(keycode, ctrl, shift);
  1167. }
  1168. } else if (visibleChildMenu != null) {
  1169. // Redirect all navigation to the submenu
  1170. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1171. } else if (getParentMenu().getParentMenu() == null) {
  1172. // Inside a sub menu, whose parent is a root menu item
  1173. VMenuBar root = getParentMenu();
  1174. root.getSelected().getSubMenu().setSelected(null);
  1175. // #15255 - disable animate-in/out when hide popup
  1176. root.hideChildren(false, false);
  1177. // Get the root menus items and select the previous one
  1178. int idx = root.getItems().indexOf(root.getSelected());
  1179. idx = idx > 0 ? idx : root.getItems().size();
  1180. CustomMenuItem selected = root.getItems().get(--idx);
  1181. while (selected.isSeparator() || !selected.isEnabled()) {
  1182. idx = idx > 0 ? idx : root.getItems().size();
  1183. selected = root.getItems().get(--idx);
  1184. }
  1185. root.setSelected(selected);
  1186. openMenuAndFocusFirstIfPossible(selected);
  1187. } else {
  1188. getParentMenu().getSelected().getSubMenu().setSelected(null);
  1189. getParentMenu().hideChildren();
  1190. }
  1191. return true;
  1192. } else if (keycode == getNavigationRightKey()) {
  1193. if (getSelected() == null) {
  1194. // If nothing is selected then select the first item
  1195. setSelected(items.get(0));
  1196. if (!getSelected().isSelectable()) {
  1197. handleNavigation(keycode, ctrl, shift);
  1198. }
  1199. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1200. // If this is the root menu then move to the right
  1201. int idx = items.indexOf(getSelected());
  1202. if (idx < items.size() - 1) {
  1203. setSelected(items.get(idx + 1));
  1204. } else {
  1205. setSelected(items.get(0));
  1206. }
  1207. if (!getSelected().isSelectable()) {
  1208. handleNavigation(keycode, ctrl, shift);
  1209. }
  1210. } else if (visibleChildMenu == null
  1211. && getSelected().getSubMenu() != null) {
  1212. // If the item has a submenu then show it and move the selection
  1213. // there
  1214. showChildMenu(getSelected());
  1215. menuVisible = true;
  1216. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1217. } else if (visibleChildMenu == null) {
  1218. // Get the root menu
  1219. VMenuBar root = getParentMenu();
  1220. while (root.getParentMenu() != null) {
  1221. root = root.getParentMenu();
  1222. }
  1223. // Hide the submenu (#15255 - disable animate-in/out when hide
  1224. // popup)
  1225. root.hideChildren(false, false);
  1226. // Get the root menus items and select the next one
  1227. int idx = root.getItems().indexOf(root.getSelected());
  1228. idx = idx < root.getItems().size() - 1 ? idx : -1;
  1229. CustomMenuItem selected = root.getItems().get(++idx);
  1230. while (selected.isSeparator() || !selected.isEnabled()) {
  1231. idx = idx < root.getItems().size() - 1 ? idx : -1;
  1232. selected = root.getItems().get(++idx);
  1233. }
  1234. root.setSelected(selected);
  1235. openMenuAndFocusFirstIfPossible(selected);
  1236. } else if (visibleChildMenu != null) {
  1237. // Redirect all navigation to the submenu
  1238. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1239. }
  1240. return true;
  1241. } else if (keycode == getNavigationUpKey()) {
  1242. if (getSelected() == null) {
  1243. // If nothing is selected then select the last item
  1244. setSelected(items.get(items.size() - 1));
  1245. if (!getSelected().isSelectable()) {
  1246. handleNavigation(keycode, ctrl, shift);
  1247. }
  1248. } else if (visibleChildMenu != null) {
  1249. // Redirect all navigation to the submenu
  1250. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1251. } else {
  1252. // Select the previous item if possible or loop to the last item
  1253. int idx = items.indexOf(getSelected());
  1254. if (idx > 0) {
  1255. setSelected(items.get(idx - 1));
  1256. } else {
  1257. setSelected(items.get(items.size() - 1));
  1258. }
  1259. if (!getSelected().isSelectable()) {
  1260. handleNavigation(keycode, ctrl, shift);
  1261. }
  1262. }
  1263. return true;
  1264. } else if (keycode == getNavigationDownKey()) {
  1265. if (getSelected() == null) {
  1266. // If nothing is selected then select the first item
  1267. selectFirstItem();
  1268. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1269. // If this is the root menu the show the child menu with arrow
  1270. // down, if there is a child menu
  1271. openMenuAndFocusFirstIfPossible(getSelected());
  1272. } else if (visibleChildMenu != null) {
  1273. // Redirect all navigation to the submenu
  1274. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1275. } else {
  1276. // Select the next item if possible or loop to the first item
  1277. int idx = items.indexOf(getSelected());
  1278. if (idx < items.size() - 1) {
  1279. setSelected(items.get(idx + 1));
  1280. } else {
  1281. setSelected(items.get(0));
  1282. }
  1283. if (!getSelected().isSelectable()) {
  1284. handleNavigation(keycode, ctrl, shift);
  1285. }
  1286. }
  1287. return true;
  1288. } else if (keycode == getCloseMenuKey()) {
  1289. setSelected(null);
  1290. hideChildren();
  1291. menuVisible = false;
  1292. } else if (isNavigationSelectKey(keycode)) {
  1293. if (getSelected() == null) {
  1294. // If nothing is selected then select the first item
  1295. selectFirstItem();
  1296. } else if (visibleChildMenu != null) {
  1297. // Redirect all navigation to the submenu
  1298. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1299. menuVisible = false;
  1300. } else if (visibleChildMenu == null
  1301. && getSelected().getSubMenu() != null) {
  1302. // If the item has a sub menu then show it and move the
  1303. // selection there
  1304. openMenuAndFocusFirstIfPossible(getSelected());
  1305. } else {
  1306. Command command = getSelected().getCommand();
  1307. if (command != null) {
  1308. command.execute();
  1309. }
  1310. setSelected(null);
  1311. hideParents(true);
  1312. }
  1313. }
  1314. return false;
  1315. }
  1316. private void selectFirstItem() {
  1317. for (int i = 0; i < items.size(); i++) {
  1318. CustomMenuItem item = items.get(i);
  1319. if (item.isSelectable()) {
  1320. setSelected(item);
  1321. break;
  1322. }
  1323. }
  1324. }
  1325. private void openMenuAndFocusFirstIfPossible(CustomMenuItem menuItem) {
  1326. VMenuBar subMenu = menuItem.getSubMenu();
  1327. if (subMenu == null) {
  1328. // No child menu? Nothing to do
  1329. return;
  1330. }
  1331. VMenuBar parentMenu = menuItem.getParentMenu();
  1332. parentMenu.showChildMenu(menuItem);
  1333. menuVisible = true;
  1334. // Select the first item in the newly open submenu
  1335. subMenu.selectFirstItem();
  1336. }
  1337. /*
  1338. * (non-Javadoc)
  1339. *
  1340. * @see
  1341. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1342. * .dom.client.FocusEvent)
  1343. */
  1344. @Override
  1345. public void onFocus(FocusEvent event) {
  1346. }
  1347. private final String SUBPART_PREFIX = "item";
  1348. @Override
  1349. public com.google.gwt.user.client.Element getSubPartElement(String subPart) {
  1350. if (subPart.startsWith(SUBPART_PREFIX)) {
  1351. int index = Integer.parseInt(subPart.substring(SUBPART_PREFIX
  1352. .length()));
  1353. CustomMenuItem item = getItems().get(index);
  1354. return item.getElement();
  1355. } else {
  1356. Queue<CustomMenuItem> submenuItems = new LinkedList<CustomMenuItem>();
  1357. for (CustomMenuItem item : getItems()) {
  1358. if (isItemNamed(item, subPart)) {
  1359. return item.getElement();
  1360. }
  1361. if (item.getSubMenu() != null) {
  1362. submenuItems.addAll(item.getSubMenu().getItems());
  1363. }
  1364. }
  1365. while (!submenuItems.isEmpty()) {
  1366. CustomMenuItem item = submenuItems.poll();
  1367. if (!item.isSeparator() && isItemNamed(item, subPart)) {
  1368. return item.getElement();
  1369. }
  1370. if (item.getSubMenu() != null && item.getSubMenu().menuVisible) {
  1371. submenuItems.addAll(item.getSubMenu().getItems());
  1372. }
  1373. }
  1374. return null;
  1375. }
  1376. }
  1377. private boolean isItemNamed(CustomMenuItem item, String name) {
  1378. Element lastChildElement = getLastChildElement(item);
  1379. if (getText(lastChildElement).equals(name)) {
  1380. return true;
  1381. }
  1382. return false;
  1383. }
  1384. /*
  1385. * Returns the text content of element without including the text of
  1386. * possible nested elements. It is assumed that the last child of element
  1387. * contains the text of interest and that the last child does not itself
  1388. * have children with text content. This method is used by
  1389. * getSubPartElement(String) so that possible text icons are not included in
  1390. * the textual matching (#14879).
  1391. */
  1392. private native String getText(Element element)
  1393. /*-{
  1394. var n = element.childNodes.length;
  1395. if(n > 0){
  1396. return element.childNodes[n - 1].nodeValue;
  1397. }
  1398. else{
  1399. return "";
  1400. }
  1401. }-*/;
  1402. private Element getLastChildElement(CustomMenuItem item) {
  1403. Element lastChildElement = item.getElement().getFirstChildElement();
  1404. while (lastChildElement.getNextSiblingElement() != null) {
  1405. lastChildElement = lastChildElement.getNextSiblingElement();
  1406. }
  1407. return lastChildElement;
  1408. }
  1409. @Override
  1410. public String getSubPartName(com.google.gwt.user.client.Element subElement) {
  1411. if (!getElement().isOrHasChild(subElement)) {
  1412. return null;
  1413. }
  1414. Element menuItemRoot = subElement;
  1415. while (menuItemRoot != null && menuItemRoot.getParentElement() != null
  1416. && menuItemRoot.getParentElement() != getElement()) {
  1417. menuItemRoot = menuItemRoot.getParentElement().cast();
  1418. }
  1419. // "menuItemRoot" is now the root of the menu item
  1420. final int itemCount = getItems().size();
  1421. for (int i = 0; i < itemCount; i++) {
  1422. if (getItems().get(i).getElement() == menuItemRoot) {
  1423. String name = SUBPART_PREFIX + i;
  1424. return name;
  1425. }
  1426. }
  1427. return null;
  1428. }
  1429. /**
  1430. * Get menu item with given DOM element
  1431. *
  1432. * @param element
  1433. * Element used in search
  1434. * @return Menu item or null if not found
  1435. * @deprecated As of 7.2, call or override
  1436. * {@link #getMenuItemWithElement(Element)} instead
  1437. */
  1438. @Deprecated
  1439. public CustomMenuItem getMenuItemWithElement(
  1440. com.google.gwt.user.client.Element element) {
  1441. for (int i = 0; i < items.size(); i++) {
  1442. CustomMenuItem item = items.get(i);
  1443. if (DOM.isOrHasChild(item.getElement(), element)) {
  1444. return item;
  1445. }
  1446. if (item.getSubMenu() != null) {
  1447. item = item.getSubMenu().getMenuItemWithElement(element);
  1448. if (item != null) {
  1449. return item;
  1450. }
  1451. }
  1452. }
  1453. return null;
  1454. }
  1455. /**
  1456. * Get menu item with given DOM element
  1457. *
  1458. * @param element
  1459. * Element used in search
  1460. * @return Menu item or null if not found
  1461. *
  1462. * @since 7.2
  1463. */
  1464. public CustomMenuItem getMenuItemWithElement(Element element) {
  1465. return getMenuItemWithElement(DOM.asOld(element));
  1466. }
  1467. }