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