12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426 |
- #include "os_osx.h"
- #include "dir_access_osx.h"
- #include "drivers/gles3/rasterizer_gles3.h"
- #include "main/main.h"
- #include "os/keyboard.h"
- #include "print_string.h"
- #include "sem_osx.h"
- #include "servers/visual/visual_server_raster.h"
- #include "version_generated.gen.h"
- #include <mach-o/dyld.h>
- #include <Carbon/Carbon.h>
- #import <Cocoa/Cocoa.h>
- #include <IOKit/IOCFPlugIn.h>
- #include <IOKit/IOKitLib.h>
- #include <IOKit/hid/IOHIDKeys.h>
- #include <IOKit/hid/IOHIDLib.h>
- #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
- #include <os/log.h>
- #endif
- #include <dlfcn.h>
- #include <fcntl.h>
- #include <libproc.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <unistd.h>
- #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200
- #define NSEventMaskAny NSAnyEventMask
- #define NSEventTypeKeyDown NSKeyDown
- #define NSEventTypeKeyUp NSKeyUp
- #define NSEventModifierFlagShift NSShiftKeyMask
- #define NSEventModifierFlagCommand NSCommandKeyMask
- #define NSEventModifierFlagControl NSControlKeyMask
- #define NSEventModifierFlagOption NSAlternateKeyMask
- #define NSWindowStyleMaskTitled NSTitledWindowMask
- #define NSWindowStyleMaskResizable NSResizableWindowMask
- #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
- #define NSWindowStyleMaskClosable NSClosableWindowMask
- #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
- #endif
- static NSRect convertRectToBacking(NSRect contentRect) {
- return [OS_OSX::singleton->window_view convertRectToBacking:contentRect];
- }
- static void get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> state) {
- state->set_shift((p_osx_state & NSEventModifierFlagShift));
- state->set_control((p_osx_state & NSEventModifierFlagControl));
- state->set_alt((p_osx_state & NSEventModifierFlagOption));
- state->set_metakey((p_osx_state & NSEventModifierFlagCommand));
- }
- static void push_to_key_event_buffer(const OS_OSX::KeyEvent &p_event) {
- Vector<OS_OSX::KeyEvent> &buffer = OS_OSX::singleton->key_event_buffer;
- if (OS_OSX::singleton->key_event_pos >= buffer.size()) {
- buffer.resize(1 + OS_OSX::singleton->key_event_pos);
- }
- buffer[OS_OSX::singleton->key_event_pos++] = p_event;
- }
- static int mouse_x = 0;
- static int mouse_y = 0;
- static int prev_mouse_x = 0;
- static int prev_mouse_y = 0;
- static int button_mask = 0;
- static bool mouse_down_control = false;
- static Vector2 get_mouse_pos(NSEvent *event) {
- const NSRect contentRect = [OS_OSX::singleton->window_view frame];
- const NSPoint p = [event locationInWindow];
- mouse_x = p.x * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
- mouse_y = (contentRect.size.height - p.y) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
- return Vector2(mouse_x, mouse_y);
- }
- @interface GodotApplication : NSApplication
- @end
- @implementation GodotApplication
- - (void)sendEvent:(NSEvent *)event {
-
-
- if ([event type] == NSEventTypeKeyDown) {
- if (([event modifierFlags] & NSEventModifierFlagCommand) && [event keyCode] == 0x2f) {
- Ref<InputEventKey> k;
- k.instance();
- get_key_modifier_state([event modifierFlags], k);
- k->set_pressed(true);
- k->set_scancode(KEY_PERIOD);
- k->set_echo([event isARepeat]);
- OS_OSX::singleton->push_input(k);
- }
- }
-
-
-
- if ([event type] == NSEventTypeKeyUp && ([event modifierFlags] & NSEventModifierFlagCommand))
- [[self keyWindow] sendEvent:event];
- else
- [super sendEvent:event];
- }
- @end
- @interface GodotApplicationDelegate : NSObject
- - (void)forceUnbundledWindowActivationHackStep1;
- - (void)forceUnbundledWindowActivationHackStep2;
- - (void)forceUnbundledWindowActivationHackStep3;
- @end
- @implementation GodotApplicationDelegate
- - (void)forceUnbundledWindowActivationHackStep1 {
-
-
- for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"]) {
- [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
- break;
- }
- [self performSelector:@selector(forceUnbundledWindowActivationHackStep2) withObject:nil afterDelay:0.02];
- }
- - (void)forceUnbundledWindowActivationHackStep2 {
-
- ProcessSerialNumber psn = { 0, kCurrentProcess };
- (void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
- [self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
- }
- - (void)forceUnbundledWindowActivationHackStep3 {
-
- [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
- }
- - (void)applicationDidFinishLaunching:(NSNotification *)notice {
- NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
- if (nsappname == nil) {
-
- [self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
- }
- }
- - (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
-
- char *utfs = strdup([filename UTF8String]);
- OS_OSX::singleton->open_with_filename.parse_utf8(utfs);
- return YES;
- }
- - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
- return NSTerminateCancel;
- }
- - (void)applicationDidHide:(NSNotification *)notification {
-
- }
- - (void)applicationDidUnhide:(NSNotification *)notification {
-
- }
- - (void)applicationDidChangeScreenParameters:(NSNotification *)notification {
-
- }
- - (void)showAbout:(id)sender {
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
- }
- @end
- @interface GodotWindowDelegate : NSObject {
-
- }
- @end
- @implementation GodotWindowDelegate
- - (BOOL)windowShouldClose:(id)sender {
-
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
- return NO;
- }
- - (void)windowDidEnterFullScreen:(NSNotification *)notification {
- OS_OSX::singleton->zoomed = true;
- }
- - (void)windowDidExitFullScreen:(NSNotification *)notification {
- OS_OSX::singleton->zoomed = false;
- }
- - (void)windowDidChangeBackingProperties:(NSNotification *)notification {
- if (!OS_OSX::singleton)
- return;
- NSWindow *window = (NSWindow *)[notification object];
- CGFloat newBackingScaleFactor = [window backingScaleFactor];
- CGFloat oldBackingScaleFactor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
- [OS_OSX::singleton->window_view setWantsBestResolutionOpenGLSurface:YES];
- if (newBackingScaleFactor != oldBackingScaleFactor) {
-
- float newDisplayScale = OS_OSX::singleton->is_hidpi_allowed() ? newBackingScaleFactor : 1.0;
- const NSRect contentRect = [OS_OSX::singleton->window_view frame];
- const NSRect fbRect = contentRect;
- OS_OSX::singleton->window_size.width = fbRect.size.width * newDisplayScale;
- OS_OSX::singleton->window_size.height = fbRect.size.height * newDisplayScale;
-
- if (OS_OSX::singleton->main_loop) {
- [OS_OSX::singleton->context update];
-
- NSRect frame = [OS_OSX::singleton->window_object frame];
- [OS_OSX::singleton->window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, 1, 1) display:YES];
- [OS_OSX::singleton->window_object setFrame:frame display:YES];
- }
- }
- }
- - (void)windowDidResize:(NSNotification *)notification {
- [OS_OSX::singleton->context update];
- const NSRect contentRect = [OS_OSX::singleton->window_view frame];
- const NSRect fbRect = contentRect;
- float displayScale = OS_OSX::singleton->_display_scale();
- OS_OSX::singleton->window_size.width = fbRect.size.width * displayScale;
- OS_OSX::singleton->window_size.height = fbRect.size.height * displayScale;
- if (OS_OSX::singleton->main_loop) {
- Main::force_redraw();
-
- Main::iteration();
- }
-
- }
- - (void)windowDidMove:(NSNotification *)notification {
-
- }
- - (void)windowDidBecomeKey:(NSNotification *)notification {
-
-
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
- }
- - (void)windowDidResignKey:(NSNotification *)notification {
-
-
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
- }
- - (void)windowDidMiniaturize:(NSNotification *)notification {
- OS_OSX::singleton->wm_minimized(true);
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
- };
- - (void)windowDidDeminiaturize:(NSNotification *)notification {
- OS_OSX::singleton->wm_minimized(false);
- if (OS_OSX::singleton->get_main_loop())
- OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
- };
- @end
- @interface GodotContentView : NSView <NSTextInputClient> {
- NSTrackingArea *trackingArea;
- NSMutableAttributedString *markedText;
- bool imeMode;
- }
- - (void)cancelComposition;
- @end
- @implementation GodotContentView
- + (void)initialize {
- if (self == [GodotContentView class]) {
-
- }
- }
- - (id)init {
- self = [super init];
- trackingArea = nil;
- imeMode = false;
- [self updateTrackingAreas];
- [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
- markedText = [[NSMutableAttributedString alloc] init];
- return self;
- }
- - (void)dealloc {
- [trackingArea release];
- [markedText release];
- [super dealloc];
- }
- static const NSRange kEmptyRange = { NSNotFound, 0 };
- - (BOOL)hasMarkedText {
- return (markedText.length > 0);
- }
- - (NSRange)markedRange {
- return (markedText.length > 0) ? NSMakeRange(0, markedText.length - 1) : kEmptyRange;
- }
- - (NSRange)selectedRange {
- return kEmptyRange;
- }
- - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
- if ([aString isKindOfClass:[NSAttributedString class]]) {
- [markedText initWithAttributedString:aString];
- } else {
- [markedText initWithString:aString];
- }
- if (OS_OSX::singleton->im_callback) {
- imeMode = true;
- String ret;
- ret.parse_utf8([[markedText mutableString] UTF8String]);
- OS_OSX::singleton->im_callback(OS_OSX::singleton->im_target, ret, Point2(selectedRange.location, selectedRange.length));
- }
- }
- - (void)doCommandBySelector:(SEL)aSelector {
- if ([self respondsToSelector:aSelector])
- [self performSelector:aSelector];
- }
- - (void)unmarkText {
- imeMode = false;
- [[markedText mutableString] setString:@""];
- if (OS_OSX::singleton->im_callback)
- OS_OSX::singleton->im_callback(OS_OSX::singleton->im_target, "", Point2());
- }
- - (NSArray *)validAttributesForMarkedText {
- return [NSArray array];
- }
- - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
- return nil;
- }
- - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
- return 0;
- }
- - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
- const NSRect contentRect = [OS_OSX::singleton->window_view frame];
- float displayScale = OS_OSX::singleton->_display_scale();
- NSRect pointInWindowRect = NSMakeRect(OS_OSX::singleton->im_position.x / displayScale, contentRect.size.height - (OS_OSX::singleton->im_position.y / displayScale) - 1, 0, 0);
- NSPoint pointOnScreen = [[OS_OSX::singleton->window_view window] convertRectToScreen:pointInWindowRect].origin;
- return NSMakeRect(pointOnScreen.x, pointOnScreen.y, 0, 0);
- }
- - (void)cancelComposition {
- [self unmarkText];
- NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
- [currentInputContext discardMarkedText];
- }
- - (void)insertText:(id)aString {
- [self insertText:aString replacementRange:NSMakeRange(0, 0)];
- }
- - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
- NSEvent *event = [NSApp currentEvent];
- NSString *characters;
- if ([aString isKindOfClass:[NSAttributedString class]]) {
- characters = [aString string];
- } else {
- characters = (NSString *)aString;
- }
- NSUInteger i, length = [characters length];
- NSCharacterSet *ctrlChars = [NSCharacterSet controlCharacterSet];
- NSCharacterSet *wsnlChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
- if ([characters rangeOfCharacterFromSet:ctrlChars].length && [characters rangeOfCharacterFromSet:wsnlChars].length == 0) {
- NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
- [currentInputContext discardMarkedText];
- [self cancelComposition];
- return;
- }
- for (i = 0; i < length; i++) {
- const unichar codepoint = [characters characterAtIndex:i];
- if ((codepoint & 0xFF00) == 0xF700)
- continue;
- OS_OSX::KeyEvent ke;
- ke.osx_state = [event modifierFlags];
- ke.pressed = true;
- ke.echo = false;
- ke.scancode = 0;
- ke.unicode = codepoint;
- push_to_key_event_buffer(ke);
- }
- [self cancelComposition];
- }
- - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
- return NSDragOperationCopy;
- }
- - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
- return NSDragOperationCopy;
- }
- - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
- NSPasteboard *pboard = [sender draggingPasteboard];
- NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
- Vector<String> files;
- for (int i = 0; i < filenames.count; i++) {
- NSString *ns = [filenames objectAtIndex:i];
- char *utfs = strdup([ns UTF8String]);
- String ret;
- ret.parse_utf8(utfs);
- free(utfs);
- files.push_back(ret);
- }
- if (files.size()) {
- OS_OSX::singleton->main_loop->drop_files(files, 0);
- OS_OSX::singleton->move_window_to_foreground();
- }
- return NO;
- }
- - (BOOL)isOpaque {
- return YES;
- }
- - (BOOL)canBecomeKeyView {
- return YES;
- }
- - (BOOL)acceptsFirstResponder {
- return YES;
- }
- - (void)cursorUpdate:(NSEvent *)event {
- OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
- OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
- OS_OSX::singleton->set_cursor_shape(p_shape);
- }
- static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) {
- if (pressed) {
- button_mask |= mask;
- } else {
- button_mask &= ~mask;
- }
- Ref<InputEventMouseButton> mb;
- mb.instance();
- get_key_modifier_state([event modifierFlags], mb);
- mb->set_button_index(index);
- mb->set_pressed(pressed);
- mb->set_position(Vector2(mouse_x, mouse_y));
- mb->set_global_position(Vector2(mouse_x, mouse_y));
- mb->set_button_mask(button_mask);
- if (index == BUTTON_LEFT && pressed) {
- mb->set_doubleclick([event clickCount] == 2);
- }
- OS_OSX::singleton->push_input(mb);
- }
- - (void)mouseDown:(NSEvent *)event {
- if (([event modifierFlags] & NSEventModifierFlagControl)) {
- mouse_down_control = true;
- _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
- } else {
- mouse_down_control = false;
- _mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, true);
- }
- }
- - (void)mouseDragged:(NSEvent *)event {
- [self mouseMoved:event];
- }
- - (void)mouseUp:(NSEvent *)event {
- if (mouse_down_control) {
- _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
- } else {
- _mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, false);
- }
- }
- - (void)mouseMoved:(NSEvent *)event {
- Ref<InputEventMouseMotion> mm;
- mm.instance();
- mm->set_button_mask(button_mask);
- prev_mouse_x = mouse_x;
- prev_mouse_y = mouse_y;
- const Vector2 pos = get_mouse_pos(event);
- mm->set_position(pos);
- mm->set_global_position(pos);
- Vector2 relativeMotion = Vector2();
- relativeMotion.x = [event deltaX] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
- relativeMotion.y = [event deltaY] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
- mm->set_relative(relativeMotion);
- get_key_modifier_state([event modifierFlags], mm);
- OS_OSX::singleton->input->set_mouse_position(Point2(mouse_x, mouse_y));
- OS_OSX::singleton->push_input(mm);
- }
- - (void)rightMouseDown:(NSEvent *)event {
- _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
- }
- - (void)rightMouseDragged:(NSEvent *)event {
- [self mouseMoved:event];
- }
- - (void)rightMouseUp:(NSEvent *)event {
- _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
- }
- - (void)otherMouseDown:(NSEvent *)event {
- if ((int)[event buttonNumber] != 2)
- return;
- _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true);
- }
- - (void)otherMouseDragged:(NSEvent *)event {
- [self mouseMoved:event];
- }
- - (void)otherMouseUp:(NSEvent *)event {
- if ((int)[event buttonNumber] != 2)
- return;
- _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false);
- }
- - (void)mouseExited:(NSEvent *)event {
- if (!OS_OSX::singleton)
- return;
- if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
- OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
- if (OS_OSX::singleton->input)
- OS_OSX::singleton->input->set_mouse_in_window(false);
- }
- - (void)mouseEntered:(NSEvent *)event {
- if (!OS_OSX::singleton)
- return;
- if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
- OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
- if (OS_OSX::singleton->input)
- OS_OSX::singleton->input->set_mouse_in_window(true);
- OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
- OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
- OS_OSX::singleton->set_cursor_shape(p_shape);
- }
- - (void)magnifyWithEvent:(NSEvent *)event {
- Ref<InputEventMagnifyGesture> ev;
- ev.instance();
- get_key_modifier_state([event modifierFlags], ev);
- ev->set_position(get_mouse_pos(event));
- ev->set_factor([event magnification] + 1.0);
- OS_OSX::singleton->push_input(ev);
- }
- - (void)viewDidChangeBackingProperties {
-
- }
- - (void)updateTrackingAreas {
- if (trackingArea != nil) {
- [self removeTrackingArea:trackingArea];
- [trackingArea release];
- }
- NSTrackingAreaOptions options =
- NSTrackingMouseEnteredAndExited |
- NSTrackingActiveInKeyWindow |
- NSTrackingCursorUpdate |
- NSTrackingInVisibleRect;
- trackingArea = [[NSTrackingArea alloc]
- initWithRect:[self bounds]
- options:options
- owner:self
- userInfo:nil];
- [self addTrackingArea:trackingArea];
- [super updateTrackingAreas];
- }
- static int translateKey(unsigned int key) {
-
- static const unsigned int table[128] = {
- KEY_A,
- KEY_S,
- KEY_D,
- KEY_F,
- KEY_H,
- KEY_G,
- KEY_Z,
- KEY_X,
- KEY_C,
- KEY_V,
- KEY_UNKNOWN,
- KEY_B,
- KEY_Q,
- KEY_W,
- KEY_E,
- KEY_R,
- KEY_Y,
- KEY_T,
- KEY_1,
- KEY_2,
- KEY_3,
- KEY_4,
- KEY_6,
- KEY_5,
- KEY_EQUAL,
- KEY_9,
- KEY_7,
- KEY_MINUS,
- KEY_8,
- KEY_0,
- KEY_BRACERIGHT,
- KEY_O,
- KEY_U,
- KEY_BRACELEFT,
- KEY_I,
- KEY_P,
- KEY_ENTER,
- KEY_L,
- KEY_J,
- KEY_APOSTROPHE,
- KEY_K,
- KEY_SEMICOLON,
- KEY_BACKSLASH,
- KEY_COMMA,
- KEY_SLASH,
- KEY_N,
- KEY_M,
- KEY_PERIOD,
- KEY_TAB,
- KEY_SPACE,
- KEY_QUOTELEFT,
- KEY_BACKSPACE,
- KEY_UNKNOWN,
- KEY_ESCAPE,
- KEY_META,
- KEY_META,
- KEY_SHIFT,
- KEY_CAPSLOCK,
- KEY_ALT,
- KEY_CONTROL,
- KEY_SHIFT,
- KEY_ALT,
- KEY_CONTROL,
- KEY_UNKNOWN,
- KEY_UNKNOWN,
- KEY_KP_PERIOD,
- KEY_UNKNOWN,
- KEY_KP_MULTIPLY,
- KEY_UNKNOWN,
- KEY_KP_ADD,
- KEY_UNKNOWN,
- KEY_NUMLOCK,
- KEY_UNKNOWN,
- KEY_UNKNOWN,
- KEY_UNKNOWN,
- KEY_KP_DIVIDE,
- KEY_KP_ENTER,
- KEY_UNKNOWN,
- KEY_KP_SUBTRACT,
- KEY_UNKNOWN,
- KEY_UNKNOWN,
- KEY_EQUAL,
- KEY_KP_0,
- KEY_KP_1,
- KEY_KP_2,
- KEY_KP_3,
- KEY_KP_4,
- KEY_KP_5,
- KEY_KP_6,
- KEY_KP_7,
- KEY_UNKNOWN,
- KEY_KP_8,
- KEY_KP_9,
- KEY_UNKNOWN,
- KEY_UNKNOWN,
- KEY_UNKNOWN,
- KEY_F5,
- KEY_F6,
- KEY_F7,
- KEY_F3,
- KEY_F8,
- KEY_F9,
- KEY_UNKNOWN,
- KEY_F11,
- KEY_UNKNOWN,
- KEY_F13,
- KEY_F16,
- KEY_F14,
- KEY_UNKNOWN,
- KEY_F10,
- KEY_UNKNOWN,
- KEY_F12,
- KEY_UNKNOWN,
- KEY_F15,
- KEY_INSERT,
- KEY_HOME,
- KEY_PAGEUP,
- KEY_DELETE,
- KEY_F4,
- KEY_END,
- KEY_F2,
- KEY_PAGEDOWN,
- KEY_F1,
- KEY_LEFT,
- KEY_RIGHT,
- KEY_DOWN,
- KEY_UP,
- KEY_UNKNOWN,
- };
- if (key >= 128)
- return KEY_UNKNOWN;
- return table[key];
- }
- - (void)keyDown:(NSEvent *)event {
-
- if (!imeMode) {
- OS_OSX::KeyEvent ke;
- ke.osx_state = [event modifierFlags];
- ke.pressed = true;
- ke.echo = [event isARepeat];
- ke.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode]));
- ke.unicode = 0;
- push_to_key_event_buffer(ke);
- }
- if ((OS_OSX::singleton->im_position.x != 0) && (OS_OSX::singleton->im_position.y != 0))
- [self interpretKeyEvents:[NSArray arrayWithObject:event]];
- }
- - (void)flagsChanged:(NSEvent *)event {
- if (!imeMode) {
- OS_OSX::KeyEvent ke;
- ke.echo = false;
- int key = [event keyCode];
- int mod = [event modifierFlags];
- if (key == 0x36 || key == 0x37) {
- if (mod & NSEventModifierFlagCommand) {
- mod &= ~NSEventModifierFlagCommand;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else if (key == 0x38 || key == 0x3c) {
- if (mod & NSEventModifierFlagShift) {
- mod &= ~NSEventModifierFlagShift;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else if (key == 0x3a || key == 0x3d) {
- if (mod & NSEventModifierFlagOption) {
- mod &= ~NSEventModifierFlagOption;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else if (key == 0x3b || key == 0x3e) {
- if (mod & NSEventModifierFlagControl) {
- mod &= ~NSEventModifierFlagControl;
- ke.pressed = true;
- } else {
- ke.pressed = false;
- }
- } else {
- return;
- }
- ke.osx_state = mod;
- ke.scancode = latin_keyboard_keycode_convert(translateKey(key));
- ke.unicode = 0;
- push_to_key_event_buffer(ke);
- }
- }
- - (void)keyUp:(NSEvent *)event {
- if (!imeMode) {
- OS_OSX::KeyEvent ke;
- ke.osx_state = [event modifierFlags];
- ke.pressed = false;
- ke.echo = false;
- ke.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode]));
- ke.unicode = 0;
- push_to_key_event_buffer(ke);
- }
- }
- inline void sendScrollEvent(int button, double factor, int modifierFlags) {
- Ref<InputEventMouseButton> sc;
- sc.instance();
- get_key_modifier_state(modifierFlags, sc);
- sc->set_button_index(button);
- sc->set_factor(factor);
- sc->set_pressed(true);
- Vector2 mouse_pos = Vector2(mouse_x, mouse_y);
- sc->set_position(mouse_pos);
- sc->set_global_position(mouse_pos);
- sc->set_button_mask(button_mask);
- OS_OSX::singleton->push_input(sc);
- sc->set_pressed(false);
- OS_OSX::singleton->push_input(sc);
- }
- inline void sendPanEvent(double dx, double dy, int modifierFlags) {
- Ref<InputEventPanGesture> pg;
- pg.instance();
- get_key_modifier_state(modifierFlags, pg);
- Vector2 mouse_pos = Vector2(mouse_x, mouse_y);
- pg->set_position(mouse_pos);
- pg->set_delta(Vector2(-dx, -dy));
- OS_OSX::singleton->push_input(pg);
- }
- - (void)scrollWheel:(NSEvent *)event {
- double deltaX, deltaY;
- deltaX = [event scrollingDeltaX];
- deltaY = [event scrollingDeltaY];
- if ([event hasPreciseScrollingDeltas]) {
- deltaX *= 0.03;
- deltaY *= 0.03;
- }
- if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
- sendPanEvent(deltaX, deltaY, [event modifierFlags]);
- } else {
- if (fabs(deltaX)) {
- sendScrollEvent(0 > deltaX ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_LEFT, fabs(deltaX * 0.3), [event modifierFlags]);
- }
- if (fabs(deltaY)) {
- sendScrollEvent(0 < deltaY ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN, fabs(deltaY * 0.3), [event modifierFlags]);
- }
- }
- }
- @end
- @interface GodotWindow : NSWindow {
- }
- @end
- @implementation GodotWindow
- - (BOOL)canBecomeKeyWindow {
-
- return YES;
- }
- @end
- void OS_OSX::set_ime_intermediate_text_callback(ImeCallback p_callback, void *p_inp) {
- im_callback = p_callback;
- im_target = p_inp;
- if (!im_callback) {
- [window_view cancelComposition];
- }
- }
- void OS_OSX::set_ime_position(const Point2 &p_pos) {
- im_position = p_pos;
- }
- int OS_OSX::get_video_driver_count() const {
- return 1;
- }
- const char *OS_OSX::get_video_driver_name(int p_driver) const {
- return "GLES3";
- }
- void OS_OSX::initialize_core() {
- crash_handler.initialize();
- OS_Unix::initialize_core();
- DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_RESOURCES);
- DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_USERDATA);
- DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
- SemaphoreOSX::make_default();
- }
- static bool keyboard_layout_dirty = true;
- static void keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
- keyboard_layout_dirty = true;
- }
- static bool displays_arrangement_dirty = true;
- static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
- displays_arrangement_dirty = true;
- }
- Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
-
-
-
- keyboard_layout_dirty = true;
- displays_arrangement_dirty = true;
-
- CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
- NULL, keyboard_layout_changed,
- kTISNotifySelectedKeyboardInputSourceChanged, NULL,
- CFNotificationSuspensionBehaviorDeliverImmediately);
-
- CGDisplayRegisterReconfigurationCallback(displays_arrangement_changed, NULL);
- window_delegate = [[GodotWindowDelegate alloc] init];
-
-
- unsigned int styleMask;
- if (p_desired.borderless_window) {
- styleMask = NSWindowStyleMaskBorderless;
- } else {
- styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (p_desired.resizable ? NSWindowStyleMaskResizable : 0);
- }
- window_object = [[GodotWindow alloc]
- initWithContentRect:NSMakeRect(0, 0, p_desired.width, p_desired.height)
- styleMask:styleMask
- backing:NSBackingStoreBuffered
- defer:NO];
- ERR_FAIL_COND_V(window_object == nil, ERR_UNAVAILABLE);
- window_view = [[GodotContentView alloc] init];
- float displayScale = 1.0;
- if (is_hidpi_allowed()) {
-
- NSScreen *screen = [NSScreen mainScreen];
- if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
- displayScale = fmax(displayScale, [screen backingScaleFactor]);
- }
- }
- window_size.width = p_desired.width * displayScale;
- window_size.height = p_desired.height * displayScale;
- if (displayScale > 1.0) {
- [window_view setWantsBestResolutionOpenGLSurface:YES];
-
- [window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
- }
-
- [window_object setContentView:window_view];
- [window_object setDelegate:window_delegate];
- [window_object setAcceptsMouseMovedEvents:YES];
- [window_object center];
- [window_object setRestorable:NO];
- unsigned int attributeCount = 0;
-
- int colorBits = 32;
-
- #define ADD_ATTR(x) \
- { attributes[attributeCount++] = x; }
- #define ADD_ATTR2(x, y) \
- { \
- ADD_ATTR(x); \
- ADD_ATTR(y); \
- }
-
- NSOpenGLPixelFormatAttribute attributes[40];
- ADD_ATTR(NSOpenGLPFADoubleBuffer);
- ADD_ATTR(NSOpenGLPFAClosestPolicy);
-
- ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core);
- ADD_ATTR2(NSOpenGLPFAColorSize, colorBits);
-
- ADD_ATTR2(NSOpenGLPFADepthSize, 24);
- ADD_ATTR2(NSOpenGLPFAStencilSize, 8);
-
-
-
-
- ADD_ATTR(0);
- #undef ADD_ATTR
- #undef ADD_ATTR2
- pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
- ERR_FAIL_COND_V(pixelFormat == nil, ERR_UNAVAILABLE);
- context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
- ERR_FAIL_COND_V(context == nil, ERR_UNAVAILABLE);
- [context setView:window_view];
- [context makeCurrentContext];
- set_use_vsync(p_desired.use_vsync);
- [NSApp activateIgnoringOtherApps:YES];
- _update_window();
- [window_object makeKeyAndOrderFront:nil];
- if (p_desired.fullscreen)
- zoomed = true;
-
- bool use_gl2 = p_video_driver != 1;
- AudioDriverManager::add_driver(&audio_driver);
-
- RasterizerGLES3::register_config();
- RasterizerGLES3::make_current();
- visual_server = memnew(VisualServerRaster);
- if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
- visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
- }
- visual_server->init();
- AudioDriverManager::initialize(p_audio_driver);
- input = memnew(InputDefault);
- joypad_osx = memnew(JoypadOSX);
- power_manager = memnew(power_osx);
- _ensure_user_data_dir();
- restore_rect = Rect2(get_window_position(), get_window_size());
- return OK;
- }
- void OS_OSX::finalize() {
- CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL);
- CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, NULL);
- delete_main_loop();
- memdelete(joypad_osx);
- memdelete(input);
- visual_server->finish();
- memdelete(visual_server);
-
- }
- void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
- main_loop = p_main_loop;
- input->set_main_loop(p_main_loop);
- }
- void OS_OSX::delete_main_loop() {
- if (!main_loop)
- return;
- memdelete(main_loop);
- main_loop = NULL;
- }
- String OS_OSX::get_name() {
- return "OSX";
- }
- #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
- class OSXTerminalLogger : public StdLogger {
- public:
- virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR) {
- if (!should_log(true)) {
- return;
- }
- const char *err_details;
- if (p_rationale && p_rationale[0])
- err_details = p_rationale;
- else
- err_details = p_code;
- switch (p_type) {
- case ERR_WARNING:
- if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
- os_log_info(OS_LOG_DEFAULT,
- "WARNING: %{public}s: %{public}s\nAt: %{public}s:%i.",
- p_function, err_details, p_file, p_line);
- }
- logf_error("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function,
- err_details);
- logf_error("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
- break;
- case ERR_SCRIPT:
- if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
- os_log_error(OS_LOG_DEFAULT,
- "SCRIPT ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
- p_function, err_details, p_file, p_line);
- }
- logf_error("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function,
- err_details);
- logf_error("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
- break;
- case ERR_SHADER:
- if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
- os_log_error(OS_LOG_DEFAULT,
- "SHADER ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
- p_function, err_details, p_file, p_line);
- }
- logf_error("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function,
- err_details);
- logf_error("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
- break;
- case ERR_ERROR:
- default:
- if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
- os_log_error(OS_LOG_DEFAULT,
- "ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
- p_function, err_details, p_file, p_line);
- }
- logf_error("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
- logf_error("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
- break;
- }
- }
- };
- #else
- typedef UnixTerminalLogger OSXTerminalLogger;
- #endif
- void OS_OSX::alert(const String &p_alert, const String &p_title) {
-
- NSAlert *window = [[NSAlert alloc] init];
- NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
- NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
- [window addButtonWithTitle:@"OK"];
- [window setMessageText:ns_title];
- [window setInformativeText:ns_alert];
- [window setAlertStyle:NSWarningAlertStyle];
-
- [window runModal];
- [window release];
- }
- Error OS_OSX::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
- String path = p_path;
- if (!FileAccess::exists(path)) {
-
- path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
- }
- if (!FileAccess::exists(path)) {
-
- path = get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file());
- }
- p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
- if (!p_library_handle) {
- ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + dlerror());
- ERR_FAIL_V(ERR_CANT_OPEN);
- }
- return OK;
- }
- void OS_OSX::set_cursor_shape(CursorShape p_shape) {
- if (cursor_shape == p_shape)
- return;
- if (cursors[p_shape] != NULL) {
- [cursors[p_shape] set];
- } else {
- switch (p_shape) {
- case CURSOR_ARROW: [[NSCursor arrowCursor] set]; break;
- case CURSOR_IBEAM: [[NSCursor IBeamCursor] set]; break;
- case CURSOR_POINTING_HAND: [[NSCursor pointingHandCursor] set]; break;
- case CURSOR_CROSS: [[NSCursor crosshairCursor] set]; break;
- case CURSOR_WAIT: [[NSCursor arrowCursor] set]; break;
- case CURSOR_BUSY: [[NSCursor arrowCursor] set]; break;
- case CURSOR_DRAG: [[NSCursor closedHandCursor] set]; break;
- case CURSOR_CAN_DROP: [[NSCursor openHandCursor] set]; break;
- case CURSOR_FORBIDDEN: [[NSCursor arrowCursor] set]; break;
- case CURSOR_VSIZE: [[NSCursor resizeUpDownCursor] set]; break;
- case CURSOR_HSIZE: [[NSCursor resizeLeftRightCursor] set]; break;
- case CURSOR_BDIAGSIZE: [[NSCursor arrowCursor] set]; break;
- case CURSOR_FDIAGSIZE: [[NSCursor arrowCursor] set]; break;
- case CURSOR_MOVE: [[NSCursor arrowCursor] set]; break;
- case CURSOR_VSPLIT: [[NSCursor resizeUpDownCursor] set]; break;
- case CURSOR_HSPLIT: [[NSCursor resizeLeftRightCursor] set]; break;
- case CURSOR_HELP: [[NSCursor arrowCursor] set]; break;
- default: {};
- }
- }
- cursor_shape = p_shape;
- }
- void OS_OSX::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
- if (p_cursor.is_valid()) {
- Ref<Texture> texture = p_cursor;
- Ref<Image> image = texture->get_data();
- int image_size = 32 * 32;
- ERR_FAIL_COND(texture->get_width() != 32 || texture->get_height() != 32);
- NSBitmapImageRep *imgrep = [[[NSBitmapImageRep alloc]
- initWithBitmapDataPlanes:NULL
- pixelsWide:image->get_width()
- pixelsHigh:image->get_height()
- bitsPerSample:8
- samplesPerPixel:4
- hasAlpha:YES
- isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bytesPerRow:image->get_width() * 4
- bitsPerPixel:32] autorelease];
- ERR_FAIL_COND(imgrep == nil);
- uint8_t *pixels = [imgrep bitmapData];
- int len = image->get_width() * image->get_height();
- PoolVector<uint8_t> data = image->get_data();
- PoolVector<uint8_t>::Read r = data.read();
-
- for (int i = 0; i < len; i++) {
- uint8_t alpha = r[i * 4 + 3];
- pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
- pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
- pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
- pixels[i * 4 + 3] = alpha;
- }
- NSImage *nsimage = [[[NSImage alloc] initWithSize:NSMakeSize(image->get_width(), image->get_height())] autorelease];
- [nsimage addRepresentation:imgrep];
- NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
- cursors[p_shape] = cursor;
- if (p_shape == CURSOR_ARROW) {
- [cursor set];
- }
- }
- }
- void OS_OSX::set_mouse_show(bool p_show) {
- }
- void OS_OSX::set_mouse_grab(bool p_grab) {
- }
- bool OS_OSX::is_mouse_grab_enabled() const {
- return mouse_grab;
- }
- void OS_OSX::warp_mouse_position(const Point2 &p_to) {
-
- if (mouse_mode == MOUSE_MODE_CAPTURED) {
- mouse_x = p_to.x;
- mouse_y = p_to.y;
- } else {
-
- const NSRect contentRect = [window_view frame];
- float displayScale = _display_scale();
- NSRect pointInWindowRect = NSMakeRect(p_to.x / displayScale, contentRect.size.height - (p_to.y / displayScale) - 1, 0, 0);
- NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin;
-
- CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
-
- CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
- CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
- CGAssociateMouseAndMouseCursorPosition(false);
- CGWarpMouseCursorPosition(lMouseWarpPos);
- CGAssociateMouseAndMouseCursorPosition(true);
- }
- }
- Point2 OS_OSX::get_mouse_position() const {
- return Vector2(mouse_x, mouse_y);
- }
- int OS_OSX::get_mouse_button_state() const {
- return button_mask;
- }
- void OS_OSX::set_window_title(const String &p_title) {
- title = p_title;
- [window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
- }
- void OS_OSX::set_icon(const Ref<Image> &p_icon) {
- Ref<Image> img = p_icon;
- img = img->duplicate();
- img->convert(Image::FORMAT_RGBA8);
- NSBitmapImageRep *imgrep = [[[NSBitmapImageRep alloc]
- initWithBitmapDataPlanes:NULL
- pixelsWide:img->get_width()
- pixelsHigh:img->get_height()
- bitsPerSample:8
- samplesPerPixel:4
- hasAlpha:YES
- isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bytesPerRow:img->get_width() * 4
- bitsPerPixel:32] autorelease];
- ERR_FAIL_COND(imgrep == nil);
- uint8_t *pixels = [imgrep bitmapData];
- int len = img->get_width() * img->get_height();
- PoolVector<uint8_t> data = img->get_data();
- PoolVector<uint8_t>::Read r = data.read();
-
- for (int i = 0; i < len; i++) {
- uint8_t alpha = r[i * 4 + 3];
- pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
- pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
- pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
- pixels[i * 4 + 3] = alpha;
- }
- NSImage *nsimg = [[[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())] autorelease];
- ERR_FAIL_COND(nsimg == nil);
- [nsimg addRepresentation:imgrep];
- [NSApp setApplicationIconImage:nsimg];
- }
- MainLoop *OS_OSX::get_main_loop() const {
- return main_loop;
- }
- String OS_OSX::get_config_path() const {
- if (has_environment("XDG_CONFIG_HOME")) {
- return get_environment("XDG_CONFIG_HOME");
- } else if (has_environment("HOME")) {
- return get_environment("HOME").plus_file("Library/Application Support");
- } else {
- return ".";
- }
- }
- String OS_OSX::get_data_path() const {
- if (has_environment("XDG_DATA_HOME")) {
- return get_environment("XDG_DATA_HOME");
- } else {
- return get_config_path();
- }
- }
- String OS_OSX::get_cache_path() const {
- if (has_environment("XDG_CACHE_HOME")) {
- return get_environment("XDG_CACHE_HOME");
- } else if (has_environment("HOME")) {
- return get_environment("HOME").plus_file("Library/Caches");
- } else {
- return get_config_path();
- }
- }
- String OS_OSX::get_godot_dir_name() const {
- return String(VERSION_SHORT_NAME).capitalize();
- }
- String OS_OSX::get_system_dir(SystemDir p_dir) const {
- NSSearchPathDirectory id = 0;
- switch (p_dir) {
- case SYSTEM_DIR_DESKTOP: {
- id = NSDesktopDirectory;
- } break;
- case SYSTEM_DIR_DOCUMENTS: {
- id = NSDocumentDirectory;
- } break;
- case SYSTEM_DIR_DOWNLOADS: {
- id = NSDownloadsDirectory;
- } break;
- case SYSTEM_DIR_MOVIES: {
- id = NSMoviesDirectory;
- } break;
- case SYSTEM_DIR_MUSIC: {
- id = NSMusicDirectory;
- } break;
- case SYSTEM_DIR_PICTURES: {
- id = NSPicturesDirectory;
- } break;
- }
- String ret;
- if (id) {
- NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
- if (paths && [paths count] >= 1) {
- char *utfs = strdup([[paths firstObject] UTF8String]);
- ret.parse_utf8(utfs);
- free(utfs);
- }
- }
- return ret;
- }
- bool OS_OSX::can_draw() const {
- return true;
- }
- void OS_OSX::set_clipboard(const String &p_text) {
- NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
- NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
- [pasteboard declareTypes:types owner:nil];
- [pasteboard setString:[NSString stringWithUTF8String:p_text.utf8().get_data()]
- forType:NSStringPboardType];
- }
- String OS_OSX::get_clipboard() const {
- NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
- if (![[pasteboard types] containsObject:NSStringPboardType]) {
- return "";
- }
- NSString *object = [pasteboard stringForType:NSStringPboardType];
- if (!object) {
- return "";
- }
- char *utfs = strdup([object UTF8String]);
- String ret;
- ret.parse_utf8(utfs);
- free(utfs);
- return ret;
- }
- void OS_OSX::release_rendering_thread() {
- [NSOpenGLContext clearCurrentContext];
- }
- void OS_OSX::make_rendering_thread() {
- [context makeCurrentContext];
- }
- Error OS_OSX::shell_open(String p_uri) {
- [[NSWorkspace sharedWorkspace] openURL:[[NSURL alloc] initWithString:[[NSString stringWithUTF8String:p_uri.utf8().get_data()] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]];
- return OK;
- }
- String OS_OSX::get_locale() const {
- NSString *locale_code = [[NSLocale currentLocale] localeIdentifier];
- return [locale_code UTF8String];
- }
- void OS_OSX::swap_buffers() {
- [context flushBuffer];
- }
- void OS_OSX::wm_minimized(bool p_minimized) {
- minimized = p_minimized;
- };
- void OS_OSX::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
- }
- OS::VideoMode OS_OSX::get_video_mode(int p_screen) const {
- VideoMode vm;
- vm.width = window_size.width;
- vm.height = window_size.height;
- return vm;
- }
- void OS_OSX::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
- }
- int OS_OSX::get_screen_count() const {
- NSArray *screenArray = [NSScreen screens];
- return [screenArray count];
- };
- Point2 OS_OSX::get_screens_origin() const {
- static Point2 origin;
- if (displays_arrangement_dirty) {
- origin = Point2();
- for (int i = 0; i < get_screen_count(); i++) {
- Point2 position = get_native_screen_position(i);
- if (position.x < origin.x) {
- origin.x = position.x;
- }
- if (position.y > origin.y) {
- origin.y = position.y;
- }
- }
- displays_arrangement_dirty = false;
- }
- return origin;
- }
- static int get_screen_index(NSScreen *screen) {
- const NSUInteger index = [[NSScreen screens] indexOfObject:screen];
- return index == NSNotFound ? 0 : index;
- }
- int OS_OSX::get_current_screen() const {
- if (window_object) {
- return get_screen_index([window_object screen]);
- } else {
- return get_screen_index([NSScreen mainScreen]);
- }
- };
- void OS_OSX::set_current_screen(int p_screen) {
- Vector2 wpos = get_window_position() - get_screen_position(get_current_screen());
- set_window_position(wpos + get_screen_position(p_screen));
- };
- Point2 OS_OSX::get_native_screen_position(int p_screen) const {
- if (p_screen == -1) {
- p_screen = get_current_screen();
- }
- NSArray *screenArray = [NSScreen screens];
- if (p_screen < [screenArray count]) {
- float display_scale = _display_scale([screenArray objectAtIndex:p_screen]);
- NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
-
- return Point2(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * display_scale;
- }
- return Point2();
- }
- Point2 OS_OSX::get_screen_position(int p_screen) const {
- Point2 position = get_native_screen_position(p_screen) - get_screens_origin();
-
-
- position.y *= -1;
- return position;
- }
- int OS_OSX::get_screen_dpi(int p_screen) const {
- if (p_screen == -1) {
- p_screen = get_current_screen();
- }
- NSArray *screenArray = [NSScreen screens];
- if (p_screen < [screenArray count]) {
- float displayScale = _display_scale([screenArray objectAtIndex:p_screen]);
- NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
- NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
- CGSize displayPhysicalSize = CGDisplayScreenSize(
- [[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
- return (displayPixelSize.width * 25.4f / displayPhysicalSize.width) * displayScale;
- }
- return 72;
- }
- Size2 OS_OSX::get_screen_size(int p_screen) const {
- if (p_screen == -1) {
- p_screen = get_current_screen();
- }
- NSArray *screenArray = [NSScreen screens];
- if (p_screen < [screenArray count]) {
- float displayScale = _display_scale([screenArray objectAtIndex:p_screen]);
-
- NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
- return Size2(nsrect.size.width, nsrect.size.height) * displayScale;
- }
- return Size2();
- }
- void OS_OSX::_update_window() {
- bool borderless_full = false;
- if (get_borderless_window()) {
- NSRect frameRect = [window_object frame];
- NSRect screenRect = [[window_object screen] frame];
-
- if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
- frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
- borderless_full = true;
- }
- }
- if (borderless_full) {
-
- [window_object setLevel:NSMainMenuWindowLevel + 1];
- [window_object setHidesOnDeactivate:YES];
- } else {
-
- [window_object setLevel:NSNormalWindowLevel];
- [window_object setHidesOnDeactivate:NO];
- }
- }
- float OS_OSX::_display_scale() const {
- if (window_object) {
- return _display_scale([window_object screen]);
- } else {
- return _display_scale([NSScreen mainScreen]);
- }
- }
- float OS_OSX::_display_scale(id screen) const {
- if (is_hidpi_allowed()) {
- if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
- return fmax(1.0, [screen backingScaleFactor]);
- }
- }
- return 1.0;
- }
- Point2 OS_OSX::get_native_window_position() const {
- NSRect nsrect = [window_object frame];
- Point2 pos;
- float display_scale = _display_scale();
-
- pos.x = nsrect.origin.x * display_scale;
- pos.y = (nsrect.origin.y + nsrect.size.height) * display_scale;
- return pos;
- };
- Point2 OS_OSX::get_window_position() const {
- Point2 position = get_native_window_position() - get_screens_origin();
-
-
- position.y *= -1;
- return position;
- }
- void OS_OSX::set_native_window_position(const Point2 &p_position) {
- NSPoint pos;
- float displayScale = _display_scale();
- pos.x = p_position.x / displayScale;
- pos.y = p_position.y / displayScale;
- [window_object setFrameTopLeftPoint:pos];
- _update_window();
- };
- void OS_OSX::set_window_position(const Point2 &p_position) {
- Point2 position = p_position;
-
-
- position.y *= -1;
- set_native_window_position(get_screens_origin() + position);
- };
- Size2 OS_OSX::get_window_size() const {
- return window_size;
- };
- Size2 OS_OSX::get_real_window_size() const {
- NSRect frame = [window_object frame];
- return Size2(frame.size.width, frame.size.height);
- }
- void OS_OSX::set_window_size(const Size2 p_size) {
- Size2 size = p_size;
- if (get_borderless_window() == false) {
-
- CGFloat menuBarHeight = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
- if (menuBarHeight != 0.f) {
- size.y += menuBarHeight;
- } else {
- #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
- if (floor(NSAppKitVersionNumber) < NSAppKitVersionNumber10_12) {
- #else
- {
- #endif
- size.y += [[NSStatusBar systemStatusBar] thickness];
- }
- }
- }
- NSRect frame = [window_object frame];
- [window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, size.x, size.y) display:YES];
- _update_window();
- };
- void OS_OSX::set_window_fullscreen(bool p_enabled) {
- if (zoomed != p_enabled) {
- [window_object toggleFullScreen:nil];
- }
- zoomed = p_enabled;
- };
- bool OS_OSX::is_window_fullscreen() const {
- return zoomed;
- };
- void OS_OSX::set_window_resizable(bool p_enabled) {
- if (p_enabled)
- [window_object setStyleMask:[window_object styleMask] | NSWindowStyleMaskResizable];
- else
- [window_object setStyleMask:[window_object styleMask] & ~NSWindowStyleMaskResizable];
- };
- bool OS_OSX::is_window_resizable() const {
- return [window_object styleMask] & NSWindowStyleMaskResizable;
- };
- void OS_OSX::set_window_minimized(bool p_enabled) {
- if (p_enabled)
- [window_object performMiniaturize:nil];
- else
- [window_object deminiaturize:nil];
- };
- bool OS_OSX::is_window_minimized() const {
- if ([window_object respondsToSelector:@selector(isMiniaturized)])
- return [window_object isMiniaturized];
- return minimized;
- };
- void OS_OSX::set_window_maximized(bool p_enabled) {
- if (p_enabled) {
- restore_rect = Rect2(get_window_position(), get_window_size());
- [window_object setFrame:[[[NSScreen screens] objectAtIndex:get_current_screen()] visibleFrame] display:YES];
- } else {
- set_window_size(restore_rect.size);
- set_window_position(restore_rect.position);
- };
- maximized = p_enabled;
- };
- bool OS_OSX::is_window_maximized() const {
-
- return maximized;
- };
- void OS_OSX::move_window_to_foreground() {
- [window_object orderFrontRegardless];
- }
- void OS_OSX::set_window_always_on_top(bool p_enabled) {
- if (is_window_always_on_top() == p_enabled)
- return;
- if (p_enabled)
- [window_object setLevel:NSFloatingWindowLevel];
- else
- [window_object setLevel:NSNormalWindowLevel];
- }
- bool OS_OSX::is_window_always_on_top() const {
- return [window_object level] == NSFloatingWindowLevel;
- }
- void OS_OSX::request_attention() {
- [NSApp requestUserAttention:NSCriticalRequest];
- }
- void OS_OSX::set_borderless_window(bool p_borderless) {
-
- [window_object orderOut:nil];
- if (p_borderless) {
- [window_object setStyleMask:NSWindowStyleMaskBorderless];
- } else {
- [window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable];
-
- NSRect frameRect = [window_object frame];
- [window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
- [window_object setFrame:frameRect display:NO];
-
- [window_object setTitle:[NSString stringWithUTF8String:title.utf8().get_data()]];
- }
- _update_window();
- [window_object makeKeyAndOrderFront:nil];
- }
- bool OS_OSX::get_borderless_window() {
- return [window_object styleMask] == NSWindowStyleMaskBorderless;
- }
- String OS_OSX::get_executable_path() const {
- int ret;
- pid_t pid;
- char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
- pid = getpid();
- ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
- if (ret <= 0) {
- return OS::get_executable_path();
- } else {
- String path;
- path.parse_utf8(pathbuf);
- return path;
- }
- }
- static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) {
- TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
- if (!currentKeyboard)
- return nil;
- CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
- if (!layoutData)
- return nil;
- const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
- OSStatus err;
- CFMutableStringRef output = CFStringCreateMutable(NULL, 0);
- for (int i = 0; i < length; ++i) {
- UInt32 keysDown = 0;
- UniChar chars[4];
- UniCharCount realLength;
- err = UCKeyTranslate(keyboardLayout,
- keyCode[i],
- kUCKeyActionDisplay,
- 0,
- LMGetKbdType(),
- kUCKeyTranslateNoDeadKeysBit,
- &keysDown,
- sizeof(chars) / sizeof(chars[0]),
- &realLength,
- chars);
- if (err != noErr) {
- CFRelease(output);
- return nil;
- }
- CFStringAppendCharacters(output, chars, 1);
- }
-
- return (NSString *)output;
- }
- OS::LatinKeyboardVariant OS_OSX::get_latin_keyboard_variant() const {
- static LatinKeyboardVariant layout = LATIN_KEYBOARD_QWERTY;
- if (keyboard_layout_dirty) {
- layout = LATIN_KEYBOARD_QWERTY;
- CGKeyCode keys[] = { kVK_ANSI_Q, kVK_ANSI_W, kVK_ANSI_E, kVK_ANSI_R, kVK_ANSI_T, kVK_ANSI_Y };
- NSString *test = createStringForKeys(keys, 6);
- if ([test isEqualToString:@"qwertz"]) {
- layout = LATIN_KEYBOARD_QWERTZ;
- } else if ([test isEqualToString:@"azerty"]) {
- layout = LATIN_KEYBOARD_AZERTY;
- } else if ([test isEqualToString:@"qzerty"]) {
- layout = LATIN_KEYBOARD_QZERTY;
- } else if ([test isEqualToString:@"',.pyf"]) {
- layout = LATIN_KEYBOARD_DVORAK;
- } else if ([test isEqualToString:@"xvlcwk"]) {
- layout = LATIN_KEYBOARD_NEO;
- } else if ([test isEqualToString:@"qwfpgj"]) {
- layout = LATIN_KEYBOARD_COLEMAK;
- }
- [test release];
- keyboard_layout_dirty = false;
- return layout;
- }
- return layout;
- }
- void OS_OSX::process_events() {
- while (true) {
- NSEvent *event = [NSApp
- nextEventMatchingMask:NSEventMaskAny
- untilDate:[NSDate distantPast]
- inMode:NSDefaultRunLoopMode
- dequeue:YES];
- if (event == nil)
- break;
- [NSApp sendEvent:event];
- }
- process_key_events();
- [autoreleasePool drain];
- autoreleasePool = [[NSAutoreleasePool alloc] init];
- }
- void OS_OSX::process_key_events() {
- Ref<InputEventKey> k;
- for (int i = 0; i < key_event_pos; i++) {
- KeyEvent &ke = key_event_buffer[i];
- if ((i == 0 && ke.scancode == 0) || (i > 0 && key_event_buffer[i - 1].scancode == 0)) {
- k.instance();
- get_key_modifier_state(ke.osx_state, k);
- k->set_pressed(ke.pressed);
- k->set_echo(ke.echo);
- k->set_scancode(0);
- k->set_unicode(ke.unicode);
- push_input(k);
- }
- if (ke.scancode != 0) {
- k.instance();
- get_key_modifier_state(ke.osx_state, k);
- k->set_pressed(ke.pressed);
- k->set_echo(ke.echo);
- k->set_scancode(ke.scancode);
- if (i + 1 < key_event_pos && key_event_buffer[i + 1].scancode == 0) {
- k->set_unicode(key_event_buffer[i + 1].unicode);
- }
- push_input(k);
- }
- }
- key_event_pos = 0;
- }
- void OS_OSX::push_input(const Ref<InputEvent> &p_event) {
- Ref<InputEvent> ev = p_event;
- input->parse_input_event(ev);
- }
- void OS_OSX::force_process_input() {
- process_events();
- joypad_osx->process_joypads();
- }
- void OS_OSX::run() {
- force_quit = false;
- if (!main_loop)
- return;
- main_loop->init();
- if (zoomed) {
- zoomed = false;
- set_window_fullscreen(true);
- }
-
-
-
- while (!force_quit) {
- process_events();
- joypad_osx->process_joypads();
- if (Main::iteration() == true)
- break;
- };
- main_loop->finish();
- }
- void OS_OSX::set_mouse_mode(MouseMode p_mode) {
- if (p_mode == mouse_mode)
- return;
- if (p_mode == MOUSE_MODE_CAPTURED) {
-
-
-
- CGDisplayHideCursor(kCGDirectMainDisplay);
- CGAssociateMouseAndMouseCursorPosition(false);
- } else if (p_mode == MOUSE_MODE_HIDDEN) {
- CGDisplayHideCursor(kCGDirectMainDisplay);
- CGAssociateMouseAndMouseCursorPosition(true);
- } else {
- CGDisplayShowCursor(kCGDirectMainDisplay);
- CGAssociateMouseAndMouseCursorPosition(true);
- }
- mouse_mode = p_mode;
- }
- OS::MouseMode OS_OSX::get_mouse_mode() const {
- return mouse_mode;
- }
- String OS_OSX::get_joy_guid(int p_device) const {
- return input->get_joy_guid_remapped(p_device);
- }
- OS::PowerState OS_OSX::get_power_state() {
- return power_manager->get_power_state();
- }
- int OS_OSX::get_power_seconds_left() {
- return power_manager->get_power_seconds_left();
- }
- int OS_OSX::get_power_percent_left() {
- return power_manager->get_power_percent_left();
- }
- Error OS_OSX::move_to_trash(const String &p_path) {
- NSFileManager *fm = [NSFileManager defaultManager];
- NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
- NSError *err;
- if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
- ERR_PRINTS("trashItemAtURL error: " + String(err.localizedDescription.UTF8String));
- return FAILED;
- }
- return OK;
- }
- void OS_OSX::_set_use_vsync(bool p_enable) {
- CGLContextObj ctx = CGLGetCurrentContext();
- if (ctx) {
- GLint swapInterval = p_enable ? 1 : 0;
- CGLSetParameter(ctx, kCGLCPSwapInterval, &swapInterval);
- }
- }
- OS_OSX *OS_OSX::singleton = NULL;
- OS_OSX::OS_OSX() {
- key_event_pos = 0;
- mouse_mode = OS::MOUSE_MODE_VISIBLE;
- main_loop = NULL;
- singleton = this;
- im_position = Point2();
- im_callback = NULL;
- im_target = NULL;
- autoreleasePool = [[NSAutoreleasePool alloc] init];
- eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
- ERR_FAIL_COND(!eventSource);
- CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0);
-
- framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
- ERR_FAIL_COND(!framework);
-
- [GodotApplication sharedApplication];
-
- [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
-
-
-
- NSMenuItem *menu_item;
- NSString *title;
- NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
- if (nsappname == nil)
- nsappname = [[NSProcessInfo processInfo] processName];
-
- NSMenu *apple_menu = [[NSMenu alloc] initWithTitle:@""];
- title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
- [apple_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
- [apple_menu addItem:[NSMenuItem separatorItem]];
- NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
- menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
- [apple_menu setSubmenu:services forItem:menu_item];
- [NSApp setServicesMenu:services];
- [services release];
- [apple_menu addItem:[NSMenuItem separatorItem]];
- title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
- [apple_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
- menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
- [menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
- [apple_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
- [apple_menu addItem:[NSMenuItem separatorItem]];
- title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
- [apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
-
- NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
- menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
- [main_menu setSubmenu:apple_menu forItem:menu_item];
- [NSApp setMainMenu:main_menu];
- [main_menu release];
- [apple_menu release];
- [NSApp finishLaunching];
- delegate = [[GodotApplicationDelegate alloc] init];
- ERR_FAIL_COND(!delegate);
- [NSApp setDelegate:delegate];
- cursor_shape = CURSOR_ARROW;
- maximized = false;
- minimized = false;
- window_size = Vector2(1024, 600);
- zoomed = false;
- Vector<Logger *> loggers;
- loggers.push_back(memnew(OSXTerminalLogger));
- _set_logger(memnew(CompositeLogger(loggers)));
-
- while (true) {
- NSEvent *event = [NSApp
- nextEventMatchingMask:NSEventMaskAny
- untilDate:[NSDate distantPast]
- inMode:NSDefaultRunLoopMode
- dequeue:YES];
- if (event == nil)
- break;
- [NSApp sendEvent:event];
- }
- }
- bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
- return p_feature == "pc" || p_feature == "s3tc";
- }
- void OS_OSX::disable_crash_handler() {
- crash_handler.disable();
- }
- bool OS_OSX::is_disable_crash_handler() const {
- return crash_handler.is_disabled();
- }
|