move 8 copies of the same function to common code
[wxWidgets.git] / src / cocoa / menuitem.mm
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        src/cocoa/menuitem.mm
3 // Purpose:     wxMenuItem implementation
4 // Author:      David Elliott
5 // Modified by:
6 // Created:     2002/12/15
7 // RCS-ID:      $Id$
8 // Copyright:   2002-2004 David Elliott
9 // Licence:     wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21
22 #if wxUSE_MENUS
23
24 #include "wx/menuitem.h"
25
26 #include "wx/cocoa/objc/objc_uniquifying.h"
27
28 #ifndef WX_PRECOMP
29     #include "wx/menu.h"
30     #include "wx/utils.h"
31     #include "wx/frame.h"
32     #include "wx/log.h"
33 #endif
34
35 #include "wx/cocoa/autorelease.h"
36 #include "wx/cocoa/string.h"
37
38 #import <AppKit/NSMenuItem.h>
39 #import <AppKit/NSMenu.h>
40 #import <Foundation/NSString.h>
41 #import <AppKit/NSCell.h> // NSOnState, NSOffState
42 #import <AppKit/NSEvent.h> // modifier key masks
43
44 // ----------------------------------------------------------------------------
45 // functions prototypes
46 // ----------------------------------------------------------------------------
47
48 // ============================================================================
49 // @class wxNSMenuItemTarget
50 // ============================================================================
51 @interface wxNSMenuItemTarget : NSObject
52 {
53 }
54
55 - (void)wxMenuItemAction: (id)sender;
56 - (BOOL)validateMenuItem: (id)menuItem;
57 @end //interface wxNSMenuItemTarget
58 WX_DECLARE_GET_OBJC_CLASS(wxNSMenuItemTarget,NSObject)
59
60 @implementation wxNSMenuItemTarget : NSObject
61
62 - (void)wxMenuItemAction: (id)sender
63 {
64     wxLogTrace(wxTRACE_COCOA,wxT("wxMenuItemAction"));
65     wxMenuItem *item = wxMenuItem::GetFromCocoa(sender);
66     wxCHECK_RET(item,wxT("wxMenuItemAction received but no wxMenuItem exists!"));
67     item->CocoaItemSelected();
68 }
69
70 - (BOOL)validateMenuItem: (id)menuItem
71 {
72     // TODO: Do wxWidgets validation here and avoid sending during idle time
73     wxLogTrace(wxTRACE_COCOA,wxT("wxMenuItemAction"));
74     wxMenuItem *item = wxMenuItem::GetFromCocoa(menuItem);
75     wxCHECK_MSG(item,NO,wxT("validateMenuItem received but no wxMenuItem exists!"));
76     return item->Cocoa_validateMenuItem();
77 }
78
79 @end //implementation wxNSMenuItemTarget
80 WX_IMPLEMENT_GET_OBJC_CLASS(wxNSMenuItemTarget,NSObject)
81
82 // ============================================================================
83 // wxMenuItemCocoa implementation
84 // ============================================================================
85 IMPLEMENT_DYNAMIC_CLASS(wxMenuItem, wxObject)
86 wxMenuItemCocoaHash wxMenuItemCocoa::sm_cocoaHash;
87
88 wxObjcAutoRefFromAlloc<struct objc_object *> wxMenuItemCocoa::sm_cocoaTarget = [[WX_GET_OBJC_CLASS(wxNSMenuItemTarget) alloc] init];
89
90 // ----------------------------------------------------------------------------
91 // wxMenuItemBase
92 // ----------------------------------------------------------------------------
93
94 wxMenuItem *wxMenuItemBase::New(wxMenu *parentMenu,
95                                 int itemid,
96                                 const wxString& name,
97                                 const wxString& help,
98                                 wxItemKind kind,
99                                 wxMenu *subMenu)
100 {
101     return new wxMenuItem(parentMenu, itemid, name, help, kind, subMenu);
102 }
103
104 void wxMenuItemCocoa::CocoaSetKeyEquivalent()
105 {
106     wxAcceleratorEntry *accel = GetAccel();
107     if(!accel)
108         return;
109
110     int accelFlags = accel->GetFlags();
111     int keyModifierMask = 0;
112     if(accelFlags & wxACCEL_ALT)
113         keyModifierMask |= NSAlternateKeyMask;
114     if(accelFlags & wxACCEL_CTRL)
115         keyModifierMask |= NSCommandKeyMask;
116     int keyCode = accel->GetKeyCode();
117     if(isalpha(keyCode))
118     {   // For alpha characters use upper/lower rather than NSShiftKeyMask
119         char alphaChar;
120         if(accelFlags & wxACCEL_SHIFT)
121             alphaChar = toupper(keyCode);
122         else
123             alphaChar = tolower(keyCode);
124         [m_cocoaNSMenuItem setKeyEquivalent:[NSString stringWithCString:&alphaChar length:1]];
125         [m_cocoaNSMenuItem setKeyEquivalentModifierMask:keyModifierMask];
126     }
127     else
128     {
129         if(accelFlags & wxACCEL_SHIFT)
130             keyModifierMask |= NSShiftKeyMask;
131         if(keyCode < 128) // low ASCII includes backspace/tab/etc.
132         {   char alphaChar = keyCode;
133             [m_cocoaNSMenuItem setKeyEquivalent:[NSString stringWithCString:&alphaChar length:1]];
134         }
135         else
136         {   // TODO
137         }
138         [m_cocoaNSMenuItem setKeyEquivalentModifierMask:keyModifierMask];
139     }
140 }
141
142 // ----------------------------------------------------------------------------
143 // ctor & dtor
144 // ----------------------------------------------------------------------------
145 wxMenuItemCocoa::wxMenuItemCocoa(wxMenu *pParentMenu,
146                        int itemid,
147                        const wxString& strName,
148                        const wxString& strHelp,
149                        wxItemKind kind,
150                        wxMenu *pSubMenu)
151           : wxMenuItemBase(pParentMenu, itemid, strName, strHelp, kind, pSubMenu)
152 {
153     wxAutoNSAutoreleasePool pool;
154     if(m_kind == wxITEM_SEPARATOR)
155         m_cocoaNSMenuItem = [[NSMenuItem separatorItem] retain];
156     else
157     {
158         NSString *menuTitle = wxInitNSStringWithWxString([NSString alloc],wxStripMenuCodes(strName));
159         SEL action;
160         if(pSubMenu)
161             action = nil;
162         else
163             action = @selector(wxMenuItemAction:);
164         m_cocoaNSMenuItem = [[NSMenuItem alloc] initWithTitle:menuTitle action:action keyEquivalent:@""];
165         sm_cocoaHash.insert(wxMenuItemCocoaHash::value_type(m_cocoaNSMenuItem,this));
166         if(pSubMenu)
167         {
168             wxASSERT(pSubMenu->GetNSMenu());
169             [pSubMenu->GetNSMenu() setTitle:menuTitle];
170             [m_cocoaNSMenuItem setSubmenu:pSubMenu->GetNSMenu()];
171         }
172         else
173             [m_cocoaNSMenuItem setTarget: sm_cocoaTarget];
174         [menuTitle release];
175         CocoaSetKeyEquivalent();
176     }
177 }
178
179 wxMenuItem::~wxMenuItem()
180 {
181     sm_cocoaHash.erase(m_cocoaNSMenuItem);
182     [m_cocoaNSMenuItem release];
183 }
184
185 void wxMenuItem::CocoaItemSelected()
186 {
187     wxMenu *menu = GetMenu();
188     wxCHECK_RET(menu,wxT("wxMenuItemAction received but wxMenuItem is not in a wxMenu"));
189     wxMenuBar *menubar = menu->GetMenuBar();
190     if(menubar)
191     {
192         wxFrame *frame = menubar->GetFrame();
193         wxCHECK_RET(frame, wxT("wxMenuBar MUST be attached to a wxFrame!"));
194         frame->ProcessCommand(GetId());
195     }
196     else
197     {
198         if(IsCheckable())
199             Toggle();
200         GetMenu()->SendEvent(GetId(), IsCheckable()?IsChecked():-1);
201     }
202 }
203
204 bool wxMenuItem::Cocoa_validateMenuItem()
205 {
206     // TODO: do more sanity checking
207     // TODO: Do wxWindows validation here and avoid sending during idle time
208     return IsEnabled();
209 }
210
211 // ----------------------------------------------------------------------------
212 // misc
213 // ----------------------------------------------------------------------------
214
215 void wxMenuItem::SetBitmaps(const wxBitmap& bmpChecked,
216         const wxBitmap& bmpUnchecked)
217 {
218     wxCHECK_RET(m_kind != wxITEM_SEPARATOR, wxT("Separator items do not have bitmaps."));
219     wxAutoNSAutoreleasePool pool;
220     m_bmpChecked = bmpChecked;
221     m_bmpUnchecked = bmpUnchecked;
222     if(IsCheckable())
223     {
224         [m_cocoaNSMenuItem setOnStateImage: bmpChecked.GetNSImage(true)];
225         [m_cocoaNSMenuItem setOffStateImage: bmpUnchecked.GetNSImage(true)];
226     }
227     else
228     {
229         wxASSERT_MSG(!bmpUnchecked.Ok(),wxT("Normal menu items should only have one bitmap"));
230         [m_cocoaNSMenuItem setImage: bmpChecked.GetNSImage(true)];
231     }
232 }
233
234 // change item state
235 // -----------------
236
237 void wxMenuItem::Enable(bool bDoEnable)
238 {
239     wxMenuItemBase::Enable(bDoEnable);
240     // NOTE: Nothing to do, we respond to validateMenuItem instead
241 }
242
243 void wxMenuItem::Check(bool check)
244 {
245     wxCHECK_RET( IsCheckable(), wxT("only checkable items may be checked") );
246     if(m_isChecked == check)
247         return;
248     wxAutoNSAutoreleasePool pool;
249     if(GetKind() == wxITEM_RADIO)
250     {
251         // it doesn't make sense to uncheck a radio item - what would this do?
252         if(!check)
253             return;
254         const wxMenuItemList& items = m_parentMenu->GetMenuItems();
255         // First search backwards for other radio items
256         wxMenuItemList::compatibility_iterator radioStart = items.Find(this);
257         for(wxMenuItemList::compatibility_iterator prevNode = radioStart;
258             prevNode && (prevNode->GetData()->GetKind() == wxITEM_RADIO);
259             prevNode = prevNode->GetPrevious())
260         {
261             radioStart = prevNode;
262         }
263         // Now starting there set the state of every item until we're
264         // out of radio items to set.
265         for(wxMenuItemList::compatibility_iterator node = radioStart;
266             node && (node->GetData()->GetKind() == wxITEM_RADIO);
267             node = node->GetNext())
268         {
269             wxMenuItem *item = node->GetData();
270             bool checkItem = (item == this);
271             item->wxMenuItemBase::Check(checkItem);
272             [item->m_cocoaNSMenuItem setState: checkItem?NSOnState:NSOffState];
273         }
274     }
275     else // normal check (non-radio) item
276     {
277         wxMenuItemBase::Check(check);
278         [m_cocoaNSMenuItem setState: check?NSOnState:NSOffState];
279     }
280 }
281
282 void wxMenuItem::SetItemLabel(const wxString& label)
283 {
284     wxMenuItemBase::SetItemLabel(label);
285     wxCHECK_RET(m_kind != wxITEM_SEPARATOR, wxT("Separator items do not have titles."));
286     [m_cocoaNSMenuItem setTitle: wxNSStringWithWxString(wxStripMenuCodes(label))];
287     CocoaSetKeyEquivalent();
288 }
289
290 void wxMenuItem::SetCheckable(bool checkable)
291 {
292     wxCHECK_RET(m_kind != wxITEM_SEPARATOR, wxT("Separator items cannot be turned into normal menu items."));
293     wxMenuItemBase::SetCheckable(checkable);
294     // NOTE: Cocoa does not discern between unchecked and normal items
295 }
296
297 #endif // wxUSE_MENUS