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 55KB

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