forked from thomashope/native-menu-bar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative_menu_bar.c
More file actions
507 lines (415 loc) · 13 KB
/
native_menu_bar.c
File metadata and controls
507 lines (415 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#include "native_menu_bar.h"
#include <stdio.h>
#define MAX_EVENTS 64
#define ERROR_BUFFER_SIZE 128
#define UNUSED(x) (void)(x)
static char errorBuffer[ERROR_BUFFER_SIZE];
static struct
{
size_t head;
size_t tail;
nmb_Event data[MAX_EVENTS];
} events;
static bool getEvent(nmb_Event* e)
{
if (events.head == events.tail) return false; /* No events available */
*e = events.data[events.head];
events.head = (events.head + 1) % MAX_EVENTS;
return true;
}
static void pushEvent(const nmb_Event* e)
{
/* TODO: print a warning if the user isn't consuming events fast enough */
if ((events.tail + 1) % MAX_EVENTS == events.head)
{
/* Buffer is full, overwrite the oldest event */
events.head = (events.head + 1) % MAX_EVENTS;
}
events.data[events.tail] = *e;
events.tail = (events.tail + 1) % MAX_EVENTS;
}
const char* nmb_getLastError(void)
{
return errorBuffer;
}
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define CAPTION_BUFFER_SIZE 256
static_assert(sizeof(HWND) == sizeof(nmb_Handle), "Window handles must be interchangeable with void*");
static_assert(sizeof(HMENU) == sizeof(nmb_Handle), "Menu handles must be interchangeable with void*");
static struct
{
HWND hwnd;
HMENU menuBar;
WNDPROC originalWndProc;
UINT nextId;
WCHAR wcharBuffer[CAPTION_BUFFER_SIZE];
} g;
static LRESULT CALLBACK menuBarWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_COMMAND)
{
nmb_Event e;
e.sender = (nmb_Handle)(uintptr_t)(LOWORD(wParam));
e.event = nmb_EventType_itemTriggered;
pushEvent(&e);
return 0;
}
return CallWindowProc(g.originalWndProc, hWnd, uMsg, wParam, lParam);
}
static WCHAR* utf8ToWide(const char* utf8)
{
if (!utf8) return NULL;
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, g.wcharBuffer, CAPTION_BUFFER_SIZE);
return g.wcharBuffer;
}
void nmb_setup(void* hWnd)
{
memset(&g, 0, sizeof(g));
errorBuffer[0] = 0;
g.nextId = 1;
g.hwnd = (HWND)hWnd;
g.originalWndProc = (WNDPROC)SetWindowLongPtr(g.hwnd, GWLP_WNDPROC, (LONG_PTR)menuBarWndProc);
g.menuBar = CreateMenu();
if (!SetMenu(g.hwnd, g.menuBar))
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to set menu on window: %lu\n", GetLastError());
}
if (!DrawMenuBar(g.hwnd))
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to draw menu bar on window: %lu\n", GetLastError());
}
}
void nmb_shutdown(void)
{
SetWindowLongPtr(g.hwnd, GWLP_WNDPROC, (LONG_PTR)g.originalWndProc); /* restore the old wndproc */
DestroyMenu(g.menuBar);
memset(&g, 0, sizeof(g));
}
bool nmb_pollEvent(nmb_Event* event)
{
return getEvent(event);
};
nmb_Platform nmb_getPlatform()
{
return nmb_Platform_windows;
}
nmb_Handle nmb_appendMenu(nmb_Handle parent, const char* caption)
{
return nmb_insertMenu(parent, -1, caption);
}
/* TODO: allow passing negative indices to insert from the end of the menu */
nmb_Handle nmb_insertMenu(nmb_Handle parent, int index, const char* caption)
{
if (index < -1)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Invalid index '%d' passed to '%s'\n", index, __func__);
return NULL;
}
if (!parent)
{
parent = g.menuBar;
}
nmb_Handle submenu = CreatePopupMenu();
BOOL result = InsertMenuW((HMENU)parent, (UINT)index, MF_BYPOSITION | MF_POPUP, (UINT_PTR)submenu, utf8ToWide(caption));
if (!result)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to insert submenu '%s'. Windows error %lu\n", caption, GetLastError());
return NULL;
}
DrawMenuBar(g.hwnd);
return submenu;
}
nmb_Handle nmb_appendMenuItem(nmb_Handle parent, const char* caption)
{
return nmb_insertMenuItem(parent, -1, caption);
}
/* TODO: allow passing negative indices to insert from the end of the menu */
nmb_Handle nmb_insertMenuItem(nmb_Handle parent, int index, const char* caption)
{
if (index < -1)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Invalid index '%d' passed to '%s'\n", index, __func__);
return NULL;
}
if (!parent)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to create menu item because parent was NULL\n");
return NULL;
}
UINT id = g.nextId++;
BOOL result = InsertMenuW((HMENU)parent, (UINT)index, MF_BYPOSITION | MF_STRING, id, utf8ToWide(caption));
if (!result)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to insert menu item '%s'. Windows error %lu\n", caption, GetLastError());
return NULL;
}
DrawMenuBar(g.hwnd);
return (nmb_Handle)(uintptr_t)id;
}
void nmb_appendSeparator(nmb_Handle parent)
{
nmb_insertSeparator(parent, -1);
}
void nmb_insertSeparator(nmb_Handle parent, int index)
{
if (index < -1)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Invalid index '%d' passed to '%s'\n", index, __func__);
return;
}
if (!parent)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to create separator because parent was NULL\n");
return;
}
InsertMenu((HMENU)parent, (UINT)index, MF_BYPOSITION | MF_SEPARATOR, 0, NULL);
DrawMenuBar(g.hwnd);
}
void nmb_setMenuItemChecked(nmb_Handle menuItem, bool checked)
{
if (!menuItem) return;
UINT flags = MF_BYCOMMAND | (checked ? MF_CHECKED : MF_UNCHECKED);
CheckMenuItem(GetMenu(g.hwnd), (UINT)(uintptr_t)menuItem, flags);
DrawMenuBar(g.hwnd);
}
bool nmb_isMenuItemChecked(nmb_Handle menuItem)
{
if (!menuItem) return false;
UINT state = GetMenuState(g.menuBar, (UINT)(uintptr_t)menuItem, MF_BYCOMMAND);
if (state == (UINT)-1)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to get menu item state: %lu\n", GetLastError());
return false;
}
return (state & MF_CHECKED) == MF_CHECKED;
}
void nmb_setMenuItemEnabled(nmb_Handle menuItem, bool enabled)
{
if (!menuItem) return;
UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_GRAYED);
BOOL result = EnableMenuItem(g.menuBar, (UINT)(uintptr_t)menuItem, flags);
if (result == -1)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to set menu item enabled state: %lu\n", GetLastError());
return;
}
DrawMenuBar(g.hwnd);
}
bool nmb_isMenuItemEnabled(nmb_Handle menuItem)
{
if (!menuItem) return false;
UINT state = GetMenuState(g.menuBar, (UINT)(uintptr_t)menuItem, MF_BYCOMMAND);
if (state == (UINT)-1)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to get menu item state: %lu\n", GetLastError());
return false;
}
return (state & MF_GRAYED) != MF_GRAYED;
}
#else
#import <Cocoa/Cocoa.h>
@interface MenuHandler : NSObject
- (void)handleAction : (id)sender;
@end
static struct
{
MenuHandler* handler;
} g;
@implementation MenuHandler
- (void)handleAction:(id)sender
{
nmb_Event e;
e.sender = sender;
e.event = nmb_EventType_itemTriggered;
pushEvent(&e);
}
@end
/*
Mac features
Looks like both MAC and WINDOWS give the app some menus by default.
Mac: Doesn't create the default menus for your, but the HIG described some minimum expected menus.
Mac SDL: SDL creates an App menu using the Bundle Name from the Info.plist + a Window menu with some stuff in it
Windows: A default menu when you click on the app icon.
On mac you can access the App menu with [NSApp mainMenu], and presuambly modify it from there?
On windows you can apparently use GetSystenMenu()?
On mac we are likely to want to insert our custom menus after the App menu but before the Window menu, plus some after the Window menu (e.g. Help)
Idea
appMenu = nmb_getAppMenu() // Returns the app menu on Mac, and system icon menu on windows
fileMenu = nmb_insertMenuAfter(appMenu, "File")
windowMenu = nmb_getMenu("Window");
if(!windowMenu)
{
windowMenu = nmb_appendMennu("window")
... make the window menu
}
nmb_insertMenuAfter(windowMenu, "Help")
Result
mac: App (default) / File / Window (default) / Help
windows: Icon (default) / File / Window / Help
*/
static NSString* getApplicationName(void)
{
NSString *appName = nil;
/* check the plist for CFBundleName first. This should be a short name of 16 characters or fewer. */
if (!appName)
{
appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
}
/* if the CFBundleName was not found, try the CFBundleDisplayName */
if (!appName)
{
appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
}
/* failing that, use the process name */
if (!appName || [appName length] == 0)
{
appName = [[NSProcessInfo processInfo] processName];
}
return appName;
}
static void createDefaultMenus(void)
{
if (NSApp == nil)
return;
/* Create the app menu */
NSString* appName = getApplicationName();
NSMenu* appMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add some minimal default menu items (the HIG actually want us to add quite a few more) */
[appMenu addItemWithTitle:[@"About " stringByAppendingString:appName] action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appMenu addItem:[NSMenuItem separatorItem]];
[appMenu addItemWithTitle:[@"Quit " stringByAppendingString:appName] action:@selector(terminate:) keyEquivalent:@"q"];
/* Attach it the app */
NSMenuItem* appMenuItem = [[NSMenuItem alloc] init];
[appMenuItem setSubmenu:appMenu];
[[NSApp mainMenu] addItem:appMenuItem];
[appMenu release];
[appMenuItem release];
}
static NSInteger adjustIndex(nmb_Handle parent, int index)
{
if(index < 0)
{
NSInteger numberOfItems = [(NSMenu*)parent numberOfItems];
return numberOfItems + index + 1;
}
return index;
}
void nmb_setup(void* windowHandle /* unused on mac */)
{
UNUSED(windowHandle);
memset(&g, 0, sizeof(g));
errorBuffer[0] = 0;
g.handler = [[MenuHandler alloc] init];
/* Check if someone else (e.g. SDL) already built the app menu */
NSInteger numItemsInAppleMenu = [[[[NSApp mainMenu] itemAtIndex:0] submenu] numberOfItems];
bool addDefaultMenuItems = numItemsInAppleMenu == 0;
/* If not, add some default menu items */
if(addDefaultMenuItems)
{
/* To add a custom app menu, we have to create our own main menu (aka menu bar) */
NSMenu* mainMenu = [[NSMenu alloc] init];
[NSApp setMainMenu:mainMenu];
[mainMenu release];
createDefaultMenus();
}
}
void nmb_shutdown()
{
[g.handler release];
memset(&g, 0, sizeof(g));
}
bool nmb_pollEvent(nmb_Event* event)
{
return getEvent(event);
}
nmb_Platform nmb_getPlatform(void)
{
return nmb_Platform_macos;
}
nmb_Handle nmb_appendMenu(nmb_Handle parent, const char* caption)
{
return nmb_insertMenu(parent, -1, caption);
}
nmb_Handle nmb_insertMenu(nmb_Handle parent, int inputIndex, const char* caption)
{
if(!parent)
{
/* If parent is null, insert into the menu bar */
parent = [NSApp mainMenu];
if(inputIndex >= 0)
{
/* Offset 0 index to be the menu item AFTER the application menu. */
inputIndex++;
}
}
NSInteger index = adjustIndex(parent, inputIndex);
if (index < 0)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Invalid index '%ld' passed to '%s'\n", index, __func__);
return NULL;
}
NSMenuItem* item = [(NSMenu*)parent insertItemWithTitle:[NSString stringWithCString:caption encoding:NSUTF8StringEncoding] action:nil keyEquivalent:@"" atIndex:index];
NSMenu* menu = [[NSMenu alloc] init];
[item setSubmenu:menu];
[menu release];
return menu;
}
nmb_Handle nmb_appendMenuItem(nmb_Handle parent, const char* caption)
{
return nmb_insertMenuItem(parent, -1, caption);
}
nmb_Handle nmb_insertMenuItem(nmb_Handle parent, int inputIndex, const char* caption)
{
if(!parent)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to create menu item because parent was NULL\n");
return NULL;
}
NSInteger index = adjustIndex(parent, inputIndex);
if (index < 0)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Invalid index '%ld' passed to '%s'\n", index, __func__);
return NULL;
}
NSMenuItem* item = [(NSMenu*)parent insertItemWithTitle:[NSString stringWithCString:caption encoding:NSUTF8StringEncoding] action:@selector(handleAction:) keyEquivalent:@"" atIndex:index];
[item setTarget:g.handler];
return item;
}
void nmb_appendSeparator(nmb_Handle parent)
{
nmb_insertSeparator(parent, -1);
}
void nmb_insertSeparator(nmb_Handle parent, int inputIndex)
{
if(!parent)
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Failed to create menu item because parent was NULL\n");
return;
}
NSInteger index = adjustIndex(parent, inputIndex);
if (index < 0) // on mac the index must be positive
{
snprintf(errorBuffer, ERROR_BUFFER_SIZE, "Invalid index '%ld' passed to '%s'\n", index, __func__);
return;
}
[(NSMenu*)parent insertItem:[NSMenuItem separatorItem] atIndex:index];
}
void nmb_setMenuItemChecked(nmb_Handle menuItem, bool checked)
{
((NSMenuItem*)menuItem).state = checked ? NSControlStateValueOn : NSControlStateValueOff;
}
bool nmb_isMenuItemChecked(nmb_Handle menuItem)
{
return ((NSMenuItem*)menuItem).state == NSControlStateValueOn;
}
void nmb_setMenuItemEnabled(nmb_Handle menuItem, bool enabled)
{
((NSMenuItem*)menuItem).action = enabled ? @selector(handleAction:) : nil;
}
bool nmb_isMenuItemEnabled(nmb_Handle menuItem)
{
return ((NSMenuItem*)menuItem).enabled;
}
#endif