]> git.saurik.com Git - wxWidgets.git/blob - src/msw/menu.cpp
update the popup menu item when it's [un]checked too, as it already happens for the...
[wxWidgets.git] / src / msw / menu.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/menu.cpp
3 // Purpose: wxMenu, wxMenuBar, wxMenuItem
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ===========================================================================
13 // declarations
14 // ===========================================================================
15
16 // ---------------------------------------------------------------------------
17 // headers
18 // ---------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_MENUS
28
29 #include "wx/menu.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
33 #include "wx/frame.h"
34 #include "wx/utils.h"
35 #include "wx/intl.h"
36 #include "wx/log.h"
37 #endif
38
39 #if wxUSE_OWNER_DRAWN
40 #include "wx/ownerdrw.h"
41 #endif
42
43 #include "wx/msw/private.h"
44
45 #ifdef __WXWINCE__
46 #include <windows.h>
47 #include <windowsx.h>
48 #include <tchar.h>
49 #include <ole2.h>
50 #include <shellapi.h>
51 #if (_WIN32_WCE < 400) && !defined(__HANDHELDPC__)
52 #include <aygshell.h>
53 #endif
54
55 #include "wx/msw/wince/missing.h"
56
57 #endif
58
59 // other standard headers
60 #include <string.h>
61
62 #if wxUSE_OWNER_DRAWN && defined(MIIM_BITMAP)
63 #include "wx/dynlib.h"
64 #endif
65
66 #ifndef MNS_CHECKORBMP
67 #define MNS_CHECKORBMP 0x04000000
68 #endif
69 #ifndef MIM_STYLE
70 #define MIM_STYLE 0x00000010
71 #endif
72
73 // ----------------------------------------------------------------------------
74 // global variables
75 // ----------------------------------------------------------------------------
76
77 // ----------------------------------------------------------------------------
78 // constants
79 // ----------------------------------------------------------------------------
80
81 // the (popup) menu title has this special id
82 static const int idMenuTitle = -3;
83
84 // ----------------------------------------------------------------------------
85 // private functions
86 // ----------------------------------------------------------------------------
87
88 // make the given menu item default
89 static void SetDefaultMenuItem(HMENU WXUNUSED_IN_WINCE(hmenu),
90 UINT WXUNUSED_IN_WINCE(id))
91 {
92 #ifndef __WXWINCE__
93 MENUITEMINFO mii;
94 wxZeroMemory(mii);
95 mii.cbSize = sizeof(MENUITEMINFO);
96 mii.fMask = MIIM_STATE;
97 mii.fState = MFS_DEFAULT;
98
99 if ( !::SetMenuItemInfo(hmenu, id, FALSE, &mii) )
100 {
101 wxLogLastError(wxT("SetMenuItemInfo"));
102 }
103 #endif
104 }
105
106 #ifdef __WXWINCE__
107 UINT GetMenuState(HMENU hMenu, UINT id, UINT flags)
108 {
109 MENUITEMINFO info;
110 wxZeroMemory(info);
111 info.cbSize = sizeof(info);
112 info.fMask = MIIM_STATE;
113 // MF_BYCOMMAND is zero so test MF_BYPOSITION
114 if ( !::GetMenuItemInfo(hMenu, id, flags & MF_BYPOSITION ? TRUE : FALSE , & info) )
115 wxLogLastError(wxT("GetMenuItemInfo"));
116 return info.fState;
117 }
118 #endif
119
120 // ============================================================================
121 // implementation
122 // ============================================================================
123
124 #include "wx/listimpl.cpp"
125
126 WX_DEFINE_LIST( wxMenuInfoList )
127
128 #if wxUSE_EXTENDED_RTTI
129
130 WX_DEFINE_FLAGS( wxMenuStyle )
131
132 wxBEGIN_FLAGS( wxMenuStyle )
133 wxFLAGS_MEMBER(wxMENU_TEAROFF)
134 wxEND_FLAGS( wxMenuStyle )
135
136 IMPLEMENT_DYNAMIC_CLASS_XTI(wxMenu, wxEvtHandler,"wx/menu.h")
137
138 wxCOLLECTION_TYPE_INFO( wxMenuItem * , wxMenuItemList ) ;
139
140 template<> void wxCollectionToVariantArray( wxMenuItemList const &theList, wxxVariantArray &value)
141 {
142 wxListCollectionToVariantArray<wxMenuItemList::compatibility_iterator>( theList , value ) ;
143 }
144
145 wxBEGIN_PROPERTIES_TABLE(wxMenu)
146 wxEVENT_PROPERTY( Select , wxEVT_COMMAND_MENU_SELECTED , wxCommandEvent)
147 wxPROPERTY( Title, wxString , SetTitle, GetTitle, wxString(), 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
148 wxREADONLY_PROPERTY_FLAGS( MenuStyle , wxMenuStyle , long , GetStyle , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
149 wxPROPERTY_COLLECTION( MenuItems , wxMenuItemList , wxMenuItem* , Append , GetMenuItems , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
150 wxEND_PROPERTIES_TABLE()
151
152 wxBEGIN_HANDLERS_TABLE(wxMenu)
153 wxEND_HANDLERS_TABLE()
154
155 wxDIRECT_CONSTRUCTOR_2( wxMenu , wxString , Title , long , MenuStyle )
156
157 WX_DEFINE_FLAGS( wxMenuBarStyle )
158
159 wxBEGIN_FLAGS( wxMenuBarStyle )
160 wxFLAGS_MEMBER(wxMB_DOCKABLE)
161 wxEND_FLAGS( wxMenuBarStyle )
162
163 // the negative id would lead the window (its superclass !) to vetoe streaming out otherwise
164 bool wxMenuBarStreamingCallback( const wxObject *WXUNUSED(object), wxWriter * , wxPersister * , wxxVariantArray & )
165 {
166 return true ;
167 }
168
169 IMPLEMENT_DYNAMIC_CLASS_XTI_CALLBACK(wxMenuBar, wxWindow ,"wx/menu.h",wxMenuBarStreamingCallback)
170
171 IMPLEMENT_DYNAMIC_CLASS_XTI(wxMenuInfo, wxObject , "wx/menu.h" )
172
173 wxBEGIN_PROPERTIES_TABLE(wxMenuInfo)
174 wxREADONLY_PROPERTY( Menu , wxMenu* , GetMenu , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
175 wxREADONLY_PROPERTY( Title , wxString , GetTitle , wxString() , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
176 wxEND_PROPERTIES_TABLE()
177
178 wxBEGIN_HANDLERS_TABLE(wxMenuInfo)
179 wxEND_HANDLERS_TABLE()
180
181 wxCONSTRUCTOR_2( wxMenuInfo , wxMenu* , Menu , wxString , Title )
182
183 wxCOLLECTION_TYPE_INFO( wxMenuInfo * , wxMenuInfoList ) ;
184
185 template<> void wxCollectionToVariantArray( wxMenuInfoList const &theList, wxxVariantArray &value)
186 {
187 wxListCollectionToVariantArray<wxMenuInfoList::compatibility_iterator>( theList , value ) ;
188 }
189
190 wxBEGIN_PROPERTIES_TABLE(wxMenuBar)
191 wxPROPERTY_COLLECTION( MenuInfos , wxMenuInfoList , wxMenuInfo* , Append , GetMenuInfos , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
192 wxEND_PROPERTIES_TABLE()
193
194 wxBEGIN_HANDLERS_TABLE(wxMenuBar)
195 wxEND_HANDLERS_TABLE()
196
197 wxCONSTRUCTOR_DUMMY( wxMenuBar )
198
199 #else
200 IMPLEMENT_DYNAMIC_CLASS(wxMenu, wxEvtHandler)
201 IMPLEMENT_DYNAMIC_CLASS(wxMenuBar, wxWindow)
202 IMPLEMENT_DYNAMIC_CLASS(wxMenuInfo, wxObject)
203 #endif
204
205 const wxMenuInfoList& wxMenuBar::GetMenuInfos() const
206 {
207 wxMenuInfoList* list = const_cast< wxMenuInfoList* >( &m_menuInfos ) ;
208 WX_CLEAR_LIST( wxMenuInfoList , *list ) ;
209 for( size_t i = 0 ; i < GetMenuCount() ; ++i )
210 {
211 wxMenuInfo* info = new wxMenuInfo() ;
212 info->Create( const_cast<wxMenuBar*>(this)->GetMenu(i) , GetLabelTop(i) ) ;
213 list->Append( info ) ;
214 }
215 return m_menuInfos ;
216 }
217
218 // ---------------------------------------------------------------------------
219 // wxMenu construction, adding and removing menu items
220 // ---------------------------------------------------------------------------
221
222 // Construct a menu with optional title (then use append)
223 void wxMenu::Init()
224 {
225 m_doBreak = false;
226 m_startRadioGroup = -1;
227
228 // create the menu
229 m_hMenu = (WXHMENU)CreatePopupMenu();
230 if ( !m_hMenu )
231 {
232 wxLogLastError(wxT("CreatePopupMenu"));
233 }
234
235 // if we have a title, insert it in the beginning of the menu
236 if ( !m_title.empty() )
237 {
238 Append(idMenuTitle, m_title);
239 AppendSeparator();
240 }
241 }
242
243 // The wxWindow destructor will take care of deleting the submenus.
244 wxMenu::~wxMenu()
245 {
246 // we should free Windows resources only if Windows doesn't do it for us
247 // which happens if we're attached to a menubar or a submenu of another
248 // menu
249 if ( !IsAttached() && !GetParent() )
250 {
251 if ( !::DestroyMenu(GetHmenu()) )
252 {
253 wxLogLastError(wxT("DestroyMenu"));
254 }
255 }
256
257 #if wxUSE_ACCEL
258 // delete accels
259 WX_CLEAR_ARRAY(m_accels);
260 #endif // wxUSE_ACCEL
261 }
262
263 void wxMenu::Break()
264 {
265 // this will take effect during the next call to Append()
266 m_doBreak = true;
267 }
268
269 void wxMenu::Attach(wxMenuBarBase *menubar)
270 {
271 wxMenuBase::Attach(menubar);
272
273 EndRadioGroup();
274 }
275
276 #if wxUSE_ACCEL
277
278 int wxMenu::FindAccel(int id) const
279 {
280 size_t n, count = m_accels.GetCount();
281 for ( n = 0; n < count; n++ )
282 {
283 if ( m_accels[n]->m_command == id )
284 return n;
285 }
286
287 return wxNOT_FOUND;
288 }
289
290 void wxMenu::UpdateAccel(wxMenuItem *item)
291 {
292 if ( item->IsSubMenu() )
293 {
294 wxMenu *submenu = item->GetSubMenu();
295 wxMenuItemList::compatibility_iterator node = submenu->GetMenuItems().GetFirst();
296 while ( node )
297 {
298 UpdateAccel(node->GetData());
299
300 node = node->GetNext();
301 }
302 }
303 else if ( !item->IsSeparator() )
304 {
305 // recurse upwards: we should only modify m_accels of the top level
306 // menus, not of the submenus as wxMenuBar doesn't look at them
307 // (alternative and arguable cleaner solution would be to recurse
308 // downwards in GetAccelCount() and CopyAccels())
309 if ( GetParent() )
310 {
311 GetParent()->UpdateAccel(item);
312 return;
313 }
314
315 // find the (new) accel for this item
316 wxAcceleratorEntry *accel = wxAcceleratorEntry::Create(item->GetText());
317 if ( accel )
318 accel->m_command = item->GetId();
319
320 // find the old one
321 int n = FindAccel(item->GetId());
322 if ( n == wxNOT_FOUND )
323 {
324 // no old, add new if any
325 if ( accel )
326 m_accels.Add(accel);
327 else
328 return; // skipping RebuildAccelTable() below
329 }
330 else
331 {
332 // replace old with new or just remove the old one if no new
333 delete m_accels[n];
334 if ( accel )
335 m_accels[n] = accel;
336 else
337 m_accels.RemoveAt(n);
338 }
339
340 if ( IsAttached() )
341 {
342 GetMenuBar()->RebuildAccelTable();
343 }
344 }
345 //else: it is a separator, they can't have accels, nothing to do
346 }
347
348 #endif // wxUSE_ACCEL
349
350 // append a new item or submenu to the menu
351 bool wxMenu::DoInsertOrAppend(wxMenuItem *pItem, size_t pos)
352 {
353 #if wxUSE_ACCEL
354 UpdateAccel(pItem);
355 #endif // wxUSE_ACCEL
356
357 UINT flags = 0;
358
359 // if "Break" has just been called, insert a menu break before this item
360 // (and don't forget to reset the flag)
361 if ( m_doBreak ) {
362 flags |= MF_MENUBREAK;
363 m_doBreak = false;
364 }
365
366 if ( pItem->IsSeparator() ) {
367 flags |= MF_SEPARATOR;
368 }
369
370 // id is the numeric id for normal menu items and HMENU for submenus as
371 // required by ::AppendMenu() API
372 UINT id;
373 wxMenu *submenu = pItem->GetSubMenu();
374 if ( submenu != NULL ) {
375 wxASSERT_MSG( submenu->GetHMenu(), wxT("invalid submenu") );
376
377 submenu->SetParent(this);
378
379 id = (UINT)submenu->GetHMenu();
380
381 flags |= MF_POPUP;
382 }
383 else {
384 id = pItem->GetId();
385 }
386
387
388 // prepare to insert the item in the menu
389 wxString itemText = pItem->GetText();
390 LPCTSTR pData = NULL;
391 if ( pos == (size_t)-1 )
392 {
393 // append at the end (note that the item is already appended to
394 // internal data structures)
395 pos = GetMenuItemCount() - 1;
396 }
397
398 // adjust position to account for the title, if any
399 if ( !m_title.empty() )
400 pos += 2; // for the title itself and its separator
401
402 BOOL ok = false;
403
404 #if wxUSE_OWNER_DRAWN
405 // Currently, mixing owner-drawn and non-owner-drawn items results in
406 // inconsistent margins, so we force this to be owner-drawn if any other
407 // items already are. Later we might want to use a boolean in the wxMenu
408 // to avoid search. Also we might make this fix unnecessary by getting the correct
409 // margin using NONCLIENTMETRICS.
410 if ( !pItem->IsOwnerDrawn() && !pItem->IsSeparator() )
411 {
412 // Check if any other items are ownerdrawn, and make ownerdrawn if so
413 wxMenuItemList::compatibility_iterator node = GetMenuItems().GetFirst();
414 while (node)
415 {
416 if (node->GetData()->IsOwnerDrawn())
417 {
418 pItem->SetOwnerDrawn(true);
419 break;
420 }
421 node = node->GetNext();
422 }
423 }
424 #endif
425
426 // check if we have something more than a simple text item
427 #if wxUSE_OWNER_DRAWN
428 if ( pItem->IsOwnerDrawn() )
429 {
430 // is the item owner-drawn just because of the [checked] bitmap?
431 if ( (pItem->GetBitmap(false).Ok() || pItem->GetBitmap(true).Ok()) &&
432 !pItem->GetTextColour().Ok() &&
433 !pItem->GetBackgroundColour().Ok() &&
434 !pItem->GetFont().Ok() )
435 {
436 // try to use InsertMenuItem() as it's guaranteed to look correct
437 // while our owner-drawn code is not
438
439 // first compile-time check
440 #if defined(MIIM_BITMAP) && (_WIN32_WINNT >= 0x0500)
441 WinStruct<MENUITEMINFO> mii;
442
443 // now run-time one: MIIM_BITMAP only works under WinME/2000+
444 if ( wxGetWinVersion() >= wxWinVersion_98 )
445 {
446 mii.fMask = MIIM_STRING | MIIM_DATA | MIIM_BITMAP;
447 if ( pItem->IsCheckable() )
448 {
449 // need to set checked/unchecked bitmaps as otherwise our
450 // MSWOnDrawItem() item is not called
451 mii.fMask |= MIIM_CHECKMARKS;
452 }
453
454 mii.cch = itemText.length();
455 mii.dwTypeData = wx_const_cast(wxChar *, itemText.c_str());
456
457 if (flags & MF_POPUP)
458 {
459 mii.fMask |= MIIM_SUBMENU;
460 mii.hSubMenu = (HMENU)pItem->GetSubMenu()->GetHMenu();
461 }
462 else
463 {
464 mii.fMask |= MIIM_ID;
465 mii.wID = id;
466 }
467
468 // we can't pass HBITMAP directly as hbmpItem for 2 reasons:
469 // 1. we can't draw it with transparency then (this is not
470 // very important now but would be with themed menu bg)
471 // 2. worse, Windows inverts the bitmap for the selected
472 // item and this looks downright ugly
473 //
474 // so instead draw it ourselves in MSWOnDrawItem()
475 mii.dwItemData = wx_reinterpret_cast(ULONG_PTR, pItem);
476 if ( pItem->IsCheckable() )
477 {
478 mii.hbmpChecked =
479 mii.hbmpUnchecked = HBMMENU_CALLBACK;
480 }
481 mii.hbmpItem = HBMMENU_CALLBACK;
482
483 ok = ::InsertMenuItem(GetHmenu(), pos, TRUE /* by pos */, &mii);
484 if ( !ok )
485 {
486 wxLogLastError(wxT("InsertMenuItem()"));
487 }
488 else // InsertMenuItem() ok
489 {
490 // we need to remove the extra indent which is reserved for
491 // the checkboxes by default as it looks ugly unless check
492 // boxes are used together with bitmaps and this is not the
493 // case in wx API
494 WinStruct<MENUINFO> mi;
495
496 // don't call SetMenuInfo() directly, this would prevent
497 // the app from starting up under Windows 95/NT 4
498 typedef BOOL (WINAPI *SetMenuInfo_t)(HMENU, MENUINFO *);
499
500 wxDynamicLibrary dllUser(_T("user32"));
501 wxDYNLIB_FUNCTION(SetMenuInfo_t, SetMenuInfo, dllUser);
502 if ( pfnSetMenuInfo )
503 {
504 mi.fMask = MIM_STYLE;
505 mi.dwStyle = MNS_CHECKORBMP;
506 if ( !(*pfnSetMenuInfo)(GetHmenu(), &mi) )
507 wxLogLastError(_T("SetMenuInfo(MNS_NOCHECK)"));
508 }
509
510 // tell the item that it's not really owner-drawn but only
511 // needs to draw its bitmap, the rest is done by Windows
512 pItem->ResetOwnerDrawn();
513 }
514 }
515 #endif // MIIM_BITMAP
516 }
517
518 if ( !ok )
519 {
520 // item draws itself, pass pointer to it in data parameter
521 flags |= MF_OWNERDRAW;
522 pData = (LPCTSTR)pItem;
523 }
524 }
525 else
526 #endif // wxUSE_OWNER_DRAWN
527 {
528 // item is just a normal string (passed in data parameter)
529 flags |= MF_STRING;
530
531 #ifdef __WXWINCE__
532 itemText = wxMenuItem::GetLabelFromText(itemText);
533 #endif
534
535 pData = (wxChar*)itemText.c_str();
536 }
537
538 // item might have already been inserted by InsertMenuItem() above
539 if ( !ok )
540 {
541 if ( !::InsertMenu(GetHmenu(), pos, flags | MF_BYPOSITION, id, pData) )
542 {
543 wxLogLastError(wxT("InsertMenu[Item]()"));
544
545 return false;
546 }
547 }
548
549
550 // if we just appended the title, highlight it
551 if ( (int)id == idMenuTitle )
552 {
553 // visually select the menu title
554 SetDefaultMenuItem(GetHmenu(), id);
555 }
556
557 // if we're already attached to the menubar, we must update it
558 if ( IsAttached() && GetMenuBar()->IsAttached() )
559 {
560 GetMenuBar()->Refresh();
561 }
562
563 return true;
564 }
565
566 void wxMenu::EndRadioGroup()
567 {
568 // we're not inside a radio group any longer
569 m_startRadioGroup = -1;
570 }
571
572 wxMenuItem* wxMenu::DoAppend(wxMenuItem *item)
573 {
574 wxCHECK_MSG( item, NULL, _T("NULL item in wxMenu::DoAppend") );
575
576 bool check = false;
577
578 if ( item->GetKind() == wxITEM_RADIO )
579 {
580 int count = GetMenuItemCount();
581
582 if ( m_startRadioGroup == -1 )
583 {
584 // start a new radio group
585 m_startRadioGroup = count;
586
587 // for now it has just one element
588 item->SetAsRadioGroupStart();
589 item->SetRadioGroupEnd(m_startRadioGroup);
590
591 // ensure that we have a checked item in the radio group
592 check = true;
593 }
594 else // extend the current radio group
595 {
596 // we need to update its end item
597 item->SetRadioGroupStart(m_startRadioGroup);
598 wxMenuItemList::compatibility_iterator node = GetMenuItems().Item(m_startRadioGroup);
599
600 if ( node )
601 {
602 node->GetData()->SetRadioGroupEnd(count);
603 }
604 else
605 {
606 wxFAIL_MSG( _T("where is the radio group start item?") );
607 }
608 }
609 }
610 else // not a radio item
611 {
612 EndRadioGroup();
613 }
614
615 if ( !wxMenuBase::DoAppend(item) || !DoInsertOrAppend(item) )
616 {
617 return NULL;
618 }
619
620 if ( check )
621 {
622 // check the item initially
623 item->Check(true);
624 }
625
626 return item;
627 }
628
629 wxMenuItem* wxMenu::DoInsert(size_t pos, wxMenuItem *item)
630 {
631 if (wxMenuBase::DoInsert(pos, item) && DoInsertOrAppend(item, pos))
632 return item;
633 else
634 return NULL;
635 }
636
637 wxMenuItem *wxMenu::DoRemove(wxMenuItem *item)
638 {
639 // we need to find the item's position in the child list
640 size_t pos;
641 wxMenuItemList::compatibility_iterator node = GetMenuItems().GetFirst();
642 for ( pos = 0; node; pos++ )
643 {
644 if ( node->GetData() == item )
645 break;
646
647 node = node->GetNext();
648 }
649
650 // DoRemove() (unlike Remove) can only be called for an existing item!
651 wxCHECK_MSG( node, NULL, wxT("bug in wxMenu::Remove logic") );
652
653 #if wxUSE_ACCEL
654 // remove the corresponding accel from the accel table
655 int n = FindAccel(item->GetId());
656 if ( n != wxNOT_FOUND )
657 {
658 delete m_accels[n];
659
660 m_accels.RemoveAt(n);
661 }
662 //else: this item doesn't have an accel, nothing to do
663 #endif // wxUSE_ACCEL
664
665 // remove the item from the menu
666 if ( !::RemoveMenu(GetHmenu(), (UINT)pos, MF_BYPOSITION) )
667 {
668 wxLogLastError(wxT("RemoveMenu"));
669 }
670
671 if ( IsAttached() && GetMenuBar()->IsAttached() )
672 {
673 // otherwise, the change won't be visible
674 GetMenuBar()->Refresh();
675 }
676
677 // and from internal data structures
678 return wxMenuBase::DoRemove(item);
679 }
680
681 // ---------------------------------------------------------------------------
682 // accelerator helpers
683 // ---------------------------------------------------------------------------
684
685 #if wxUSE_ACCEL
686
687 // create the wxAcceleratorEntries for our accels and put them into the provided
688 // array - return the number of accels we have
689 size_t wxMenu::CopyAccels(wxAcceleratorEntry *accels) const
690 {
691 size_t count = GetAccelCount();
692 for ( size_t n = 0; n < count; n++ )
693 {
694 *accels++ = *m_accels[n];
695 }
696
697 return count;
698 }
699
700 #endif // wxUSE_ACCEL
701
702 // ---------------------------------------------------------------------------
703 // set wxMenu title
704 // ---------------------------------------------------------------------------
705
706 void wxMenu::SetTitle(const wxString& label)
707 {
708 bool hasNoTitle = m_title.empty();
709 m_title = label;
710
711 HMENU hMenu = GetHmenu();
712
713 if ( hasNoTitle )
714 {
715 if ( !label.empty() )
716 {
717 if ( !::InsertMenu(hMenu, 0u, MF_BYPOSITION | MF_STRING,
718 (unsigned)idMenuTitle, m_title) ||
719 !::InsertMenu(hMenu, 1u, MF_BYPOSITION, (unsigned)-1, NULL) )
720 {
721 wxLogLastError(wxT("InsertMenu"));
722 }
723 }
724 }
725 else
726 {
727 if ( label.empty() )
728 {
729 // remove the title and the separator after it
730 if ( !RemoveMenu(hMenu, 0, MF_BYPOSITION) ||
731 !RemoveMenu(hMenu, 0, MF_BYPOSITION) )
732 {
733 wxLogLastError(wxT("RemoveMenu"));
734 }
735 }
736 else
737 {
738 // modify the title
739 #ifdef __WXWINCE__
740 MENUITEMINFO info;
741 wxZeroMemory(info);
742 info.cbSize = sizeof(info);
743 info.fMask = MIIM_TYPE;
744 info.fType = MFT_STRING;
745 info.cch = m_title.length();
746 info.dwTypeData = (LPTSTR) m_title.c_str();
747 if ( !SetMenuItemInfo(hMenu, 0, TRUE, & info) )
748 {
749 wxLogLastError(wxT("SetMenuItemInfo"));
750 }
751 #else
752 if ( !ModifyMenu(hMenu, 0u,
753 MF_BYPOSITION | MF_STRING,
754 (unsigned)idMenuTitle, m_title) )
755 {
756 wxLogLastError(wxT("ModifyMenu"));
757 }
758 #endif
759 }
760 }
761
762 #ifdef __WIN32__
763 // put the title string in bold face
764 if ( !m_title.empty() )
765 {
766 SetDefaultMenuItem(GetHmenu(), (UINT)idMenuTitle);
767 }
768 #endif // Win32
769 }
770
771 // ---------------------------------------------------------------------------
772 // event processing
773 // ---------------------------------------------------------------------------
774
775 bool wxMenu::MSWCommand(WXUINT WXUNUSED(param), WXWORD id)
776 {
777 // ignore commands from the menu title
778 if ( id != (WXWORD)idMenuTitle )
779 {
780 // update the check item when it's clicked
781 wxMenuItem * const item = FindItem(id);
782 if ( item && item->IsCheckable() )
783 item->Toggle();
784
785 // get the checked status of the menu item: note that menuState is the
786 // old state of the menu, so the test for MF_CHECKED must be inverted
787 UINT menuState = ::GetMenuState(GetHmenu(), id, MF_BYCOMMAND);
788 SendEvent(id, !(menuState & MF_CHECKED));
789 }
790
791 return true;
792 }
793
794 // ---------------------------------------------------------------------------
795 // other
796 // ---------------------------------------------------------------------------
797
798 wxWindow *wxMenu::GetWindow() const
799 {
800 if ( m_invokingWindow != NULL )
801 return m_invokingWindow;
802 else if ( GetMenuBar() != NULL)
803 return GetMenuBar()->GetFrame();
804
805 return NULL;
806 }
807
808 // ---------------------------------------------------------------------------
809 // Menu Bar
810 // ---------------------------------------------------------------------------
811
812 void wxMenuBar::Init()
813 {
814 m_eventHandler = this;
815 m_hMenu = 0;
816 #if wxUSE_TOOLBAR && defined(__WXWINCE__)
817 m_toolBar = NULL;
818 #endif
819 // Not using a combined wxToolBar/wxMenuBar? then use
820 // a commandbar in WinCE .NET just to implement the
821 // menubar.
822 #if defined(WINCE_WITH_COMMANDBAR)
823 m_commandBar = NULL;
824 m_adornmentsAdded = false;
825 #endif
826 }
827
828 wxMenuBar::wxMenuBar()
829 {
830 Init();
831 }
832
833 wxMenuBar::wxMenuBar( long WXUNUSED(style) )
834 {
835 Init();
836 }
837
838 wxMenuBar::wxMenuBar(size_t count, wxMenu *menus[], const wxString titles[], long WXUNUSED(style))
839 {
840 Init();
841
842 m_titles.Alloc(count);
843
844 for ( size_t i = 0; i < count; i++ )
845 {
846 m_menus.Append(menus[i]);
847 m_titles.Add(titles[i]);
848
849 menus[i]->Attach(this);
850 }
851 }
852
853 wxMenuBar::~wxMenuBar()
854 {
855 // In Windows CE (not .NET), the menubar is always associated
856 // with a toolbar, which destroys the menu implicitly.
857 #if defined(WINCE_WITHOUT_COMMANDBAR) && defined(__POCKETPC__)
858 if (GetToolBar())
859 {
860 wxToolMenuBar* toolMenuBar = wxDynamicCast(GetToolBar(), wxToolMenuBar);
861 if (toolMenuBar)
862 toolMenuBar->SetMenuBar(NULL);
863 }
864 #else
865 // we should free Windows resources only if Windows doesn't do it for us
866 // which happens if we're attached to a frame
867 if (m_hMenu && !IsAttached())
868 {
869 #if defined(WINCE_WITH_COMMANDBAR)
870 ::DestroyWindow((HWND) m_commandBar);
871 m_commandBar = (WXHWND) NULL;
872 #else
873 ::DestroyMenu((HMENU)m_hMenu);
874 #endif
875 m_hMenu = (WXHMENU)NULL;
876 }
877 #endif
878 }
879
880 // ---------------------------------------------------------------------------
881 // wxMenuBar helpers
882 // ---------------------------------------------------------------------------
883
884 void wxMenuBar::Refresh()
885 {
886 if ( IsFrozen() )
887 return;
888
889 wxCHECK_RET( IsAttached(), wxT("can't refresh unattached menubar") );
890
891 #if defined(WINCE_WITHOUT_COMMANDBAR)
892 if (GetToolBar())
893 {
894 CommandBar_DrawMenuBar((HWND) GetToolBar()->GetHWND(), 0);
895 }
896 #elif defined(WINCE_WITH_COMMANDBAR)
897 if (m_commandBar)
898 DrawMenuBar((HWND) m_commandBar);
899 #else
900 DrawMenuBar(GetHwndOf(GetFrame()));
901 #endif
902 }
903
904 WXHMENU wxMenuBar::Create()
905 {
906 // Note: this doesn't work at all on Smartphone,
907 // since you have to use resources.
908 // We'll have to find another way to add a menu
909 // by changing/adding menu items to an existing menu.
910 #if defined(WINCE_WITHOUT_COMMANDBAR)
911 if ( m_hMenu != 0 )
912 return m_hMenu;
913
914 if (!GetToolBar())
915 return 0;
916
917 HWND hCommandBar = (HWND) GetToolBar()->GetHWND();
918 HMENU hMenu = (HMENU)::SendMessage(hCommandBar, SHCMBM_GETMENU, (WPARAM)0, (LPARAM)0);
919
920 // hMenu may be zero on Windows Mobile 5. So add the menus anyway.
921 if (1) // (hMenu)
922 {
923 TBBUTTON tbButton;
924 memset(&tbButton, 0, sizeof(TBBUTTON));
925 tbButton.iBitmap = I_IMAGENONE;
926 tbButton.fsState = TBSTATE_ENABLED;
927 tbButton.fsStyle = TBSTYLE_DROPDOWN | TBSTYLE_NO_DROPDOWN_ARROW | TBSTYLE_AUTOSIZE;
928
929 size_t i;
930 for (i = 0; i < GetMenuCount(); i++)
931 {
932 HMENU hPopupMenu = (HMENU) GetMenu(i)->GetHMenu() ;
933 tbButton.dwData = (DWORD)hPopupMenu;
934 wxString label = wxStripMenuCodes(GetLabelTop(i));
935 tbButton.iString = (int) label.c_str();
936
937 int position = i;
938
939 tbButton.idCommand = NewControlId();
940 if (!::SendMessage(hCommandBar, TB_INSERTBUTTON, position, (LPARAM)&tbButton))
941 {
942 wxLogLastError(wxT("TB_INSERTBUTTON"));
943 }
944 }
945 }
946 m_hMenu = (WXHMENU) hMenu;
947 return m_hMenu;
948 #else
949 if ( m_hMenu != 0 )
950 return m_hMenu;
951
952 m_hMenu = (WXHMENU)::CreateMenu();
953
954 if ( !m_hMenu )
955 {
956 wxLogLastError(wxT("CreateMenu"));
957 }
958 else
959 {
960 size_t count = GetMenuCount(), i;
961 wxMenuList::iterator it;
962 for ( i = 0, it = m_menus.begin(); i < count; i++, it++ )
963 {
964 if ( !::AppendMenu((HMENU)m_hMenu, MF_POPUP | MF_STRING,
965 (UINT)(*it)->GetHMenu(),
966 m_titles[i]) )
967 {
968 wxLogLastError(wxT("AppendMenu"));
969 }
970 }
971 }
972
973 return m_hMenu;
974 #endif
975 }
976
977 int wxMenuBar::MSWPositionForWxMenu(wxMenu *menu, int wxpos)
978 {
979 wxASSERT(menu);
980 wxASSERT(menu->GetHMenu());
981 wxASSERT(m_hMenu);
982
983 #if defined(__WXWINCE__)
984 int totalMSWItems = GetMenuCount();
985 #else
986 int totalMSWItems = GetMenuItemCount((HMENU)m_hMenu);
987 #endif
988
989 int i; // For old C++ compatibility
990 for(i=wxpos; i<totalMSWItems; i++)
991 {
992 if(GetSubMenu((HMENU)m_hMenu,i)==(HMENU)menu->GetHMenu())
993 return i;
994 }
995 for(i=0; i<wxpos; i++)
996 {
997 if(GetSubMenu((HMENU)m_hMenu,i)==(HMENU)menu->GetHMenu())
998 return i;
999 }
1000 wxFAIL;
1001 return -1;
1002 }
1003
1004 // ---------------------------------------------------------------------------
1005 // wxMenuBar functions to work with the top level submenus
1006 // ---------------------------------------------------------------------------
1007
1008 // NB: we don't support owner drawn top level items for now, if we do these
1009 // functions would have to be changed to use wxMenuItem as well
1010
1011 void wxMenuBar::EnableTop(size_t pos, bool enable)
1012 {
1013 wxCHECK_RET( IsAttached(), wxT("doesn't work with unattached menubars") );
1014 wxCHECK_RET( pos < GetMenuCount(), wxT("invalid menu index") );
1015
1016 int flag = enable ? MF_ENABLED : MF_GRAYED;
1017
1018 EnableMenuItem((HMENU)m_hMenu, MSWPositionForWxMenu(GetMenu(pos),pos), MF_BYPOSITION | flag);
1019
1020 Refresh();
1021 }
1022
1023 void wxMenuBar::SetLabelTop(size_t pos, const wxString& label)
1024 {
1025 wxCHECK_RET( pos < GetMenuCount(), wxT("invalid menu index") );
1026
1027 m_titles[pos] = label;
1028
1029 if ( !IsAttached() )
1030 {
1031 return;
1032 }
1033 //else: have to modify the existing menu
1034
1035 int mswpos = MSWPositionForWxMenu(GetMenu(pos),pos);
1036
1037 UINT id;
1038 UINT flagsOld = ::GetMenuState((HMENU)m_hMenu, mswpos, MF_BYPOSITION);
1039 if ( flagsOld == 0xFFFFFFFF )
1040 {
1041 wxLogLastError(wxT("GetMenuState"));
1042
1043 return;
1044 }
1045
1046 if ( flagsOld & MF_POPUP )
1047 {
1048 // HIBYTE contains the number of items in the submenu in this case
1049 flagsOld &= 0xff;
1050 id = (UINT)::GetSubMenu((HMENU)m_hMenu, mswpos);
1051 }
1052 else
1053 {
1054 id = pos;
1055 }
1056
1057 #ifdef __WXWINCE__
1058 MENUITEMINFO info;
1059 wxZeroMemory(info);
1060 info.cbSize = sizeof(info);
1061 info.fMask = MIIM_TYPE;
1062 info.fType = MFT_STRING;
1063 info.cch = label.length();
1064 info.dwTypeData = (LPTSTR) label.c_str();
1065 if ( !SetMenuItemInfo(GetHmenu(), id, TRUE, & info) )
1066 {
1067 wxLogLastError(wxT("SetMenuItemInfo"));
1068 }
1069
1070 #else
1071 if ( ::ModifyMenu(GetHmenu(), mswpos, MF_BYPOSITION | MF_STRING | flagsOld,
1072 id, label) == (int)0xFFFFFFFF )
1073 {
1074 wxLogLastError(wxT("ModifyMenu"));
1075 }
1076 #endif
1077
1078 Refresh();
1079 }
1080
1081 wxString wxMenuBar::GetLabelTop(size_t pos) const
1082 {
1083 wxCHECK_MSG( pos < GetMenuCount(), wxEmptyString,
1084 wxT("invalid menu index in wxMenuBar::GetLabelTop") );
1085
1086 return wxMenuItem::GetLabelFromText(m_titles[pos]);
1087 }
1088
1089 // ---------------------------------------------------------------------------
1090 // wxMenuBar construction
1091 // ---------------------------------------------------------------------------
1092
1093 wxMenu *wxMenuBar::Replace(size_t pos, wxMenu *menu, const wxString& title)
1094 {
1095 wxMenu *menuOld = wxMenuBarBase::Replace(pos, menu, title);
1096 if ( !menuOld )
1097 return NULL;
1098
1099 m_titles[pos] = title;
1100
1101 #if defined(WINCE_WITHOUT_COMMANDBAR)
1102 if (IsAttached())
1103 #else
1104 if (GetHmenu())
1105 #endif
1106 {
1107 int mswpos = MSWPositionForWxMenu(menuOld,pos);
1108
1109 // can't use ModifyMenu() because it deletes the submenu it replaces
1110 if ( !::RemoveMenu(GetHmenu(), (UINT)mswpos, MF_BYPOSITION) )
1111 {
1112 wxLogLastError(wxT("RemoveMenu"));
1113 }
1114
1115 if ( !::InsertMenu(GetHmenu(), (UINT)mswpos,
1116 MF_BYPOSITION | MF_POPUP | MF_STRING,
1117 (UINT)GetHmenuOf(menu), title) )
1118 {
1119 wxLogLastError(wxT("InsertMenu"));
1120 }
1121
1122 #if wxUSE_ACCEL
1123 if ( menuOld->HasAccels() || menu->HasAccels() )
1124 {
1125 // need to rebuild accell table
1126 RebuildAccelTable();
1127 }
1128 #endif // wxUSE_ACCEL
1129
1130 if (IsAttached())
1131 Refresh();
1132 }
1133
1134 return menuOld;
1135 }
1136
1137 bool wxMenuBar::Insert(size_t pos, wxMenu *menu, const wxString& title)
1138 {
1139 // Find out which MSW item before which we'll be inserting before
1140 // wxMenuBarBase::Insert is called and GetMenu(pos) is the new menu.
1141 // If IsAttached() is false this won't be used anyway
1142 bool isAttached =
1143 #if defined(WINCE_WITHOUT_COMMANDBAR)
1144 IsAttached();
1145 #else
1146 (GetHmenu() != 0);
1147 #endif
1148
1149 int mswpos = (!isAttached || (pos == m_menus.GetCount()))
1150 ? -1 // append the menu
1151 : MSWPositionForWxMenu(GetMenu(pos),pos);
1152
1153 if ( !wxMenuBarBase::Insert(pos, menu, title) )
1154 return false;
1155
1156 m_titles.Insert(title, pos);
1157
1158 if ( isAttached )
1159 {
1160 #if defined(WINCE_WITHOUT_COMMANDBAR)
1161 if (!GetToolBar())
1162 return false;
1163 TBBUTTON tbButton;
1164 memset(&tbButton, 0, sizeof(TBBUTTON));
1165 tbButton.iBitmap = I_IMAGENONE;
1166 tbButton.fsState = TBSTATE_ENABLED;
1167 tbButton.fsStyle = TBSTYLE_DROPDOWN | TBSTYLE_NO_DROPDOWN_ARROW | TBSTYLE_AUTOSIZE;
1168
1169 HMENU hPopupMenu = (HMENU) menu->GetHMenu() ;
1170 tbButton.dwData = (DWORD)hPopupMenu;
1171 wxString label = wxStripMenuCodes(title);
1172 tbButton.iString = (int) label.c_str();
1173
1174 tbButton.idCommand = NewControlId();
1175 if (!::SendMessage((HWND) GetToolBar()->GetHWND(), TB_INSERTBUTTON, pos, (LPARAM)&tbButton))
1176 {
1177 wxLogLastError(wxT("TB_INSERTBUTTON"));
1178 return false;
1179 }
1180 wxUnusedVar(mswpos);
1181 #else
1182 if ( !::InsertMenu(GetHmenu(), mswpos,
1183 MF_BYPOSITION | MF_POPUP | MF_STRING,
1184 (UINT)GetHmenuOf(menu), title) )
1185 {
1186 wxLogLastError(wxT("InsertMenu"));
1187 }
1188 #endif
1189 #if wxUSE_ACCEL
1190 if ( menu->HasAccels() )
1191 {
1192 // need to rebuild accell table
1193 RebuildAccelTable();
1194 }
1195 #endif // wxUSE_ACCEL
1196
1197 if (IsAttached())
1198 Refresh();
1199 }
1200
1201 return true;
1202 }
1203
1204 bool wxMenuBar::Append(wxMenu *menu, const wxString& title)
1205 {
1206 WXHMENU submenu = menu ? menu->GetHMenu() : 0;
1207 wxCHECK_MSG( submenu, false, wxT("can't append invalid menu to menubar") );
1208
1209 if ( !wxMenuBarBase::Append(menu, title) )
1210 return false;
1211
1212 m_titles.Add(title);
1213
1214 #if defined(WINCE_WITHOUT_COMMANDBAR)
1215 if (IsAttached())
1216 #else
1217 if (GetHmenu())
1218 #endif
1219 {
1220 #if defined(WINCE_WITHOUT_COMMANDBAR)
1221 if (!GetToolBar())
1222 return false;
1223 TBBUTTON tbButton;
1224 memset(&tbButton, 0, sizeof(TBBUTTON));
1225 tbButton.iBitmap = I_IMAGENONE;
1226 tbButton.fsState = TBSTATE_ENABLED;
1227 tbButton.fsStyle = TBSTYLE_DROPDOWN | TBSTYLE_NO_DROPDOWN_ARROW | TBSTYLE_AUTOSIZE;
1228
1229 size_t pos = GetMenuCount();
1230 HMENU hPopupMenu = (HMENU) menu->GetHMenu() ;
1231 tbButton.dwData = (DWORD)hPopupMenu;
1232 wxString label = wxStripMenuCodes(title);
1233 tbButton.iString = (int) label.c_str();
1234
1235 tbButton.idCommand = NewControlId();
1236 if (!::SendMessage((HWND) GetToolBar()->GetHWND(), TB_INSERTBUTTON, pos, (LPARAM)&tbButton))
1237 {
1238 wxLogLastError(wxT("TB_INSERTBUTTON"));
1239 return false;
1240 }
1241 #else
1242 if ( !::AppendMenu(GetHmenu(), MF_POPUP | MF_STRING,
1243 (UINT)submenu, title) )
1244 {
1245 wxLogLastError(wxT("AppendMenu"));
1246 }
1247 #endif
1248
1249 #if wxUSE_ACCEL
1250 if ( menu->HasAccels() )
1251 {
1252 // need to rebuild accelerator table
1253 RebuildAccelTable();
1254 }
1255 #endif // wxUSE_ACCEL
1256
1257 if (IsAttached())
1258 Refresh();
1259 }
1260
1261 return true;
1262 }
1263
1264 wxMenu *wxMenuBar::Remove(size_t pos)
1265 {
1266 wxMenu *menu = wxMenuBarBase::Remove(pos);
1267 if ( !menu )
1268 return NULL;
1269
1270 #if defined(WINCE_WITHOUT_COMMANDBAR)
1271 if (IsAttached())
1272 #else
1273 if (GetHmenu())
1274 #endif
1275 {
1276 #if defined(WINCE_WITHOUT_COMMANDBAR)
1277 if (GetToolBar())
1278 {
1279 if (!::SendMessage((HWND) GetToolBar()->GetHWND(), TB_DELETEBUTTON, (UINT) pos, (LPARAM) 0))
1280 {
1281 wxLogLastError(wxT("TB_DELETEBUTTON"));
1282 }
1283 }
1284 #else
1285 if ( !::RemoveMenu(GetHmenu(), (UINT)MSWPositionForWxMenu(menu,pos), MF_BYPOSITION) )
1286 {
1287 wxLogLastError(wxT("RemoveMenu"));
1288 }
1289 #endif
1290
1291 #if wxUSE_ACCEL
1292 if ( menu->HasAccels() )
1293 {
1294 // need to rebuild accell table
1295 RebuildAccelTable();
1296 }
1297 #endif // wxUSE_ACCEL
1298
1299 if (IsAttached())
1300 Refresh();
1301 }
1302
1303 m_titles.RemoveAt(pos);
1304
1305 return menu;
1306 }
1307
1308 #if wxUSE_ACCEL
1309
1310 void wxMenuBar::RebuildAccelTable()
1311 {
1312 // merge the accelerators of all menus into one accel table
1313 size_t nAccelCount = 0;
1314 size_t i, count = GetMenuCount();
1315 wxMenuList::iterator it;
1316 for ( i = 0, it = m_menus.begin(); i < count; i++, it++ )
1317 {
1318 nAccelCount += (*it)->GetAccelCount();
1319 }
1320
1321 if ( nAccelCount )
1322 {
1323 wxAcceleratorEntry *accelEntries = new wxAcceleratorEntry[nAccelCount];
1324
1325 nAccelCount = 0;
1326 for ( i = 0, it = m_menus.begin(); i < count; i++, it++ )
1327 {
1328 nAccelCount += (*it)->CopyAccels(&accelEntries[nAccelCount]);
1329 }
1330
1331 m_accelTable = wxAcceleratorTable(nAccelCount, accelEntries);
1332
1333 delete [] accelEntries;
1334 }
1335 }
1336
1337 #endif // wxUSE_ACCEL
1338
1339 void wxMenuBar::Attach(wxFrame *frame)
1340 {
1341 wxMenuBarBase::Attach(frame);
1342
1343 #if defined(WINCE_WITH_COMMANDBAR)
1344 if (!m_hMenu)
1345 this->Create();
1346 if (!m_commandBar)
1347 m_commandBar = (WXHWND) CommandBar_Create(wxGetInstance(), (HWND) frame->GetHWND(), NewControlId());
1348 if (m_commandBar)
1349 {
1350 if (m_hMenu)
1351 {
1352 if (!CommandBar_InsertMenubarEx((HWND) m_commandBar, NULL, (LPTSTR) m_hMenu, 0))
1353 {
1354 wxLogLastError(wxT("CommandBar_InsertMenubarEx"));
1355 }
1356 }
1357 }
1358 #endif
1359
1360 #if wxUSE_ACCEL
1361 RebuildAccelTable();
1362 #endif // wxUSE_ACCEL
1363 }
1364
1365 #if defined(WINCE_WITH_COMMANDBAR)
1366 bool wxMenuBar::AddAdornments(long style)
1367 {
1368 if (m_adornmentsAdded || !m_commandBar)
1369 return false;
1370
1371 if (style & wxCLOSE_BOX)
1372 {
1373 if (!CommandBar_AddAdornments((HWND) m_commandBar, 0, 0))
1374 wxLogLastError(wxT("CommandBar_AddAdornments"));
1375 else
1376 return true;
1377 }
1378 return false;
1379 }
1380 #endif
1381
1382 void wxMenuBar::Detach()
1383 {
1384 wxMenuBarBase::Detach();
1385 }
1386
1387 #endif // wxUSE_MENUS