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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  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
  614. && !(visibleChildMenu == item.getSubMenu())) {
  615. popup.hide();
  616. }
  617. }
  618. /**
  619. * When the menu is shown.
  620. */
  621. public void onShow() {
  622. // remove possible previous selection
  623. if (selected != null) {
  624. selected.setSelected(false);
  625. selected = null;
  626. }
  627. menuVisible = true;
  628. }
  629. /**
  630. * Listener method, fired when this menu is closed.
  631. */
  632. @Override
  633. public void onClose(CloseEvent<PopupPanel> event) {
  634. hideChildren();
  635. if (event.isAutoClosed()) {
  636. hideParents(true);
  637. menuVisible = false;
  638. }
  639. visibleChildMenu = null;
  640. popup = null;
  641. }
  642. /**
  643. * Recursively hide all child menus.
  644. */
  645. public void hideChildren() {
  646. hideChildren(true, true);
  647. }
  648. /**
  649. *
  650. * Recursively hide all child menus.
  651. *
  652. * @param animateIn
  653. * enable/disable animate-in animation when hide popup
  654. * @param animateOut
  655. * enable/disable animate-out animation when hide popup
  656. * @since 7.3.7
  657. */
  658. public void hideChildren(boolean animateIn, boolean animateOut) {
  659. if (visibleChildMenu != null) {
  660. visibleChildMenu.hideChildren(animateIn, animateOut);
  661. popup.hide(false, animateIn, animateOut);
  662. }
  663. }
  664. /**
  665. * Recursively hide all parent menus.
  666. */
  667. public void hideParents(boolean autoClosed) {
  668. if (visibleChildMenu != null) {
  669. popup.hide();
  670. setSelected(null);
  671. menuVisible = !autoClosed;
  672. }
  673. if (getParentMenu() != null) {
  674. getParentMenu().hideParents(autoClosed);
  675. }
  676. }
  677. /**
  678. * Returns the parent menu of this menu, or null if this is the top-level
  679. * menu.
  680. *
  681. * @return
  682. */
  683. public VMenuBar getParentMenu() {
  684. return parentMenu;
  685. }
  686. /**
  687. * Set the parent menu of this menu.
  688. *
  689. * @param parent
  690. */
  691. public void setParentMenu(VMenuBar parent) {
  692. parentMenu = parent;
  693. }
  694. /**
  695. * Returns the currently selected item of this menu, or null if nothing is
  696. * selected.
  697. *
  698. * @return
  699. */
  700. public CustomMenuItem getSelected() {
  701. return selected;
  702. }
  703. /**
  704. * Set the currently selected item of this menu.
  705. *
  706. * @param item
  707. */
  708. public void setSelected(CustomMenuItem item) {
  709. // If we had something selected, unselect
  710. if (item != selected && selected != null) {
  711. selected.setSelected(false);
  712. }
  713. // If we have a valid selection, select it
  714. if (item != null) {
  715. item.setSelected(true);
  716. }
  717. selected = item;
  718. }
  719. /**
  720. *
  721. * A class to hold information on menu items.
  722. *
  723. */
  724. public static class CustomMenuItem extends Widget implements HasHTML {
  725. protected String html = null;
  726. protected Command command = null;
  727. protected VMenuBar subMenu = null;
  728. protected VMenuBar parentMenu = null;
  729. protected boolean enabled = true;
  730. protected boolean isSeparator = false;
  731. protected boolean checkable = false;
  732. protected boolean checked = false;
  733. protected boolean selected = false;
  734. protected String description = null;
  735. private String styleName;
  736. /**
  737. * Default menu item {@link Widget} constructor for GWT.create().
  738. *
  739. * Use {@link #setHTML(String)} and {@link #setCommand(Command)} after
  740. * constructing a menu item.
  741. */
  742. public CustomMenuItem() {
  743. this("", null);
  744. }
  745. /**
  746. * Creates a menu item {@link Widget}.
  747. *
  748. * @param html
  749. * @param cmd
  750. * @deprecated use the default constructor and {@link #setHTML(String)}
  751. * and {@link #setCommand(Command)} instead
  752. */
  753. @Deprecated
  754. public CustomMenuItem(String html, Command cmd) {
  755. // We need spans to allow inline-block in IE
  756. setElement(DOM.createSpan());
  757. setHTML(html);
  758. setCommand(cmd);
  759. setSelected(false);
  760. }
  761. @Override
  762. public void setStyleName(String style) {
  763. super.setStyleName(style);
  764. updateStyleNames();
  765. // Pass stylename down to submenus
  766. if (getSubMenu() != null) {
  767. getSubMenu().setStyleName(style);
  768. }
  769. }
  770. public void setSelected(boolean selected) {
  771. this.selected = selected;
  772. updateStyleNames();
  773. }
  774. public void setChecked(boolean checked) {
  775. if (checkable && !isSeparator) {
  776. this.checked = checked;
  777. } else {
  778. this.checked = false;
  779. }
  780. updateStyleNames();
  781. }
  782. public boolean isChecked() {
  783. return checked;
  784. }
  785. public void setCheckable(boolean checkable) {
  786. if (checkable && !isSeparator) {
  787. this.checkable = true;
  788. } else {
  789. setChecked(false);
  790. this.checkable = false;
  791. }
  792. }
  793. public boolean isCheckable() {
  794. return checkable;
  795. }
  796. /*
  797. * setters and getters for the fields
  798. */
  799. public void setSubMenu(VMenuBar subMenu) {
  800. this.subMenu = subMenu;
  801. }
  802. public VMenuBar getSubMenu() {
  803. return subMenu;
  804. }
  805. public void setParentMenu(VMenuBar parentMenu) {
  806. this.parentMenu = parentMenu;
  807. updateStyleNames();
  808. }
  809. protected void updateStyleNames() {
  810. if (parentMenu == null) {
  811. // Style names depend on the parent menu's primary style name so
  812. // don't do updates until the item has a parent
  813. return;
  814. }
  815. String primaryStyleName = parentMenu.getStylePrimaryName();
  816. if (parentMenu.subMenu) {
  817. primaryStyleName = primaryStyleName
  818. .replace(SUBMENU_CLASSNAME_PREFIX, "");
  819. }
  820. String currentStyles = super.getStyleName();
  821. List<String> customStyles = new ArrayList<>();
  822. for (String style : currentStyles.split(" ")) {
  823. if (!style.isEmpty() && !style.startsWith(primaryStyleName)) {
  824. customStyles.add(style);
  825. }
  826. }
  827. if (isSeparator) {
  828. super.setStyleName(primaryStyleName + "-separator");
  829. } else {
  830. super.setStyleName(primaryStyleName + "-menuitem");
  831. }
  832. for (String customStyle : customStyles) {
  833. super.addStyleName(customStyle);
  834. }
  835. if (styleName != null) {
  836. addStyleDependentName(styleName);
  837. }
  838. if (enabled) {
  839. removeStyleDependentName("disabled");
  840. } else {
  841. addStyleDependentName("disabled");
  842. }
  843. if (selected && isSelectable()) {
  844. addStyleDependentName("selected");
  845. // needed for IE6 to have a single style name to match for an
  846. // element
  847. // TODO Can be optimized now that IE6 is not supported any more
  848. if (checkable) {
  849. if (checked) {
  850. removeStyleDependentName("selected-unchecked");
  851. addStyleDependentName("selected-checked");
  852. } else {
  853. removeStyleDependentName("selected-checked");
  854. addStyleDependentName("selected-unchecked");
  855. }
  856. }
  857. } else {
  858. removeStyleDependentName("selected");
  859. // needed for IE6 to have a single style name to match for an
  860. // element
  861. removeStyleDependentName("selected-checked");
  862. removeStyleDependentName("selected-unchecked");
  863. }
  864. if (checkable && !isSeparator) {
  865. if (checked) {
  866. addStyleDependentName("checked");
  867. removeStyleDependentName("unchecked");
  868. } else {
  869. addStyleDependentName("unchecked");
  870. removeStyleDependentName("checked");
  871. }
  872. }
  873. }
  874. public VMenuBar getParentMenu() {
  875. return parentMenu;
  876. }
  877. public void setCommand(Command command) {
  878. this.command = command;
  879. }
  880. public Command getCommand() {
  881. return command;
  882. }
  883. @Override
  884. public String getHTML() {
  885. return html;
  886. }
  887. @Override
  888. public void setHTML(String html) {
  889. this.html = html;
  890. DOM.setInnerHTML(getElement(), html);
  891. // Sink the onload event for any icons. The onload
  892. // events are handled by the parent VMenuBar.
  893. WidgetUtil.sinkOnloadForImages(getElement());
  894. }
  895. @Override
  896. public String getText() {
  897. return html;
  898. }
  899. @Override
  900. public void setText(String text) {
  901. setHTML(WidgetUtil.escapeHTML(text));
  902. }
  903. public void setEnabled(boolean enabled) {
  904. this.enabled = enabled;
  905. updateStyleNames();
  906. }
  907. public boolean isEnabled() {
  908. return enabled;
  909. }
  910. private void setSeparator(boolean separator) {
  911. isSeparator = separator;
  912. updateStyleNames();
  913. if (!separator) {
  914. setEnabled(enabled);
  915. }
  916. }
  917. public boolean isSeparator() {
  918. return isSeparator;
  919. }
  920. public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
  921. setSeparator(uidl.hasAttribute("separator"));
  922. setEnabled(!uidl
  923. .hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_DISABLED));
  924. if (!isSeparator()
  925. && uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_CHECKED)) {
  926. // if the selected attribute is present (either true or false),
  927. // the item is selectable
  928. setCheckable(true);
  929. setChecked(uidl.getBooleanAttribute(
  930. MenuBarConstants.ATTRIBUTE_CHECKED));
  931. } else {
  932. setCheckable(false);
  933. }
  934. if (uidl.hasAttribute(MenuBarConstants.ATTRIBUTE_ITEM_STYLE)) {
  935. styleName = uidl.getStringAttribute(
  936. MenuBarConstants.ATTRIBUTE_ITEM_STYLE);
  937. }
  938. if (uidl.hasAttribute(
  939. MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION)) {
  940. description = uidl.getStringAttribute(
  941. MenuBarConstants.ATTRIBUTE_ITEM_DESCRIPTION);
  942. }
  943. updateStyleNames();
  944. }
  945. public TooltipInfo getTooltip() {
  946. if (description == null) {
  947. return null;
  948. }
  949. return new TooltipInfo(description, ContentMode.PREFORMATTED, null,
  950. this);
  951. }
  952. /**
  953. * Checks if the item can be selected.
  954. *
  955. * @return true if it is possible to select this item, false otherwise
  956. */
  957. public boolean isSelectable() {
  958. return !isSeparator() && isEnabled();
  959. }
  960. }
  961. /**
  962. * @author Jouni Koivuviita / Vaadin Ltd.
  963. */
  964. public void iLayout() {
  965. iLayout(false);
  966. updateSize();
  967. }
  968. public void iLayout(boolean iconLoadEvent) {
  969. // Only collapse if there is more than one item in the root menu and the
  970. // menu has an explicit size
  971. if ((getItems().size() > 1 || (collapsedRootItems != null
  972. && !collapsedRootItems.getItems().isEmpty()))
  973. && getElement().getStyle().getProperty("width") != null
  974. && moreItem != null) {
  975. // Measure the width of the "more" item
  976. final boolean morePresent = getItems().contains(moreItem);
  977. addItem(moreItem);
  978. final int moreItemWidth = moreItem.getOffsetWidth();
  979. if (!morePresent) {
  980. removeItem(moreItem);
  981. }
  982. int availableWidth = LayoutManager.get(client)
  983. .getInnerWidth(getElement());
  984. // Used width includes the "more" item if present
  985. int usedWidth = getConsumedWidth();
  986. int diff = availableWidth - usedWidth;
  987. removeItem(moreItem);
  988. if (diff < 0) {
  989. // Too many items: collapse last items from root menu
  990. int widthNeeded = usedWidth - availableWidth;
  991. if (!morePresent) {
  992. widthNeeded += moreItemWidth;
  993. }
  994. int widthReduced = 0;
  995. while (widthReduced < widthNeeded && !getItems().isEmpty()) {
  996. // Move last root menu item to collapsed menu
  997. CustomMenuItem collapse = getItems()
  998. .get(getItems().size() - 1);
  999. widthReduced += collapse.getOffsetWidth();
  1000. removeItem(collapse);
  1001. collapsedRootItems.addItem(collapse, 0);
  1002. }
  1003. } else if (!collapsedRootItems.getItems().isEmpty()) {
  1004. // Space available for items: expand first items from collapsed
  1005. // menu
  1006. int widthAvailable = diff + moreItemWidth;
  1007. int widthGrowth = 0;
  1008. while (widthAvailable > widthGrowth
  1009. && !collapsedRootItems.getItems().isEmpty()) {
  1010. // Move first item from collapsed menu to the root menu
  1011. CustomMenuItem expand = collapsedRootItems.getItems()
  1012. .get(0);
  1013. collapsedRootItems.removeItem(expand);
  1014. addItem(expand);
  1015. widthGrowth += expand.getOffsetWidth();
  1016. if (!collapsedRootItems.getItems().isEmpty()) {
  1017. widthAvailable -= moreItemWidth;
  1018. }
  1019. if (widthGrowth > widthAvailable) {
  1020. removeItem(expand);
  1021. collapsedRootItems.addItem(expand, 0);
  1022. } else {
  1023. widthAvailable = diff + moreItemWidth;
  1024. }
  1025. }
  1026. }
  1027. if (!collapsedRootItems.getItems().isEmpty()) {
  1028. addItem(moreItem);
  1029. }
  1030. }
  1031. // If a popup is open we might need to adjust the shadow as well if an
  1032. // icon shown in that popup was loaded
  1033. if (popup != null) {
  1034. // Forces a recalculation of the shadow size
  1035. popup.show();
  1036. }
  1037. if (iconLoadEvent) {
  1038. // Size have changed if the width is undefined
  1039. Util.notifyParentOfSizeChange(this, false);
  1040. }
  1041. }
  1042. private int getConsumedWidth() {
  1043. int w = 0;
  1044. for (CustomMenuItem item : getItems()) {
  1045. if (!collapsedRootItems.getItems().contains(item)) {
  1046. w += item.getOffsetWidth();
  1047. }
  1048. }
  1049. return w;
  1050. }
  1051. /*
  1052. * (non-Javadoc)
  1053. *
  1054. * @see
  1055. * com.google.gwt.event.dom.client.KeyPressHandler#onKeyPress(com.google
  1056. * .gwt.event.dom.client.KeyPressEvent)
  1057. */
  1058. @Override
  1059. public void onKeyPress(KeyPressEvent event) {
  1060. // A bug fix for #14041
  1061. // getKeyCode and getCharCode return different values for different
  1062. // browsers
  1063. int keyCode = event.getNativeEvent().getKeyCode();
  1064. if (keyCode == 0) {
  1065. keyCode = event.getNativeEvent().getCharCode();
  1066. }
  1067. if (handleNavigation(keyCode,
  1068. event.isControlKeyDown() || event.isMetaKeyDown(),
  1069. event.isShiftKeyDown())) {
  1070. event.preventDefault();
  1071. }
  1072. }
  1073. /*
  1074. * (non-Javadoc)
  1075. *
  1076. * @see
  1077. * com.google.gwt.event.dom.client.KeyDownHandler#onKeyDown(com.google.gwt
  1078. * .event.dom.client.KeyDownEvent)
  1079. */
  1080. @Override
  1081. public void onKeyDown(KeyDownEvent event) {
  1082. // A bug fix for #14041
  1083. // getKeyCode and getCharCode return different values for different
  1084. // browsers
  1085. int keyCode = event.getNativeEvent().getKeyCode();
  1086. if (keyCode == 0) {
  1087. keyCode = event.getNativeEvent().getCharCode();
  1088. }
  1089. if (handleNavigation(keyCode,
  1090. event.isControlKeyDown() || event.isMetaKeyDown(),
  1091. event.isShiftKeyDown())) {
  1092. event.preventDefault();
  1093. }
  1094. }
  1095. /**
  1096. * Get the key that moves the selection upwards. By default it is the up
  1097. * arrow key but by overriding this you can change the key to whatever you
  1098. * want.
  1099. *
  1100. * @return The keycode of the key
  1101. */
  1102. protected int getNavigationUpKey() {
  1103. return KeyCodes.KEY_UP;
  1104. }
  1105. /**
  1106. * Get the key that moves the selection downwards. By default it is the down
  1107. * arrow key but by overriding this you can change the key to whatever you
  1108. * want.
  1109. *
  1110. * @return The keycode of the key
  1111. */
  1112. protected int getNavigationDownKey() {
  1113. return KeyCodes.KEY_DOWN;
  1114. }
  1115. /**
  1116. * Get the key that moves the selection left. By default it is the left
  1117. * arrow key but by overriding this you can change the key to whatever you
  1118. * want.
  1119. *
  1120. * @return The keycode of the key
  1121. */
  1122. protected int getNavigationLeftKey() {
  1123. return KeyCodes.KEY_LEFT;
  1124. }
  1125. /**
  1126. * Get the key that moves the selection right. By default it is the right
  1127. * arrow key but by overriding this you can change the key to whatever you
  1128. * want.
  1129. *
  1130. * @return The keycode of the key
  1131. */
  1132. protected int getNavigationRightKey() {
  1133. return KeyCodes.KEY_RIGHT;
  1134. }
  1135. /**
  1136. * Get the key that selects a menu item. By default it is the Enter key but
  1137. * by overriding this you can change the key to whatever you want.
  1138. *
  1139. * @deprecated use {@link #isNavigationSelectKey(int)} instead
  1140. * @return
  1141. */
  1142. @Deprecated
  1143. protected int getNavigationSelectKey() {
  1144. return KeyCodes.KEY_ENTER;
  1145. }
  1146. /**
  1147. * Checks whether key code selects a menu item. By default it is the Enter
  1148. * and Space keys but by overriding this you can change the keys to whatever
  1149. * you want.
  1150. *
  1151. * @since 7.2
  1152. * @param keycode
  1153. * @return true if key selects menu item
  1154. */
  1155. protected boolean isNavigationSelectKey(int keycode) {
  1156. return keycode == getNavigationSelectKey()
  1157. || keycode == KeyCodes.KEY_SPACE;
  1158. }
  1159. /**
  1160. * Get the key that closes the menu. By default it is the escape key but by
  1161. * overriding this yoy can change the key to whatever you want.
  1162. *
  1163. * @return
  1164. */
  1165. protected int getCloseMenuKey() {
  1166. return KeyCodes.KEY_ESCAPE;
  1167. }
  1168. /**
  1169. * Handles the keyboard events handled by the MenuBar.
  1170. *
  1171. * @param keycode
  1172. * The key code received
  1173. * @param ctrl
  1174. * Whether {@code CTRL} was pressed
  1175. * @param shift
  1176. * Whether {@code SHIFT} was pressed
  1177. * @return true if the navigation event was handled
  1178. */
  1179. public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
  1180. // If tab or shift+tab close menus
  1181. if (keycode == KeyCodes.KEY_TAB) {
  1182. setSelected(null);
  1183. hideChildren();
  1184. menuVisible = false;
  1185. return false;
  1186. }
  1187. if (ctrl || shift || !isEnabled()) {
  1188. // Do not handle tab key, nor ctrl keys
  1189. return false;
  1190. }
  1191. if (keycode == getNavigationLeftKey()) {
  1192. if (getSelected() == null) {
  1193. // If nothing is selected then select the last item
  1194. setSelected(items.get(items.size() - 1));
  1195. if (!getSelected().isSelectable()) {
  1196. handleNavigation(keycode, ctrl, shift);
  1197. }
  1198. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1199. // If this is the root menu then move to the left
  1200. int idx = items.indexOf(getSelected());
  1201. if (idx > 0) {
  1202. setSelected(items.get(idx - 1));
  1203. } else {
  1204. setSelected(items.get(items.size() - 1));
  1205. }
  1206. if (!getSelected().isSelectable()) {
  1207. handleNavigation(keycode, ctrl, shift);
  1208. }
  1209. } else if (visibleChildMenu != null) {
  1210. // Redirect all navigation to the submenu
  1211. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1212. } else if (getParentMenu().getParentMenu() == null) {
  1213. // Inside a sub menu, whose parent is a root menu item
  1214. VMenuBar root = getParentMenu();
  1215. root.getSelected().getSubMenu().setSelected(null);
  1216. // #15255 - disable animate-in/out when hide popup
  1217. root.hideChildren(false, false);
  1218. // Get the root menus items and select the previous one
  1219. int idx = root.getItems().indexOf(root.getSelected());
  1220. idx = idx > 0 ? idx : root.getItems().size();
  1221. CustomMenuItem selected = root.getItems().get(--idx);
  1222. while (selected.isSeparator() || !selected.isEnabled()) {
  1223. idx = idx > 0 ? idx : root.getItems().size();
  1224. selected = root.getItems().get(--idx);
  1225. }
  1226. root.setSelected(selected);
  1227. openMenuAndFocusFirstIfPossible(selected);
  1228. } else {
  1229. getParentMenu().getSelected().getSubMenu().setSelected(null);
  1230. getParentMenu().hideChildren();
  1231. }
  1232. return true;
  1233. } else if (keycode == getNavigationRightKey()) {
  1234. if (getSelected() == null) {
  1235. // If nothing is selected then select the first item
  1236. setSelected(items.get(0));
  1237. if (!getSelected().isSelectable()) {
  1238. handleNavigation(keycode, ctrl, shift);
  1239. }
  1240. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1241. // If this is the root menu then move to the right
  1242. int idx = items.indexOf(getSelected());
  1243. if (idx < items.size() - 1) {
  1244. setSelected(items.get(idx + 1));
  1245. } else {
  1246. setSelected(items.get(0));
  1247. }
  1248. if (!getSelected().isSelectable()) {
  1249. handleNavigation(keycode, ctrl, shift);
  1250. }
  1251. } else if (visibleChildMenu == null
  1252. && getSelected().getSubMenu() != null) {
  1253. // If the item has a submenu then show it and move the selection
  1254. // there
  1255. showChildMenu(getSelected());
  1256. menuVisible = true;
  1257. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1258. } else if (visibleChildMenu == null) {
  1259. // Get the root menu
  1260. VMenuBar root = getParentMenu();
  1261. while (root.getParentMenu() != null) {
  1262. root = root.getParentMenu();
  1263. }
  1264. // Hide the submenu (#15255 - disable animate-in/out when hide
  1265. // popup)
  1266. root.hideChildren(false, false);
  1267. // Get the root menus items and select the next one
  1268. int idx = root.getItems().indexOf(root.getSelected());
  1269. idx = idx < root.getItems().size() - 1 ? idx : -1;
  1270. CustomMenuItem selected = root.getItems().get(++idx);
  1271. while (selected.isSeparator() || !selected.isEnabled()) {
  1272. idx = idx < root.getItems().size() - 1 ? idx : -1;
  1273. selected = root.getItems().get(++idx);
  1274. }
  1275. root.setSelected(selected);
  1276. openMenuAndFocusFirstIfPossible(selected);
  1277. } else if (visibleChildMenu != null) {
  1278. // Redirect all navigation to the submenu
  1279. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1280. }
  1281. return true;
  1282. } else if (keycode == getNavigationUpKey()) {
  1283. if (getSelected() == null) {
  1284. // If nothing is selected then select the last item
  1285. setSelected(items.get(items.size() - 1));
  1286. if (!getSelected().isSelectable()) {
  1287. handleNavigation(keycode, ctrl, shift);
  1288. }
  1289. } else if (visibleChildMenu != null) {
  1290. // Redirect all navigation to the submenu
  1291. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1292. } else {
  1293. // Select the previous item if possible or loop to the last item
  1294. int idx = items.indexOf(getSelected());
  1295. if (idx > 0) {
  1296. setSelected(items.get(idx - 1));
  1297. } else {
  1298. setSelected(items.get(items.size() - 1));
  1299. }
  1300. if (!getSelected().isSelectable()) {
  1301. handleNavigation(keycode, ctrl, shift);
  1302. }
  1303. }
  1304. return true;
  1305. } else if (keycode == getNavigationDownKey()) {
  1306. if (getSelected() == null) {
  1307. // If nothing is selected then select the first item
  1308. selectFirstItem();
  1309. } else if (visibleChildMenu == null && getParentMenu() == null) {
  1310. // If this is the root menu the show the child menu with arrow
  1311. // down, if there is a child menu
  1312. openMenuAndFocusFirstIfPossible(getSelected());
  1313. } else if (visibleChildMenu != null) {
  1314. // Redirect all navigation to the submenu
  1315. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1316. } else {
  1317. // Select the next item if possible or loop to the first item
  1318. int idx = items.indexOf(getSelected());
  1319. if (idx < items.size() - 1) {
  1320. setSelected(items.get(idx + 1));
  1321. } else {
  1322. setSelected(items.get(0));
  1323. }
  1324. if (!getSelected().isSelectable()) {
  1325. handleNavigation(keycode, ctrl, shift);
  1326. }
  1327. }
  1328. return true;
  1329. } else if (keycode == getCloseMenuKey()) {
  1330. setSelected(null);
  1331. hideChildren();
  1332. menuVisible = false;
  1333. } else if (isNavigationSelectKey(keycode)) {
  1334. if (getSelected() == null) {
  1335. // If nothing is selected then select the first item
  1336. selectFirstItem();
  1337. } else if (visibleChildMenu != null) {
  1338. // Redirect all navigation to the submenu
  1339. visibleChildMenu.handleNavigation(keycode, ctrl, shift);
  1340. menuVisible = false;
  1341. } else if (visibleChildMenu == null
  1342. && getSelected().getSubMenu() != null) {
  1343. // If the item has a sub menu then show it and move the
  1344. // selection there
  1345. openMenuAndFocusFirstIfPossible(getSelected());
  1346. } else {
  1347. try {
  1348. final Command command = getSelected().getCommand();
  1349. if (command != null) {
  1350. command.execute();
  1351. }
  1352. } finally {
  1353. setSelected(null);
  1354. hideParents(true);
  1355. // #17076 keyboard selected menuitem without children: do
  1356. // not leave menu to visible ("hover open") mode
  1357. menuVisible = false;
  1358. }
  1359. }
  1360. }
  1361. return false;
  1362. }
  1363. private void selectFirstItem() {
  1364. for (int i = 0; i < items.size(); i++) {
  1365. CustomMenuItem item = items.get(i);
  1366. if (item.isSelectable()) {
  1367. setSelected(item);
  1368. break;
  1369. }
  1370. }
  1371. }
  1372. private void openMenuAndFocusFirstIfPossible(CustomMenuItem menuItem) {
  1373. VMenuBar subMenu = menuItem.getSubMenu();
  1374. if (subMenu == null) {
  1375. // No child menu? Nothing to do
  1376. return;
  1377. }
  1378. VMenuBar parentMenu = menuItem.getParentMenu();
  1379. parentMenu.showChildMenu(menuItem);
  1380. menuVisible = true;
  1381. // Select the first item in the newly open submenu
  1382. subMenu.selectFirstItem();
  1383. }
  1384. /*
  1385. * (non-Javadoc)
  1386. *
  1387. * @see
  1388. * com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
  1389. * .dom.client.FocusEvent)
  1390. */
  1391. @Override
  1392. public void onFocus(FocusEvent event) {
  1393. }
  1394. private final String SUBPART_PREFIX = "item";
  1395. @Override
  1396. public com.google.gwt.user.client.Element getSubPartElement(
  1397. String subPart) {
  1398. if (subPart.startsWith(SUBPART_PREFIX)) {
  1399. int index = Integer
  1400. .parseInt(subPart.substring(SUBPART_PREFIX.length()));
  1401. CustomMenuItem item = getItems().get(index);
  1402. return item.getElement();
  1403. } else {
  1404. Queue<CustomMenuItem> submenuItems = new LinkedList<>();
  1405. for (CustomMenuItem item : getItems()) {
  1406. if (isItemNamed(item, subPart)) {
  1407. return item.getElement();
  1408. }
  1409. if (item.getSubMenu() != null) {
  1410. submenuItems.addAll(item.getSubMenu().getItems());
  1411. }
  1412. }
  1413. while (!submenuItems.isEmpty()) {
  1414. CustomMenuItem item = submenuItems.poll();
  1415. if (!item.isSeparator() && isItemNamed(item, subPart)) {
  1416. return item.getElement();
  1417. }
  1418. if (item.getSubMenu() != null
  1419. && item.getSubMenu().menuVisible) {
  1420. submenuItems.addAll(item.getSubMenu().getItems());
  1421. }
  1422. }
  1423. return null;
  1424. }
  1425. }
  1426. private boolean isItemNamed(CustomMenuItem item, String name) {
  1427. Element lastChildElement = getLastChildElement(item);
  1428. if (getText(lastChildElement).equals(name)) {
  1429. return true;
  1430. }
  1431. return false;
  1432. }
  1433. /*
  1434. * Returns the text content of element without including the text of
  1435. * possible nested elements. It is assumed that the last child of element
  1436. * contains the text of interest and that the last child does not itself
  1437. * have children with text content. This method is used by
  1438. * getSubPartElement(String) so that possible text icons are not included in
  1439. * the textual matching (#14879).
  1440. */
  1441. private native String getText(Element element)
  1442. /*-{
  1443. var n = element.childNodes.length;
  1444. if(n > 0){
  1445. return element.childNodes[n - 1].nodeValue;
  1446. }
  1447. else{
  1448. return "";
  1449. }
  1450. }-*/;
  1451. private Element getLastChildElement(CustomMenuItem item) {
  1452. Element lastChildElement = item.getElement().getFirstChildElement();
  1453. while (lastChildElement.getNextSiblingElement() != null) {
  1454. lastChildElement = lastChildElement.getNextSiblingElement();
  1455. }
  1456. return lastChildElement;
  1457. }
  1458. @Override
  1459. public String getSubPartName(
  1460. com.google.gwt.user.client.Element subElement) {
  1461. if (!getElement().isOrHasChild(subElement)) {
  1462. return null;
  1463. }
  1464. Element menuItemRoot = subElement;
  1465. while (menuItemRoot != null && menuItemRoot.getParentElement() != null
  1466. && menuItemRoot.getParentElement() != getElement()) {
  1467. menuItemRoot = menuItemRoot.getParentElement().cast();
  1468. }
  1469. // "menuItemRoot" is now the root of the menu item
  1470. final int itemCount = getItems().size();
  1471. for (int i = 0; i < itemCount; i++) {
  1472. if (getItems().get(i).getElement() == menuItemRoot) {
  1473. String name = SUBPART_PREFIX + i;
  1474. return name;
  1475. }
  1476. }
  1477. return null;
  1478. }
  1479. /**
  1480. * Get menu item with given DOM element.
  1481. *
  1482. * @param element
  1483. * Element used in search
  1484. * @return Menu item or null if not found
  1485. * @deprecated As of 7.2, call or override
  1486. * {@link #getMenuItemWithElement(Element)} instead
  1487. */
  1488. @Deprecated
  1489. public CustomMenuItem getMenuItemWithElement(
  1490. com.google.gwt.user.client.Element element) {
  1491. for (int i = 0; i < items.size(); i++) {
  1492. CustomMenuItem item = items.get(i);
  1493. if (DOM.isOrHasChild(item.getElement(), element)) {
  1494. return item;
  1495. }
  1496. if (item.getSubMenu() != null) {
  1497. item = item.getSubMenu().getMenuItemWithElement(element);
  1498. if (item != null) {
  1499. return item;
  1500. }
  1501. }
  1502. }
  1503. return null;
  1504. }
  1505. /**
  1506. * Get menu item with given DOM element.
  1507. *
  1508. * @param element
  1509. * Element used in search
  1510. * @return Menu item or null if not found
  1511. *
  1512. * @since 7.2
  1513. */
  1514. public CustomMenuItem getMenuItemWithElement(Element element) {
  1515. return getMenuItemWithElement(DOM.asOld(element));
  1516. }
  1517. @Override
  1518. public void onMouseOver(MouseOverEvent event) {
  1519. LazyCloser.cancelClosing();
  1520. }
  1521. @Override
  1522. public void onMouseOut(MouseOutEvent event) {
  1523. LazyCloser.schedule();
  1524. }
  1525. }