]> git.saurik.com Git - wxWidgets.git/blob - src/univ/menu.cpp
New attempt to implement wxNO_FULL_REDRAW_ON_REPAINT.
[wxWidgets.git] / src / univ / menu.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: univ/menu.cpp
3 // Purpose: wxMenuItem, wxMenu and wxMenuBar implementation
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 25.08.00
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000 SciTech Software, Inc. (www.scitechsoft.com)
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 #pragma implementation "univmenuitem.h"
22 #pragma implementation "univmenu.h"
23 #endif
24
25 #include "wx/wxprec.h"
26
27 #ifdef __BORLANDC__
28 #pragma hdrstop
29 #endif
30
31 #ifndef WX_PRECOMP
32 #include "wx/dynarray.h"
33 #include "wx/control.h" // for FindAccelIndex()
34 #include "wx/menu.h"
35 #include "wx/settings.h"
36 #include "wx/accel.h"
37 #include "wx/log.h"
38 #endif // WX_PRECOMP
39
40 #if wxUSE_MENUS
41
42 #include "wx/popupwin.h"
43 #include "wx/evtloop.h"
44 #include "wx/dcclient.h"
45 #include "wx/frame.h"
46
47 #include "wx/univ/renderer.h"
48
49 #ifdef __WXMSW__
50 #include "wx/msw/private.h"
51 #endif // __WXMSW__
52
53 // ----------------------------------------------------------------------------
54 // wxMenuInfo contains all extra information about top level menus we need
55 // ----------------------------------------------------------------------------
56
57 class WXDLLEXPORT wxMenuInfo
58 {
59 public:
60 // ctor
61 wxMenuInfo(const wxString& text)
62 {
63 SetLabel(text);
64 SetEnabled();
65 }
66
67 // modifiers
68
69 void SetLabel(const wxString& text)
70 {
71 // remember the accel char (may be -1 if none)
72 m_indexAccel = wxControl::FindAccelIndex(text, &m_label);
73
74 // calculate the width later, after the menu bar is created
75 m_width = 0;
76 }
77
78 void SetEnabled(bool enabled = TRUE) { m_isEnabled = enabled; }
79
80 // accessors
81
82 const wxString& GetLabel() const { return m_label; }
83 bool IsEnabled() const { return m_isEnabled; }
84 wxCoord GetWidth(wxMenuBar *menubar) const
85 {
86 if ( !m_width )
87 {
88 wxConstCast(this, wxMenuInfo)->CalcWidth(menubar);
89 }
90
91 return m_width;
92 }
93
94 int GetAccelIndex() const { return m_indexAccel; }
95
96 private:
97 void CalcWidth(wxMenuBar *menubar)
98 {
99 wxSize size;
100 wxClientDC dc(menubar);
101 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
102 dc.GetTextExtent(m_label, &size.x, &size.y);
103
104 // adjust for the renderer we use and store the width
105 m_width = menubar->GetRenderer()->GetMenuBarItemSize(size).x;
106 }
107
108 wxString m_label;
109 wxCoord m_width;
110 int m_indexAccel;
111 bool m_isEnabled;
112 };
113
114 #include "wx/arrimpl.cpp"
115
116 WX_DEFINE_OBJARRAY(wxMenuInfoArray);
117
118 // ----------------------------------------------------------------------------
119 // wxPopupMenuWindow: a popup window showing a menu
120 // ----------------------------------------------------------------------------
121
122 class wxPopupMenuWindow : public wxPopupTransientWindow
123 {
124 public:
125 wxPopupMenuWindow(wxWindow *parent, wxMenu *menu);
126
127 ~wxPopupMenuWindow();
128
129 // override the base class version to select the first item initially
130 virtual void Popup(wxWindow *focus = NULL);
131
132 // override the base class version to dismiss any open submenus
133 virtual void Dismiss();
134
135 // notify the menu when the window disappears from screen
136 virtual void OnDismiss();
137
138 // called when a submenu is dismissed
139 void OnSubmenuDismiss() { m_hasOpenSubMenu = FALSE; }
140
141 // get the currently selected item (may be NULL)
142 wxMenuItem *GetCurrentItem() const
143 {
144 return m_nodeCurrent ? m_nodeCurrent->GetData() : NULL;
145 }
146
147 // find the menu item at given position
148 wxMenuItemList::Node *GetMenuItemFromPoint(const wxPoint& pt) const;
149
150 // refresh the given item
151 void RefreshItem(wxMenuItem *item);
152
153 // preselect the first item
154 void SelectFirst() { SetCurrent(m_menu->GetMenuItems().GetFirst()); }
155
156 // process the key event, return TRUE if done
157 bool ProcessKeyDown(int key);
158
159 // process mouse move event
160 void ProcessMouseMove(const wxPoint& pt);
161
162 // don't dismiss the popup window if the parent menu was clicked
163 virtual bool ProcessLeftDown(wxMouseEvent& event);
164
165 protected:
166 // how did we perform this operation?
167 enum InputMethod
168 {
169 WithKeyboard,
170 WithMouse
171 };
172
173 // draw the menu inside this window
174 virtual void DoDraw(wxControlRenderer *renderer);
175
176 // event handlers
177 void OnLeftUp(wxMouseEvent& event);
178 void OnMouseMove(wxMouseEvent& event);
179 void OnMouseLeave(wxMouseEvent& event);
180 void OnKeyDown(wxKeyEvent& event);
181
182 // reset the current item and node
183 void ResetCurrent();
184
185 // set the current node and item withotu refreshing anything
186 void SetCurrent(wxMenuItemList::Node *node);
187
188 // change the current item refreshing the old and new items
189 void ChangeCurrent(wxMenuItemList::Node *node);
190
191 // activate item, i.e. call either ClickItem() or OpenSubmenu() depending
192 // on what it is, return TRUE if something was done (i.e. it's not a
193 // separator...)
194 bool ActivateItem(wxMenuItem *item, InputMethod how = WithKeyboard);
195
196 // send the event about the item click
197 void ClickItem(wxMenuItem *item);
198
199 // show the submenu for this item
200 void OpenSubmenu(wxMenuItem *item, InputMethod how = WithKeyboard);
201
202 // can this tiem be opened?
203 bool CanOpen(wxMenuItem *item)
204 {
205 return item && item->IsEnabled() && item->IsSubMenu();
206 }
207
208 // dismiss the menu and all parent menus too
209 void DismissAndNotify();
210
211 // react to dimissing this menu and also dismiss the parent if
212 // dismissParent
213 void HandleDismiss(bool dismissParent);
214
215 // do we have an open submenu?
216 bool HasOpenSubmenu() const { return m_hasOpenSubMenu; }
217
218 // get previous node after the current one
219 wxMenuItemList::Node *GetPrevNode() const;
220
221 // get previous node before the given one, wrapping if it's the first one
222 wxMenuItemList::Node *GetPrevNode(wxMenuItemList::Node *node) const;
223
224 // get next node after the current one
225 wxMenuItemList::Node *GetNextNode() const;
226
227 // get next node after the given one, wrapping if it's the last one
228 wxMenuItemList::Node *GetNextNode(wxMenuItemList::Node *node) const;
229
230 private:
231 // the menu we show
232 wxMenu *m_menu;
233
234 // the menu node corresponding to the current item
235 wxMenuItemList::Node *m_nodeCurrent;
236
237 // do we currently have an opened submenu?
238 bool m_hasOpenSubMenu;
239
240 DECLARE_EVENT_TABLE()
241 };
242
243 // ----------------------------------------------------------------------------
244 // wxMenuKbdRedirector: an event handler which redirects kbd input to wxMenu
245 // ----------------------------------------------------------------------------
246
247 class wxMenuKbdRedirector : public wxEvtHandler
248 {
249 public:
250 wxMenuKbdRedirector(wxMenu *menu) { m_menu = menu; }
251
252 virtual bool ProcessEvent(wxEvent& event)
253 {
254 if ( event.GetEventType() == wxEVT_KEY_DOWN )
255 {
256 return m_menu->ProcessKeyDown(((wxKeyEvent &)event).GetKeyCode());
257 }
258 else
259 {
260 // return FALSE;
261
262 return wxEvtHandler::ProcessEvent(event);
263 }
264 }
265
266 private:
267 wxMenu *m_menu;
268 };
269
270 // ----------------------------------------------------------------------------
271 // wxWin macros
272 // ----------------------------------------------------------------------------
273
274 IMPLEMENT_DYNAMIC_CLASS(wxMenu, wxEvtHandler)
275 IMPLEMENT_DYNAMIC_CLASS(wxMenuBar, wxWindow)
276 IMPLEMENT_DYNAMIC_CLASS(wxMenuItem, wxObject)
277
278 BEGIN_EVENT_TABLE(wxPopupMenuWindow, wxPopupTransientWindow)
279 EVT_KEY_DOWN(wxPopupMenuWindow::OnKeyDown)
280
281 EVT_LEFT_UP(wxPopupMenuWindow::OnLeftUp)
282 EVT_MOTION(wxPopupMenuWindow::OnMouseMove)
283 EVT_LEAVE_WINDOW(wxPopupMenuWindow::OnMouseLeave)
284 END_EVENT_TABLE()
285
286 BEGIN_EVENT_TABLE(wxMenuBar, wxMenuBarBase)
287 EVT_KILL_FOCUS(wxMenuBar::OnKillFocus)
288
289 EVT_KEY_DOWN(wxMenuBar::OnKeyDown)
290
291 EVT_LEFT_DOWN(wxMenuBar::OnLeftDown)
292 EVT_MOTION(wxMenuBar::OnMouseMove)
293 END_EVENT_TABLE()
294
295 // ============================================================================
296 // implementation
297 // ============================================================================
298
299 // ----------------------------------------------------------------------------
300 // wxPopupMenuWindow
301 // ----------------------------------------------------------------------------
302
303 wxPopupMenuWindow::wxPopupMenuWindow(wxWindow *parent, wxMenu *menu)
304 {
305 m_menu = menu;
306 m_hasOpenSubMenu = FALSE;
307
308 ResetCurrent();
309
310 (void)Create(parent, wxBORDER_RAISED);
311
312 SetCursor(wxCURSOR_ARROW);
313 }
314
315 wxPopupMenuWindow::~wxPopupMenuWindow()
316 {
317 }
318
319 // ----------------------------------------------------------------------------
320 // wxPopupMenuWindow current item/node handling
321 // ----------------------------------------------------------------------------
322
323 void wxPopupMenuWindow::ResetCurrent()
324 {
325 SetCurrent(NULL);
326 }
327
328 void wxPopupMenuWindow::SetCurrent(wxMenuItemList::Node *node)
329 {
330 m_nodeCurrent = node;
331 }
332
333 void wxPopupMenuWindow::ChangeCurrent(wxMenuItemList::Node *node)
334 {
335 if ( node != m_nodeCurrent )
336 {
337 wxMenuItemList::Node *nodeOldCurrent = m_nodeCurrent;
338
339 m_nodeCurrent = node;
340
341 if ( nodeOldCurrent )
342 {
343 wxMenuItem *item = nodeOldCurrent->GetData();
344 wxCHECK_RET( item, _T("no current item?") );
345
346 // if it was the currently opened menu, close it
347 if ( item->IsSubMenu() && item->GetSubMenu()->IsShown() )
348 {
349 item->GetSubMenu()->Dismiss();
350 OnSubmenuDismiss();
351 }
352
353 RefreshItem(item);
354 }
355
356 if ( m_nodeCurrent )
357 RefreshItem(m_nodeCurrent->GetData());
358 }
359 }
360
361 wxMenuItemList::Node *wxPopupMenuWindow::GetPrevNode() const
362 {
363 // return the last node if there had been no previously selected one
364 return m_nodeCurrent ? GetPrevNode(m_nodeCurrent)
365 : m_menu->GetMenuItems().GetLast();
366 }
367
368 wxMenuItemList::Node *
369 wxPopupMenuWindow::GetPrevNode(wxMenuItemList::Node *node) const
370 {
371 if ( node )
372 {
373 node = node->GetPrevious();
374 if ( !node )
375 {
376 node = m_menu->GetMenuItems().GetLast();
377 }
378 }
379 //else: the menu is empty
380
381 return node;
382 }
383
384 wxMenuItemList::Node *wxPopupMenuWindow::GetNextNode() const
385 {
386 // return the first node if there had been no previously selected one
387 return m_nodeCurrent ? GetNextNode(m_nodeCurrent)
388 : m_menu->GetMenuItems().GetFirst();
389 }
390
391 wxMenuItemList::Node *
392 wxPopupMenuWindow::GetNextNode(wxMenuItemList::Node *node) const
393 {
394 if ( node )
395 {
396 node = node->GetNext();
397 if ( !node )
398 {
399 node = m_menu->GetMenuItems().GetFirst();
400 }
401 }
402 //else: the menu is empty
403
404 return node;
405 }
406
407 // ----------------------------------------------------------------------------
408 // wxPopupMenuWindow popup/dismiss
409 // ----------------------------------------------------------------------------
410
411 void wxPopupMenuWindow::Popup(wxWindow *focus)
412 {
413 // check that the current item had been properly reset before
414 wxASSERT_MSG( !m_nodeCurrent ||
415 m_nodeCurrent == m_menu->GetMenuItems().GetFirst(),
416 _T("menu current item preselected incorrectly") );
417
418 wxPopupTransientWindow::Popup(focus);
419
420 #ifdef __WXMSW__
421 // ensure that this window is really on top of everything: without using
422 // SetWindowPos() it can be covered by its parent menu which is not
423 // really what we want
424 wxMenu *menuParent = m_menu->GetParent();
425 if ( menuParent )
426 {
427 wxPopupMenuWindow *win = menuParent->m_popupMenu;
428
429 // if we're shown, the parent menu must be also shown
430 wxCHECK_RET( win, _T("parent menu is not shown?") );
431
432 if ( !::SetWindowPos(GetHwndOf(win), GetHwnd(),
433 0, 0, 0, 0,
434 SWP_NOMOVE | SWP_NOSIZE | SWP_NOREDRAW) )
435 {
436 wxLogLastError(_T("SetWindowPos(HWND_TOP)"));
437 }
438
439 Refresh();
440 }
441 #endif // __WXMSW__
442 }
443
444 void wxPopupMenuWindow::Dismiss()
445 {
446 if ( HasOpenSubmenu() )
447 {
448 wxMenuItem *item = GetCurrentItem();
449 wxCHECK_RET( item && item->IsSubMenu(), _T("where is our open submenu?") );
450
451 wxPopupMenuWindow *win = item->GetSubMenu()->m_popupMenu;
452 wxCHECK_RET( win, _T("opened submenu is not opened?") );
453
454 win->Dismiss();
455 OnSubmenuDismiss();
456 }
457
458 wxPopupTransientWindow::Dismiss();
459 }
460
461 void wxPopupMenuWindow::OnDismiss()
462 {
463 // when we are dismissed because the user clicked elsewhere or we lost
464 // focus in any other way, hide the parent menu as well
465 HandleDismiss(TRUE);
466 }
467
468 void wxPopupMenuWindow::HandleDismiss(bool dismissParent)
469 {
470 ResetCurrent();
471
472 m_menu->OnDismiss(dismissParent);
473 }
474
475 void wxPopupMenuWindow::DismissAndNotify()
476 {
477 Dismiss();
478 HandleDismiss(TRUE);
479 }
480
481 // ----------------------------------------------------------------------------
482 // wxPopupMenuWindow geometry
483 // ----------------------------------------------------------------------------
484
485 wxMenuItemList::Node *
486 wxPopupMenuWindow::GetMenuItemFromPoint(const wxPoint& pt) const
487 {
488 // we only use the y coord normally, but still check x in case the point is
489 // outside the window completely
490 if ( wxWindow::HitTest(pt) == wxHT_WINDOW_INSIDE )
491 {
492 wxCoord y = 0;
493 for ( wxMenuItemList::Node *node = m_menu->GetMenuItems().GetFirst();
494 node;
495 node = node->GetNext() )
496 {
497 wxMenuItem *item = node->GetData();
498 y += item->GetHeight();
499 if ( y > pt.y )
500 {
501 // found
502 return node;
503 }
504 }
505 }
506
507 return NULL;
508 }
509
510 // ----------------------------------------------------------------------------
511 // wxPopupMenuWindow drawing
512 // ----------------------------------------------------------------------------
513
514 void wxPopupMenuWindow::RefreshItem(wxMenuItem *item)
515 {
516 wxCHECK_RET( item, _T("can't refresh NULL item") );
517
518 wxASSERT_MSG( IsShown(), _T("can't refresh menu which is not shown") );
519
520 // FIXME: -1 here because of SetLogicalOrigin(1, 1) in DoDraw()
521 RefreshRect(wxRect(0, item->GetPosition() - 1,
522 m_menu->GetGeometryInfo().GetSize().x, item->GetHeight()));
523 }
524
525 void wxPopupMenuWindow::DoDraw(wxControlRenderer *renderer)
526 {
527 // no clipping so far - do we need it? I don't think so as the menu is
528 // never partially covered as it is always on top of everything
529
530 wxDC& dc = renderer->GetDC();
531 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
532
533 // FIXME: this should be done in the renderer, however when it is fixed
534 // wxPopupMenuWindow::RefreshItem() should be changed too!
535 dc.SetLogicalOrigin(1, 1);
536
537 wxRenderer *rend = renderer->GetRenderer();
538
539 wxCoord y = 0;
540 const wxMenuGeometryInfo& gi = m_menu->GetGeometryInfo();
541 for ( wxMenuItemList::Node *node = m_menu->GetMenuItems().GetFirst();
542 node;
543 node = node->GetNext() )
544 {
545 wxMenuItem *item = node->GetData();
546
547 if ( item->IsSeparator() )
548 {
549 rend->DrawMenuSeparator(dc, y, gi);
550 }
551 else // not a separator
552 {
553 int flags = 0;
554 if ( item->IsCheckable() )
555 {
556 flags |= wxCONTROL_CHECKABLE;
557
558 if ( item->IsChecked() )
559 {
560 flags |= wxCONTROL_CHECKED;
561 }
562 }
563
564 if ( !item->IsEnabled() )
565 flags |= wxCONTROL_DISABLED;
566
567 if ( item->IsSubMenu() )
568 flags |= wxCONTROL_ISSUBMENU;
569
570 if ( item == GetCurrentItem() )
571 flags |= wxCONTROL_SELECTED;
572
573 rend->DrawMenuItem
574 (
575 dc,
576 y,
577 gi,
578 item->GetLabel(),
579 item->GetAccelString(),
580 // strangely enough, for unchecked item we use the
581 // "checked" bitmap because this is the default one - this
582 // explains this strange boolean expression
583 item->GetBitmap(!item->IsCheckable() || item->IsChecked()),
584 flags,
585 item->GetAccelIndex()
586 );
587 }
588
589 y += item->GetHeight();
590 }
591 }
592
593 // ----------------------------------------------------------------------------
594 // wxPopupMenuWindow actions
595 // ----------------------------------------------------------------------------
596
597 void wxPopupMenuWindow::ClickItem(wxMenuItem *item)
598 {
599 wxCHECK_RET( item, _T("can't click NULL item") );
600
601 wxASSERT_MSG( !item->IsSeparator() && !item->IsSubMenu(),
602 _T("can't click this item") );
603
604 wxMenu* menu = m_menu;
605
606 // close all menus
607 DismissAndNotify();
608
609 menu->ClickItem(item);
610 }
611
612 void wxPopupMenuWindow::OpenSubmenu(wxMenuItem *item, InputMethod how)
613 {
614 wxCHECK_RET( item, _T("can't open NULL submenu") );
615
616 wxMenu *submenu = item->GetSubMenu();
617 wxCHECK_RET( submenu, _T("can only open submenus!") );
618
619 // FIXME: should take into account the border width
620 submenu->Popup(ClientToScreen(wxPoint(0, item->GetPosition())),
621 wxSize(m_menu->GetGeometryInfo().GetSize().x, 0),
622 how == WithKeyboard /* preselect first item then */);
623
624 m_hasOpenSubMenu = TRUE;
625 }
626
627 bool wxPopupMenuWindow::ActivateItem(wxMenuItem *item, InputMethod how)
628 {
629 // don't activate disabled items
630 if ( !item || !item->IsEnabled() )
631 {
632 return FALSE;
633 }
634
635 // normal menu items generate commands, submenus can be opened and
636 // the separators don't do anything
637 if ( item->IsSubMenu() )
638 {
639 OpenSubmenu(item, how);
640 }
641 else if ( !item->IsSeparator() )
642 {
643 ClickItem(item);
644 }
645 else // separator, can't activate
646 {
647 return FALSE;
648 }
649
650 return TRUE;
651 }
652
653 // ----------------------------------------------------------------------------
654 // wxPopupMenuWindow input handling
655 // ----------------------------------------------------------------------------
656
657 bool wxPopupMenuWindow::ProcessLeftDown(wxMouseEvent& event)
658 {
659 // wxPopupWindowHandler dismisses the window when the mouse is clicked
660 // outside it which is usually just fine, but there is one case when we
661 // don't want to do it: if the mouse was clicked on the parent submenu item
662 // which opens this menu, so check for it
663
664 wxPoint pos = event.GetPosition();
665 if ( HitTest(pos.x, pos.y) == wxHT_WINDOW_OUTSIDE )
666 {
667 wxMenu *menu = m_menu->GetParent();
668 if ( menu )
669 {
670 wxPopupMenuWindow *win = menu->m_popupMenu;
671
672 wxCHECK_MSG( win, FALSE, _T("parent menu not shown?") );
673
674 pos = ClientToScreen(pos);
675 if ( win->GetMenuItemFromPoint(win->ScreenToClient(pos)) )
676 {
677 // eat the event
678 return TRUE;
679 }
680 //else: it is outside the parent menu as well, do dismiss this one
681 }
682 }
683
684 return FALSE;
685 }
686
687 void wxPopupMenuWindow::OnLeftUp(wxMouseEvent& event)
688 {
689 wxMenuItemList::Node *node = GetMenuItemFromPoint(event.GetPosition());
690 if ( node )
691 {
692 ActivateItem(node->GetData(), WithMouse);
693 }
694 }
695
696 void wxPopupMenuWindow::OnMouseMove(wxMouseEvent& event)
697 {
698 const wxPoint pt = event.GetPosition();
699
700 // we need to ignore extra mouse events: example when this happens is when
701 // the mouse is on the menu and we open a submenu from keyboard - Windows
702 // then sends us a dummy mouse move event, we (correctly) determine that it
703 // happens in the parent menu and so immediately close the just opened
704 // submenu!
705 #ifdef __WXMSW__
706 static wxPoint s_ptLast;
707 wxPoint ptCur = ClientToScreen(pt);
708 if ( ptCur == s_ptLast )
709 {
710 return;
711 }
712
713 s_ptLast = ptCur;
714 #endif // __WXMSW__
715
716 ProcessMouseMove(pt);
717
718 event.Skip();
719 }
720
721 void wxPopupMenuWindow::ProcessMouseMove(const wxPoint& pt)
722 {
723 wxMenuItemList::Node *node = GetMenuItemFromPoint(pt);
724
725 // don't reset current to NULL here, we only do it when the mouse leaves
726 // the window (see below)
727 if ( node )
728 {
729 if ( node != m_nodeCurrent )
730 {
731 ChangeCurrent(node);
732
733 wxMenuItem *item = GetCurrentItem();
734 if ( CanOpen(item) )
735 {
736 OpenSubmenu(item, WithMouse);
737 }
738 }
739 //else: same item, nothing to do
740 }
741 else // not on an item
742 {
743 // the last open submenu forwards the mouse move messages to its
744 // parent, so if the mouse moves to another item of the parent menu,
745 // this menu is closed and this other item is selected - in the similar
746 // manner, the top menu forwards the mouse moves to the menubar which
747 // allows to select another top level menu by just moving the mouse
748
749 // we need to translate our client coords to the client coords of the
750 // window we forward this event to
751 wxPoint ptScreen = ClientToScreen(pt);
752
753 // if the mouse is outside this menu, let the parent one to
754 // process it
755 wxMenu *menuParent = m_menu->GetParent();
756 if ( menuParent )
757 {
758 wxPopupMenuWindow *win = menuParent->m_popupMenu;
759
760 // if we're shown, the parent menu must be also shown
761 wxCHECK_RET( win, _T("parent menu is not shown?") );
762
763 win->ProcessMouseMove(win->ScreenToClient(ptScreen));
764 }
765 else // no parent menu
766 {
767 wxMenuBar *menubar = m_menu->GetMenuBar();
768 if ( menubar )
769 {
770 if ( menubar->ProcessMouseEvent(
771 menubar->ScreenToClient(ptScreen)) )
772 {
773 // menubar has closed this menu and opened another one, probably
774 return;
775 }
776 }
777 }
778 //else: top level popup menu, no other processing to do
779 }
780 }
781
782 void wxPopupMenuWindow::OnMouseLeave(wxMouseEvent& event)
783 {
784 // due to the artefact of mouse events generation under MSW, we actually
785 // may get the mouse leave event after the menu had been already dismissed
786 // and calling ChangeCurrent() would then assert, so don't do it
787 if ( IsShown() )
788 {
789 // we shouldn't change the current them if our submenu is opened and
790 // mouse moved there, in this case the submenu is responsable for
791 // handling it
792 bool resetCurrent;
793 if ( HasOpenSubmenu() )
794 {
795 wxMenuItem *item = GetCurrentItem();
796 wxCHECK_RET( CanOpen(item), _T("where is our open submenu?") );
797
798 wxPopupMenuWindow *win = item->GetSubMenu()->m_popupMenu;
799 wxCHECK_RET( win, _T("submenu is opened but not shown?") );
800
801 // only handle this event if the mouse is not inside the submenu
802 wxPoint pt = ClientToScreen(event.GetPosition());
803 resetCurrent =
804 win->HitTest(win->ScreenToClient(pt)) == wxHT_WINDOW_OUTSIDE;
805 }
806 else
807 {
808 // this menu is the last opened
809 resetCurrent = TRUE;
810 }
811
812 if ( resetCurrent )
813 {
814 ChangeCurrent(NULL);
815 }
816 }
817
818 event.Skip();
819 }
820
821 void wxPopupMenuWindow::OnKeyDown(wxKeyEvent& event)
822 {
823 if ( !ProcessKeyDown(event.GetKeyCode()) )
824 {
825 event.Skip();
826 }
827 }
828
829 bool wxPopupMenuWindow::ProcessKeyDown(int key)
830 {
831 wxMenuItem *item = GetCurrentItem();
832
833 // first let the opened submenu to have it (no test for IsEnabled() here,
834 // the keys navigate even in a disabled submenu if we had somehow managed
835 // to open it inspit of this)
836 if ( HasOpenSubmenu() )
837 {
838 wxCHECK_MSG( CanOpen(item), FALSE,
839 _T("has open submenu but another item selected?") );
840
841 if ( item->GetSubMenu()->ProcessKeyDown(key) )
842 return TRUE;
843 }
844
845 bool processed = TRUE;
846
847 // handle the up/down arrows, home, end, esc and return here, pass the
848 // left/right arrows to the menu bar except when the right arrow can be
849 // used to open a submenu
850 switch ( key )
851 {
852 case WXK_LEFT:
853 // if we're not a top level menu, close us, else leave this to the
854 // menubar
855 if ( !m_menu->GetParent() )
856 {
857 processed = FALSE;
858 break;
859 }
860
861 // fall through
862
863 case WXK_ESCAPE:
864 // close just this menu
865 Dismiss();
866 HandleDismiss(FALSE);
867 break;
868
869 case WXK_RETURN:
870 processed = ActivateItem(item);
871 break;
872
873 case WXK_HOME:
874 ChangeCurrent(m_menu->GetMenuItems().GetFirst());
875 break;
876
877 case WXK_END:
878 ChangeCurrent(m_menu->GetMenuItems().GetLast());
879 break;
880
881 case WXK_UP:
882 case WXK_DOWN:
883 {
884 bool up = key == WXK_UP;
885
886 wxMenuItemList::Node *nodeStart = up ? GetPrevNode()
887 : GetNextNode(),
888 *node = nodeStart;
889 while ( node && node->GetData()->IsSeparator() )
890 {
891 node = up ? GetPrevNode(node) : GetNextNode(node);
892
893 if ( node == nodeStart )
894 {
895 // nothing but separators and disabled items in this
896 // menu, break out
897 node = NULL;
898 }
899 }
900
901 if ( node )
902 {
903 ChangeCurrent(node);
904 }
905 else
906 {
907 processed = FALSE;
908 }
909 }
910 break;
911
912 case WXK_RIGHT:
913 // don't try to reopen an already opened menu
914 if ( !HasOpenSubmenu() && CanOpen(item) )
915 {
916 OpenSubmenu(item);
917 }
918 else
919 {
920 processed = FALSE;
921 }
922 break;
923
924 default:
925 // look for the menu item starting with this letter
926 if ( wxIsalnum(key) )
927 {
928 // we want to start from the item after this one because
929 // if we're already on the item with the given accel we want to
930 // go to the next one, not to stay in place
931 wxMenuItemList::Node *nodeStart = GetNextNode();
932
933 // do we have more than one item with this accel?
934 bool notUnique = FALSE;
935
936 // translate everything to lower case before comparing
937 wxChar chAccel = wxTolower(key);
938
939 // loop through all items searching for the item with this
940 // accel
941 wxMenuItemList::Node *node = nodeStart,
942 *nodeFound = NULL;
943 for ( ;; )
944 {
945 item = node->GetData();
946
947 int idxAccel = item->GetAccelIndex();
948 if ( idxAccel != -1 &&
949 wxTolower(item->GetLabel()[(size_t)idxAccel])
950 == chAccel )
951 {
952 // ok, found an item with this accel
953 if ( !nodeFound )
954 {
955 // store it but continue searching as we need to
956 // know if it's the only item with this accel or if
957 // there are more
958 nodeFound = node;
959 }
960 else // we already had found such item
961 {
962 notUnique = TRUE;
963
964 // no need to continue further, we won't find
965 // anything we don't already know
966 break;
967 }
968 }
969
970 // we want to iterate over all items wrapping around if
971 // necessary
972 node = GetNextNode(node);
973 if ( node == nodeStart )
974 {
975 // we've seen all nodes
976 break;
977 }
978 }
979
980 if ( nodeFound )
981 {
982 item = nodeFound->GetData();
983
984 // go to this item anyhow
985 ChangeCurrent(nodeFound);
986
987 if ( !notUnique && item->IsEnabled() )
988 {
989 // unique item with this accel - activate it
990 processed = ActivateItem(item);
991 }
992 //else: just select it but don't activate as the user might
993 // have wanted to activate another item
994
995 // skip "processed = FALSE" below
996 break;
997 }
998 }
999
1000 processed = FALSE;
1001 }
1002
1003 return processed;
1004 }
1005
1006 // ----------------------------------------------------------------------------
1007 // wxMenu
1008 // ----------------------------------------------------------------------------
1009
1010 void wxMenu::Init()
1011 {
1012 m_geometry = NULL;
1013
1014 m_popupMenu = NULL;
1015 }
1016
1017 wxMenu::~wxMenu()
1018 {
1019 delete m_geometry;
1020 delete m_popupMenu;
1021 }
1022
1023 // ----------------------------------------------------------------------------
1024 // wxMenu and wxMenuGeometryInfo
1025 // ----------------------------------------------------------------------------
1026
1027 wxMenuGeometryInfo::~wxMenuGeometryInfo()
1028 {
1029 }
1030
1031 const wxMenuGeometryInfo& wxMenu::GetGeometryInfo() const
1032 {
1033 if ( !m_geometry )
1034 {
1035 if ( m_popupMenu )
1036 {
1037 wxConstCast(this, wxMenu)->m_geometry =
1038 m_popupMenu->GetRenderer()->GetMenuGeometry(m_popupMenu, *this);
1039 }
1040 else
1041 {
1042 wxFAIL_MSG( _T("can't get geometry without window") );
1043 }
1044 }
1045
1046 return *m_geometry;
1047 }
1048
1049 void wxMenu::InvalidateGeometryInfo()
1050 {
1051 if ( m_geometry )
1052 {
1053 delete m_geometry;
1054 m_geometry = NULL;
1055 }
1056 }
1057
1058 // ----------------------------------------------------------------------------
1059 // wxMenu adding/removing items
1060 // ----------------------------------------------------------------------------
1061
1062 void wxMenu::OnItemAdded(wxMenuItem *item)
1063 {
1064 InvalidateGeometryInfo();
1065
1066 #if wxUSE_ACCEL
1067 AddAccelFor(item);
1068 #endif // wxUSE_ACCEL
1069
1070 // the submenus of a popup menu should have the same invoking window as it
1071 // has
1072 if ( m_invokingWindow && item->IsSubMenu() )
1073 {
1074 item->GetSubMenu()->SetInvokingWindow(m_invokingWindow);
1075 }
1076 }
1077
1078 bool wxMenu::DoAppend(wxMenuItem *item)
1079 {
1080 if ( !wxMenuBase::DoAppend(item) )
1081 return FALSE;
1082
1083 OnItemAdded(item);
1084
1085 return TRUE;
1086 }
1087
1088 bool wxMenu::DoInsert(size_t pos, wxMenuItem *item)
1089 {
1090 if ( !wxMenuBase::DoInsert(pos, item) )
1091 return FALSE;
1092
1093 OnItemAdded(item);
1094
1095 return TRUE;
1096 }
1097
1098 wxMenuItem *wxMenu::DoRemove(wxMenuItem *item)
1099 {
1100 wxMenuItem *itemOld = wxMenuBase::DoRemove(item);
1101
1102 if ( itemOld )
1103 {
1104 InvalidateGeometryInfo();
1105
1106 #if wxUSE_ACCEL
1107 RemoveAccelFor(item);
1108 #endif // wxUSE_ACCEL
1109 }
1110
1111 return itemOld;
1112 }
1113
1114 // ----------------------------------------------------------------------------
1115 // wxMenu attaching/detaching
1116 // ----------------------------------------------------------------------------
1117
1118 void wxMenu::Attach(wxMenuBarBase *menubar)
1119 {
1120 wxMenuBase::Attach(menubar);
1121
1122 wxCHECK_RET( m_menuBar, _T("menubar can't be NULL after attaching") );
1123
1124 // unfortunately, we can't use m_menuBar->GetEventHandler() here because,
1125 // if the menubar is currently showing a menu, its event handler is a
1126 // temporary one installed by wxPopupWindow and so will disappear soon any
1127 // any attempts to use it from the newly attached menu would result in a
1128 // crash
1129 //
1130 // so we use the menubar itself, even if it's a pity as it means we can't
1131 // redirect all menu events by changing the menubar handler (FIXME)
1132 SetNextHandler(m_menuBar);
1133 }
1134
1135 void wxMenu::Detach()
1136 {
1137 wxMenuBase::Detach();
1138 }
1139
1140 // ----------------------------------------------------------------------------
1141 // wxMenu misc functions
1142 // ----------------------------------------------------------------------------
1143
1144 wxWindow *wxMenu::GetRootWindow() const
1145 {
1146 if ( m_menuBar )
1147 {
1148 // simple case - a normal menu attached to the menubar
1149 return m_menuBar;
1150 }
1151
1152 // we're a popup menu but the trouble is that only the top level popup menu
1153 // has a pointer to the invoking window, so we must walk up the menu chain
1154 // if needed
1155 wxWindow *win = GetInvokingWindow();
1156 if ( win )
1157 {
1158 // we already have it
1159 return win;
1160 }
1161
1162 wxMenu *menu = GetParent();
1163 while ( menu )
1164 {
1165 // We are a submenu of a menu of a menubar
1166 if (menu->GetMenuBar())
1167 return menu->GetMenuBar();
1168
1169 win = menu->GetInvokingWindow();
1170 if ( win )
1171 break;
1172
1173 menu = menu->GetParent();
1174 }
1175
1176 // we're probably going to crash in the caller anyhow, but try to detect
1177 // this error as soon as possible
1178 wxASSERT_MSG( win, _T("menu without any associated window?") );
1179
1180 // also remember it in this menu so that we don't have to search for it the
1181 // next time
1182 wxConstCast(this, wxMenu)->m_invokingWindow = win;
1183
1184 return win;
1185 }
1186
1187 wxRenderer *wxMenu::GetRenderer() const
1188 {
1189 // we're going to crash without renderer!
1190 wxCHECK_MSG( m_popupMenu, NULL, _T("neither popup nor menubar menu?") );
1191
1192 return m_popupMenu->GetRenderer();
1193 }
1194
1195 void wxMenu::RefreshItem(wxMenuItem *item)
1196 {
1197 // the item geometry changed, so our might have changed as well
1198 InvalidateGeometryInfo();
1199
1200 if ( IsShown() )
1201 {
1202 // this would be a bug in IsShown()
1203 wxCHECK_RET( m_popupMenu, _T("must have popup window if shown!") );
1204
1205 // recalc geometry to update the item height and such
1206 (void)GetGeometryInfo();
1207
1208 m_popupMenu->RefreshItem(item);
1209 }
1210 }
1211
1212 // ----------------------------------------------------------------------------
1213 // wxMenu showing and hiding
1214 // ----------------------------------------------------------------------------
1215
1216 bool wxMenu::IsShown() const
1217 {
1218 return m_popupMenu && m_popupMenu->IsShown();
1219 }
1220
1221 void wxMenu::OnDismiss(bool dismissParent)
1222 {
1223 if ( m_menuParent )
1224 {
1225 // always notify the parent about submenu disappearance
1226 wxPopupMenuWindow *win = m_menuParent->m_popupMenu;
1227 if ( win )
1228 {
1229 win->OnSubmenuDismiss();
1230 }
1231 else
1232 {
1233 wxFAIL_MSG( _T("parent menu not shown?") );
1234 }
1235
1236 // and if we dismiss everything, propagate to parent
1237 if ( dismissParent )
1238 {
1239 // dismissParent is recursive
1240 m_menuParent->Dismiss();
1241 m_menuParent->OnDismiss(TRUE);
1242 }
1243 }
1244 else // no parent menu
1245 {
1246 // notify the menu bar if we're a top level menu
1247 if ( m_menuBar )
1248 {
1249 m_menuBar->OnDismissMenu(dismissParent);
1250 }
1251 else // popup menu
1252 {
1253 wxCHECK_RET( m_invokingWindow, _T("what kind of menu is this?") );
1254
1255 m_invokingWindow->DismissPopupMenu();
1256
1257 // Why reset it here? We need it for sending the event to...
1258 // SetInvokingWindow(NULL);
1259 }
1260 }
1261 }
1262
1263 void wxMenu::Popup(const wxPoint& pos, const wxSize& size, bool selectFirst)
1264 {
1265 // create the popup window if not done yet
1266 if ( !m_popupMenu )
1267 {
1268 m_popupMenu = new wxPopupMenuWindow(GetRootWindow(), this);
1269 }
1270
1271 // select the first item unless disabled
1272 if ( selectFirst )
1273 {
1274 m_popupMenu->SelectFirst();
1275 }
1276
1277 // the geometry might have changed since the last time we were shown, so
1278 // always resize
1279 m_popupMenu->SetClientSize(GetGeometryInfo().GetSize());
1280
1281 // position it as specified
1282 m_popupMenu->Position(pos, size);
1283
1284 // the menu can't have the focus itself (it is a Windows limitation), so
1285 // always keep the focus at the originating window
1286 wxWindow *focus = GetRootWindow();
1287
1288 wxASSERT_MSG( focus, _T("no window to keep focus on?") );
1289
1290 // and show it
1291 m_popupMenu->Popup(focus);
1292 }
1293
1294 void wxMenu::Dismiss()
1295 {
1296 wxCHECK_RET( IsShown(), _T("can't dismiss hidden menu") );
1297
1298 m_popupMenu->Dismiss();
1299 }
1300
1301 // ----------------------------------------------------------------------------
1302 // wxMenu event processing
1303 // ----------------------------------------------------------------------------
1304
1305 bool wxMenu::ProcessKeyDown(int key)
1306 {
1307 wxCHECK_MSG( m_popupMenu, FALSE,
1308 _T("can't process key events if not shown") );
1309
1310 return m_popupMenu->ProcessKeyDown(key);
1311 }
1312
1313 bool wxMenu::ClickItem(wxMenuItem *item)
1314 {
1315 int isChecked;
1316 if ( item->IsCheckable() )
1317 {
1318 // update the item state
1319 isChecked = !item->IsChecked();
1320
1321 item->Check(isChecked != 0);
1322 }
1323 else
1324 {
1325 // not applicabled
1326 isChecked = -1;
1327 }
1328
1329 return SendEvent(item->GetId(), isChecked);
1330 }
1331
1332 // ----------------------------------------------------------------------------
1333 // wxMenu accel support
1334 // ----------------------------------------------------------------------------
1335
1336 #if wxUSE_ACCEL
1337
1338 bool wxMenu::ProcessAccelEvent(const wxKeyEvent& event)
1339 {
1340 // do we have an item for this accel?
1341 wxMenuItem *item = m_accelTable.GetMenuItem(event);
1342 if ( item && item->IsEnabled() )
1343 {
1344 return ClickItem(item);
1345 }
1346
1347 // try our submenus
1348 for ( wxMenuItemList::Node *node = GetMenuItems().GetFirst();
1349 node;
1350 node = node->GetNext() )
1351 {
1352 const wxMenuItem *item = node->GetData();
1353 if ( item->IsSubMenu() && item->IsEnabled() )
1354 {
1355 // try its elements
1356 if ( item->GetSubMenu()->ProcessAccelEvent(event) )
1357 {
1358 return TRUE;
1359 }
1360 }
1361 }
1362
1363 return FALSE;
1364 }
1365
1366 void wxMenu::AddAccelFor(wxMenuItem *item)
1367 {
1368 wxAcceleratorEntry *accel = item->GetAccel();
1369 if ( accel )
1370 {
1371 accel->SetMenuItem(item);
1372
1373 m_accelTable.Add(*accel);
1374
1375 delete accel;
1376 }
1377 }
1378
1379 void wxMenu::RemoveAccelFor(wxMenuItem *item)
1380 {
1381 wxAcceleratorEntry *accel = item->GetAccel();
1382 if ( accel )
1383 {
1384 m_accelTable.Remove(*accel);
1385
1386 delete accel;
1387 }
1388 }
1389
1390 #endif // wxUSE_ACCEL
1391
1392 // ----------------------------------------------------------------------------
1393 // wxMenuItem construction
1394 // ----------------------------------------------------------------------------
1395
1396 wxMenuItem::wxMenuItem(wxMenu *parentMenu,
1397 int id,
1398 const wxString& text,
1399 const wxString& help,
1400 bool isCheckable,
1401 wxMenu *subMenu)
1402 {
1403 m_id = id;
1404 m_parentMenu = parentMenu;
1405 m_subMenu = subMenu;
1406
1407 m_text = text;
1408 m_help = help;
1409
1410 m_isCheckable = isCheckable;
1411 m_isEnabled = TRUE;
1412 m_isChecked = FALSE;
1413
1414 m_posY =
1415 m_height = -1;
1416
1417 UpdateAccelInfo();
1418 }
1419
1420 wxMenuItem::~wxMenuItem()
1421 {
1422 }
1423
1424 // ----------------------------------------------------------------------------
1425 // wxMenuItemBase methods implemented here
1426 // ----------------------------------------------------------------------------
1427
1428 /* static */
1429 wxMenuItem *wxMenuItemBase::New(wxMenu *parentMenu,
1430 int id,
1431 const wxString& name,
1432 const wxString& help,
1433 bool isCheckable,
1434 wxMenu *subMenu)
1435 {
1436 return new wxMenuItem(parentMenu, id, name, help, isCheckable, subMenu);
1437 }
1438
1439 /* static */
1440 wxString wxMenuItemBase::GetLabelFromText(const wxString& text)
1441 {
1442 return wxStripMenuCodes(text);
1443 }
1444
1445 // ----------------------------------------------------------------------------
1446 // wxMenuItem operations
1447 // ----------------------------------------------------------------------------
1448
1449 void wxMenuItem::NotifyMenu()
1450 {
1451 m_parentMenu->RefreshItem(this);
1452 }
1453
1454 void wxMenuItem::UpdateAccelInfo()
1455 {
1456 m_indexAccel = wxControl::FindAccelIndex(m_text);
1457
1458 // will be empty if the text contains no TABs - ok
1459 m_strAccel = m_text.AfterFirst(_T('\t'));
1460 }
1461
1462 void wxMenuItem::SetText(const wxString& text)
1463 {
1464 if ( text != m_text )
1465 {
1466 // first call the base class version to change m_text
1467 wxMenuItemBase::SetText(text);
1468
1469 UpdateAccelInfo();
1470
1471 NotifyMenu();
1472 }
1473 }
1474
1475 void wxMenuItem::SetCheckable(bool checkable)
1476 {
1477 if ( checkable != m_isCheckable )
1478 {
1479 wxMenuItemBase::SetCheckable(checkable);
1480
1481 NotifyMenu();
1482 }
1483 }
1484
1485 void wxMenuItem::SetBitmaps(const wxBitmap& bmpChecked,
1486 const wxBitmap& bmpUnchecked)
1487 {
1488 m_bmpChecked = bmpChecked;
1489 m_bmpUnchecked = bmpUnchecked;
1490
1491 NotifyMenu();
1492 }
1493
1494 void wxMenuItem::Enable(bool enable)
1495 {
1496 if ( enable != m_isEnabled )
1497 {
1498 wxMenuItemBase::Enable(enable);
1499
1500 NotifyMenu();
1501 }
1502 }
1503
1504 void wxMenuItem::Check(bool check)
1505 {
1506 if ( check != m_isChecked )
1507 {
1508 wxMenuItemBase::Check(check);
1509
1510 NotifyMenu();
1511 }
1512 }
1513
1514 // ----------------------------------------------------------------------------
1515 // wxMenuBar creation
1516 // ----------------------------------------------------------------------------
1517
1518 void wxMenuBar::Init()
1519 {
1520 m_frameLast = NULL;
1521
1522 m_current = -1;
1523
1524 m_menuShown = NULL;
1525
1526 m_shouldShowMenu = FALSE;
1527
1528 // m_windowStyle |= wxNO_FULL_REPAINT_ON_RESIZE;
1529 }
1530
1531 void wxMenuBar::Attach(wxFrame *frame)
1532 {
1533 // maybe you really wanted to call Detach()?
1534 wxCHECK_RET( frame, _T("wxMenuBar::Attach(NULL) called") );
1535
1536 wxMenuBarBase::Attach(frame);
1537
1538 if ( IsCreated() )
1539 {
1540 // reparent if necessary
1541 if ( m_frameLast != frame )
1542 {
1543 Reparent(frame);
1544 }
1545
1546 // show it back - was hidden by Detach()
1547 Show();
1548 }
1549 else // not created yet, do it now
1550 {
1551 // we have no way to return the error from here anyhow :-(
1552 (void)Create(frame, -1);
1553
1554 SetCursor(wxCURSOR_ARROW);
1555
1556 SetFont(wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT));
1557
1558 // calculate and set our height (it won't be changed any more)
1559 SetSize(-1, GetBestSize().y);
1560 }
1561
1562 // remember the last frame which had us to avoid unnecessarily reparenting
1563 // above
1564 m_frameLast = frame;
1565 }
1566
1567 void wxMenuBar::Detach()
1568 {
1569 // don't delete the window because we may be reattached later, just hide it
1570 if ( m_frameLast )
1571 {
1572 Hide();
1573 }
1574
1575 wxMenuBarBase::Detach();
1576 }
1577
1578 wxMenuBar::~wxMenuBar()
1579 {
1580 }
1581
1582 // ----------------------------------------------------------------------------
1583 // wxMenuBar adding/removing items
1584 // ----------------------------------------------------------------------------
1585
1586 bool wxMenuBar::Append(wxMenu *menu, const wxString& title)
1587 {
1588 return Insert(GetCount(), menu, title);
1589 }
1590
1591 bool wxMenuBar::Insert(size_t pos, wxMenu *menu, const wxString& title)
1592 {
1593 if ( !wxMenuBarBase::Insert(pos, menu, title) )
1594 return FALSE;
1595
1596 wxMenuInfo *info = new wxMenuInfo(title);
1597 m_menuInfos.Insert(info, pos);
1598
1599 RefreshAllItemsAfter(pos);
1600
1601 return TRUE;
1602 }
1603
1604 wxMenu *wxMenuBar::Replace(size_t pos, wxMenu *menu, const wxString& title)
1605 {
1606 wxMenu *menuOld = wxMenuBarBase::Replace(pos, menu, title);
1607
1608 if ( menuOld )
1609 {
1610 wxMenuInfo& info = m_menuInfos[pos];
1611
1612 info.SetLabel(title);
1613
1614 // even if the old menu was disabled, the new one is not any more
1615 info.SetEnabled();
1616
1617 // even if we change only this one, the new label has different width,
1618 // so we need to refresh everything beyond this item as well
1619 RefreshAllItemsAfter(pos);
1620 }
1621
1622 return menuOld;
1623 }
1624
1625 wxMenu *wxMenuBar::Remove(size_t pos)
1626 {
1627 wxMenu *menuOld = wxMenuBarBase::Remove(pos);
1628
1629 if ( menuOld )
1630 {
1631 m_menuInfos.RemoveAt(pos);
1632
1633 // this doesn't happen too often, so don't try to be too smart - just
1634 // refresh everything
1635 Refresh();
1636 }
1637
1638 return menuOld;
1639 }
1640
1641 // ----------------------------------------------------------------------------
1642 // wxMenuBar top level menus access
1643 // ----------------------------------------------------------------------------
1644
1645 wxCoord wxMenuBar::GetItemWidth(size_t pos) const
1646 {
1647 return m_menuInfos[pos].GetWidth(wxConstCast(this, wxMenuBar));
1648 }
1649
1650 void wxMenuBar::EnableTop(size_t pos, bool enable)
1651 {
1652 wxCHECK_RET( pos < GetCount(), _T("invalid index in EnableTop") );
1653
1654 if ( enable != m_menuInfos[pos].IsEnabled() )
1655 {
1656 m_menuInfos[pos].SetEnabled(enable);
1657
1658 RefreshItem(pos);
1659 }
1660 //else: nothing to do
1661 }
1662
1663 bool wxMenuBar::IsEnabledTop(size_t pos) const
1664 {
1665 wxCHECK_MSG( pos < GetCount(), FALSE, _T("invalid index in IsEnabledTop") );
1666
1667 return m_menuInfos[pos].IsEnabled();
1668 }
1669
1670 void wxMenuBar::SetLabelTop(size_t pos, const wxString& label)
1671 {
1672 wxCHECK_RET( pos < GetCount(), _T("invalid index in EnableTop") );
1673
1674 if ( label != m_menuInfos[pos].GetLabel() )
1675 {
1676 m_menuInfos[pos].SetLabel(label);
1677
1678 RefreshItem(pos);
1679 }
1680 //else: nothing to do
1681 }
1682
1683 wxString wxMenuBar::GetLabelTop(size_t pos) const
1684 {
1685 wxCHECK_MSG( pos < GetCount(), _T(""), _T("invalid index in GetLabelTop") );
1686
1687 return m_menuInfos[pos].GetLabel();
1688 }
1689
1690 // ----------------------------------------------------------------------------
1691 // wxMenuBar drawing
1692 // ----------------------------------------------------------------------------
1693
1694 void wxMenuBar::RefreshAllItemsAfter(size_t pos)
1695 {
1696 if ( !IsCreated() )
1697 {
1698 // no need to refresh if nothing is shown yet
1699 return;
1700 }
1701
1702 wxRect rect = GetItemRect(pos);
1703 rect.width = GetClientSize().x - rect.x;
1704 RefreshRect(rect);
1705 }
1706
1707 void wxMenuBar::RefreshItem(size_t pos)
1708 {
1709 wxCHECK_RET( pos != (size_t)-1,
1710 _T("invalid item in wxMenuBar::RefreshItem") );
1711
1712 if ( !IsCreated() )
1713 {
1714 // no need to refresh if nothing is shown yet
1715 return;
1716 }
1717
1718 RefreshRect(GetItemRect(pos));
1719 }
1720
1721 void wxMenuBar::DoDraw(wxControlRenderer *renderer)
1722 {
1723 wxDC& dc = renderer->GetDC();
1724 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
1725
1726 // redraw only the items which must be redrawn
1727
1728 // we don't have to use GetUpdateClientRect() here because our client rect
1729 // is the same as total one
1730 wxRect rectUpdate = GetUpdateRegion().GetBox();
1731
1732 int flagsMenubar = GetStateFlags();
1733
1734 wxRect rect;
1735 rect.y = 0;
1736 rect.height = GetClientSize().y;
1737
1738 wxCoord x = 0;
1739 size_t count = GetCount();
1740 for ( size_t n = 0; n < count; n++ )
1741 {
1742 if ( x > rectUpdate.GetRight() )
1743 {
1744 // all remaining items are to the right of rectUpdate
1745 break;
1746 }
1747
1748 rect.x = x;
1749 rect.width = GetItemWidth(n);
1750 x += rect.width;
1751 if ( x < rectUpdate.x )
1752 {
1753 // this item is still to the left of rectUpdate
1754 continue;
1755 }
1756
1757 int flags = flagsMenubar;
1758 if ( m_current != -1 && n == (size_t)m_current )
1759 {
1760 flags |= wxCONTROL_SELECTED;
1761 }
1762
1763 if ( !IsEnabledTop(n) )
1764 {
1765 flags |= wxCONTROL_DISABLED;
1766 }
1767
1768 GetRenderer()->DrawMenuBarItem
1769 (
1770 dc,
1771 rect,
1772 m_menuInfos[n].GetLabel(),
1773 flags,
1774 m_menuInfos[n].GetAccelIndex()
1775 );
1776 }
1777 }
1778
1779 // ----------------------------------------------------------------------------
1780 // wxMenuBar geometry
1781 // ----------------------------------------------------------------------------
1782
1783 wxRect wxMenuBar::GetItemRect(size_t pos) const
1784 {
1785 wxASSERT_MSG( pos < GetCount(), _T("invalid menu bar item index") );
1786 wxASSERT_MSG( IsCreated(), _T("can't call this method yet") );
1787
1788 wxRect rect;
1789 rect.x =
1790 rect.y = 0;
1791 rect.height = GetClientSize().y;
1792
1793 for ( size_t n = 0; n < pos; n++ )
1794 {
1795 rect.x += GetItemWidth(n);
1796 }
1797
1798 rect.width = GetItemWidth(pos);
1799
1800 return rect;
1801 }
1802
1803 wxSize wxMenuBar::DoGetBestClientSize() const
1804 {
1805 wxSize size;
1806 if ( GetMenuCount() > 0 )
1807 {
1808 wxClientDC dc(wxConstCast(this, wxMenuBar));
1809 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
1810 dc.GetTextExtent(GetLabelTop(0), &size.x, &size.y);
1811
1812 // adjust for the renderer we use
1813 size = GetRenderer()->GetMenuBarItemSize(size);
1814 }
1815 else // empty menubar
1816 {
1817 size.x =
1818 size.y = 0;
1819 }
1820
1821 // the width is arbitrary, of course, for horizontal menubar
1822 size.x = 100;
1823
1824 return size;
1825 }
1826
1827 int wxMenuBar::GetMenuFromPoint(const wxPoint& pos) const
1828 {
1829 if ( pos.x < 0 || pos.y < 0 || pos.y > GetClientSize().y )
1830 return -1;
1831
1832 // do find it
1833 wxCoord x = 0;
1834 size_t count = GetCount();
1835 for ( size_t item = 0; item < count; item++ )
1836 {
1837 x += GetItemWidth(item);
1838
1839 if ( x > pos.x )
1840 {
1841 return item;
1842 }
1843 }
1844
1845 // to the right of the last menu item
1846 return -1;
1847 }
1848
1849 // ----------------------------------------------------------------------------
1850 // wxMenuBar menu operations
1851 // ----------------------------------------------------------------------------
1852
1853 void wxMenuBar::SelectMenu(size_t pos)
1854 {
1855 SetFocus();
1856 wxLogTrace(_T("mousecapture"), _T("Capturing mouse from wxMenuBar::SelectMenu"));
1857 CaptureMouse();
1858
1859 DoSelectMenu(pos);
1860 }
1861
1862 void wxMenuBar::DoSelectMenu(size_t pos)
1863 {
1864 wxCHECK_RET( pos < GetCount(), _T("invalid menu index in DoSelectMenu") );
1865
1866 int posOld = m_current;
1867
1868 m_current = pos;
1869
1870 if ( posOld != -1 )
1871 {
1872 // close the previous menu
1873 if ( IsShowingMenu() )
1874 {
1875 // restore m_shouldShowMenu flag after DismissMenu() which resets
1876 // it to FALSE
1877 bool old = m_shouldShowMenu;
1878
1879 DismissMenu();
1880
1881 m_shouldShowMenu = old;
1882 }
1883
1884 RefreshItem((size_t)posOld);
1885 }
1886
1887 RefreshItem(pos);
1888 }
1889
1890 void wxMenuBar::PopupMenu(size_t pos)
1891 {
1892 wxCHECK_RET( pos < GetCount(), _T("invalid menu index in PopupCurrentMenu") );
1893
1894 SetFocus();
1895 DoSelectMenu(pos);
1896 PopupCurrentMenu();
1897 }
1898
1899 // ----------------------------------------------------------------------------
1900 // wxMenuBar input handing
1901 // ----------------------------------------------------------------------------
1902
1903 /*
1904 Note that wxMenuBar doesn't use wxInputHandler but handles keyboard and
1905 mouse in the same way under all platforms. This is because it doesn't derive
1906 from wxControl (which works with input handlers) but directly from wxWindow.
1907
1908 Also, menu bar input handling is rather simple, so maybe it's not really
1909 worth making it themeable - at least I've decided against doing it now as it
1910 would merging the changes back into trunk more difficult. But it still could
1911 be done later if really needed.
1912 */
1913
1914 void wxMenuBar::OnKillFocus(wxFocusEvent& event)
1915 {
1916 if ( m_current != -1 )
1917 {
1918 RefreshItem((size_t)m_current);
1919
1920 m_current = -1;
1921 }
1922
1923 event.Skip();
1924 }
1925
1926 void wxMenuBar::OnLeftDown(wxMouseEvent& event)
1927 {
1928 if ( HasCapture() )
1929 {
1930 OnDismiss();
1931
1932 event.Skip();
1933 }
1934 else // we didn't have mouse capture, capture it now
1935 {
1936 m_current = GetMenuFromPoint(event.GetPosition());
1937 if ( m_current == -1 )
1938 {
1939 // unfortunately, we can't prevent wxMSW from giving us the focus,
1940 // so we can only give it back
1941 GiveAwayFocus();
1942 }
1943 else // on item
1944 {
1945 wxLogTrace(_T("mousecapture"), _T("Capturing mouse from wxMenuBar::OnLeftDown"));
1946 CaptureMouse();
1947
1948 // show it as selected
1949 RefreshItem((size_t)m_current);
1950
1951 // show the menu
1952 PopupCurrentMenu(FALSE /* don't select first item - as Windows does */);
1953 }
1954 }
1955 }
1956
1957 void wxMenuBar::OnMouseMove(wxMouseEvent& event)
1958 {
1959 if ( HasCapture() )
1960 {
1961 (void)ProcessMouseEvent(event.GetPosition());
1962 }
1963 else
1964 {
1965 event.Skip();
1966 }
1967 }
1968
1969 bool wxMenuBar::ProcessMouseEvent(const wxPoint& pt)
1970 {
1971 // a hack to ignore the extra mouse events MSW sends us: this is similar to
1972 // wxUSE_MOUSEEVENT_HACK in wxWin itself but it isn't enough for us here as
1973 // we get the messages from different windows (old and new popup menus for
1974 // example)
1975 #ifdef __WXMSW__
1976 static wxPoint s_ptLast;
1977 if ( pt == s_ptLast )
1978 {
1979 return FALSE;
1980 }
1981
1982 s_ptLast = pt;
1983 #endif // __WXMSW__
1984
1985 int currentNew = GetMenuFromPoint(pt);
1986 if ( (currentNew == -1) || (currentNew == m_current) )
1987 {
1988 return FALSE;
1989 }
1990
1991 // select the new active item
1992 DoSelectMenu(currentNew);
1993
1994 // show the menu if we know that we should, even if we hadn't been showing
1995 // it before (this may happen if the previous menu was disabled)
1996 if ( m_shouldShowMenu && !m_menuShown)
1997 {
1998 // open the new menu if the old one we closed had been opened
1999 PopupCurrentMenu(FALSE /* don't select first item - as Windows does */);
2000 }
2001
2002 return TRUE;
2003 }
2004
2005 void wxMenuBar::OnKeyDown(wxKeyEvent& event)
2006 {
2007 // ensure that we have a current item - we might not have it if we're
2008 // given the focus with Alt or F10 press (and under GTK+ the menubar
2009 // somehow gets the keyboard events even when it doesn't have focus...)
2010 if ( m_current == -1 )
2011 {
2012 if ( !HasCapture() )
2013 {
2014 SelectMenu(0);
2015 }
2016 else // we do have capture
2017 {
2018 // we always maintain a valid current item while we're in modal
2019 // state (i.e. have the capture)
2020 wxFAIL_MSG( _T("how did we manage to lose current item?") );
2021
2022 return;
2023 }
2024 }
2025
2026 int key = event.GetKeyCode();
2027
2028 // first let the menu have it
2029 if ( IsShowingMenu() && m_menuShown->ProcessKeyDown(key) )
2030 {
2031 return;
2032 }
2033
2034 // cycle through the menu items when left/right arrows are pressed and open
2035 // the menu when up/down one is
2036 switch ( key )
2037 {
2038 case WXK_MENU:
2039 // Alt must be processed at wxWindow level too
2040 event.Skip();
2041 // fall through
2042
2043 case WXK_ESCAPE:
2044 // remove the selection and give the focus away
2045 if ( m_current != -1 )
2046 {
2047 if ( IsShowingMenu() )
2048 {
2049 DismissMenu();
2050 }
2051
2052 OnDismiss();
2053 }
2054 break;
2055
2056 case WXK_LEFT:
2057 case WXK_RIGHT:
2058 {
2059 size_t count = GetCount();
2060 if ( count == 1 )
2061 {
2062 // the item won't change anyhow
2063 break;
2064 }
2065 //else: otherwise, it will
2066
2067 // remember if we were showing a menu - if we did, we should
2068 // show the new menu after changing the item
2069 bool wasMenuOpened = IsShowingMenu();
2070 if ( wasMenuOpened )
2071 {
2072 DismissMenu();
2073 }
2074
2075 // cast is safe as we tested for -1 above
2076 size_t currentNew = (size_t)m_current;
2077
2078 if ( key == WXK_LEFT )
2079 {
2080 if ( currentNew-- == 0 )
2081 currentNew = count - 1;
2082 }
2083 else // right
2084 {
2085 if ( ++currentNew == count )
2086 currentNew = 0;
2087 }
2088
2089 DoSelectMenu(currentNew);
2090
2091 if ( wasMenuOpened )
2092 {
2093 PopupCurrentMenu();
2094 }
2095 }
2096 break;
2097
2098 case WXK_DOWN:
2099 case WXK_UP:
2100 case WXK_RETURN:
2101 // open the menu
2102 PopupCurrentMenu();
2103 break;
2104
2105 default:
2106 // letters open the corresponding menu
2107 {
2108 bool unique;
2109 int idxFound = FindNextItemForAccel(m_current, key, &unique);
2110
2111 if ( idxFound != -1 )
2112 {
2113 if ( IsShowingMenu() )
2114 {
2115 DismissMenu();
2116 }
2117
2118 DoSelectMenu((size_t)idxFound);
2119
2120 // if the item is not unique, just select it but don't
2121 // activate as the user might have wanted to activate
2122 // another item
2123 //
2124 // also, don't try to open a disabled menu
2125 if ( unique && IsEnabledTop((size_t)idxFound) )
2126 {
2127 // open the menu
2128 PopupCurrentMenu();
2129 }
2130
2131 // skip the "event.Skip()" below
2132 break;
2133 }
2134 }
2135
2136 event.Skip();
2137 }
2138 }
2139
2140 // ----------------------------------------------------------------------------
2141 // wxMenuBar accel handling
2142 // ----------------------------------------------------------------------------
2143
2144 int wxMenuBar::FindNextItemForAccel(int idxStart, int key, bool *unique) const
2145 {
2146 if ( !wxIsalnum(key) )
2147 {
2148 // we only support letters/digits as accels
2149 return -1;
2150 }
2151
2152 // do we have more than one item with this accel?
2153 if ( unique )
2154 *unique = TRUE;
2155
2156 // translate everything to lower case before comparing
2157 wxChar chAccel = wxTolower(key);
2158
2159 // the index of the item with this accel
2160 int idxFound = -1;
2161
2162 // loop through all items searching for the item with this
2163 // accel starting at the item after the current one
2164 int count = GetCount();
2165 int n = idxStart == -1 ? 0 : idxStart + 1;
2166
2167 if ( n == count )
2168 {
2169 // wrap
2170 n = 0;
2171 }
2172
2173 idxStart = n;
2174 for ( ;; )
2175 {
2176 const wxMenuInfo& info = m_menuInfos[n];
2177
2178 int idxAccel = info.GetAccelIndex();
2179 if ( idxAccel != -1 &&
2180 wxTolower(info.GetLabel()[(size_t)idxAccel])
2181 == chAccel )
2182 {
2183 // ok, found an item with this accel
2184 if ( idxFound == -1 )
2185 {
2186 // store it but continue searching as we need to
2187 // know if it's the only item with this accel or if
2188 // there are more
2189 idxFound = n;
2190 }
2191 else // we already had found such item
2192 {
2193 if ( unique )
2194 *unique = FALSE;
2195
2196 // no need to continue further, we won't find
2197 // anything we don't already know
2198 break;
2199 }
2200 }
2201
2202 // we want to iterate over all items wrapping around if
2203 // necessary
2204 if ( ++n == count )
2205 {
2206 // wrap
2207 n = 0;
2208 }
2209
2210 if ( n == idxStart )
2211 {
2212 // we've seen all items
2213 break;
2214 }
2215 }
2216
2217 return idxFound;
2218 }
2219
2220 #if wxUSE_ACCEL
2221
2222 bool wxMenuBar::ProcessAccelEvent(const wxKeyEvent& event)
2223 {
2224 size_t n = 0;
2225 for ( wxMenuList::Node *node = m_menus.GetFirst();
2226 node;
2227 node = node->GetNext(), n++ )
2228 {
2229 // accels of the items in the disabled menus shouldn't work
2230 if ( m_menuInfos[n].IsEnabled() )
2231 {
2232 if ( node->GetData()->ProcessAccelEvent(event) )
2233 {
2234 // menu processed it
2235 return TRUE;
2236 }
2237 }
2238 }
2239
2240 // not found
2241 return FALSE;
2242 }
2243
2244 #endif // wxUSE_ACCEL
2245
2246 // ----------------------------------------------------------------------------
2247 // wxMenuBar menus showing
2248 // ----------------------------------------------------------------------------
2249
2250 void wxMenuBar::PopupCurrentMenu(bool selectFirst)
2251 {
2252 wxCHECK_RET( m_current != -1, _T("no menu to popup") );
2253
2254 // forgot to call DismissMenu()?
2255 wxASSERT_MSG( !m_menuShown, _T("shouldn't show two menu at once!") );
2256
2257 // in any case, we should show it - even if we won't
2258 m_shouldShowMenu = TRUE;
2259
2260 if ( IsEnabledTop(m_current) )
2261 {
2262 // remember the menu we show
2263 m_menuShown = GetMenu(m_current);
2264
2265 // we don't show the menu at all if it has no items
2266 if ( !m_menuShown->IsEmpty() )
2267 {
2268 // position it correctly: note that we must use screen coords and
2269 // that we pass 0 as width to position the menu exactly below the
2270 // item, not to the right of it
2271 wxRect rectItem = GetItemRect(m_current);
2272
2273 m_menuShown->Popup(ClientToScreen(rectItem.GetPosition()),
2274 wxSize(0, rectItem.GetHeight()),
2275 selectFirst);
2276 }
2277 else
2278 {
2279 // reset it back as no menu is shown
2280 m_menuShown = NULL;
2281 }
2282 }
2283 //else: don't show disabled menu
2284 }
2285
2286 void wxMenuBar::DismissMenu()
2287 {
2288 wxCHECK_RET( m_menuShown, _T("can't dismiss menu if none is shown") );
2289
2290 m_menuShown->Dismiss();
2291 OnDismissMenu();
2292 }
2293
2294 void wxMenuBar::OnDismissMenu(bool dismissMenuBar)
2295 {
2296 m_shouldShowMenu = FALSE;
2297 m_menuShown = NULL;
2298 if ( dismissMenuBar )
2299 {
2300 OnDismiss();
2301 }
2302 }
2303
2304 void wxMenuBar::OnDismiss()
2305 {
2306 if ( GetCapture() )
2307 {
2308 wxLogTrace(_T("mousecapture"), _T("Releasing mouse from wxMenuBar::OnDismiss"));
2309 GetCapture()->ReleaseMouse();
2310 }
2311
2312 if ( m_current != -1 )
2313 {
2314 size_t current = m_current;
2315 m_current = -1;
2316
2317 RefreshItem(current);
2318 }
2319
2320 GiveAwayFocus();
2321 }
2322
2323 void wxMenuBar::GiveAwayFocus()
2324 {
2325 GetFrame()->SetFocus();
2326 }
2327
2328 // ----------------------------------------------------------------------------
2329 // popup menu support
2330 // ----------------------------------------------------------------------------
2331
2332 wxEventLoop *wxWindow::ms_evtLoopPopup = NULL;
2333
2334 bool wxWindow::DoPopupMenu(wxMenu *menu, int x, int y)
2335 {
2336 wxCHECK_MSG( !ms_evtLoopPopup, FALSE,
2337 _T("can't show more than one popup menu at a time") );
2338
2339 #ifdef __WXMSW__
2340 // we need to change the cursor before showing the menu as, apparently, no
2341 // cursor changes took place while the mouse is captured
2342 wxCursor cursorOld = GetCursor();
2343 SetCursor(wxCURSOR_ARROW);
2344 #endif // __WXMSW__
2345
2346 #if 0
2347 // flash any delayed log messages before showing the menu, otherwise it
2348 // could be dismissed (because it would lose focus) immediately after being
2349 // shown
2350 wxLog::FlushActive();
2351
2352 // some controls update themselves from OnIdle() call - let them do it
2353 wxIdleEvent event;
2354 wxTheApp->ProcessEvent(event);
2355
2356 // if the window hadn't been refreshed yet, the menu can adversely affect
2357 // its next OnPaint() handler execution - i.e. scrolled window refresh
2358 // logic breaks then as it scrolls part of the menu which hadn't been there
2359 // when the update event was generated into view
2360 Update();
2361 #endif // 0
2362
2363 menu->SetInvokingWindow(this);
2364
2365 // wxLogDebug( "Name of invoking window %s", menu->GetInvokingWindow()->GetName().c_str() );
2366
2367 menu->Popup(ClientToScreen(wxPoint(x, y)), wxSize(0, 0));
2368
2369 // this is not very useful if the menu was popped up because of the mouse
2370 // click but I think it is nice to do when it appears because of a key
2371 // press (i.e. Windows menu key)
2372 //
2373 // Windows itself doesn't do it, but IMHO this is nice
2374 WarpPointer(x, y);
2375
2376 // we have to redirect all keyboard input to the menu temporarily
2377 PushEventHandler(new wxMenuKbdRedirector(menu));
2378
2379 // enter the local modal loop
2380 ms_evtLoopPopup = new wxEventLoop;
2381 ms_evtLoopPopup->Run();
2382
2383 delete ms_evtLoopPopup;
2384 ms_evtLoopPopup = NULL;
2385
2386 // remove the handler
2387 PopEventHandler(TRUE /* delete it */);
2388
2389 menu->SetInvokingWindow(NULL);
2390
2391 #ifdef __WXMSW__
2392 SetCursor(cursorOld);
2393 #endif // __WXMSW__
2394
2395 return TRUE;
2396 }
2397
2398 void wxWindow::DismissPopupMenu()
2399 {
2400 wxCHECK_RET( ms_evtLoopPopup, _T("no popup menu shown") );
2401
2402 ms_evtLoopPopup->Exit();
2403 }
2404
2405 #endif // wxUSE_MENUS
2406