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

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