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