OpenTTD Source 20261112-master-gbcbec5e63f
cocoa_wnd.mm
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
19
20#if defined(WITH_COCOA) || defined(DOXYGEN_API)
21
22#include "../../stdafx.h"
24
26#include "../../openttd.h"
27#include "../../debug.h"
28#include "cocoa_v.h"
29#include "cocoa_wnd.h"
30#include "../../settings_type.h"
31#include "../../string_func.h"
32#include "../../gfx_func.h"
33#include "../../window_func.h"
34#include "../../window_gui.h"
35#include "../../spritecache.h"
36#include "../../textbuf_type.h"
37#include "../../toolbar_gui.h"
38#include "../../core/utf8.hpp"
39
40#include "../../table/sprites.h"
41
42/* Table data for key mapping. */
43#include "cocoa_keys.h"
44
47 NSTouchBarItemIdentifier key;
49 MainToolbarHotkeys hotkey;
50 NSString *fallback_text;
51};
52
57static const std::array<TouchBarButton, 9> _touchbar_buttons{{
58 { @"openttd.pause", SPR_IMG_PAUSE, MTHK_PAUSE, @"Pause" },
59 { @"openttd.fastforward", SPR_IMG_FASTFORWARD, MTHK_FASTFORWARD, @"Fast Forward" },
60 { @"openttd.zoom_in", SPR_IMG_ZOOMIN, MTHK_ZOOM_IN, @"Zoom In" },
61 { @"openttd.zoom_out", SPR_IMG_ZOOMOUT, MTHK_ZOOM_OUT, @"Zoom Out" },
62 { @"openttd.build_rail", SPR_IMG_BUILDRAIL, MTHK_BUILD_RAIL, @"Rail" },
63 { @"openttd.build_road", SPR_IMG_BUILDROAD, MTHK_BUILD_ROAD, @"Road" },
64 { @"openttd.build_tram", SPR_IMG_BUILDTRAMS, MTHK_BUILD_TRAM, @"Tram" },
65 { @"openttd.build_docks", SPR_IMG_BUILDWATER, MTHK_BUILD_DOCKS, @"Docks" },
66 { @"openttd.build_airport", SPR_IMG_BUILDAIR, MTHK_BUILD_AIRPORT, @"Airport" }
67}};
68
70
71@interface OTTDMain : NSObject <NSApplicationDelegate>
72@end
73
75NSString *OTTDMainLaunchGameEngine = @"ottdmain_launch_game_engine";
76
78
79static bool _cocoa_video_dialog = false;
81
82
88static NSUInteger CountUtf16Units(std::string_view str)
89{
90 NSUInteger i = 0;
91 for (char32_t c : Utf8View(str)) {
92 i += c < 0x10000 ? 1 : 2; // Watch for surrogate pairs.
93 }
94 return i;
95}
96
103static size_t Utf8AdvanceByUtf16Units(std::string_view str, NSUInteger count)
104{
105 Utf8View view(str);
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; // Watch for surrogate pairs.
110 }
111 return it.GetByteOffset();
112}
113
119static std::vector<char32_t> NSStringToUTF32(NSString *s)
120{
121 std::vector<char32_t> unicode_str;
122
123 unichar lead = 0;
124 for (NSUInteger i = 0; i < s.length; i++) {
125 unichar c = [ s characterAtIndex:i ];
126 if (Utf16IsLeadSurrogate(c)) {
127 lead = c;
128 continue;
129 } else if (Utf16IsTrailSurrogate(c)) {
130 if (lead != 0) unicode_str.push_back(Utf16DecodeSurrogate(lead, c));
131 } else {
132 unicode_str.push_back(c);
133 }
134 }
135
136 return unicode_str;
137}
138
143static void CGDataFreeCallback(void *, const void *data, size_t)
144{
145 delete[] (const uint32_t *)data;
146}
147
154static NSImage *NSImageFromSprite(SpriteID sprite_id, ZoomLevel zoom)
155{
156 if (!SpriteExists(sprite_id)) return nullptr;
157
158 /* Fetch the sprite and create a new bitmap */
159 Dimension dim = GetSpriteSize(sprite_id, nullptr, zoom);
160 std::unique_ptr<uint32_t[]> buffer = DrawSpriteToRgbaBuffer(sprite_id, zoom);
161 if (!buffer) return nullptr; // Failed to blit sprite for some reason.
162
163 CFAutoRelease<CGDataProvider> data(CGDataProviderCreateWithData(nullptr, buffer.release(), dim.width * dim.height * 4, &CGDataFreeCallback));
164 if (!data) return nullptr;
165
166 CGBitmapInfo info = kCGImageAlphaFirst | kCGBitmapByteOrder32Host;
167 CFAutoRelease<CGColorSpaceRef> colour_space(CGColorSpaceCreateWithName(kCGColorSpaceSRGB));
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;
170
171 return [ [ [ NSImage alloc ] initWithCGImage:bitmap.get() size:NSZeroSize ] autorelease ];
172}
173
174
178@implementation OTTDMain
183{
184 [ NSApp stop:self ];
185
186 /* Send an empty event to return from the run loop. Without that, application is stuck waiting for an event. */
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 ];
190}
191
196- (void)launchGameEngine: (NSNotification*) note
197{
198 auto *drv = static_cast<VideoDriver_Cocoa *>(VideoDriver::GetInstance());
199
200 /* Hide the cursor to start with since the very first call to
201 * mouseEntered: won't */
202 if (_game_mode != GameMode::Bootstrap && _cursor.in_window) [ NSCursor hide ];
203
204 /* Hand off to main application code. */
205 drv->MainLoopReal();
206
207 /* We are done, thank you for playing. */
208 [ self performSelectorOnMainThread:@selector(stopEngine) withObject:nil waitUntilDone:FALSE ];
209}
210
215- (void) applicationDidFinishLaunching: (NSNotification*) note
216{
217 /* Add a notification observer so we can restart the game loop later on if necessary. */
218 [ [ NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(launchGameEngine:) name:OTTDMainLaunchGameEngine object:nil ];
219
220 /* Start game loop. */
221 [ [ NSNotificationCenter defaultCenter ] postNotificationName:OTTDMainLaunchGameEngine object:nil ];
222}
223
229- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*) sender
230{
231 HandleExitGameRequest();
232
233 return NSTerminateCancel;
234}
235
240{
241 [ [ NSNotificationCenter defaultCenter ] removeObserver:self ];
242}
243
253- (BOOL)applicationSupportsSecureRestorableState:(NSApplication*) sender
254{
255 return YES;
256}
257@end
258
263{
264 NSString *appName = @"OpenTTD";
265 NSMenu *appleMenu = [ [ NSMenu alloc ] initWithTitle:appName ];
266
267 /* Add menu items */
268 NSString *title = [ @"About " stringByAppendingString:appName ];
269 [ appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@"" ];
270
271 [ appleMenu addItem:[ NSMenuItem separatorItem ] ];
272
273 title = [ @"Hide " stringByAppendingString:appName ];
274 [ appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h" ];
275
276 NSMenuItem *menuItem = [ appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h" ];
277 [ menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand) ];
278
279 [ appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@"" ];
280
281 [ appleMenu addItem:[ NSMenuItem separatorItem ] ];
282
283 title = [ @"Quit " stringByAppendingString:appName ];
284 [ appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q" ];
285
286 /* Put menu into the menubar */
287 menuItem = [ [ NSMenuItem alloc ] initWithTitle:@"" action:nil keyEquivalent:@"" ];
288 [ menuItem setSubmenu:appleMenu ];
289 [ [ NSApp mainMenu ] addItem:menuItem ];
290
291 /* Tell the application object that this is now the application menu.
292 * This interesting Objective-C construct is used because not all SDK
293 * versions define this method publicly. */
294 if ([ NSApp respondsToSelector:@selector(setAppleMenu:) ]) {
295 [ NSApp performSelector:@selector(setAppleMenu:) withObject:appleMenu ];
296 }
297
298 /* Finally give up our references to the objects */
299 [ appleMenu release ];
300 [ menuItem release ];
301}
302
306static void setupWindowMenu()
307{
308 NSMenu *windowMenu = [ [ NSMenu alloc ] initWithTitle:@"Window" ];
309
310 /* "Minimize" item */
311 [ windowMenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m" ];
312
313 /* Put menu into the menubar */
314 NSMenuItem *menuItem = [ [ NSMenuItem alloc ] initWithTitle:@"Window" action:nil keyEquivalent:@"" ];
315 [ menuItem setSubmenu:windowMenu ];
316 [ [ NSApp mainMenu ] addItem:menuItem ];
317
318 /* The OS will change the name of this menu item automatically */
319 [ windowMenu addItemWithTitle:@"Fullscreen" action:@selector(toggleFullScreen:) keyEquivalent:@"^f" ];
320
321 /* Tell the application object that this is now the window menu */
322 [ NSApp setWindowsMenu:windowMenu ];
323
324 /* Finally give up our references to the objects */
325 [ windowMenu release ];
326 [ menuItem release ];
327}
328
334{
335 ProcessSerialNumber psn = { 0, kCurrentProcess };
336
337 /* Ensure the application object is initialised */
338 [ NSApplication sharedApplication ];
339
340 /* Tell the dock about us */
341 OSStatus returnCode = TransformProcessType(&psn, kProcessTransformToForegroundApplication);
342 if (returnCode != 0) Debug(Facility::Driver, Severity::Critical, "Could not change to foreground application. Error {}", (int)returnCode);
343
344 /* Disable the system-wide tab feature as we only have one window. */
345 if ([ NSWindow respondsToSelector:@selector(setAllowsAutomaticWindowTabbing:) ]) {
346 /* We use nil instead of NO as withObject requires an id. */
347 [ NSWindow performSelector:@selector(setAllowsAutomaticWindowTabbing:) withObject:nil];
348 }
349
350 /* Become the front process, important when start from the command line. */
351 [ [ NSApplication sharedApplication ] setActivationPolicy:NSApplicationActivationPolicyRegular ];
352 [ [ NSApplication sharedApplication ] activateIgnoringOtherApps:YES ];
353
354 /* Set up the menubar */
355 [ NSApp setMainMenu:[ [ NSMenu alloc ] init ] ];
358
359 /* Create OTTDMain and make it the app delegate */
360 _ottd_main = [ [ OTTDMain alloc ] init ];
361 [ NSApp setDelegate:_ottd_main ];
362
363 return true;
364}
365
370{
372 [ _ottd_main release ];
373}
374
384void CocoaDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
385{
386 _cocoa_video_dialog = true;
387
388 bool wasstarted = _cocoa_video_started;
389 if (VideoDriver::GetInstance() == nullptr) {
390 CocoaSetupApplication(); // Setup application before showing dialog
391 } else if (!_cocoa_video_started && VideoDriver::GetInstance()->Start({}).has_value()) {
392 fmt::print(stderr, "{}: {}\n", title, message);
393 return;
394 }
395
396 @autoreleasepool {
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 ] ];
402 [ alert runModal ];
403 [ alert release ];
404 }
405
406 if (!wasstarted && VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
407
408 _cocoa_video_dialog = false;
409}
410
411@implementation OTTD_CocoaWindow {
412 VideoDriver_Cocoa *driver;
414}
415
425- (instancetype)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask backing:(NSBackingStoreType)backingType defer:(BOOL)flag driver:(VideoDriver_Cocoa *)drv
426{
427 if (self = [ super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag ]) {
428 self->driver = drv;
429 self->touchbar_created = false;
430
431 [ self setContentMinSize:NSMakeSize(64.0f, 64.0f) ];
432
433 std::string caption = VideoDriver::GetCaption();
434 NSString *nsscaption = [ [ NSString alloc ] initWithBytes:caption.data() length:caption.size() encoding:NSUTF8StringEncoding ];
435 [ self setTitle:nsscaption ];
436 [ self setMiniwindowTitle:nsscaption ];
437 [ nsscaption release ];
438 }
439
440 return self;
441}
442
448- (void)setFrame:(NSRect)frameRect display:(BOOL)flag
449{
450 [ super setFrame:frameRect display:flag ];
451
452 driver->AllocateBackingStore();
453}
454
455- (void)touchBarButtonAction:(id)sender
456{
457 NSButton *btn = (NSButton *)sender;
458 if (auto item = std::ranges::find(_touchbar_buttons, (NSTouchBarItemIdentifier)btn.identifier, &TouchBarButton::key); item != _touchbar_buttons.end()) {
459 HandleToolbarHotkey(item->hotkey);
460 }
461}
462
463- (nullable NSTouchBar *)makeTouchBar
464{
465 /* Make button identifier array. */
466 NSMutableArray<NSTouchBarItemIdentifier> *button_ids = [ [ NSMutableArray alloc ] init ];
467 for (const auto &button : _touchbar_buttons) {
468 [ button_ids addObject:button.key ];
469 }
470 [ button_ids addObject:NSTouchBarItemIdentifierOtherItemsProxy ];
471
472 NSTouchBar *bar = [ [ NSTouchBar alloc ] init ];
473 bar.delegate = self;
474 bar.defaultItemIdentifiers = button_ids;
475 [ button_ids release ];
476
477 self->touchbar_created = true;
478
479 return bar;
480}
481
482- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier
483{
484 auto item = std::ranges::find(_touchbar_buttons, identifier, &TouchBarButton::key);
485 assert(item != _touchbar_buttons.end());
486
487 NSButton *button = [ NSButton buttonWithTitle:item->fallback_text target:self action:@selector(touchBarButtonAction:) ];
488 button.identifier = identifier;
489 button.imageScaling = NSImageScaleProportionallyDown;
490
491 NSCustomTouchBarItem *tb_item = [ [ NSCustomTouchBarItem alloc] initWithIdentifier:identifier ];
492 tb_item.view = button;
493 return tb_item;
494}
495
496- (void)refreshSystemSprites
497{
498 if (!self->touchbar_created || ![ self respondsToSelector:@selector(touchBar) ] || self.touchBar == nil) return;
499
500 /* Re-create button images from OTTD sprites. */
501 for (NSTouchBarItemIdentifier ident in self.touchBar.itemIdentifiers) {
502 auto item = std::ranges::find(_touchbar_buttons, ident, &TouchBarButton::key);
503 if (item == _touchbar_buttons.end()) continue;
504
505 NSCustomTouchBarItem *tb_item = [ self.touchBar itemForIdentifier:ident ];
506 NSButton *button = tb_item.view;
507
508 NSImage *image = NSImageFromSprite(item->sprite, _settings_client.gui.zoom_min);
509 if (image != nil) {
510 /* Human Interface Guidelines: Maximum touch bar glyph size 22 pt. */
511 CGFloat max_dim = std::max(image.size.width, image.size.height);
512 if (max_dim > 0.0) {
513 CGFloat scale = 22.0 / max_dim;
514 image.size = NSMakeSize(image.size.width * scale, image.size.height * scale);
515 }
516
517 button.image = image;
518 button.imagePosition = NSImageOnly;
519 } else {
520 button.image = nil;
521 button.imagePosition = NSNoImage;
522 }
523 }
524}
525
526@end
527
528@implementation OTTD_CocoaView {
529 float _current_magnification;
530 NSUInteger _current_mods;
533}
534
535- (instancetype)initWithFrame:(NSRect)frameRect
536{
537 if (self = [ super initWithFrame:frameRect ]) {
538 self->_use_hidpi = _allow_hidpi_window && [ self respondsToSelector:@selector(convertRectToBacking:) ] && [ self respondsToSelector:@selector(convertRectFromBacking:) ];
539 }
540 return self;
541}
542
543- (NSRect)getRealRect:(NSRect)rect
544{
545 return _use_hidpi ? [ self convertRectToBacking:rect ] : rect;
546}
547
548- (NSRect)getVirtualRect:(NSRect)rect
549{
550 return _use_hidpi ? [ self convertRectFromBacking:rect ] : rect;
551}
552
553- (CGFloat)getContentsScale
554{
555 return _use_hidpi && self.window != nil ? [ self.window backingScaleFactor ] : 1.0f;
556}
557
563{
564 return YES;
565}
566
567- (void)setNeedsDisplayInRect:(NSRect)invalidRect
568{
569 /* Drawing is handled by our sub-views. Just pass it along. */
570 for ( NSView *v in [ self subviews ]) {
571 [ v setNeedsDisplayInRect:[ v convertRect:invalidRect fromView:self ] ];
572 }
573}
574
575- (void)viewWillMoveToWindow:(NSWindow *)win
576{
577 for (NSTrackingArea *a in [ self trackingAreas ]) {
578 [ self removeTrackingArea:a ];
579 }
580}
581
582- (void)viewDidMoveToWindow
583{
584 /* Install mouse tracking area. */
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 ];
588 [ track release ];
589}
594- (void)mouseEntered:(NSEvent *)theEvent
595{
596 if (_game_mode != GameMode::Bootstrap && !_cursor.in_window) {
597 [ NSCursor hide ];
598 }
599 _cursor.in_window = true;
600}
601
605- (void)mouseExited:(NSEvent *)theEvent
606{
607 if ([ self window ] != nil) UndrawMouseCursor();
608
609 /* We can't unconditionally call unhide as the hide/unhide calls
610 * should be balanced. */
611 if (_game_mode != GameMode::Bootstrap && _cursor.in_window) {
612 [ NSCursor unhide ];
613 }
614 _cursor.in_window = false;
615}
616
622- (NSPoint)mousePositionFromEvent:(NSEvent *)e
623{
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 ];
627
628 return [ self getRealRect:NSMakeRect(pt.x, self.bounds.size.height - pt.y, 0, 0) ].origin;
629}
630
635- (void)internalMouseMoveEvent:(NSEvent *)event
636{
637 if (_cursor.fix_at) {
638 _cursor.UpdateCursorPositionRelative(event.deltaX * self.getContentsScale, event.deltaY * self.getContentsScale);
639 } else {
640 NSPoint pt = [ self mousePositionFromEvent:event ];
641 _cursor.UpdateCursorPosition(pt.x, pt.y);
642 }
643
645}
646
651{
652 bool cur_fix = _cursor.fix_at;
654
655 /* Cursor fix mode was changed, synchronize with OS. */
656 if (cur_fix != _cursor.fix_at) CGAssociateMouseAndMouseCursorPosition(!_cursor.fix_at);
657}
658
664- (BOOL)emulateRightButton:(NSEvent *)event
665{
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;
669
670 return (event.modifierFlags & keymask) != 0;
671}
672
677- (void)mouseMoved:(NSEvent *)event
678{
679 [ self internalMouseMoveEvent:event ];
680}
681
686- (void)mouseDragged:(NSEvent *)event
687{
688 [ self internalMouseMoveEvent:event ];
689}
690
695- (void)mouseDown:(NSEvent *)event
696{
697 if ([ self emulateRightButton:event ]) {
698 self->_emulated_down = true;
699 [ self rightMouseDown:event ];
700 } else {
703 }
704}
705
710- (void)mouseUp:(NSEvent *)event
711{
712 if (self->_emulated_down) {
713 self->_emulated_down = false;
714 [ self rightMouseUp:event ];
715 } else {
719 }
720}
721
726- (void)rightMouseDragged:(NSEvent *)event
727{
728 [ self internalMouseMoveEvent:event ];
729}
730
735- (void)rightMouseDown:(NSEvent *)event
736{
740}
741
746- (void)rightMouseUp:(NSEvent *)event
747{
750}
751
756- (void)otherMouseDown:(NSEvent *)event
757{
758 ControlInput ci;
759 switch ([ event buttonNumber ]) {
760 case 2: ci = ControlInput::Middle; break;
761 case 3: ci = ControlInput::X1; break;
762 case 4: ci = ControlInput::X2; break;
763 default: return;
764 }
765 _input_pressed.Set(ci);
766 _input_clicked.Set(ci);
768}
769
774- (void)otherMouseUp:(NSEvent *)event
775{
776 ControlInput ci;
777 switch ([ event buttonNumber ]) {
778 case 2: ci = ControlInput::Middle; break;
779 case 3: ci = ControlInput::X1; break;
780 case 4: ci = ControlInput::X2; break;
781 default: return;
782 }
783 _input_pressed.Reset(ci);
785}
786
791- (void)scrollWheel:(NSEvent *)event
792{
793 if ([ event deltaY ] > 0.0) { /* Scroll up */
794 _cursor.wheel--;
795 } else if ([ event deltaY ] < 0.0) { /* Scroll down */
796 _cursor.wheel++;
797 } /* else: deltaY was 0.0 and we don't want to do anything */
798
799 /* Update the scroll count for 2D scrolling */
800 CGFloat deltaX;
801 CGFloat deltaY;
802
803 /* Use precise scrolling-specific deltas if they're supported. */
804 if ([ event respondsToSelector:@selector(hasPreciseScrollingDeltas) ]) {
805 /* No precise deltas indicates a scroll wheel is being used, so we don't want 2D scrolling. */
806 if (![ event hasPreciseScrollingDeltas ]) return;
807
808 deltaX = [ event scrollingDeltaX ] * 0.5f;
809 deltaY = [ event scrollingDeltaY ] * 0.5f;
810 } else {
811 deltaX = [ event deltaX ] * 5;
812 deltaY = [ event deltaY ] * 5;
813 }
814
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;
818}
819
824- (void)magnifyWithEvent:(NSEvent *)event
825{
826 /* Pinch open or close gesture. */
827 self->_current_magnification += [ event magnification ] * 5.0f;
828
829 while (self->_current_magnification >= 1.0f) {
830 self->_current_magnification -= 1.0f;
831 _cursor.wheel--;
833 }
834 while (self->_current_magnification <= -1.0f) {
835 self->_current_magnification += 1.0f;
836 _cursor.wheel++;
838 }
839}
840
845- (void)endGestureWithEvent:(NSEvent *)event
846{
847 /* Gesture ended. */
848 self->_current_magnification = 0.0f;
849}
850
851
860- (BOOL)internalHandleKeycode:(unsigned short)keycode unicode:(char32_t)unicode pressed:(BOOL)down modifiers:(NSUInteger)modifiers
861{
862 switch (keycode) {
863 case QZ_UP: _dirkeys.Set(DirectionKey::Up, down); break;
864 case QZ_DOWN: _dirkeys.Set(DirectionKey::Down, down); break;
865 case QZ_LEFT: _dirkeys.Set(DirectionKey::Left, down); break;
866 case QZ_RIGHT: _dirkeys.Set(DirectionKey::Right, down); break;
867
868 case QZ_TAB:
869 _tab_is_down = down;
870 if (down && EditBoxInGlobalFocus()) {
871 HandleKeypress(WKC_TAB, unicode);
872 }
873 break;
874
875 case QZ_RETURN:
876 case QZ_f:
877 if (down && (modifiers & NSEventModifierFlagCommand)) {
879 }
880 break;
881
882 case QZ_v:
883 if (down && EditBoxInGlobalFocus() && (modifiers & (NSEventModifierFlagCommand | NSEventModifierFlagControl))) {
884 HandleKeypress(WKC_CTRL | 'V', unicode);
885 }
886 break;
887 case QZ_u:
888 if (down && EditBoxInGlobalFocus() && (modifiers & (NSEventModifierFlagCommand | NSEventModifierFlagControl))) {
889 HandleKeypress(WKC_CTRL | 'U', unicode);
890 }
891 break;
892 }
893
894 BOOL interpret_keys = YES;
895 if (down) {
896 /* Map keycode to OTTD code. */
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;
899
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);
904
905 static bool console = false;
906
907 /* The second backquote may have a character, which we don't want to interpret. */
908 if (pressed_key == WKC_BACKQUOTE && (console || unicode == 0)) {
909 if (!console) {
910 /* Backquote is a dead key, require a double press for hotkey behaviour (i.e. console). */
911 console = true;
912 return YES;
913 } else {
914 /* Second backquote, don't interpret as text input. */
915 interpret_keys = NO;
916 }
917 }
918 console = false;
919
920 /* Don't handle normal characters if an edit box has the focus. */
921 if (!EditBoxInGlobalFocus() || IsInsideMM(pressed_key & ~WKC_SPECIAL_KEYS, WKC_F1, WKC_PAUSE + 1)) {
922 HandleKeypress(pressed_key, unicode);
923 }
924 Debug(Facility::Driver, Severity::Notice, "cocoa_v: QZ_KeyEvent: {:x} ({:x}), down, mapping: {:x}", keycode, (int)unicode, pressed_key);
925 } else {
926 Debug(Facility::Driver, Severity::Notice, "cocoa_v: QZ_KeyEvent: {:x} ({:x}), up", keycode, (int)unicode);
927 }
928
929 return interpret_keys;
930}
931
936- (void)keyDown:(NSEvent *)event
937{
938 /* Quit, hide and minimize */
939 switch (event.keyCode) {
940 case QZ_q:
941 case QZ_h:
942 case QZ_m:
943 if (event.modifierFlags & NSEventModifierFlagCommand) {
944 [ self interpretKeyEvents:[ NSArray arrayWithObject:event ] ];
945 }
946 break;
947 }
948
949 /* Convert UTF-16 characters to UCS-4 chars. */
950 std::vector<char32_t> unicode_str = NSStringToUTF32([ event characters ]);
951 if (unicode_str.empty()) unicode_str.push_back(0);
952
953 if (EditBoxInGlobalFocus()) {
954 if ([ self internalHandleKeycode:event.keyCode unicode:unicode_str[0] pressed:YES modifiers:event.modifierFlags ]) {
955 [ self interpretKeyEvents:[ NSArray arrayWithObject:event ] ];
956 }
957 } else {
958 [ self internalHandleKeycode:event.keyCode unicode:unicode_str[0] pressed:YES modifiers:event.modifierFlags ];
959 for (size_t i = 1; i < unicode_str.size(); i++) {
960 [ self internalHandleKeycode:0 unicode:unicode_str[i] pressed:YES modifiers:event.modifierFlags ];
961 }
962 }
963}
964
969- (void)keyUp:(NSEvent *)event
970{
971 /* Quit, hide and minimize */
972 switch (event.keyCode) {
973 case QZ_q:
974 case QZ_h:
975 case QZ_m:
976 if (event.modifierFlags & NSEventModifierFlagCommand) {
977 [ self interpretKeyEvents:[ NSArray arrayWithObject:event ] ];
978 }
979 break;
980 }
981
982 /* Convert UTF-16 characters to UCS-4 chars. */
983 std::vector<char32_t> unicode_str = NSStringToUTF32([ event characters ]);
984 if (unicode_str.empty()) unicode_str.push_back(0);
985
986 [ self internalHandleKeycode:event.keyCode unicode:unicode_str[0] pressed:NO modifiers:event.modifierFlags ];
987}
988
993- (void)flagsChanged:(NSEvent *)event
994{
995 const int mapping[] = { QZ_CAPSLOCK, QZ_LSHIFT, QZ_LCTRL, QZ_LALT, QZ_LMETA };
996
997 NSUInteger newMods = event.modifierFlags;
998 if (self->_current_mods == newMods) return;
999
1000 /* Iterate through the bits, testing each against the current modifiers */
1001 for (unsigned int i = 0, bit = NSEventModifierFlagCapsLock; bit <= NSEventModifierFlagCommand; bit <<= 1, ++i) {
1002 unsigned int currentMask, newMask;
1003
1004 currentMask = self->_current_mods & bit;
1005 newMask = newMods & bit;
1006
1007 if (currentMask && currentMask != newMask) { // modifier up event
1008 [ self internalHandleKeycode:mapping[i] unicode:0 pressed:NO modifiers:newMods ];
1009 } else if (newMask && currentMask != newMask) { // modifier down event
1010 [ self internalHandleKeycode:mapping[i] unicode:0 pressed:YES modifiers:newMods ];
1011 }
1012 }
1013
1014 _current_mods = newMods;
1015}
1016
1017
1023- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
1024{
1025 if (!EditBoxInGlobalFocus()) return;
1026
1027 NSString *s = [ aString isKindOfClass:[ NSAttributedString class ] ] ? [ aString string ] : (NSString *)aString;
1028
1029 std::optional<size_t> insert_point;
1030 std::optional<size_t> replace_range;
1031 if (replacementRange.location != NSNotFound) {
1032 /* Calculate the part to be replaced. */
1033 std::string_view focused_text{_focused_window->GetFocusedTextbuf()->GetText()};
1034 insert_point = Utf8AdvanceByUtf16Units(focused_text, replacementRange.location);
1035 replace_range = *insert_point + Utf8AdvanceByUtf16Units(focused_text.substr(*insert_point), replacementRange.length);
1036 }
1037
1038 HandleTextInput({}, true);
1039 HandleTextInput([ s UTF8String ], false, std::nullopt, insert_point, replace_range);
1040}
1041
1046- (void)insertText:(id)aString
1047{
1048 [ self insertText:aString replacementRange:NSMakeRange(NSNotFound, 0) ];
1049}
1050
1057- (void)setMarkedText:(id)aString selectedRange:(NSRange)selRange replacementRange:(NSRange)replacementRange
1058{
1059 if (!EditBoxInGlobalFocus()) return;
1060
1061 NSString *s = [ aString isKindOfClass:[ NSAttributedString class ] ] ? [ aString string ] : (NSString *)aString;
1062
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) {
1068 /* Calculate the part to be replaced. */
1069 NSRange marked = [ self markedRange ];
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);
1073 }
1074
1075 /* Convert caret index into a pointer in the UTF-8 string. */
1076 size_t selection = Utf8AdvanceByUtf16Units(utf8, selRange.location);
1077
1078 HandleTextInput(utf8, true, selection, insert_point, replace_range);
1079 }
1080}
1081
1087- (void)setMarkedText:(id)aString selectedRange:(NSRange)selRange
1088{
1089 [ self setMarkedText:aString selectedRange:selRange replacementRange:NSMakeRange(NSNotFound, 0) ];
1090}
1091
1094{
1095 HandleTextInput({}, true);
1096}
1097
1103{
1104 if (!EditBoxInGlobalFocus()) return NSMakeRange(NSNotFound, 0);
1105
1106 const Textbuf *text_buf = _focused_window->GetFocusedTextbuf();
1107 std::string_view text = text_buf->GetText();
1108 NSUInteger start = CountUtf16Units(text.substr(0, text_buf->caretpos));
1109 return NSMakeRange(start, 0);
1110}
1111
1116- (NSRange)markedRange
1117{
1118 if (!EditBoxInGlobalFocus()) return NSMakeRange(NSNotFound, 0);
1119
1120 const Textbuf *text_buf = _focused_window->GetFocusedTextbuf();
1121 if (text_buf->markend != 0) {
1122 std::string_view text = text_buf->GetText();
1123 NSUInteger start = CountUtf16Units(text.substr(0, text_buf->markpos));
1124 NSUInteger len = CountUtf16Units(text.substr(text_buf->markpos, text_buf->markend - text_buf->markpos));
1125
1126 return NSMakeRange(start, len);
1127 }
1128
1129 return NSMakeRange(NSNotFound, 0);
1130}
1131
1137{
1138 if (!EditBoxInGlobalFocus()) return NO;
1139
1140 return _focused_window->GetFocusedTextbuf()->markend != 0;
1141}
1142
1149- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
1150{
1151 if (!EditBoxInGlobalFocus()) return nil;
1152
1153 auto text = _focused_window->GetFocusedTextbuf()->GetText();
1154 NSString *s = [ [ NSString alloc] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding ];
1155 NSRange valid_range = NSIntersectionRange(NSMakeRange(0, [ s length ]), theRange);
1156
1157 if (actualRange != nullptr) *actualRange = valid_range;
1158 if (valid_range.length == 0) return nil;
1159
1160 return [ [ [ NSAttributedString alloc ] initWithString:[ s substringWithRange:valid_range ] ] autorelease ];
1161}
1162
1168- (NSAttributedString *)attributedSubstringFromRange:(NSRange)theRange
1169{
1170 return [ self attributedSubstringForProposedRange:theRange actualRange:nil ];
1171}
1172
1177- (NSAttributedString *)attributedString
1178{
1179 if (!EditBoxInGlobalFocus()) return [ [ [ NSAttributedString alloc ] initWithString:@"" ] autorelease ];
1180
1181 auto text = _focused_window->GetFocusedTextbuf()->GetText();
1182 return [ [ [ NSAttributedString alloc ] initWithString:[ [ NSString alloc ] initWithBytes:text.data() length:text.size() encoding:NSUTF8StringEncoding ] ] autorelease ];
1183}
1184
1190- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1191{
1192 if (!EditBoxInGlobalFocus()) return NSNotFound;
1193
1194 NSPoint view_pt = [ self convertRect:[ [ self window ] convertRectFromScreen:NSMakeRect(thePoint.x, thePoint.y, 0, 0) ] fromView:nil ].origin;
1195
1196 Point pt = { (int)view_pt.x, (int)[ self frame ].size.height - (int)view_pt.y };
1197
1198 auto index = _focused_window->GetTextCharacterAtPosition(pt);
1199 if (index == -1) return NSNotFound;
1200
1201 auto text = _focused_window->GetFocusedTextbuf()->GetText();
1202 return CountUtf16Units(text.substr(0, index));
1203}
1204
1210- (NSRect)firstRectForCharacterRange:(NSRange)aRange
1211{
1212 if (!EditBoxInGlobalFocus()) return NSMakeRect(0, 0, 0, 0);
1213
1214 std::string_view focused_text = _focused_window->GetFocusedTextbuf()->GetText();
1215 /* Convert range to UTF-8 string pointers. */
1216 size_t start = Utf8AdvanceByUtf16Units(focused_text, aRange.location);
1217 size_t end = start + Utf8AdvanceByUtf16Units(focused_text.substr(start), aRange.length);
1218
1219 /* Get the bounding rect for the text range.*/
1220 Rect r = _focused_window->GetTextBoundingRect(start, end);
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);
1222
1223 return [ [ self window ] convertRectToScreen:[ self convertRect:view_rect toView:nil ] ];
1224}
1225
1232- (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
1233{
1234 return [ self firstRectForCharacterRange:aRange ];
1235}
1236
1242{
1243 return [ NSArray array ];
1244}
1245
1250- (void)deleteBackward:(id)sender
1251{
1252 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_BACKSPACE, 0);
1253}
1254
1259- (void)deleteWordBackward:(id)sender
1260{
1261 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_BACKSPACE | WKC_CTRL, 0);
1262}
1263
1268- (void)deleteForward:(id)sender
1269{
1270 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_DELETE, 0);
1271}
1272
1277- (void)deleteWordForward:(id)sender
1278{
1279 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_DELETE | WKC_CTRL, 0);
1280}
1281
1286- (void)moveLeft:(id)sender
1287{
1288 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_LEFT, 0);
1289}
1290
1295- (void)moveWordLeft:(id)sender
1296{
1297 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_LEFT | WKC_CTRL, 0);
1298}
1299
1304- (void)moveRight:(id)sender
1305{
1306 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_RIGHT, 0);
1307}
1308
1313- (void)moveWordRight:(id)sender
1314{
1315 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_RIGHT | WKC_CTRL, 0);
1316}
1317
1322- (void)moveUp:(id)sender
1323{
1324 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_UP, 0);
1325}
1326
1331- (void)moveDown:(id)sender
1332{
1333 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_DOWN, 0);
1334}
1335
1340- (void)moveUpAndModifySelection:(id)sender
1341{
1342 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_UP | WKC_SHIFT, 0);
1343}
1344
1349- (void)moveDownAndModifySelection:(id)sender
1350{
1351 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_DOWN | WKC_SHIFT, 0);
1352}
1353
1358- (void)moveToBeginningOfLine:(id)sender
1359{
1360 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_HOME, 0);
1361}
1362
1367- (void)moveToEndOfLine:(id)sender
1368{
1369 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_END, 0);
1370}
1371
1376- (void)scrollPageUp:(id)sender
1377{
1378 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_PAGEUP, 0);
1379}
1380
1385- (void)scrollPageDown:(id)sender
1386{
1387 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_PAGEDOWN, 0);
1388}
1389
1394- (void)pageUpAndModifySelection:(id)sender
1395{
1396 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_PAGEUP | WKC_SHIFT, 0);
1397}
1398
1403- (void)pageDownAndModifySelection:(id)sender
1404{
1405 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_PAGEDOWN | WKC_SHIFT, 0);
1406}
1407
1412- (void)scrollToBeginningOfDocument:(id)sender
1413{
1414 /* For compatibility with OTTD on Win/Linux. */
1415 [ self moveToBeginningOfLine:sender ];
1416}
1417
1422- (void)scrollToEndOfDocument:(id)sender
1423{
1424 /* For compatibility with OTTD on Win/Linux. */
1425 [ self moveToEndOfLine:sender ];
1426}
1427
1432- (void)insertNewline:(id)sender
1433{
1434 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_RETURN, '\r');
1435}
1436
1441- (void)cancelOperation:(id)sender
1442{
1443 if (EditBoxInGlobalFocus()) HandleKeypress(WKC_ESC, 0);
1444}
1445
1450- (void)doCommandBySelector:(SEL)aSelector
1451{
1452 if ([ self respondsToSelector:aSelector ]) [ self performSelector:aSelector ];
1453}
1454
1455@end
1456
1457
1458@implementation OTTD_CocoaWindowDelegate {
1459 VideoDriver_Cocoa *driver;
1460}
1461
1467- (instancetype)initWithDriver:(VideoDriver_Cocoa *)drv
1468{
1469 if (self = [ super init ]) {
1470 self->driver = drv;
1471 }
1472 return self;
1473}
1474
1479- (BOOL)windowShouldClose:(id)sender
1480{
1481 HandleExitGameRequest();
1482
1483 return NO;
1484}
1485
1489- (void)windowDidEnterFullScreen:(NSNotification *)aNotification
1490{
1491 NSPoint loc = [ driver->cocoaview convertPoint:[ [ aNotification object ] mouseLocationOutsideOfEventStream ] fromView:nil ];
1492 BOOL inside = ([ driver->cocoaview hitTest:loc ] == driver->cocoaview);
1493
1494 if (inside) {
1495 /* We don't care about the event, but the compiler does. */
1496 NSEvent *e = [ [ NSEvent alloc ] init ];
1497 [ driver->cocoaview mouseEntered:e ];
1498 [ e release ];
1499 }
1500}
1501
1505- (void)windowDidChangeBackingProperties:(NSNotification *)notification
1506{
1507 bool did_adjust = AdjustGUIZoom(true);
1508
1509 /* Reallocate screen buffer if necessary. */
1510 driver->AllocateBackingStore();
1511
1512 if (did_adjust) ReInitAllWindows(true);
1513}
1514
1521- (NSApplicationPresentationOptions)window:(NSWindow *)window willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)proposedOptions
1522{
1523 return NSApplicationPresentationFullScreen | NSApplicationPresentationHideMenuBar | NSApplicationPresentationHideDock;
1524}
1525
1526@end
1527
1528#endif /* WITH_COCOA or DOXYGEN_API */
virtual void Stop()=0
Stop this driver.
Constant span of UTF-8 encoded data.
Definition utf8.hpp:28
virtual void AllocateBackingStore(bool force=false)=0
Resize the window.
void MainLoopReal()
Main game loop.
Definition cocoa_v.mm:459
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.
Mappings of Cocoa keys.
The Cocoa video driver.
bool _cocoa_video_started
Is the Cocoa video driver running.
Definition cocoa_v.mm:44
bool _tab_is_down
Is tab button pressed.
Definition cocoa_wnd.mm:77
OS interface for the cocoa video driver.
bool _allow_hidpi_window
Storage for allow_hidpi setting. If true renders OTTD in native resolution.
Definition cocoa_wnd.mm:69
NSString * OTTDMainLaunchGameEngine
Name of notification observer used to restart the game loop if necessary.
Definition cocoa_wnd.mm:75
static bool _cocoa_video_dialog
True iff inside the scope of CocoaDialog method.
Definition cocoa_wnd.mm:79
static NSImage * NSImageFromSprite(SpriteID sprite_id, ZoomLevel zoom)
Render an OTTD sprite to a Cocoa image.
Definition cocoa_wnd.mm:154
bool _emulated_down
Whether the mouse button is emulated or real.
Definition cocoa_wnd.mm:531
bool touchbar_created
Whether the touchbar exists.
Definition cocoa_wnd.mm:413
static void setupWindowMenu()
Create a window menu.
Definition cocoa_wnd.mm:306
void CocoaDialog(std::string_view title, std::string_view message, std::string_view buttonLabel)
Catch asserts prior to initialization of the videodriver.
Definition cocoa_wnd.mm:384
bool _use_hidpi
Render content in native resolution?
Definition cocoa_wnd.mm:532
static const std::array< TouchBarButton, 9 > _touchbar_buttons
Storage of defined touch bar buttons.
Definition cocoa_wnd.mm:57
static NSUInteger CountUtf16Units(std::string_view str)
Count the number of UTF-16 code points in a range of an UTF-8 string.
Definition cocoa_wnd.mm:88
static size_t Utf8AdvanceByUtf16Units(std::string_view str, NSUInteger count)
Advance an UTF-8 string by a number of equivalent UTF-16 code points.
Definition cocoa_wnd.mm:103
static void CGDataFreeCallback(void *, const void *data, size_t)
Free memory where data was stored.
Definition cocoa_wnd.mm:143
static void setApplicationMenu()
Initialize the application menu shown in top bar.
Definition cocoa_wnd.mm:262
static std::vector< char32_t > NSStringToUTF32(NSString *s)
Convert a NSString to an UTF-32 encoded string.
Definition cocoa_wnd.mm:119
NSUInteger _current_mods
Currently applied modifier flags.
Definition cocoa_wnd.mm:530
static OTTDMain * _ottd_main
App delegate instance of OTTDMain.
Definition cocoa_wnd.mm:80
bool CocoaSetupApplication()
Startup the application.
Definition cocoa_wnd.mm:333
void CocoaExitApplication()
Deregister app delegate.
Definition cocoa_wnd.mm:369
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Driver
Driver message facility.
Definition debug_type.h:29
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Start
Align to the start, LTR/RTL aware.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
ControlInputs _input_pressed
Control inputs that are currently pressed.
Definition gfx.cpp:34
ControlInputs _input_clicked
Control inputs that have been actioned.
Definition gfx.cpp:35
DirectionKeys _dirkeys
Pressed direction keys.
Definition gfx.cpp:36
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.
Definition gfx.cpp:1189
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Definition gfx.cpp:1859
Functions related to the gfx engine.
void HandleToolbarHotkey(int hotkey)
Handle Toolbar hotkey events - can come from a source like the MacBook Touch Bar.
Definition window.cpp:2698
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:3032
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2715
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.
Definition window.cpp:2807
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
@ Down
Down.
Definition gfx_type.h:438
@ Right
Right.
Definition gfx_type.h:437
@ Left
Left.
Definition gfx_type.h:435
ControlInput
Mouse control inputs and keyboard modifiers.
Definition gfx_type.h:443
@ X2
X2 mouse button is pressed.
Definition gfx_type.h:448
@ Right
Right mouse button is pressed.
Definition gfx_type.h:445
@ Left
Left mouse button is pressed.
Definition gfx_type.h:444
@ Middle
Middle mouse button is pressed.
Definition gfx_type.h:446
@ X1
X1 mouse button is pressed.
Definition gfx_type.h:447
The main class of the application, the application's delegate.
Definition cocoa_wnd.mm:72
void unregisterObserver()
Remove ourself as a notification observer.
Definition cocoa_wnd.mm:239
void stopEngine()
Stop the game engine.
Definition cocoa_wnd.mm:182
Subclass of NSView to support mouse awareness and text input.
Definition cocoa_wnd.h:39
void unmarkText()
Unmark the current marked text.
NSRange selectedRange()
Get the caret position.
NSPoint mousePositionFromEvent:(NSEvent *e)
Return the mouse location.
Definition cocoa_wnd.mm:622
void rightMouseDown:(NSEvent *event)
Handler of right mouse button pressing.
Definition cocoa_wnd.mm:735
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.
Definition cocoa_wnd.mm:650
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.
Definition cocoa_wnd.mm:635
BOOL internalHandleKeycode:unicode:pressed:modifiers:(unsigned short keycode, [unicode] char32_t unicode, [pressed] BOOL down, [modifiers] NSUInteger modifiers)
Internal handler of keyboard keys.
Definition cocoa_wnd.mm:860
void moveToBeginningOfLine:(id sender)
Move cursor to the start of the line.
void rightMouseUp:(NSEvent *event)
Handler of right mouse button releasing.
Definition cocoa_wnd.mm:746
BOOL acceptsFirstResponder()
Allow to handle events.
Definition cocoa_wnd.mm:562
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.
Definition cocoa_wnd.h:47
Subclass of NSWindow to cater our special needs.
Definition cocoa_wnd.h:28
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.
Definition macos.h:34
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.
Some generic types.
@ Bootstrap
In the content bootstrap process.
Definition openttd.h:22
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
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
Definition sprites.h:1271
static const SpriteID SPR_IMG_BUILDWATER
Definition sprites.h:1270
static const SpriteID SPR_IMG_PAUSE
Definition sprites.h:1244
static const SpriteID SPR_IMG_BUILDTRAMS
Definition sprites.h:1269
static const SpriteID SPR_IMG_ZOOMIN
Definition sprites.h:1265
static const SpriteID SPR_IMG_ZOOMOUT
Definition sprites.h:1266
static const SpriteID SPR_IMG_FASTFORWARD
Definition sprites.h:1245
static const SpriteID SPR_IMG_BUILDROAD
Definition sprites.h:1268
static const SpriteID SPR_IMG_BUILDRAIL
Definition sprites.h:1267
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.
Definition string_func.h:82
bool Utf16IsLeadSurrogate(uint c)
Is the given character a lead surrogate code point?
Definition string_func.h:61
bool Utf16IsTrailSurrogate(uint c)
Is the given character a lead surrogate code point?
Definition string_func.h:71
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.
Definition textbuf.cpp:283
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
Structure to store information about single touch bar button.
Definition cocoa_wnd.mm:46
NSString * fallback_text
Text to use if sprite is unavailable.
Definition cocoa_wnd.mm:50
NSTouchBarItemIdentifier key
Unique identifier for this button.
Definition cocoa_wnd.mm:47
SpriteID sprite
Sprite to display on button.
Definition cocoa_wnd.mm:48
MainToolbarHotkeys hotkey
Index of widget that corresponds to this button.
Definition cocoa_wnd.mm:49
Stuff related to text buffers.
Stuff related to the (main) toolbar.
Handling of UTF-8 encoded data.
Window * _focused_window
Window that currently has focus.
Definition window.cpp:80
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3494
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
Definition window.cpp:456
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20