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