20#if defined(WITH_COCOA) || defined(DOXYGEN_API)
47 NSTouchBarItemIdentifier
key;
66 {
@"openttd.build_airport",
SPR_IMG_BUILDAIR, MTHK_BUILD_AIRPORT,
@"Airport" }
71@interface OTTDMain : NSObject <NSApplicationDelegate>
92 i += c < 0x10000 ? 1 : 2;
106 auto it = view.begin();
107 const auto end = view.end();
108 for (NSUInteger i = 0; it != end && i < count; ++it) {
109 i += *it < 0x10000 ? 1 : 2;
111 return it.GetByteOffset();
121 std::vector<char32_t> unicode_str;
124 for (NSUInteger i = 0; i < s.length; i++) {
125 unichar c = [ s characterAtIndex:i ];
132 unicode_str.push_back(c);
145 delete[] (
const uint32_t *)data;
156 if (!SpriteExists(sprite_id))
return nullptr;
161 if (!buffer)
return nullptr;
164 if (!data)
return nullptr;
166 CGBitmapInfo info = kCGImageAlphaFirst | kCGBitmapByteOrder32Host;
168 CFAutoRelease<CGImage> bitmap(CGImageCreate(dim.
width, dim.
height, 8, 32, dim.
width * 4, colour_space.get(), info, data.get(),
nullptr,
false, kCGRenderingIntentDefault));
169 if (!bitmap)
return nullptr;
171 return [ [ [ NSImage alloc ] initWithCGImage:bitmap.get() size:NSZeroSize ] autorelease ];
178@implementation OTTDMain
187 NSEventType type = NSEventTypeApplicationDefined;
188 NSEvent *
event = [
NSEvent otherEventWithType:type location:NSMakePoint(0, 0) modifierFlags:0 timestamp:0.0 windowNumber:0 context:nil subtype:0 data1:0 data2:0 ];
189 [
NSApp postEvent:event atStart:YES ];
196- (void)launchGameEngine: (NSNotification*) note
208 [
self performSelectorOnMainThread:@selector(stopEngine) withObject:nil waitUntilDone:FALSE ];
215- (void) applicationDidFinishLaunching: (NSNotification*) note
218 [ [
NSNotificationCenter defaultCenter ] addObserver:
self selector:@selector(launchGameEngine:) name:OTTDMainLaunchGameEngine object:nil ];
221 [ [
NSNotificationCenter defaultCenter ] postNotificationName:OTTDMainLaunchGameEngine object:nil ];
229- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*) sender
231 HandleExitGameRequest();
233 return NSTerminateCancel;
253- (BOOL)applicationSupportsSecureRestorableState:(NSApplication*) sender
264 NSString *appName =
@"OpenTTD";
265 NSMenu *appleMenu = [ [ NSMenu alloc ] initWithTitle:appName ];
268 NSString *title = [ @"About " stringByAppendingString:appName ];
269 [ appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@"" ];
271 [ appleMenu addItem:[ NSMenuItem separatorItem ] ];
273 title = [ @"Hide " stringByAppendingString:appName ];
274 [ appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h" ];
276 NSMenuItem *menuItem = [ appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h" ];
277 [ menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand) ];
279 [ appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@"" ];
281 [ appleMenu addItem:[ NSMenuItem separatorItem ] ];
283 title = [ @"Quit " stringByAppendingString:appName ];
284 [ appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q" ];
287 menuItem = [ [ NSMenuItem alloc ] initWithTitle:@"" action:nil keyEquivalent:@"" ];
288 [ menuItem setSubmenu:appleMenu ];
289 [ [ NSApp mainMenu ] addItem:menuItem ];
294 if ([ NSApp respondsToSelector:
@selector(setAppleMenu:) ]) {
295 [ NSApp performSelector:@selector(setAppleMenu:) withObject:appleMenu ];
299 [ appleMenu release ];
300 [ menuItem release ];
308 NSMenu *windowMenu = [ [ NSMenu alloc ] initWithTitle:@"Window" ];
311 [ windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m" ];
314 NSMenuItem *menuItem = [ [ NSMenuItem alloc ] initWithTitle:@"Window" action:nil keyEquivalent:@"" ];
315 [ menuItem setSubmenu:windowMenu ];
316 [ [ NSApp mainMenu ] addItem:menuItem ];
319 [ windowMenu addItemWithTitle:@"Fullscreen" action:@selector(toggleFullScreen:) keyEquivalent:@"^f" ];
322 [ NSApp setWindowsMenu:windowMenu ];
325 [ windowMenu release ];
326 [ menuItem release ];
335 ProcessSerialNumber psn = { 0, kCurrentProcess };
338 [ NSApplication sharedApplication ];
341 OSStatus returnCode = TransformProcessType(&psn, kProcessTransformToForegroundApplication);
345 if ([ NSWindow respondsToSelector:
@selector(setAllowsAutomaticWindowTabbing:) ]) {
347 [
NSWindow performSelector:@selector(setAllowsAutomaticWindowTabbing:) withObject:nil];
351 [ [ NSApplication sharedApplication ] setActivationPolicy:NSApplicationActivationPolicyRegular ];
352 [ [ NSApplication sharedApplication ] activateIgnoringOtherApps:YES ];
355 [ NSApp setMainMenu:[ [ NSMenu alloc ] init ] ];
361 [ NSApp setDelegate:_ottd_main ];
384void CocoaDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
392 fmt::print(stderr,
"{}: {}\n", title, message);
397 NSAlert *alert = [ [ NSAlert alloc ] init ];
398 [ alert setAlertStyle: NSAlertStyleCritical ];
399 [ alert setMessageText:[ [ NSString alloc ] initWithBytes:title.data() length:title.size() encoding:NSUTF8StringEncoding ] ];
400 [ alert setInformativeText:[ [ NSString alloc ] initWithBytes:message.data() length:message.size() encoding:NSUTF8StringEncoding ] ];
401 [ alert addButtonWithTitle: [ [ NSString alloc ] initWithBytes:buttonLabel.data() length:buttonLabel.size() encoding:NSUTF8StringEncoding ] ];
411@implementation OTTD_CocoaWindow {
412 VideoDriver_Cocoa *driver;
425- (instancetype)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag driver:(
VideoDriver_Cocoa *)drv
427 if (self = [ super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag ]) {
429 self->touchbar_created =
false;
431 [
self setContentMinSize:NSMakeSize(64.0f, 64.0f) ];
434 NSString *nsscaption = [ [
NSString alloc ] initWithBytes:caption.data() length:caption.size() encoding:NSUTF8StringEncoding ];
435 [
self setTitle:nsscaption ];
436 [
self setMiniwindowTitle:nsscaption ];
448- (void)setFrame:(NSRect)frameRect display:(BOOL)flag
450 [
super setFrame:frameRect display:flag ];
455- (void)touchBarButtonAction:(
id)sender
457 NSButton *btn = (NSButton *)sender;
463- (nullable NSTouchBar *)makeTouchBar
466 NSMutableArray<NSTouchBarItemIdentifier> *button_ids = [ [ NSMutableArray alloc ] init ];
468 [ button_ids addObject:button.key ];
470 [ button_ids addObject:NSTouchBarItemIdentifierOtherItemsProxy ];
472 NSTouchBar *bar = [ [ NSTouchBar alloc ] init ];
474 bar.defaultItemIdentifiers = button_ids;
475 [ button_ids release ];
477 self->touchbar_created =
true;
482- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
487 NSButton *button = [ NSButton buttonWithTitle:item->fallback_text target:
self action:@selector(touchBarButtonAction:) ];
488 button.identifier = identifier;
489 button.imageScaling = NSImageScaleProportionallyDown;
491 NSCustomTouchBarItem *tb_item = [ [ NSCustomTouchBarItem alloc] initWithIdentifier:identifier ];
492 tb_item.view = button;
496- (void)refreshSystemSprites
498 if (!self->touchbar_created || ![ self respondsToSelector:
@selector(touchBar) ] || self.touchBar == nil)
return;
501 for (NSTouchBarItemIdentifier ident in self.touchBar.itemIdentifiers) {
505 NSCustomTouchBarItem *tb_item = [
self.touchBar itemForIdentifier:ident ];
506 NSButton *button = tb_item.view;
511 CGFloat max_dim = std::max(image.size.width, image.size.height);
513 CGFloat scale = 22.0 / max_dim;
514 image.size = NSMakeSize(image.size.width * scale, image.size.height * scale);
517 button.image = image;
518 button.imagePosition = NSImageOnly;
521 button.imagePosition = NSNoImage;
529 float _current_magnification;
535- (instancetype)initWithFrame:(NSRect)frameRect
537 if (self = [ super initWithFrame:frameRect ]) {
538 self->_use_hidpi =
_allow_hidpi_window && [
self respondsToSelector:@selector(convertRectToBacking:) ] && [
self respondsToSelector:@selector(convertRectFromBacking:) ];
543- (NSRect)getRealRect:(NSRect)rect
545 return _use_hidpi ? [
self convertRectToBacking:rect ] : rect;
548- (NSRect)getVirtualRect:(NSRect)rect
550 return _use_hidpi ? [
self convertRectFromBacking:rect ] : rect;
553- (CGFloat)getContentsScale
555 return _use_hidpi && self.window != nil ? [
self.window backingScaleFactor ] : 1.0f;
567- (void)setNeedsDisplayInRect:(NSRect)invalidRect
570 for ( NSView *v in [ self subviews ]) {
571 [ v setNeedsDisplayInRect:[ v convertRect:invalidRect fromView:
self ] ];
575- (void)viewWillMoveToWindow:(NSWindow *)win
577 for (NSTrackingArea *a in [ self trackingAreas ]) {
578 [
self removeTrackingArea:a ];
582- (void)viewDidMoveToWindow
585 NSTrackingAreaOptions track_opt = NSTrackingInVisibleRect | NSTrackingActiveInActiveApp | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingCursorUpdate;
586 NSTrackingArea *track = [ [ NSTrackingArea alloc ] initWithRect:[
self bounds ] options:track_opt owner:
self userInfo:nil ];
587 [
self addTrackingArea:track ];
594- (void)mouseEntered:(NSEvent *)theEvent
599 _cursor.in_window =
true;
605- (void)mouseExited:(NSEvent *)theEvent
607 if ([ self window ] != nil) UndrawMouseCursor();
614 _cursor.in_window =
false;
622- (NSPoint)mousePositionFromEvent:(NSEvent *)e
624 NSPoint pt = e.locationInWindow;
625 if ([ e window ] == nil) pt = [
self.
window convertRectFromScreen:NSMakeRect(pt.x, pt.y, 0, 0) ].origin;
626 pt = [
self convertPoint:pt fromView:nil ];
628 return [
self getRealRect:NSMakeRect(pt.x,
self.bounds.size.height - pt.y, 0, 0) ].origin;
635- (void)internalMouseMoveEvent:(NSEvent *)event
637 if (_cursor.fix_at) {
638 _cursor.UpdateCursorPositionRelative(event.deltaX * self.getContentsScale, event.deltaY * self.getContentsScale);
641 _cursor.UpdateCursorPosition(pt.x, pt.y);
652 bool cur_fix = _cursor.fix_at;
656 if (cur_fix != _cursor.fix_at) CGAssociateMouseAndMouseCursorPosition(!_cursor.fix_at);
664- (BOOL)emulateRightButton:(NSEvent *)event
666 uint32_t keymask = 0;
667 if (
_settings_client.gui.right_mouse_btn_emulation == RMBE_COMMAND) keymask |= NSEventModifierFlagCommand;
668 if (
_settings_client.gui.right_mouse_btn_emulation == RMBE_CONTROL) keymask |= NSEventModifierFlagControl;
670 return (event.modifierFlags & keymask) != 0;
677- (void)mouseMoved:(NSEvent *)event
686- (void)mouseDragged:(NSEvent *)event
695- (void)mouseDown:(NSEvent *)event
697 if ([ self emulateRightButton:event ]) {
698 self->_emulated_down =
true;
710- (void)mouseUp:(NSEvent *)event
712 if (self->_emulated_down) {
713 self->_emulated_down =
false;
726- (void)rightMouseDragged:(NSEvent *)event
735- (void)rightMouseDown:(NSEvent *)event
746- (void)rightMouseUp:(NSEvent *)event
756- (void)otherMouseDown:(NSEvent *)event
759 switch ([ event buttonNumber ]) {
774- (void)otherMouseUp:(NSEvent *)event
777 switch ([ event buttonNumber ]) {
791- (void)scrollWheel:(NSEvent *)event
793 if ([ event deltaY ] > 0.0) {
795 }
else if ([ event deltaY ] < 0.0) {
804 if ([ event respondsToSelector:
@selector(hasPreciseScrollingDeltas) ]) {
806 if (![ event hasPreciseScrollingDeltas ])
return;
808 deltaX = [
event scrollingDeltaX ] * 0.5f;
809 deltaY = [
event scrollingDeltaY ] * 0.5f;
811 deltaX = [
event deltaX ] * 5;
812 deltaY = [
event deltaY ] * 5;
815 _cursor.h_wheel -=
static_cast<float>(deltaX *
_settings_client.gui.scrollwheel_multiplier);
816 _cursor.v_wheel -=
static_cast<float>(deltaY *
_settings_client.gui.scrollwheel_multiplier);
817 _cursor.wheel_moved =
true;
824- (void)magnifyWithEvent:(NSEvent *)event
827 self->_current_magnification += [
event magnification ] * 5.0f;
829 while (self->_current_magnification >= 1.0f) {
830 self->_current_magnification -= 1.0f;
834 while (self->_current_magnification <= -1.0f) {
835 self->_current_magnification += 1.0f;
845- (void)endGestureWithEvent:(NSEvent *)event
848 self->_current_magnification = 0.0f;
860- (BOOL)internalHandleKeycode:(
unsigned short)keycode unicode:(
char32_t)unicode pressed:(BOOL)down modifiers:(NSUInteger)modifiers
877 if (down && (modifiers & NSEventModifierFlagCommand)) {
883 if (down &&
EditBoxInGlobalFocus() && (modifiers & (NSEventModifierFlagCommand | NSEventModifierFlagControl))) {
888 if (down &&
EditBoxInGlobalFocus() && (modifiers & (NSEventModifierFlagCommand | NSEventModifierFlagControl))) {
894 BOOL interpret_keys = YES;
897 auto vk = std::ranges::find(_vk_mapping, keycode, &CocoaVkMapping::vk_from);
898 uint32_t pressed_key = vk != std::end(_vk_mapping) ? vk->map_to : 0;
900 if (modifiers & NSEventModifierFlagShift) pressed_key |= WKC_SHIFT;
901 if (modifiers & NSEventModifierFlagControl) pressed_key |= (
_settings_client.gui.right_mouse_btn_emulation != RMBE_CONTROL ? WKC_CTRL : WKC_META);
902 if (modifiers & NSEventModifierFlagOption) pressed_key |= WKC_ALT;
903 if (modifiers & NSEventModifierFlagCommand) pressed_key |= (
_settings_client.gui.right_mouse_btn_emulation != RMBE_CONTROL ? WKC_META : WKC_CTRL);
905 static bool console =
false;
908 if (pressed_key == WKC_BACKQUOTE && (console || unicode == 0)) {
929 return interpret_keys;
936- (void)keyDown:(NSEvent *)event
939 switch (event.keyCode) {
943 if (event.modifierFlags & NSEventModifierFlagCommand) {
944 [
self interpretKeyEvents:[
NSArray arrayWithObject:event ] ];
950 std::vector<char32_t> unicode_str =
NSStringToUTF32([ event characters ]);
951 if (unicode_str.empty()) unicode_str.push_back(0);
954 if ([ self internalHandleKeycode:event.keyCode unicode:unicode_str[0] pressed:YES modifiers:event.modifierFlags ]) {
955 [
self interpretKeyEvents:[
NSArray arrayWithObject:event ] ];
959 for (
size_t i = 1; i < unicode_str.size(); i++) {
969- (void)keyUp:(NSEvent *)event
972 switch (event.keyCode) {
976 if (event.modifierFlags & NSEventModifierFlagCommand) {
977 [
self interpretKeyEvents:[
NSArray arrayWithObject:event ] ];
983 std::vector<char32_t> unicode_str =
NSStringToUTF32([ event characters ]);
984 if (unicode_str.empty()) unicode_str.push_back(0);
993- (void)flagsChanged:(NSEvent *)event
995 const int mapping[] = { QZ_CAPSLOCK, QZ_LSHIFT, QZ_LCTRL, QZ_LALT, QZ_LMETA };
997 NSUInteger newMods =
event.modifierFlags;
998 if (self->_current_mods == newMods)
return;
1001 for (
unsigned int i = 0, bit = NSEventModifierFlagCapsLock; bit <= NSEventModifierFlagCommand; bit <<= 1, ++i) {
1002 unsigned int currentMask, newMask;
1004 currentMask = self->_current_mods & bit;
1005 newMask = newMods & bit;
1007 if (currentMask && currentMask != newMask) {
1009 }
else if (newMask && currentMask != newMask) {
1023- (void)insertText:(
id)aString replacementRange:(NSRange)replacementRange
1029 std::optional<size_t> insert_point;
1030 std::optional<size_t> replace_range;
1031 if (replacementRange.location != NSNotFound) {
1033 std::string_view focused_text{
_focused_window->GetFocusedTextbuf()->GetText()};
1035 replace_range = *insert_point +
Utf8AdvanceByUtf16Units(focused_text.substr(*insert_point), replacementRange.length);
1039 HandleTextInput([ s UTF8String ],
false, std::nullopt, insert_point, replace_range);
1046- (void)insertText:(
id)aString
1057- (void)setMarkedText:(
id)aString selectedRange:(NSRange)selRange replacementRange:(NSRange)replacementRange
1063 const char *utf8 = [
s UTF8String ];
1064 if (utf8 !=
nullptr) {
1065 std::optional<size_t> insert_point;
1066 std::optional<size_t> replace_range;
1067 if (replacementRange.location != NSNotFound) {
1070 std::string_view focused_text{
_focused_window->GetFocusedTextbuf()->GetText()};
1071 insert_point =
Utf8AdvanceByUtf16Units(focused_text, replacementRange.location + (marked.location != NSNotFound ? marked.location : 0u));
1072 replace_range = *insert_point +
Utf8AdvanceByUtf16Units(focused_text.substr(*insert_point), replacementRange.length);
1087- (void)setMarkedText:(
id)aString selectedRange:(NSRange)selRange
1107 std::string_view text = text_buf->
GetText();
1109 return NSMakeRange(start, 0);
1122 std::string_view text = text_buf->
GetText();
1126 return NSMakeRange(start, len);
1129 return NSMakeRange(NSNotFound, 0);
1149- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1154 NSString *s = [ [
NSString alloc] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding ];
1155 NSRange valid_range = NSIntersectionRange(NSMakeRange(0, [ s length ]), theRange);
1157 if (actualRange !=
nullptr) *actualRange = valid_range;
1158 if (valid_range.length == 0)
return nil;
1160 return [ [ [
NSAttributedString alloc ] initWithString:[
s substringWithRange:valid_range ] ] autorelease ];
1168- (NSAttributedString *)attributedSubstringFromRange:(NSRange)theRange
1182 return [ [ [
NSAttributedString alloc ] initWithString:[ [
NSString alloc ] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding ] ] autorelease ];
1190- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1194 NSPoint view_pt = [
self convertRect:[ [
self window ] convertRectFromScreen:NSMakeRect(thePoint.x, thePoint.y, 0, 0) ] fromView:nil ].origin;
1196 Point pt = { (int)view_pt.x, (
int)[
self frame ].size.height - (int)view_pt.y };
1199 if (index == -1)
return NSNotFound;
1210- (NSRect)firstRectForCharacterRange:(NSRange)aRange
1214 std::string_view focused_text =
_focused_window->GetFocusedTextbuf()->GetText();
1221 NSRect view_rect = NSMakeRect(
_focused_window->left + r.left, [ self frame ].size.height -
_focused_window->top - r.bottom, r.right - r.left, r.bottom - r.top);
1223 return [ [
self window ] convertRectToScreen:[
self convertRect:view_rect toView:nil ] ];
1232- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
1250- (void)deleteBackward:(
id)sender
1259- (void)deleteWordBackward:(
id)sender
1268- (void)deleteForward:(
id)sender
1277- (void)deleteWordForward:(
id)sender
1286- (void)moveLeft:(
id)sender
1295- (void)moveWordLeft:(
id)sender
1304- (void)moveRight:(
id)sender
1313- (void)moveWordRight:(
id)sender
1322- (void)moveUp:(
id)sender
1331- (void)moveDown:(
id)sender
1340- (void)moveUpAndModifySelection:(
id)sender
1349- (void)moveDownAndModifySelection:(
id)sender
1358- (void)moveToBeginningOfLine:(
id)sender
1367- (void)moveToEndOfLine:(
id)sender
1376- (void)scrollPageUp:(
id)sender
1385- (void)scrollPageDown:(
id)sender
1394- (void)pageUpAndModifySelection:(
id)sender
1403- (void)pageDownAndModifySelection:(
id)sender
1412- (void)scrollToBeginningOfDocument:(
id)sender
1422- (void)scrollToEndOfDocument:(
id)sender
1432- (void)insertNewline:(
id)sender
1441- (void)cancelOperation:(
id)sender
1450- (void)doCommandBySelector:(
SEL)aSelector
1452 if ([ self respondsToSelector:aSelector ]) [
self performSelector:aSelector ];
1469 if (self = [ super init ]) {
1479- (BOOL)windowShouldClose:(
id)sender
1481 HandleExitGameRequest();
1489- (void)windowDidEnterFullScreen:(NSNotification *)aNotification
1491 NSPoint loc = [
driver->cocoaview convertPoint:[ [
aNotification object ] mouseLocationOutsideOfEventStream ] fromView:nil ];
1492 BOOL inside = ([
driver->cocoaview hitTest:loc ] == driver->cocoaview);
1496 NSEvent *e = [ [
NSEvent alloc ] init ];
1497 [
driver->cocoaview mouseEntered:e ];
1505- (void)windowDidChangeBackingProperties:(NSNotification *)notification
1510 driver->AllocateBackingStore();
1521- (NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions
1523 return NSApplicationPresentationFullScreen | NSApplicationPresentationHideMenuBar | NSApplicationPresentationHideDock;
virtual void Stop()=0
Stop this driver.
Constant span of UTF-8 encoded data.
virtual void AllocateBackingStore(bool force=false)=0
Resize the window.
void MainLoopReal()
Main game loop.
virtual bool ToggleFullscreen(bool fullscreen)=0
Change the full screen setting.
static std::string GetCaption()
Get the caption to use for the game's title bar.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
bool _cocoa_video_started
Is the Cocoa video driver running.
bool _tab_is_down
Is tab button pressed.
OS interface for the cocoa video driver.
bool _allow_hidpi_window
Storage for allow_hidpi setting. If true renders OTTD in native resolution.
NSString * OTTDMainLaunchGameEngine
Name of notification observer used to restart the game loop if necessary.
static bool _cocoa_video_dialog
True iff inside the scope of CocoaDialog method.
static NSImage * NSImageFromSprite(SpriteID sprite_id, ZoomLevel zoom)
Render an OTTD sprite to a Cocoa image.
bool _emulated_down
Whether the mouse button is emulated or real.
bool touchbar_created
Whether the touchbar exists.
static void setupWindowMenu()
Create a window menu.
void CocoaDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
Catch asserts prior to initialization of the videodriver.
bool _use_hidpi
Render content in native resolution?
static const std::array< TouchBarButton, 9 > _touchbar_buttons
Storage of defined touch bar buttons.
static NSUInteger CountUtf16Units(std::string_view str)
Count the number of UTF-16 code points in a range of an UTF-8 string.
static size_t Utf8AdvanceByUtf16Units(std::string_view str, NSUInteger count)
Advance an UTF-8 string by a number of equivalent UTF-16 code points.
static void CGDataFreeCallback(void *, const void *data, size_t)
Free memory where data was stored.
static void setApplicationMenu()
Initialize the application menu shown in top bar.
static std::vector< char32_t > NSStringToUTF32(NSString *s)
Convert a NSString to an UTF-32 encoded string.
NSUInteger _current_mods
Currently applied modifier flags.
static OTTDMain * _ottd_main
App delegate instance of OTTDMain.
bool CocoaSetupApplication()
Startup the application.
void CocoaExitApplication()
Deregister app delegate.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Driver
Driver message facility.
@ Critical
Critical, user should know about this.
@ Start
Align to the start, LTR/RTL aware.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
ControlInputs _input_pressed
Control inputs that are currently pressed.
ControlInputs _input_clicked
Control inputs that have been actioned.
DirectionKeys _dirkeys
Pressed direction keys.
std::unique_ptr< uint32_t[]> DrawSpriteToRgbaBuffer(SpriteID spriteId, ZoomLevel zoom)
Draws a sprite to a new RGBA buffer (see Colour union) instead of drawing to the screen.
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Functions related to the gfx engine.
void HandleToolbarHotkey(int hotkey)
Handle Toolbar hotkey events - can come from a source like the MacBook Touch Bar.
void HandleMouseEvents()
Handle a mouse event from the video driver.
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
void HandleTextInput(std::string_view str, bool marked=false, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Handle text input.
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
ControlInput
Mouse control inputs and keyboard modifiers.
@ X2
X2 mouse button is pressed.
@ Right
Right mouse button is pressed.
@ Left
Left mouse button is pressed.
@ Middle
Middle mouse button is pressed.
@ X1
X1 mouse button is pressed.
The main class of the application, the application's delegate.
void unregisterObserver()
Remove ourself as a notification observer.
void stopEngine()
Stop the game engine.
Subclass of NSView to support mouse awareness and text input.
void unmarkText()
Unmark the current marked text.
NSRange selectedRange()
Get the caret position.
NSPoint mousePositionFromEvent:(NSEvent *e)
Return the mouse location.
void rightMouseDown:(NSEvent *event)
Handler of right mouse button pressing.
void setMarkedText:selectedRange:replacementRange:(id aString, [selectedRange] NSRange selRange, [replacementRange] NSRange replacementRange)
Set a new marked text and reposition the caret.
void internalMouseButtonEvent()
Internal handler of mouse buttons.
void moveToEndOfLine:(id sender)
Move cursor to the end of the line.
NSAttributedString * attributedString()
Get the current edit box string.
BOOL hasMarkedText()
Is any text marked?
void internalMouseMoveEvent:(NSEvent *event)
Internal handler of mouse movement.
BOOL internalHandleKeycode:unicode:pressed:modifiers:(unsigned short keycode, [unicode] char32_t unicode, [pressed] BOOL down, [modifiers] NSUInteger modifiers)
Internal handler of keyboard keys.
void moveToBeginningOfLine:(id sender)
Move cursor to the start of the line.
void rightMouseUp:(NSEvent *event)
Handler of right mouse button releasing.
BOOL acceptsFirstResponder()
Allow to handle events.
NSRect firstRectForCharacterRange:(NSRange aRange)
Get the bounding rect for the given range.
NSArray * validAttributesForMarkedText()
Get all string attributes that we can process for marked text.
NSRange markedRange()
Get the currently marked range.
void insertText:replacementRange:(id aString, [replacementRange] NSRange replacementRange)
Insert the given text at the given range.
NSAttributedString * attributedSubstringForProposedRange:actualRange:(NSRange theRange, [actualRange] NSRangePointer actualRange)
Get a string corresponding to the given range.
Delegate for our NSWindow to send ask for quit on close.
Subclass of NSWindow to cater our special needs.
Functions related to MacOS support.
std::unique_ptr< typename std::remove_pointer< T >::type, CFDeleter< typename std::remove_pointer< T >::type > > CFAutoRelease
Specialisation of std::unique_ptr for CoreFoundation objects.
Includes of mac os specific headers which contain objective c.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
@ Bootstrap
In the content bootstrap process.
ClientSettings _settings_client
The current settings for this game.
Types related to global configuration settings.
Functions to cache sprites in memory.
This file contains all sprite-related enums and defines.
static const SpriteID SPR_IMG_BUILDAIR
static const SpriteID SPR_IMG_BUILDWATER
static const SpriteID SPR_IMG_PAUSE
static const SpriteID SPR_IMG_BUILDTRAMS
static const SpriteID SPR_IMG_ZOOMIN
static const SpriteID SPR_IMG_ZOOMOUT
static const SpriteID SPR_IMG_FASTFORWARD
static const SpriteID SPR_IMG_BUILDROAD
static const SpriteID SPR_IMG_BUILDRAIL
Definition of base types and functions in a cross-platform compatible way.
Functions related to low-level strings.
char32_t Utf16DecodeSurrogate(uint lead, uint trail)
Convert an UTF-16 surrogate pair to the corresponding Unicode character.
bool Utf16IsLeadSurrogate(uint c)
Is the given character a lead surrogate code point?
bool Utf16IsTrailSurrogate(uint c)
Is the given character a lead surrogate code point?
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Specification of a rectangle with absolute coordinates of all edges.
Helper/buffer for input fields.
uint16_t caretpos
the current position of the caret in the buffer, in bytes
std::string_view GetText() const
Get the current text.
uint16_t markend
the end position of the marked area in the buffer, in bytes
uint16_t markpos
the start position of the marked area in the buffer, in bytes
Stuff related to text buffers.
Handling of UTF-8 encoded data.
Window * _focused_window
Window that currently has focus.
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
ZoomLevel
All zoom levels we know.