/// @file platform/window_mac.mm /// @brief macOS (Cocoa, Metal) implementation of platform/window.h. #include "platform/window.h" #import #import #import #include #include "platform/keyboard.h" #include "render/frame_buffer.h" /// @brief Handles close requests and keyboard focus changes. @interface KumoWindowDelegate : NSObject { @public kumo::Keyboard keyboard; } @property(nonatomic) BOOL should_close; @end @implementation KumoWindowDelegate /// Called when the close button is pressed. Returning NO keeps the window /// open; the main loop sees the flag and shuts down on its own terms. - (BOOL)windowShouldClose:(NSWindow*)sender { self.should_close = YES; return NO; } - (void)windowDidResignKey:(NSNotification*)notification { (void)notification; keyboard.release_all(); } @end /// @brief A view whose backing layer is a CAMetalLayer, so that Metal can draw /// into it and AppKit still sizes the layer to the view. @interface KumoView : NSView @end @implementation KumoView - (CALayer*)makeBackingLayer { return [CAMetalLayer layer]; } @end namespace kumo { /// @brief Cocoa and Metal state behind the opaque Window handle. struct Window { NSWindow* ns_window; KumoWindowDelegate* delegate; CAMetalLayer* layer; id queue; id texture; ///< Holds the last frame; made again on a new size. }; /// @brief Creates the application object and a minimal menu with Cmd+Q. /// /// A bare executable (not an .app bundle) has no menu and is not a regular /// foreground application by default; without this it could neither receive /// keyboard focus nor be quit from the keyboard. static void init_application() { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; NSMenu* menu_bar = [[NSMenu alloc] init]; NSMenuItem* app_item = [[NSMenuItem alloc] init]; [menu_bar addItem:app_item]; NSMenu* app_menu = [[NSMenu alloc] init]; [app_menu addItemWithTitle:@"Quit Kumo" action:@selector(terminate:) keyEquivalent:@"q"]; [app_item setSubmenu:app_menu]; [NSApp setMainMenu:menu_bar]; // Finish launching by hand: events are pumped by window_poll_events() // instead of [NSApp run], which would take over the main loop. [NSApp finishLaunching]; } Window* window_create(const WindowDesc& desc) { static bool application_ready = false; if (!application_ready) { init_application(); application_ready = true; } id device = MTLCreateSystemDefaultDevice(); if (device == nil) return nullptr; NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable; NSRect frame = NSMakeRect(0, 0, desc.width, desc.height); NSWindow* ns_window = [[NSWindow alloc] initWithContentRect:frame styleMask:style backing:NSBackingStoreBuffered defer:NO]; if (ns_window == nil) return nullptr; KumoView* view = [[KumoView alloc] initWithFrame:frame]; [view setWantsLayer:YES]; CAMetalLayer* layer = (CAMetalLayer*)view.layer; layer.device = device; // Color is 0xAARRGGBB in a 32-bit integer, which is the bytes B, G, R, A on // a little-endian machine: exactly this format, so no conversion is needed. layer.pixelFormat = MTLPixelFormatBGRA8Unorm; // The frame is copied into the drawable, which a framebuffer-only texture // does not allow. layer.framebufferOnly = NO; // The drawable has the size of the frame, not of the window; the window // system stretches it. Nearest keeps the pixels square and sharp. layer.magnificationFilter = kCAFilterNearest; [ns_window setContentView:view]; KumoWindowDelegate* delegate = [[KumoWindowDelegate alloc] init]; // We own the reference through Window; AppKit must not release it on close. [ns_window setReleasedWhenClosed:NO]; [ns_window setDelegate:delegate]; [ns_window setTitle:[NSString stringWithUTF8String:desc.title]]; [ns_window center]; [ns_window makeKeyAndOrderFront:nil]; [NSApp activate]; return new Window{ns_window, delegate, layer, [device newCommandQueue], nil}; } void window_destroy(Window* window) { if (window == nullptr) return; [window->ns_window setDelegate:nil]; [window->ns_window close]; delete window; } static Key key_from_event(NSEvent* event) { NSString* characters = event.charactersIgnoringModifiers; if (characters.length != 1) return Key::Count; using namespace ptn; return match([characters characterAtIndex:0]) | on( val >> Key::Left, val >> Key::Right, val >> Key::Up, val >> Key::Down, val<' '> >> Key::Space, _ >> Key::Count); } static bool handle_key_event(Window* window, NSEvent* event, bool down) { if (event.window != window->ns_window || ![window->ns_window isKeyWindow]) { return false; } if (down && (event.modifierFlags & NSEventModifierFlagCommand) != 0) { return false; } constexpr unsigned short kEscapeKeyCode = 53; if (down && event.keyCode == kEscapeKeyCode) { window->delegate.should_close = YES; return true; } const Key key = key_from_event(event); if (key == Key::Count) return false; if (!down || ![event isARepeat]) { window->delegate->keyboard.set_key(key, down); } return true; } static bool handle_event(Window* window, NSEvent* event) { using namespace ptn; return match(event.type) | on(val >> [&] { return handle_key_event(window, event, true); }, val >> [&] { return handle_key_event(window, event, false); }, _ >> false); } void window_poll_events(Window* window) { // Keeps the autoreleased event objects from piling up across frames. @autoreleasepool { for (;;) { // distantPast: return at once if no event is queued. NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES]; if (event == nil) break; if (!handle_event(window, event)) { [NSApp sendEvent:event]; } } } } Keyboard& window_keyboard(Window* window) { return window->delegate->keyboard; } bool window_should_close(const Window* window) { return window->delegate.should_close; } void window_present(Window* window, const FrameBuffer& framebuffer) { @autoreleasepool { const NSUInteger width = static_cast(framebuffer.width); const NSUInteger height = static_cast(framebuffer.height); if (window->texture == nil || window->texture.width != width || window->texture.height != height) { MTLTextureDescriptor* texture_desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:width height:height mipmapped:NO]; window->texture = [window->layer.device newTextureWithDescriptor:texture_desc]; window->layer.drawableSize = CGSizeMake(width, height); } // Blocks until the display can take another frame: this is the vsync wait. id drawable = [window->layer nextDrawable]; if (drawable == nil) return; [window->texture replaceRegion:MTLRegionMake2D(0, 0, width, height) mipmapLevel:0 withBytes:framebuffer.pixels.data() bytesPerRow:width * sizeof(Color)]; id commands = [window->queue commandBuffer]; id blit = [commands blitCommandEncoder]; [blit copyFromTexture:window->texture sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(width, height, 1) toTexture:drawable.texture destinationSlice:0 destinationLevel:0 destinationOrigin:MTLOriginMake(0, 0, 0)]; [blit endEncoding]; [commands presentDrawable:drawable]; [commands commit]; // The texture is written again by the next call, so the copy must be done // by then. Waiting is cheap next to drawing the frame on the CPU. [commands waitUntilCompleted]; } } void window_set_title(Window* window, const char* title) { [window->ns_window setTitle:[NSString stringWithUTF8String:title]]; } } // namespace kumo