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