display_server_macos.mm 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788
  1. /**************************************************************************/
  2. /* display_server_macos.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "display_server_macos.h"
  31. #include "godot_button_view.h"
  32. #include "godot_content_view.h"
  33. #include "godot_menu_delegate.h"
  34. #include "godot_menu_item.h"
  35. #include "godot_open_save_delegate.h"
  36. #include "godot_status_item.h"
  37. #include "godot_window.h"
  38. #include "godot_window_delegate.h"
  39. #include "key_mapping_macos.h"
  40. #include "os_macos.h"
  41. #include "tts_macos.h"
  42. #include "core/config/project_settings.h"
  43. #include "core/io/marshalls.h"
  44. #include "core/math/geometry_2d.h"
  45. #include "core/os/keyboard.h"
  46. #include "drivers/png/png_driver_common.h"
  47. #include "main/main.h"
  48. #include "scene/resources/image_texture.h"
  49. #if defined(GLES3_ENABLED)
  50. #include "drivers/gles3/rasterizer_gles3.h"
  51. #endif
  52. #if defined(RD_ENABLED)
  53. #include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
  54. #endif
  55. #import <Carbon/Carbon.h>
  56. #import <Cocoa/Cocoa.h>
  57. #import <IOKit/IOCFPlugIn.h>
  58. #import <IOKit/IOKitLib.h>
  59. #import <IOKit/hid/IOHIDKeys.h>
  60. #import <IOKit/hid/IOHIDLib.h>
  61. DisplayServerMacOS::WindowID DisplayServerMacOS::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, const Rect2i &p_rect) {
  62. WindowID id;
  63. const float scale = screen_get_max_scale();
  64. {
  65. WindowData wd;
  66. wd.window_delegate = [[GodotWindowDelegate alloc] init];
  67. ERR_FAIL_NULL_V_MSG(wd.window_delegate, INVALID_WINDOW_ID, "Can't create a window delegate");
  68. [wd.window_delegate setWindowID:window_id_counter];
  69. int rq_screen = get_screen_from_rect(p_rect);
  70. if (rq_screen < 0) {
  71. rq_screen = get_primary_screen(); // Requested window rect is outside any screen bounds.
  72. }
  73. Rect2i srect = screen_get_usable_rect(rq_screen);
  74. Point2i wpos = p_rect.position;
  75. if (srect != Rect2i()) {
  76. wpos = wpos.clamp(srect.position, srect.position + srect.size - p_rect.size / 3);
  77. }
  78. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  79. // Godot passes a positive value.
  80. wpos.y *= -1;
  81. wpos += _get_screens_origin();
  82. wpos /= scale;
  83. // initWithContentRect uses bottom-left corner of the window’s frame as origin.
  84. wd.window_object = [[GodotWindow alloc]
  85. initWithContentRect:NSMakeRect(100, 100, MAX(1, p_rect.size.width / scale), MAX(1, p_rect.size.height / scale))
  86. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
  87. backing:NSBackingStoreBuffered
  88. defer:NO];
  89. ERR_FAIL_NULL_V_MSG(wd.window_object, INVALID_WINDOW_ID, "Can't create a window");
  90. [wd.window_object setWindowID:window_id_counter];
  91. [wd.window_object setReleasedWhenClosed:NO];
  92. wd.window_view = [[GodotContentView alloc] init];
  93. ERR_FAIL_NULL_V_MSG(wd.window_view, INVALID_WINDOW_ID, "Can't create a window view");
  94. [wd.window_view setWindowID:window_id_counter];
  95. [wd.window_view setWantsLayer:TRUE];
  96. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  97. [wd.window_object setContentView:wd.window_view];
  98. [wd.window_object setDelegate:wd.window_delegate];
  99. [wd.window_object setAcceptsMouseMovedEvents:YES];
  100. [wd.window_object setRestorable:NO];
  101. [wd.window_object setColorSpace:[NSColorSpace sRGBColorSpace]];
  102. if ([wd.window_object respondsToSelector:@selector(setTabbingMode:)]) {
  103. [wd.window_object setTabbingMode:NSWindowTabbingModeDisallowed];
  104. }
  105. CALayer *layer = [(NSView *)wd.window_view layer];
  106. if (layer) {
  107. layer.contentsScale = scale;
  108. }
  109. NSColor *bg_color = [NSColor windowBackgroundColor];
  110. Color _bg_color;
  111. if (_get_window_early_clear_override(_bg_color)) {
  112. bg_color = [NSColor colorWithCalibratedRed:_bg_color.r green:_bg_color.g blue:_bg_color.b alpha:1.f];
  113. }
  114. [wd.window_object setBackgroundColor:bg_color];
  115. if (layer) {
  116. [layer setBackgroundColor:bg_color.CGColor];
  117. }
  118. #if defined(RD_ENABLED)
  119. if (rendering_context) {
  120. union {
  121. #ifdef VULKAN_ENABLED
  122. RenderingContextDriverVulkanMacOS::WindowPlatformData vulkan;
  123. #endif
  124. #ifdef METAL_ENABLED
  125. RenderingContextDriverMetal::WindowPlatformData metal;
  126. #endif
  127. } wpd;
  128. #ifdef VULKAN_ENABLED
  129. if (rendering_driver == "vulkan") {
  130. wpd.vulkan.layer_ptr = (CAMetalLayer *const *)&layer;
  131. }
  132. #endif
  133. #ifdef METAL_ENABLED
  134. if (rendering_driver == "metal") {
  135. wpd.metal.layer = (CAMetalLayer *)layer;
  136. }
  137. #endif
  138. Error err = rendering_context->window_create(window_id_counter, &wpd);
  139. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, vformat("Can't create a %s context", rendering_driver));
  140. rendering_context->window_set_size(window_id_counter, p_rect.size.width, p_rect.size.height);
  141. rendering_context->window_set_vsync_mode(window_id_counter, p_vsync_mode);
  142. }
  143. #endif
  144. #if defined(GLES3_ENABLED)
  145. if (gl_manager_legacy) {
  146. Error err = gl_manager_legacy->window_create(window_id_counter, wd.window_view, p_rect.size.width, p_rect.size.height);
  147. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context.");
  148. }
  149. if (gl_manager_angle) {
  150. CALayer *layer = [(NSView *)wd.window_view layer];
  151. Error err = gl_manager_angle->window_create(window_id_counter, nullptr, (__bridge void *)layer, p_rect.size.width, p_rect.size.height);
  152. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context.");
  153. }
  154. window_set_vsync_mode(p_vsync_mode, window_id_counter);
  155. #endif
  156. [wd.window_view updateLayerDelegate];
  157. const NSRect contentRect = [wd.window_view frame];
  158. const NSRect windowRect = [wd.window_object frame];
  159. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  160. Point2i offset;
  161. offset.x = (nsrect.origin.x - windowRect.origin.x);
  162. offset.y = (nsrect.origin.y + nsrect.size.height);
  163. offset.y -= (windowRect.origin.y + windowRect.size.height);
  164. [wd.window_object setFrameTopLeftPoint:NSMakePoint(wpos.x - offset.x, wpos.y - offset.y)];
  165. id = window_id_counter++;
  166. windows[id] = wd;
  167. }
  168. WindowData &wd = windows[id];
  169. window_set_mode(p_mode, id);
  170. const NSRect contentRect = [wd.window_view frame];
  171. wd.size.width = contentRect.size.width * scale;
  172. wd.size.height = contentRect.size.height * scale;
  173. CALayer *layer = [(NSView *)wd.window_view layer];
  174. if (layer) {
  175. layer.contentsScale = scale;
  176. }
  177. #if defined(GLES3_ENABLED)
  178. if (gl_manager_legacy) {
  179. gl_manager_legacy->window_resize(id, wd.size.width, wd.size.height);
  180. }
  181. if (gl_manager_angle) {
  182. gl_manager_angle->window_resize(id, wd.size.width, wd.size.height);
  183. }
  184. #endif
  185. return id;
  186. }
  187. void DisplayServerMacOS::_update_window_style(WindowData p_wd) {
  188. bool borderless_full = false;
  189. if (p_wd.borderless) {
  190. NSRect frameRect = [p_wd.window_object frame];
  191. NSRect screenRect = [[p_wd.window_object screen] frame];
  192. // Check if our window covers up the screen.
  193. if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
  194. frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
  195. borderless_full = true;
  196. }
  197. }
  198. if (borderless_full) {
  199. // If the window covers up the screen set the level to above the main menu and hide on deactivate.
  200. [(NSWindow *)p_wd.window_object setLevel:NSMainMenuWindowLevel + 1];
  201. [(NSWindow *)p_wd.window_object setHidesOnDeactivate:YES];
  202. } else {
  203. // Reset these when our window is not a borderless window that covers up the screen.
  204. if (p_wd.on_top && !p_wd.fullscreen) {
  205. [(NSWindow *)p_wd.window_object setLevel:NSFloatingWindowLevel];
  206. } else {
  207. [(NSWindow *)p_wd.window_object setLevel:NSNormalWindowLevel];
  208. }
  209. [(NSWindow *)p_wd.window_object setHidesOnDeactivate:NO];
  210. }
  211. }
  212. void DisplayServerMacOS::set_window_per_pixel_transparency_enabled(bool p_enabled, WindowID p_window) {
  213. ERR_FAIL_COND(!windows.has(p_window));
  214. WindowData &wd = windows[p_window];
  215. if (!OS::get_singleton()->is_layered_allowed()) {
  216. return;
  217. }
  218. if (p_enabled) {
  219. [wd.window_object setBackgroundColor:[NSColor clearColor]];
  220. [wd.window_object setOpaque:NO];
  221. [wd.window_object setHasShadow:NO];
  222. CALayer *layer = [(NSView *)wd.window_view layer];
  223. if (layer) {
  224. [layer setBackgroundColor:[NSColor clearColor].CGColor];
  225. [layer setOpaque:NO];
  226. }
  227. #if defined(GLES3_ENABLED)
  228. if (gl_manager_legacy) {
  229. gl_manager_legacy->window_set_per_pixel_transparency_enabled(p_window, true);
  230. }
  231. #endif
  232. } else {
  233. NSColor *bg_color = [NSColor windowBackgroundColor];
  234. Color _bg_color;
  235. if (_get_window_early_clear_override(_bg_color)) {
  236. bg_color = [NSColor colorWithCalibratedRed:_bg_color.r green:_bg_color.g blue:_bg_color.b alpha:1.f];
  237. }
  238. [wd.window_object setBackgroundColor:bg_color];
  239. [wd.window_object setOpaque:YES];
  240. [wd.window_object setHasShadow:YES];
  241. CALayer *layer = [(NSView *)wd.window_view layer];
  242. if (layer) {
  243. [layer setBackgroundColor:bg_color.CGColor];
  244. [layer setOpaque:YES];
  245. }
  246. #if defined(GLES3_ENABLED)
  247. if (gl_manager_legacy) {
  248. gl_manager_legacy->window_set_per_pixel_transparency_enabled(p_window, false);
  249. }
  250. #endif
  251. }
  252. }
  253. void DisplayServerMacOS::_update_displays_arrangement() {
  254. origin = Point2i();
  255. for (int i = 0; i < get_screen_count(); i++) {
  256. Point2i position = _get_native_screen_position(i);
  257. if (position.x < origin.x) {
  258. origin.x = position.x;
  259. }
  260. if (position.y > origin.y) {
  261. origin.y = position.y;
  262. }
  263. }
  264. displays_arrangement_dirty = false;
  265. }
  266. void DisplayServerMacOS::set_menu_delegate(NSMenu *p_menu) {
  267. [p_menu setDelegate:menu_delegate];
  268. }
  269. Point2i DisplayServerMacOS::_get_screens_origin() const {
  270. // Returns the native top-left screen coordinate of the smallest rectangle
  271. // that encompasses all screens. Needed in get_screen_position(),
  272. // window_get_position, and window_set_position()
  273. // to convert between macOS native screen coordinates and the ones expected by Godot.
  274. if (displays_arrangement_dirty) {
  275. const_cast<DisplayServerMacOS *>(this)->_update_displays_arrangement();
  276. }
  277. return origin;
  278. }
  279. Point2i DisplayServerMacOS::_get_native_screen_position(int p_screen) const {
  280. NSArray *screenArray = [NSScreen screens];
  281. if ((NSUInteger)p_screen < [screenArray count]) {
  282. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  283. // Return the top-left corner of the screen, for macOS the y starts at the bottom.
  284. return Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * screen_get_max_scale();
  285. }
  286. return Point2i();
  287. }
  288. void DisplayServerMacOS::_displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
  289. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  290. if (ds) {
  291. ds->displays_arrangement_dirty = true;
  292. }
  293. }
  294. DisplayServer::WindowID DisplayServerMacOS::_get_focused_window_or_popup() const {
  295. const List<WindowID>::Element *E = popup_list.back();
  296. if (E) {
  297. return E->get();
  298. }
  299. return last_focused_window;
  300. }
  301. void DisplayServerMacOS::mouse_enter_window(WindowID p_window) {
  302. if (window_mouseover_id != p_window) {
  303. if (window_mouseover_id != INVALID_WINDOW_ID) {
  304. send_window_event(windows[window_mouseover_id], WINDOW_EVENT_MOUSE_EXIT);
  305. }
  306. window_mouseover_id = p_window;
  307. if (p_window != INVALID_WINDOW_ID) {
  308. send_window_event(windows[p_window], WINDOW_EVENT_MOUSE_ENTER);
  309. }
  310. }
  311. }
  312. void DisplayServerMacOS::mouse_exit_window(WindowID p_window) {
  313. if (window_mouseover_id == p_window && p_window != INVALID_WINDOW_ID) {
  314. send_window_event(windows[p_window], WINDOW_EVENT_MOUSE_EXIT);
  315. }
  316. window_mouseover_id = INVALID_WINDOW_ID;
  317. }
  318. void DisplayServerMacOS::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  319. ((DisplayServerMacOS *)(get_singleton()))->_dispatch_input_event(p_event);
  320. }
  321. void DisplayServerMacOS::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  322. if (!in_dispatch_input_event) {
  323. in_dispatch_input_event = true;
  324. {
  325. List<WindowID>::Element *E = popup_list.back();
  326. if (E && Object::cast_to<InputEventKey>(*p_event)) {
  327. // Redirect keyboard input to active popup.
  328. if (windows.has(E->get())) {
  329. Callable callable = windows[E->get()].input_event_callback;
  330. if (callable.is_valid()) {
  331. callable.call(p_event);
  332. }
  333. }
  334. in_dispatch_input_event = false;
  335. return;
  336. }
  337. }
  338. Ref<InputEventFromWindow> event_from_window = p_event;
  339. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  340. // Send to a window.
  341. if (windows.has(event_from_window->get_window_id())) {
  342. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  343. if (callable.is_valid()) {
  344. callable.call(p_event);
  345. }
  346. }
  347. } else {
  348. // Send to all windows.
  349. for (KeyValue<WindowID, WindowData> &E : windows) {
  350. Callable callable = E.value.input_event_callback;
  351. if (callable.is_valid()) {
  352. callable.call(p_event);
  353. }
  354. }
  355. }
  356. in_dispatch_input_event = false;
  357. }
  358. }
  359. void DisplayServerMacOS::_push_input(const Ref<InputEvent> &p_event) {
  360. Ref<InputEvent> ev = p_event;
  361. Input::get_singleton()->parse_input_event(ev);
  362. }
  363. void DisplayServerMacOS::_process_key_events() {
  364. Ref<InputEventKey> k;
  365. for (int i = 0; i < key_event_pos; i++) {
  366. const KeyEvent &ke = key_event_buffer[i];
  367. if (ke.raw) {
  368. // Non IME input - no composite characters, pass events as is.
  369. k.instantiate();
  370. k->set_window_id(ke.window_id);
  371. get_key_modifier_state(ke.macos_state, k);
  372. k->set_pressed(ke.pressed);
  373. k->set_echo(ke.echo);
  374. k->set_keycode(ke.keycode);
  375. k->set_physical_keycode(ke.physical_keycode);
  376. k->set_key_label(ke.key_label);
  377. k->set_unicode(ke.unicode);
  378. k->set_location(ke.location);
  379. _push_input(k);
  380. } else {
  381. // IME input.
  382. if ((i == 0 && ke.keycode == Key::NONE) || (i > 0 && key_event_buffer[i - 1].keycode == Key::NONE)) {
  383. k.instantiate();
  384. k->set_window_id(ke.window_id);
  385. get_key_modifier_state(ke.macos_state, k);
  386. k->set_pressed(ke.pressed);
  387. k->set_echo(ke.echo);
  388. k->set_keycode(Key::NONE);
  389. k->set_physical_keycode(Key::NONE);
  390. k->set_key_label(Key::NONE);
  391. k->set_unicode(ke.unicode);
  392. _push_input(k);
  393. }
  394. if (ke.keycode != Key::NONE) {
  395. k.instantiate();
  396. k->set_window_id(ke.window_id);
  397. get_key_modifier_state(ke.macos_state, k);
  398. k->set_pressed(ke.pressed);
  399. k->set_echo(ke.echo);
  400. k->set_keycode(ke.keycode);
  401. k->set_physical_keycode(ke.physical_keycode);
  402. k->set_key_label(ke.key_label);
  403. k->set_location(ke.location);
  404. if (i + 1 < key_event_pos && key_event_buffer[i + 1].keycode == Key::NONE) {
  405. k->set_unicode(key_event_buffer[i + 1].unicode);
  406. }
  407. _push_input(k);
  408. }
  409. }
  410. }
  411. key_event_pos = 0;
  412. }
  413. void DisplayServerMacOS::_update_keyboard_layouts() {
  414. kbd_layouts.clear();
  415. current_layout = 0;
  416. TISInputSourceRef cur_source = TISCopyCurrentKeyboardInputSource();
  417. NSString *cur_name = (__bridge NSString *)TISGetInputSourceProperty(cur_source, kTISPropertyLocalizedName);
  418. CFRelease(cur_source);
  419. // Enum IME layouts.
  420. NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
  421. NSArray *list_ime = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_ime, false);
  422. for (NSUInteger i = 0; i < [list_ime count]; i++) {
  423. LayoutInfo ly;
  424. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
  425. ly.name.parse_utf8([name UTF8String]);
  426. NSArray *langs = (__bridge NSArray *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyInputSourceLanguages);
  427. ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
  428. kbd_layouts.push_back(ly);
  429. if ([name isEqualToString:cur_name]) {
  430. current_layout = kbd_layouts.size() - 1;
  431. }
  432. }
  433. // Enum plain keyboard layouts.
  434. NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
  435. NSArray *list_kbd = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_kbd, false);
  436. for (NSUInteger i = 0; i < [list_kbd count]; i++) {
  437. LayoutInfo ly;
  438. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
  439. ly.name.parse_utf8([name UTF8String]);
  440. NSArray *langs = (__bridge NSArray *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyInputSourceLanguages);
  441. ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
  442. kbd_layouts.push_back(ly);
  443. if ([name isEqualToString:cur_name]) {
  444. current_layout = kbd_layouts.size() - 1;
  445. }
  446. }
  447. keyboard_layout_dirty = false;
  448. }
  449. void DisplayServerMacOS::_keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
  450. DisplayServerMacOS *ds = (DisplayServerMacOS *)DisplayServer::get_singleton();
  451. if (ds) {
  452. ds->keyboard_layout_dirty = true;
  453. }
  454. }
  455. NSImage *DisplayServerMacOS::_convert_to_nsimg(Ref<Image> &p_image) const {
  456. p_image->convert(Image::FORMAT_RGBA8);
  457. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  458. initWithBitmapDataPlanes:nullptr
  459. pixelsWide:p_image->get_width()
  460. pixelsHigh:p_image->get_height()
  461. bitsPerSample:8
  462. samplesPerPixel:4
  463. hasAlpha:YES
  464. isPlanar:NO
  465. colorSpaceName:NSDeviceRGBColorSpace
  466. bytesPerRow:int(p_image->get_width()) * 4
  467. bitsPerPixel:32];
  468. ERR_FAIL_NULL_V(imgrep, nil);
  469. uint8_t *pixels = [imgrep bitmapData];
  470. int len = p_image->get_width() * p_image->get_height();
  471. const uint8_t *r = p_image->get_data().ptr();
  472. /* Premultiply the alpha channel */
  473. for (int i = 0; i < len; i++) {
  474. uint8_t alpha = r[i * 4 + 3];
  475. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  476. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  477. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  478. pixels[i * 4 + 3] = alpha;
  479. }
  480. NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(p_image->get_width(), p_image->get_height())];
  481. ERR_FAIL_NULL_V(nsimg, nil);
  482. [nsimg addRepresentation:imgrep];
  483. return nsimg;
  484. }
  485. NSCursor *DisplayServerMacOS::_cursor_from_selector(SEL p_selector, SEL p_fallback) {
  486. if ([NSCursor respondsToSelector:p_selector]) {
  487. id object = [NSCursor performSelector:p_selector];
  488. if ([object isKindOfClass:[NSCursor class]]) {
  489. return object;
  490. }
  491. }
  492. if (p_fallback) {
  493. // Fallback should be a reasonable default, no need to check.
  494. return [NSCursor performSelector:p_fallback];
  495. }
  496. return [NSCursor arrowCursor];
  497. }
  498. void DisplayServerMacOS::menu_callback(id p_sender) {
  499. if (![p_sender representedObject]) {
  500. return;
  501. }
  502. GodotMenuItem *value = [p_sender representedObject];
  503. if (value) {
  504. if (value->callback.is_valid()) {
  505. MenuCall mc;
  506. mc.tag = value->meta;
  507. mc.callback = value->callback;
  508. deferred_menu_calls.push_back(mc);
  509. // Do not run callback from here! If it is opening a new window or calling process_events, it will corrupt OS event queue and crash.
  510. }
  511. }
  512. }
  513. bool DisplayServerMacOS::has_window(WindowID p_window) const {
  514. return windows.has(p_window);
  515. }
  516. DisplayServerMacOS::WindowData &DisplayServerMacOS::get_window(WindowID p_window) {
  517. return windows[p_window];
  518. }
  519. void DisplayServerMacOS::send_event(NSEvent *p_event) {
  520. // Special case handling of shortcuts that don't arrive at the regular keyDown handler
  521. if ([p_event type] == NSEventTypeKeyDown) {
  522. NSEventModifierFlags flags = [p_event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
  523. // Command-period
  524. if ((flags == NSEventModifierFlagCommand) && [p_event keyCode] == 0x2f) {
  525. Ref<InputEventKey> k;
  526. k.instantiate();
  527. get_key_modifier_state([p_event modifierFlags], k);
  528. k->set_window_id(DisplayServerMacOS::INVALID_WINDOW_ID);
  529. k->set_pressed(true);
  530. k->set_keycode(Key::PERIOD);
  531. k->set_physical_keycode(Key::PERIOD);
  532. k->set_key_label(Key::PERIOD);
  533. k->set_echo([p_event isARepeat]);
  534. Input::get_singleton()->parse_input_event(k);
  535. return;
  536. }
  537. // Ctrl+Tab and Ctrl+Shift+Tab
  538. if (((flags == NSEventModifierFlagControl) || (flags == (NSEventModifierFlagControl | NSEventModifierFlagShift))) && [p_event keyCode] == 0x30) {
  539. Ref<InputEventKey> k;
  540. k.instantiate();
  541. get_key_modifier_state([p_event modifierFlags], k);
  542. k->set_window_id(DisplayServerMacOS::INVALID_WINDOW_ID);
  543. k->set_pressed(true);
  544. k->set_keycode(Key::TAB);
  545. k->set_physical_keycode(Key::TAB);
  546. k->set_key_label(Key::TAB);
  547. k->set_echo([p_event isARepeat]);
  548. Input::get_singleton()->parse_input_event(k);
  549. return;
  550. }
  551. }
  552. }
  553. void DisplayServerMacOS::send_window_event(const WindowData &wd, WindowEvent p_event) {
  554. _THREAD_SAFE_METHOD_
  555. if (wd.event_callback.is_valid()) {
  556. Variant event = int(p_event);
  557. wd.event_callback.call(event);
  558. }
  559. }
  560. void DisplayServerMacOS::release_pressed_events() {
  561. _THREAD_SAFE_METHOD_
  562. if (Input::get_singleton()) {
  563. Input::get_singleton()->release_pressed_events();
  564. }
  565. }
  566. void DisplayServerMacOS::get_key_modifier_state(unsigned int p_macos_state, Ref<InputEventWithModifiers> r_state) const {
  567. r_state->set_shift_pressed((p_macos_state & NSEventModifierFlagShift));
  568. r_state->set_ctrl_pressed((p_macos_state & NSEventModifierFlagControl));
  569. r_state->set_alt_pressed((p_macos_state & NSEventModifierFlagOption));
  570. r_state->set_meta_pressed((p_macos_state & NSEventModifierFlagCommand));
  571. }
  572. void DisplayServerMacOS::update_mouse_pos(DisplayServerMacOS::WindowData &p_wd, NSPoint p_location_in_window) {
  573. const NSRect content_rect = [p_wd.window_view frame];
  574. const float scale = screen_get_max_scale();
  575. p_wd.mouse_pos.x = p_location_in_window.x * scale;
  576. p_wd.mouse_pos.y = (content_rect.size.height - p_location_in_window.y) * scale;
  577. Input::get_singleton()->set_mouse_position(p_wd.mouse_pos);
  578. }
  579. void DisplayServerMacOS::pop_last_key_event() {
  580. // Does not pop last key event when it is an IME key event.
  581. if (key_event_pos > 0 && key_event_buffer[key_event_pos - 1].raw) {
  582. key_event_pos--;
  583. }
  584. }
  585. void DisplayServerMacOS::push_to_key_event_buffer(const DisplayServerMacOS::KeyEvent &p_event) {
  586. if (key_event_pos >= key_event_buffer.size()) {
  587. key_event_buffer.resize(1 + key_event_pos);
  588. }
  589. key_event_buffer.write[key_event_pos++] = p_event;
  590. }
  591. void DisplayServerMacOS::update_im_text(const Point2i &p_selection, const String &p_text) {
  592. im_selection = p_selection;
  593. im_text = p_text;
  594. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  595. }
  596. void DisplayServerMacOS::set_last_focused_window(WindowID p_window) {
  597. last_focused_window = p_window;
  598. }
  599. void DisplayServerMacOS::set_is_resizing(bool p_is_resizing) {
  600. is_resizing = p_is_resizing;
  601. }
  602. bool DisplayServerMacOS::get_is_resizing() const {
  603. return is_resizing;
  604. }
  605. void DisplayServerMacOS::window_destroy(WindowID p_window) {
  606. #if defined(GLES3_ENABLED)
  607. if (gl_manager_legacy) {
  608. gl_manager_legacy->window_destroy(p_window);
  609. }
  610. #endif
  611. #ifdef RD_ENABLED
  612. if (rendering_device) {
  613. rendering_device->screen_free(p_window);
  614. }
  615. if (rendering_context) {
  616. rendering_context->window_destroy(p_window);
  617. }
  618. #endif
  619. windows.erase(p_window);
  620. update_presentation_mode();
  621. }
  622. void DisplayServerMacOS::window_resize(WindowID p_window, int p_width, int p_height) {
  623. #if defined(RD_ENABLED)
  624. if (rendering_context) {
  625. rendering_context->window_set_size(p_window, p_width, p_height);
  626. }
  627. #endif
  628. #if defined(GLES3_ENABLED)
  629. if (gl_manager_legacy) {
  630. gl_manager_legacy->window_resize(p_window, p_width, p_height);
  631. }
  632. if (gl_manager_angle) {
  633. gl_manager_angle->window_resize(p_window, p_width, p_height);
  634. }
  635. #endif
  636. }
  637. bool DisplayServerMacOS::has_feature(Feature p_feature) const {
  638. switch (p_feature) {
  639. #ifndef DISABLE_DEPRECATED
  640. case FEATURE_GLOBAL_MENU: {
  641. return (native_menu && native_menu->has_feature(NativeMenu::FEATURE_GLOBAL_MENU));
  642. } break;
  643. #endif
  644. case FEATURE_SUBWINDOWS:
  645. //case FEATURE_TOUCHSCREEN:
  646. case FEATURE_MOUSE:
  647. case FEATURE_MOUSE_WARP:
  648. case FEATURE_CLIPBOARD:
  649. case FEATURE_CURSOR_SHAPE:
  650. case FEATURE_CUSTOM_CURSOR_SHAPE:
  651. case FEATURE_NATIVE_DIALOG:
  652. case FEATURE_NATIVE_DIALOG_INPUT:
  653. case FEATURE_NATIVE_DIALOG_FILE:
  654. case FEATURE_NATIVE_DIALOG_FILE_EXTRA:
  655. case FEATURE_IME:
  656. case FEATURE_WINDOW_TRANSPARENCY:
  657. case FEATURE_HIDPI:
  658. case FEATURE_ICON:
  659. case FEATURE_NATIVE_ICON:
  660. //case FEATURE_KEEP_SCREEN_ON:
  661. case FEATURE_SWAP_BUFFERS:
  662. case FEATURE_TEXT_TO_SPEECH:
  663. case FEATURE_EXTEND_TO_TITLE:
  664. case FEATURE_SCREEN_CAPTURE:
  665. case FEATURE_STATUS_INDICATOR:
  666. case FEATURE_NATIVE_HELP:
  667. return true;
  668. default: {
  669. }
  670. }
  671. return false;
  672. }
  673. String DisplayServerMacOS::get_name() const {
  674. return "macOS";
  675. }
  676. void DisplayServerMacOS::help_set_search_callbacks(const Callable &p_search_callback, const Callable &p_action_callback) {
  677. help_search_callback = p_search_callback;
  678. help_action_callback = p_action_callback;
  679. }
  680. Callable DisplayServerMacOS::_help_get_search_callback() const {
  681. return help_search_callback;
  682. }
  683. Callable DisplayServerMacOS::_help_get_action_callback() const {
  684. return help_action_callback;
  685. }
  686. bool DisplayServerMacOS::tts_is_speaking() const {
  687. ERR_FAIL_NULL_V_MSG(tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  688. return [tts isSpeaking];
  689. }
  690. bool DisplayServerMacOS::tts_is_paused() const {
  691. ERR_FAIL_NULL_V_MSG(tts, false, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  692. return [tts isPaused];
  693. }
  694. TypedArray<Dictionary> DisplayServerMacOS::tts_get_voices() const {
  695. ERR_FAIL_NULL_V_MSG(tts, Array(), "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  696. return [tts getVoices];
  697. }
  698. void DisplayServerMacOS::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
  699. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  700. [tts speak:p_text voice:p_voice volume:p_volume pitch:p_pitch rate:p_rate utterance_id:p_utterance_id interrupt:p_interrupt];
  701. }
  702. void DisplayServerMacOS::tts_pause() {
  703. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  704. [tts pauseSpeaking];
  705. }
  706. void DisplayServerMacOS::tts_resume() {
  707. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  708. [tts resumeSpeaking];
  709. }
  710. void DisplayServerMacOS::tts_stop() {
  711. ERR_FAIL_NULL_MSG(tts, "Enable the \"audio/general/text_to_speech\" project setting to use text-to-speech.");
  712. [tts stopSpeaking];
  713. }
  714. bool DisplayServerMacOS::is_dark_mode_supported() const {
  715. if (@available(macOS 10.14, *)) {
  716. return true;
  717. } else {
  718. return false;
  719. }
  720. }
  721. bool DisplayServerMacOS::is_dark_mode() const {
  722. if (@available(macOS 10.14, *)) {
  723. if (![[NSUserDefaults standardUserDefaults] objectForKey:@"AppleInterfaceStyle"]) {
  724. return false;
  725. } else {
  726. return ([[[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"] isEqual:@"Dark"]);
  727. }
  728. } else {
  729. return false;
  730. }
  731. }
  732. Color DisplayServerMacOS::get_accent_color() const {
  733. if (@available(macOS 10.14, *)) {
  734. __block NSColor *color = nullptr;
  735. if (@available(macOS 11.0, *)) {
  736. [NSApp.effectiveAppearance performAsCurrentDrawingAppearance:^{
  737. color = [[NSColor controlAccentColor] colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
  738. }];
  739. } else {
  740. NSAppearance *saved_appearance = [NSAppearance currentAppearance];
  741. [NSAppearance setCurrentAppearance:[NSApp effectiveAppearance]];
  742. color = [[NSColor controlAccentColor] colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
  743. [NSAppearance setCurrentAppearance:saved_appearance];
  744. }
  745. if (color) {
  746. CGFloat components[4];
  747. [color getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
  748. return Color(components[0], components[1], components[2], components[3]);
  749. } else {
  750. return Color(0, 0, 0, 0);
  751. }
  752. } else {
  753. return Color(0, 0, 0, 0);
  754. }
  755. }
  756. Color DisplayServerMacOS::get_base_color() const {
  757. if (@available(macOS 10.14, *)) {
  758. __block NSColor *color = nullptr;
  759. if (@available(macOS 11.0, *)) {
  760. [NSApp.effectiveAppearance performAsCurrentDrawingAppearance:^{
  761. color = [[NSColor controlColor] colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
  762. }];
  763. } else {
  764. NSAppearance *saved_appearance = [NSAppearance currentAppearance];
  765. [NSAppearance setCurrentAppearance:[NSApp effectiveAppearance]];
  766. color = [[NSColor controlColor] colorUsingColorSpace:[NSColorSpace genericRGBColorSpace]];
  767. [NSAppearance setCurrentAppearance:saved_appearance];
  768. }
  769. if (color) {
  770. CGFloat components[4];
  771. [color getRed:&components[0] green:&components[1] blue:&components[2] alpha:&components[3]];
  772. return Color(components[0], components[1], components[2], components[3]);
  773. } else {
  774. return Color(0, 0, 0, 0);
  775. }
  776. } else {
  777. return Color(0, 0, 0, 0);
  778. }
  779. }
  780. void DisplayServerMacOS::set_system_theme_change_callback(const Callable &p_callable) {
  781. system_theme_changed = p_callable;
  782. }
  783. void DisplayServerMacOS::emit_system_theme_changed() {
  784. if (system_theme_changed.is_valid()) {
  785. Variant ret;
  786. Callable::CallError ce;
  787. system_theme_changed.callp(nullptr, 0, ret, ce);
  788. if (ce.error != Callable::CallError::CALL_OK) {
  789. ERR_PRINT(vformat("Failed to execute system theme changed callback: %s.", Variant::get_callable_error_text(system_theme_changed, nullptr, 0, ce)));
  790. }
  791. }
  792. }
  793. Error DisplayServerMacOS::dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) {
  794. _THREAD_SAFE_METHOD_
  795. NSAlert *window = [[NSAlert alloc] init];
  796. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  797. NSString *ns_description = [NSString stringWithUTF8String:p_description.utf8().get_data()];
  798. for (int i = 0; i < p_buttons.size(); i++) {
  799. NSString *ns_button = [NSString stringWithUTF8String:p_buttons[i].utf8().get_data()];
  800. [window addButtonWithTitle:ns_button];
  801. }
  802. [window setMessageText:ns_title];
  803. [window setInformativeText:ns_description];
  804. [window setAlertStyle:NSAlertStyleInformational];
  805. Variant button_pressed;
  806. NSInteger ret = [window runModal];
  807. if (ret == NSAlertFirstButtonReturn) {
  808. button_pressed = int64_t(0);
  809. } else if (ret == NSAlertSecondButtonReturn) {
  810. button_pressed = int64_t(1);
  811. } else if (ret == NSAlertThirdButtonReturn) {
  812. button_pressed = int64_t(2);
  813. } else {
  814. button_pressed = int64_t(2 + (ret - NSAlertThirdButtonReturn));
  815. }
  816. if (p_callback.is_valid()) {
  817. Variant ret;
  818. Callable::CallError ce;
  819. const Variant *args[1] = { &button_pressed };
  820. p_callback.callp(args, 1, ret, ce);
  821. if (ce.error != Callable::CallError::CALL_OK) {
  822. ERR_PRINT(vformat("Failed to execute dialog callback: %s.", Variant::get_callable_error_text(p_callback, args, 1, ce)));
  823. }
  824. }
  825. return OK;
  826. }
  827. Error DisplayServerMacOS::file_dialog_show(const String &p_title, const String &p_current_directory, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const Callable &p_callback) {
  828. return _file_dialog_with_options_show(p_title, p_current_directory, String(), p_filename, p_show_hidden, p_mode, p_filters, TypedArray<Dictionary>(), p_callback, false);
  829. }
  830. Error DisplayServerMacOS::file_dialog_with_options_show(const String &p_title, const String &p_current_directory, const String &p_root, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const TypedArray<Dictionary> &p_options, const Callable &p_callback) {
  831. return _file_dialog_with_options_show(p_title, p_current_directory, p_root, p_filename, p_show_hidden, p_mode, p_filters, p_options, p_callback, true);
  832. }
  833. Error DisplayServerMacOS::_file_dialog_with_options_show(const String &p_title, const String &p_current_directory, const String &p_root, const String &p_filename, bool p_show_hidden, FileDialogMode p_mode, const Vector<String> &p_filters, const TypedArray<Dictionary> &p_options, const Callable &p_callback, bool p_options_in_cb) {
  834. _THREAD_SAFE_METHOD_
  835. ERR_FAIL_INDEX_V(int(p_mode), FILE_DIALOG_MODE_SAVE_MAX, FAILED);
  836. NSString *url = [NSString stringWithUTF8String:p_current_directory.utf8().get_data()];
  837. WindowID prev_focus = last_focused_window;
  838. GodotOpenSaveDelegate *panel_delegate = [[GodotOpenSaveDelegate alloc] init];
  839. if (p_root.length() > 0) {
  840. [panel_delegate setRootPath:p_root];
  841. }
  842. Callable callback = p_callback; // Make a copy for async completion handler.
  843. if (p_mode == FILE_DIALOG_MODE_SAVE_FILE) {
  844. NSSavePanel *panel = [NSSavePanel savePanel];
  845. [panel setDirectoryURL:[NSURL fileURLWithPath:url]];
  846. [panel_delegate makeAccessoryView:panel filters:p_filters options:p_options];
  847. [panel setExtensionHidden:YES];
  848. [panel setCanSelectHiddenExtension:YES];
  849. [panel setCanCreateDirectories:YES];
  850. [panel setShowsHiddenFiles:p_show_hidden];
  851. [panel setDelegate:panel_delegate];
  852. if (p_filename != "") {
  853. NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()];
  854. [panel setNameFieldStringValue:fileurl];
  855. }
  856. [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow]
  857. completionHandler:^(NSInteger ret) {
  858. if (ret == NSModalResponseOK) {
  859. // Save bookmark for folder.
  860. if (OS::get_singleton()->is_sandboxed()) {
  861. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  862. bool skip = false;
  863. for (id bookmark in bookmarks) {
  864. NSError *error = nil;
  865. BOOL isStale = NO;
  866. NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  867. if (!error && !isStale && ([[exurl path] compare:[[panel directoryURL] path]] == NSOrderedSame)) {
  868. skip = true;
  869. break;
  870. }
  871. }
  872. if (!skip) {
  873. NSError *error = nil;
  874. NSData *bookmark = [[panel directoryURL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
  875. if (!error) {
  876. NSArray *new_bookmarks = [bookmarks arrayByAddingObject:bookmark];
  877. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  878. }
  879. }
  880. }
  881. // Callback.
  882. Vector<String> files;
  883. String url;
  884. url.parse_utf8([[[panel URL] path] UTF8String]);
  885. files.push_back(url);
  886. if (callback.is_valid()) {
  887. if (p_options_in_cb) {
  888. Variant v_result = true;
  889. Variant v_files = files;
  890. Variant v_index = [panel_delegate getIndex];
  891. Variant v_opt = [panel_delegate getSelection];
  892. Variant ret;
  893. Callable::CallError ce;
  894. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  895. callback.callp(args, 4, ret, ce);
  896. if (ce.error != Callable::CallError::CALL_OK) {
  897. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  898. }
  899. } else {
  900. Variant v_result = true;
  901. Variant v_files = files;
  902. Variant v_index = [panel_delegate getIndex];
  903. Variant ret;
  904. Callable::CallError ce;
  905. const Variant *args[3] = { &v_result, &v_files, &v_index };
  906. callback.callp(args, 3, ret, ce);
  907. if (ce.error != Callable::CallError::CALL_OK) {
  908. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  909. }
  910. }
  911. }
  912. } else {
  913. if (callback.is_valid()) {
  914. if (p_options_in_cb) {
  915. Variant v_result = false;
  916. Variant v_files = Vector<String>();
  917. Variant v_index = [panel_delegate getIndex];
  918. Variant v_opt = [panel_delegate getSelection];
  919. Variant ret;
  920. Callable::CallError ce;
  921. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  922. callback.callp(args, 4, ret, ce);
  923. if (ce.error != Callable::CallError::CALL_OK) {
  924. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  925. }
  926. } else {
  927. Variant v_result = false;
  928. Variant v_files = Vector<String>();
  929. Variant v_index = [panel_delegate getIndex];
  930. Variant ret;
  931. Callable::CallError ce;
  932. const Variant *args[3] = { &v_result, &v_files, &v_index };
  933. callback.callp(args, 3, ret, ce);
  934. if (ce.error != Callable::CallError::CALL_OK) {
  935. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  936. }
  937. }
  938. }
  939. }
  940. if (prev_focus != INVALID_WINDOW_ID) {
  941. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(prev_focus);
  942. }
  943. }];
  944. } else {
  945. NSOpenPanel *panel = [NSOpenPanel openPanel];
  946. [panel setDirectoryURL:[NSURL fileURLWithPath:url]];
  947. [panel_delegate makeAccessoryView:panel filters:p_filters options:p_options];
  948. [panel setExtensionHidden:YES];
  949. [panel setCanSelectHiddenExtension:YES];
  950. [panel setCanCreateDirectories:YES];
  951. [panel setCanChooseFiles:(p_mode != FILE_DIALOG_MODE_OPEN_DIR)];
  952. [panel setCanChooseDirectories:(p_mode == FILE_DIALOG_MODE_OPEN_DIR || p_mode == FILE_DIALOG_MODE_OPEN_ANY)];
  953. [panel setShowsHiddenFiles:p_show_hidden];
  954. [panel setDelegate:panel_delegate];
  955. if (p_filename != "") {
  956. NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()];
  957. [panel setNameFieldStringValue:fileurl];
  958. }
  959. [panel setAllowsMultipleSelection:(p_mode == FILE_DIALOG_MODE_OPEN_FILES)];
  960. [panel beginSheetModalForWindow:[[NSApplication sharedApplication] mainWindow]
  961. completionHandler:^(NSInteger ret) {
  962. if (ret == NSModalResponseOK) {
  963. // Save bookmark for folder.
  964. NSArray *urls = [(NSOpenPanel *)panel URLs];
  965. if (OS::get_singleton()->is_sandboxed()) {
  966. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  967. NSMutableArray *new_bookmarks = [bookmarks mutableCopy];
  968. for (NSUInteger i = 0; i != [urls count]; ++i) {
  969. bool skip = false;
  970. for (id bookmark in bookmarks) {
  971. NSError *error = nil;
  972. BOOL isStale = NO;
  973. NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  974. if (!error && !isStale && ([[exurl path] compare:[[urls objectAtIndex:i] path]] == NSOrderedSame)) {
  975. skip = true;
  976. break;
  977. }
  978. }
  979. if (!skip) {
  980. NSError *error = nil;
  981. NSData *bookmark = [[urls objectAtIndex:i] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
  982. if (!error) {
  983. [new_bookmarks addObject:bookmark];
  984. }
  985. }
  986. }
  987. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  988. }
  989. // Callback.
  990. Vector<String> files;
  991. for (NSUInteger i = 0; i != [urls count]; ++i) {
  992. String url;
  993. url.parse_utf8([[[urls objectAtIndex:i] path] UTF8String]);
  994. files.push_back(url);
  995. }
  996. if (callback.is_valid()) {
  997. if (p_options_in_cb) {
  998. Variant v_result = true;
  999. Variant v_files = files;
  1000. Variant v_index = [panel_delegate getIndex];
  1001. Variant v_opt = [panel_delegate getSelection];
  1002. Variant ret;
  1003. Callable::CallError ce;
  1004. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  1005. callback.callp(args, 4, ret, ce);
  1006. if (ce.error != Callable::CallError::CALL_OK) {
  1007. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  1008. }
  1009. } else {
  1010. Variant v_result = true;
  1011. Variant v_files = files;
  1012. Variant v_index = [panel_delegate getIndex];
  1013. Variant ret;
  1014. Callable::CallError ce;
  1015. const Variant *args[3] = { &v_result, &v_files, &v_index };
  1016. callback.callp(args, 3, ret, ce);
  1017. if (ce.error != Callable::CallError::CALL_OK) {
  1018. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  1019. }
  1020. }
  1021. }
  1022. } else {
  1023. if (callback.is_valid()) {
  1024. if (p_options_in_cb) {
  1025. Variant v_result = false;
  1026. Variant v_files = Vector<String>();
  1027. Variant v_index = [panel_delegate getIndex];
  1028. Variant v_opt = [panel_delegate getSelection];
  1029. Variant ret;
  1030. Callable::CallError ce;
  1031. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  1032. callback.callp(args, 4, ret, ce);
  1033. if (ce.error != Callable::CallError::CALL_OK) {
  1034. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  1035. }
  1036. } else {
  1037. Variant v_result = false;
  1038. Variant v_files = Vector<String>();
  1039. Variant v_index = [panel_delegate getIndex];
  1040. Variant ret;
  1041. Callable::CallError ce;
  1042. const Variant *args[3] = { &v_result, &v_files, &v_index };
  1043. callback.callp(args, 3, ret, ce);
  1044. if (ce.error != Callable::CallError::CALL_OK) {
  1045. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  1046. }
  1047. }
  1048. }
  1049. }
  1050. if (prev_focus != INVALID_WINDOW_ID) {
  1051. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(prev_focus);
  1052. }
  1053. }];
  1054. }
  1055. return OK;
  1056. }
  1057. Error DisplayServerMacOS::dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) {
  1058. _THREAD_SAFE_METHOD_
  1059. NSAlert *window = [[NSAlert alloc] init];
  1060. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  1061. NSString *ns_description = [NSString stringWithUTF8String:p_description.utf8().get_data()];
  1062. NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 250, 30)];
  1063. [window addButtonWithTitle:@"OK"];
  1064. [window setMessageText:ns_title];
  1065. [window setInformativeText:ns_description];
  1066. [window setAlertStyle:NSAlertStyleInformational];
  1067. [input setStringValue:[NSString stringWithUTF8String:p_partial.utf8().get_data()]];
  1068. [window setAccessoryView:input];
  1069. [window runModal];
  1070. String ret;
  1071. ret.parse_utf8([[input stringValue] UTF8String]);
  1072. if (p_callback.is_valid()) {
  1073. Variant v_result = ret;
  1074. Variant ret;
  1075. Callable::CallError ce;
  1076. const Variant *args[1] = { &v_result };
  1077. p_callback.callp(args, 1, ret, ce);
  1078. if (ce.error != Callable::CallError::CALL_OK) {
  1079. ERR_PRINT(vformat("Failed to execute input dialog callback: %s.", Variant::get_callable_error_text(p_callback, args, 1, ce)));
  1080. }
  1081. }
  1082. return OK;
  1083. }
  1084. void DisplayServerMacOS::mouse_set_mode(MouseMode p_mode) {
  1085. _THREAD_SAFE_METHOD_
  1086. if (p_mode == mouse_mode) {
  1087. return;
  1088. }
  1089. WindowID window_id = _get_focused_window_or_popup();
  1090. if (!windows.has(window_id)) {
  1091. window_id = MAIN_WINDOW_ID;
  1092. }
  1093. WindowData &wd = windows[window_id];
  1094. bool show_cursor = (p_mode == MOUSE_MODE_VISIBLE || p_mode == MOUSE_MODE_CONFINED);
  1095. bool previously_shown = (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED);
  1096. if (show_cursor && !previously_shown) {
  1097. window_id = get_window_at_screen_position(mouse_get_position());
  1098. mouse_enter_window(window_id);
  1099. }
  1100. if (p_mode == MOUSE_MODE_CAPTURED) {
  1101. // Apple Docs state that the display parameter is not used.
  1102. // "This parameter is not used. By default, you may pass kCGDirectMainDisplay."
  1103. // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html
  1104. if (previously_shown) {
  1105. CGDisplayHideCursor(kCGDirectMainDisplay);
  1106. }
  1107. CGAssociateMouseAndMouseCursorPosition(false);
  1108. [wd.window_object setMovable:NO];
  1109. const NSRect contentRect = [wd.window_view frame];
  1110. NSRect pointInWindowRect = NSMakeRect(contentRect.size.width / 2, contentRect.size.height / 2, 0, 0);
  1111. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  1112. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1113. CGWarpMouseCursorPosition(lMouseWarpPos);
  1114. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  1115. if (previously_shown) {
  1116. CGDisplayHideCursor(kCGDirectMainDisplay);
  1117. }
  1118. [wd.window_object setMovable:YES];
  1119. CGAssociateMouseAndMouseCursorPosition(true);
  1120. } else if (p_mode == MOUSE_MODE_CONFINED) {
  1121. CGDisplayShowCursor(kCGDirectMainDisplay);
  1122. [wd.window_object setMovable:NO];
  1123. CGAssociateMouseAndMouseCursorPosition(false);
  1124. } else if (p_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  1125. if (previously_shown) {
  1126. CGDisplayHideCursor(kCGDirectMainDisplay);
  1127. }
  1128. [wd.window_object setMovable:NO];
  1129. CGAssociateMouseAndMouseCursorPosition(false);
  1130. } else { // MOUSE_MODE_VISIBLE
  1131. CGDisplayShowCursor(kCGDirectMainDisplay);
  1132. [wd.window_object setMovable:YES];
  1133. CGAssociateMouseAndMouseCursorPosition(true);
  1134. }
  1135. last_warp = [[NSProcessInfo processInfo] systemUptime];
  1136. ignore_warp = true;
  1137. warp_events.clear();
  1138. mouse_mode = p_mode;
  1139. if (show_cursor) {
  1140. cursor_update_shape();
  1141. }
  1142. }
  1143. DisplayServer::MouseMode DisplayServerMacOS::mouse_get_mode() const {
  1144. return mouse_mode;
  1145. }
  1146. bool DisplayServerMacOS::update_mouse_wrap(WindowData &p_wd, NSPoint &r_delta, NSPoint &r_mpos, NSTimeInterval p_timestamp) {
  1147. _THREAD_SAFE_METHOD_
  1148. if (ignore_warp) {
  1149. // Discard late events, before warp.
  1150. if (p_timestamp < last_warp) {
  1151. return true;
  1152. }
  1153. ignore_warp = false;
  1154. return true;
  1155. }
  1156. if (mouse_mode == DisplayServer::MOUSE_MODE_CONFINED || mouse_mode == DisplayServer::MOUSE_MODE_CONFINED_HIDDEN) {
  1157. // Discard late events.
  1158. if (p_timestamp < last_warp) {
  1159. return true;
  1160. }
  1161. // Warp affects next event delta, subtract previous warp deltas.
  1162. List<WarpEvent>::Element *F = warp_events.front();
  1163. while (F) {
  1164. if (F->get().timestamp < p_timestamp) {
  1165. List<DisplayServerMacOS::WarpEvent>::Element *E = F;
  1166. r_delta.x -= E->get().delta.x;
  1167. r_delta.y -= E->get().delta.y;
  1168. F = F->next();
  1169. warp_events.erase(E);
  1170. } else {
  1171. F = F->next();
  1172. }
  1173. }
  1174. // Confine mouse position to the window, and update delta.
  1175. NSRect frame = [p_wd.window_view frame];
  1176. NSPoint conf_pos = r_mpos;
  1177. conf_pos.x = CLAMP(conf_pos.x + r_delta.x, 0.f, frame.size.width);
  1178. conf_pos.y = CLAMP(conf_pos.y - r_delta.y, 0.f, frame.size.height);
  1179. r_delta.x = conf_pos.x - r_mpos.x;
  1180. r_delta.y = r_mpos.y - conf_pos.y;
  1181. r_mpos = conf_pos;
  1182. // Move mouse cursor.
  1183. NSRect point_in_window_rect = NSMakeRect(conf_pos.x, conf_pos.y, 0, 0);
  1184. conf_pos = [[p_wd.window_view window] convertRectToScreen:point_in_window_rect].origin;
  1185. conf_pos.y = CGDisplayBounds(CGMainDisplayID()).size.height - conf_pos.y;
  1186. CGWarpMouseCursorPosition(conf_pos);
  1187. // Save warp data.
  1188. last_warp = [[NSProcessInfo processInfo] systemUptime];
  1189. DisplayServerMacOS::WarpEvent ev;
  1190. ev.timestamp = last_warp;
  1191. ev.delta = r_delta;
  1192. warp_events.push_back(ev);
  1193. }
  1194. return false;
  1195. }
  1196. void DisplayServerMacOS::warp_mouse(const Point2i &p_position) {
  1197. _THREAD_SAFE_METHOD_
  1198. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  1199. WindowID window_id = _get_focused_window_or_popup();
  1200. if (!windows.has(window_id)) {
  1201. window_id = MAIN_WINDOW_ID;
  1202. }
  1203. WindowData &wd = windows[window_id];
  1204. // Local point in window coords.
  1205. const NSRect contentRect = [wd.window_view frame];
  1206. const float scale = screen_get_max_scale();
  1207. NSRect pointInWindowRect = NSMakeRect(p_position.x / scale, contentRect.size.height - (p_position.y / scale), scale, scale);
  1208. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  1209. // Point in screen coords.
  1210. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1211. // Do the warping.
  1212. CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
  1213. CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
  1214. CGAssociateMouseAndMouseCursorPosition(false);
  1215. CGWarpMouseCursorPosition(lMouseWarpPos);
  1216. if (mouse_mode != MOUSE_MODE_CONFINED && mouse_mode != MOUSE_MODE_CONFINED_HIDDEN) {
  1217. CGAssociateMouseAndMouseCursorPosition(true);
  1218. }
  1219. }
  1220. }
  1221. Point2i DisplayServerMacOS::mouse_get_position() const {
  1222. _THREAD_SAFE_METHOD_
  1223. const NSPoint mouse_pos = [NSEvent mouseLocation];
  1224. const float scale = screen_get_max_scale();
  1225. for (NSScreen *screen in [NSScreen screens]) {
  1226. NSRect frame = [screen frame];
  1227. if (NSMouseInRect(mouse_pos, frame, NO)) {
  1228. Vector2i pos = Vector2i((int)mouse_pos.x, (int)mouse_pos.y);
  1229. pos *= scale;
  1230. pos -= _get_screens_origin();
  1231. pos.y *= -1;
  1232. return pos;
  1233. }
  1234. }
  1235. return Vector2i();
  1236. }
  1237. BitField<MouseButtonMask> DisplayServerMacOS::mouse_get_button_state() const {
  1238. BitField<MouseButtonMask> last_button_state = 0;
  1239. NSUInteger buttons = [NSEvent pressedMouseButtons];
  1240. if (buttons & (1 << 0)) {
  1241. last_button_state.set_flag(MouseButtonMask::LEFT);
  1242. }
  1243. if (buttons & (1 << 1)) {
  1244. last_button_state.set_flag(MouseButtonMask::RIGHT);
  1245. }
  1246. if (buttons & (1 << 2)) {
  1247. last_button_state.set_flag(MouseButtonMask::MIDDLE);
  1248. }
  1249. if (buttons & (1 << 3)) {
  1250. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
  1251. }
  1252. if (buttons & (1 << 4)) {
  1253. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
  1254. }
  1255. return last_button_state;
  1256. }
  1257. void DisplayServerMacOS::clipboard_set(const String &p_text) {
  1258. _THREAD_SAFE_METHOD_
  1259. NSString *copiedString = [NSString stringWithUTF8String:p_text.utf8().get_data()];
  1260. NSArray *copiedStringArray = [NSArray arrayWithObject:copiedString];
  1261. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1262. [pasteboard clearContents];
  1263. [pasteboard writeObjects:copiedStringArray];
  1264. }
  1265. String DisplayServerMacOS::clipboard_get() const {
  1266. _THREAD_SAFE_METHOD_
  1267. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1268. NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
  1269. NSDictionary *options = [NSDictionary dictionary];
  1270. BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
  1271. if (!ok) {
  1272. return "";
  1273. }
  1274. NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
  1275. NSString *string = [objectsToPaste objectAtIndex:0];
  1276. String ret;
  1277. ret.parse_utf8([string UTF8String]);
  1278. return ret;
  1279. }
  1280. Ref<Image> DisplayServerMacOS::clipboard_get_image() const {
  1281. Ref<Image> image;
  1282. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1283. NSString *result = [pasteboard availableTypeFromArray:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSPasteboardTypePNG, nil]];
  1284. if (!result) {
  1285. return image;
  1286. }
  1287. NSData *data = [pasteboard dataForType:result];
  1288. if (!data) {
  1289. return image;
  1290. }
  1291. NSBitmapImageRep *bitmap = [NSBitmapImageRep imageRepWithData:data];
  1292. NSData *pngData = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
  1293. image.instantiate();
  1294. PNGDriverCommon::png_to_image((const uint8_t *)pngData.bytes, pngData.length, false, image);
  1295. return image;
  1296. }
  1297. bool DisplayServerMacOS::clipboard_has() const {
  1298. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1299. NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
  1300. NSDictionary *options = [NSDictionary dictionary];
  1301. return [pasteboard canReadObjectForClasses:classArray options:options];
  1302. }
  1303. bool DisplayServerMacOS::clipboard_has_image() const {
  1304. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1305. NSString *result = [pasteboard availableTypeFromArray:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSPasteboardTypePNG, nil]];
  1306. return result;
  1307. }
  1308. int DisplayServerMacOS::get_screen_count() const {
  1309. _THREAD_SAFE_METHOD_
  1310. NSArray *screenArray = [NSScreen screens];
  1311. return [screenArray count];
  1312. }
  1313. int DisplayServerMacOS::get_primary_screen() const {
  1314. return 0;
  1315. }
  1316. int DisplayServerMacOS::get_keyboard_focus_screen() const {
  1317. const NSUInteger index = [[NSScreen screens] indexOfObject:[NSScreen mainScreen]];
  1318. return (index == NSNotFound) ? 0 : index;
  1319. }
  1320. Point2i DisplayServerMacOS::screen_get_position(int p_screen) const {
  1321. _THREAD_SAFE_METHOD_
  1322. p_screen = _get_screen_index(p_screen);
  1323. Point2i position = _get_native_screen_position(p_screen) - _get_screens_origin();
  1324. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1325. // Godot expects a positive value.
  1326. position.y *= -1;
  1327. return position;
  1328. }
  1329. Size2i DisplayServerMacOS::screen_get_size(int p_screen) const {
  1330. _THREAD_SAFE_METHOD_
  1331. p_screen = _get_screen_index(p_screen);
  1332. NSArray *screenArray = [NSScreen screens];
  1333. if ((NSUInteger)p_screen < [screenArray count]) {
  1334. // Note: Use frame to get the whole screen size.
  1335. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1336. return Size2i(nsrect.size.width, nsrect.size.height) * screen_get_max_scale();
  1337. }
  1338. return Size2i();
  1339. }
  1340. int DisplayServerMacOS::screen_get_dpi(int p_screen) const {
  1341. _THREAD_SAFE_METHOD_
  1342. p_screen = _get_screen_index(p_screen);
  1343. NSArray *screenArray = [NSScreen screens];
  1344. if ((NSUInteger)p_screen < [screenArray count]) {
  1345. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1346. const NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
  1347. const CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1348. float scale = [[screenArray objectAtIndex:p_screen] backingScaleFactor];
  1349. float den2 = (displayPhysicalSize.width / 25.4f) * (displayPhysicalSize.width / 25.4f) + (displayPhysicalSize.height / 25.4f) * (displayPhysicalSize.height / 25.4f);
  1350. if (den2 > 0.0f) {
  1351. return ceil(sqrt(displayPixelSize.width * displayPixelSize.width + displayPixelSize.height * displayPixelSize.height) / sqrt(den2) * scale);
  1352. }
  1353. }
  1354. return 72;
  1355. }
  1356. float DisplayServerMacOS::screen_get_scale(int p_screen) const {
  1357. _THREAD_SAFE_METHOD_
  1358. p_screen = _get_screen_index(p_screen);
  1359. if (OS::get_singleton()->is_hidpi_allowed()) {
  1360. NSArray *screenArray = [NSScreen screens];
  1361. if ((NSUInteger)p_screen < [screenArray count]) {
  1362. if ([[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
  1363. return fmax(1.0, [[screenArray objectAtIndex:p_screen] backingScaleFactor]);
  1364. }
  1365. }
  1366. }
  1367. return 1.f;
  1368. }
  1369. float DisplayServerMacOS::screen_get_max_scale() const {
  1370. _THREAD_SAFE_METHOD_
  1371. // Note: Do not update max display scale on screen configuration change, existing editor windows can't be rescaled on the fly.
  1372. return display_max_scale;
  1373. }
  1374. Rect2i DisplayServerMacOS::screen_get_usable_rect(int p_screen) const {
  1375. _THREAD_SAFE_METHOD_
  1376. p_screen = _get_screen_index(p_screen);
  1377. NSArray *screenArray = [NSScreen screens];
  1378. if ((NSUInteger)p_screen < [screenArray count]) {
  1379. const float scale = screen_get_max_scale();
  1380. NSRect nsrect = [[screenArray objectAtIndex:p_screen] visibleFrame];
  1381. Point2i position = Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * scale - _get_screens_origin();
  1382. position.y *= -1;
  1383. Size2i size = Size2i(nsrect.size.width, nsrect.size.height) * scale;
  1384. return Rect2i(position, size);
  1385. }
  1386. return Rect2i();
  1387. }
  1388. Color DisplayServerMacOS::screen_get_pixel(const Point2i &p_position) const {
  1389. Point2i position = p_position;
  1390. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1391. // Godot passes a positive value.
  1392. position.y *= -1;
  1393. position += _get_screens_origin();
  1394. position /= screen_get_max_scale();
  1395. Color color;
  1396. for (NSScreen *screen in [NSScreen screens]) {
  1397. NSRect frame = [screen frame];
  1398. if (NSMouseInRect(NSMakePoint(position.x, position.y), frame, NO)) {
  1399. NSDictionary *screenDescription = [screen deviceDescription];
  1400. CGDirectDisplayID display_id = [[screenDescription objectForKey:@"NSScreenNumber"] unsignedIntValue];
  1401. CGImageRef image = CGDisplayCreateImageForRect(display_id, CGRectMake(position.x - frame.origin.x, frame.size.height - (position.y - frame.origin.y), 1, 1));
  1402. if (image) {
  1403. CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
  1404. if (color_space) {
  1405. uint8_t img_data[4];
  1406. CGContextRef context = CGBitmapContextCreate(img_data, 1, 1, 8, 4, color_space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  1407. if (context) {
  1408. CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), image);
  1409. color = Color(img_data[0] / 255.0f, img_data[1] / 255.0f, img_data[2] / 255.0f, img_data[3] / 255.0f);
  1410. CGContextRelease(context);
  1411. }
  1412. CGColorSpaceRelease(color_space);
  1413. }
  1414. CGImageRelease(image);
  1415. }
  1416. }
  1417. }
  1418. return color;
  1419. }
  1420. Ref<Image> DisplayServerMacOS::screen_get_image(int p_screen) const {
  1421. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), Ref<Image>());
  1422. switch (p_screen) {
  1423. case SCREEN_PRIMARY: {
  1424. p_screen = get_primary_screen();
  1425. } break;
  1426. case SCREEN_OF_MAIN_WINDOW: {
  1427. p_screen = window_get_current_screen(MAIN_WINDOW_ID);
  1428. } break;
  1429. default:
  1430. break;
  1431. }
  1432. Ref<Image> img;
  1433. NSArray *screenArray = [NSScreen screens];
  1434. if ((NSUInteger)p_screen < [screenArray count]) {
  1435. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1436. NSDictionary *screenDescription = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1437. CGDirectDisplayID display_id = [[screenDescription objectForKey:@"NSScreenNumber"] unsignedIntValue];
  1438. CGImageRef image = CGDisplayCreateImageForRect(display_id, CGRectMake(0, 0, nsrect.size.width, nsrect.size.height));
  1439. if (image) {
  1440. CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
  1441. if (color_space) {
  1442. NSUInteger width = CGImageGetWidth(image);
  1443. NSUInteger height = CGImageGetHeight(image);
  1444. Vector<uint8_t> img_data;
  1445. img_data.resize(height * width * 4);
  1446. CGContextRef context = CGBitmapContextCreate(img_data.ptrw(), width, height, 8, 4 * width, color_space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  1447. if (context) {
  1448. CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
  1449. img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
  1450. CGContextRelease(context);
  1451. }
  1452. CGColorSpaceRelease(color_space);
  1453. }
  1454. CGImageRelease(image);
  1455. }
  1456. }
  1457. return img;
  1458. }
  1459. float DisplayServerMacOS::screen_get_refresh_rate(int p_screen) const {
  1460. _THREAD_SAFE_METHOD_
  1461. p_screen = _get_screen_index(p_screen);
  1462. NSArray *screenArray = [NSScreen screens];
  1463. if ((NSUInteger)p_screen < [screenArray count]) {
  1464. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1465. const CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1466. const double displayRefreshRate = CGDisplayModeGetRefreshRate(displayMode);
  1467. return (float)displayRefreshRate;
  1468. }
  1469. ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
  1470. return SCREEN_REFRESH_RATE_FALLBACK;
  1471. }
  1472. bool DisplayServerMacOS::screen_is_kept_on() const {
  1473. return (screen_keep_on_assertion);
  1474. }
  1475. void DisplayServerMacOS::screen_set_keep_on(bool p_enable) {
  1476. if (screen_keep_on_assertion) {
  1477. IOPMAssertionRelease(screen_keep_on_assertion);
  1478. screen_keep_on_assertion = kIOPMNullAssertionID;
  1479. }
  1480. if (p_enable) {
  1481. String app_name_string = GLOBAL_GET("application/config/name");
  1482. NSString *name = [NSString stringWithUTF8String:(app_name_string.is_empty() ? "Godot Engine" : app_name_string.utf8().get_data())];
  1483. NSString *reason = @"Godot Engine running with display/window/energy_saving/keep_screen_on = true";
  1484. IOPMAssertionCreateWithDescription(kIOPMAssertPreventUserIdleDisplaySleep, (__bridge CFStringRef)name, (__bridge CFStringRef)reason, (__bridge CFStringRef)reason, nullptr, 0, nullptr, &screen_keep_on_assertion);
  1485. }
  1486. }
  1487. Vector<DisplayServer::WindowID> DisplayServerMacOS::get_window_list() const {
  1488. _THREAD_SAFE_METHOD_
  1489. Vector<int> ret;
  1490. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1491. ret.push_back(E.key);
  1492. }
  1493. return ret;
  1494. }
  1495. DisplayServer::WindowID DisplayServerMacOS::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect, bool p_exclusive, WindowID p_transient_parent) {
  1496. _THREAD_SAFE_METHOD_
  1497. WindowID id = _create_window(p_mode, p_vsync_mode, p_rect);
  1498. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  1499. if (p_flags & (1 << i)) {
  1500. window_set_flag(WindowFlags(i), true, id);
  1501. }
  1502. }
  1503. #ifdef RD_ENABLED
  1504. if (rendering_device) {
  1505. rendering_device->screen_create(id);
  1506. }
  1507. #endif
  1508. window_set_exclusive(id, p_exclusive);
  1509. if (p_transient_parent != INVALID_WINDOW_ID) {
  1510. window_set_transient(id, p_transient_parent);
  1511. }
  1512. return id;
  1513. }
  1514. void DisplayServerMacOS::show_window(WindowID p_id) {
  1515. WindowData &wd = windows[p_id];
  1516. popup_open(p_id);
  1517. if ([wd.window_object isMiniaturized]) {
  1518. return;
  1519. } else if (wd.no_focus) {
  1520. [wd.window_object orderFront:nil];
  1521. } else {
  1522. [wd.window_object makeKeyAndOrderFront:nil];
  1523. }
  1524. }
  1525. void DisplayServerMacOS::delete_sub_window(WindowID p_id) {
  1526. _THREAD_SAFE_METHOD_
  1527. ERR_FAIL_COND(!windows.has(p_id));
  1528. ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted");
  1529. WindowData &wd = windows[p_id];
  1530. [wd.window_object setContentView:nil];
  1531. [wd.window_object close];
  1532. }
  1533. void DisplayServerMacOS::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1534. _THREAD_SAFE_METHOD_
  1535. ERR_FAIL_COND(!windows.has(p_window));
  1536. WindowData &wd = windows[p_window];
  1537. wd.rect_changed_callback = p_callable;
  1538. }
  1539. void DisplayServerMacOS::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1540. _THREAD_SAFE_METHOD_
  1541. ERR_FAIL_COND(!windows.has(p_window));
  1542. WindowData &wd = windows[p_window];
  1543. wd.event_callback = p_callable;
  1544. }
  1545. void DisplayServerMacOS::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1546. _THREAD_SAFE_METHOD_
  1547. ERR_FAIL_COND(!windows.has(p_window));
  1548. WindowData &wd = windows[p_window];
  1549. wd.input_event_callback = p_callable;
  1550. }
  1551. void DisplayServerMacOS::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1552. _THREAD_SAFE_METHOD_
  1553. ERR_FAIL_COND(!windows.has(p_window));
  1554. WindowData &wd = windows[p_window];
  1555. wd.input_text_callback = p_callable;
  1556. }
  1557. void DisplayServerMacOS::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1558. _THREAD_SAFE_METHOD_
  1559. ERR_FAIL_COND(!windows.has(p_window));
  1560. WindowData &wd = windows[p_window];
  1561. wd.drop_files_callback = p_callable;
  1562. }
  1563. void DisplayServerMacOS::window_set_title(const String &p_title, WindowID p_window) {
  1564. _THREAD_SAFE_METHOD_
  1565. ERR_FAIL_COND(!windows.has(p_window));
  1566. WindowData &wd = windows[p_window];
  1567. [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
  1568. }
  1569. Size2i DisplayServerMacOS::window_get_title_size(const String &p_title, WindowID p_window) const {
  1570. _THREAD_SAFE_METHOD_
  1571. Size2i size;
  1572. ERR_FAIL_COND_V(!windows.has(p_window), size);
  1573. const WindowData &wd = windows[p_window];
  1574. if (wd.fullscreen || wd.borderless) {
  1575. return size;
  1576. }
  1577. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  1578. if ([wd.window_object isMiniaturized]) {
  1579. return size;
  1580. }
  1581. }
  1582. float scale = screen_get_max_scale();
  1583. if (wd.window_button_view) {
  1584. size.x = ([wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width);
  1585. size.y = ([wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height);
  1586. } else {
  1587. NSButton *cb = [wd.window_object standardWindowButton:NSWindowCloseButton];
  1588. NSButton *mb = [wd.window_object standardWindowButton:NSWindowMiniaturizeButton];
  1589. float cb_frame = NSMinX([cb frame]);
  1590. float mb_frame = NSMinX([mb frame]);
  1591. bool is_rtl = ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft);
  1592. float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame);
  1593. size.x = window_buttons_spacing * 4;
  1594. size.y = [cb frame].origin.y + [cb frame].size.height;
  1595. }
  1596. NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont titleBarFontOfSize:0], NSFontAttributeName, nil];
  1597. NSSize text_size = [[[NSAttributedString alloc] initWithString:[NSString stringWithUTF8String:p_title.utf8().get_data()] attributes:attributes] size];
  1598. size.x += text_size.width;
  1599. size.y = MAX(size.y, text_size.height);
  1600. return size * scale;
  1601. }
  1602. void DisplayServerMacOS::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1603. _THREAD_SAFE_METHOD_
  1604. ERR_FAIL_COND(!windows.has(p_window));
  1605. WindowData &wd = windows[p_window];
  1606. wd.mpath = p_region;
  1607. }
  1608. int DisplayServerMacOS::window_get_current_screen(WindowID p_window) const {
  1609. _THREAD_SAFE_METHOD_
  1610. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  1611. const WindowData &wd = windows[p_window];
  1612. const NSUInteger index = [[NSScreen screens] indexOfObject:[wd.window_object screen]];
  1613. return (index == NSNotFound) ? 0 : index;
  1614. }
  1615. void DisplayServerMacOS::window_set_current_screen(int p_screen, WindowID p_window) {
  1616. _THREAD_SAFE_METHOD_
  1617. ERR_FAIL_COND(!windows.has(p_window));
  1618. WindowData &wd = windows[p_window];
  1619. if (window_get_current_screen(p_window) == p_screen) {
  1620. return;
  1621. }
  1622. bool was_fullscreen = false;
  1623. if (wd.fullscreen) {
  1624. // Temporary exit fullscreen mode to move window.
  1625. [wd.window_object toggleFullScreen:nil];
  1626. was_fullscreen = true;
  1627. }
  1628. bool was_maximized = false;
  1629. if (!was_fullscreen && NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1630. [wd.window_object zoom:nil];
  1631. was_maximized = true;
  1632. }
  1633. Rect2i srect = screen_get_usable_rect(p_screen);
  1634. Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  1635. Size2i wsize = window_get_size(p_window);
  1636. wpos += srect.position;
  1637. wpos = wpos.clamp(srect.position, srect.position + srect.size - wsize / 3);
  1638. window_set_position(wpos, p_window);
  1639. if (was_maximized) {
  1640. [wd.window_object zoom:nil];
  1641. }
  1642. if (was_fullscreen) {
  1643. // Re-enter fullscreen mode.
  1644. [wd.window_object toggleFullScreen:nil];
  1645. }
  1646. }
  1647. void DisplayServerMacOS::reparent_check(WindowID p_window) {
  1648. ERR_FAIL_COND(!windows.has(p_window));
  1649. WindowData &wd = windows[p_window];
  1650. NSScreen *screen = [wd.window_object screen];
  1651. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1652. WindowData &wd_parent = windows[wd.transient_parent];
  1653. NSScreen *parent_screen = [wd_parent.window_object screen];
  1654. if (parent_screen == screen) {
  1655. if (![[wd_parent.window_object childWindows] containsObject:wd.window_object]) {
  1656. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
  1657. [wd_parent.window_object addChildWindow:wd.window_object ordered:NSWindowAbove];
  1658. }
  1659. } else {
  1660. if ([[wd_parent.window_object childWindows] containsObject:wd.window_object]) {
  1661. [wd_parent.window_object removeChildWindow:wd.window_object];
  1662. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1663. [wd.window_object orderFront:nil];
  1664. }
  1665. }
  1666. }
  1667. for (const WindowID &child : wd.transient_children) {
  1668. WindowData &wd_child = windows[child];
  1669. NSScreen *child_screen = [wd_child.window_object screen];
  1670. if (child_screen == screen) {
  1671. if (![[wd.window_object childWindows] containsObject:wd_child.window_object]) {
  1672. if (wd_child.fullscreen) {
  1673. [wd_child.window_object toggleFullScreen:nil];
  1674. }
  1675. [wd_child.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
  1676. [wd.window_object addChildWindow:wd_child.window_object ordered:NSWindowAbove];
  1677. }
  1678. } else {
  1679. if ([[wd.window_object childWindows] containsObject:wd_child.window_object]) {
  1680. [wd.window_object removeChildWindow:wd_child.window_object];
  1681. [wd_child.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1682. }
  1683. }
  1684. }
  1685. }
  1686. void DisplayServerMacOS::window_set_exclusive(WindowID p_window, bool p_exclusive) {
  1687. _THREAD_SAFE_METHOD_
  1688. ERR_FAIL_COND(!windows.has(p_window));
  1689. WindowData &wd = windows[p_window];
  1690. if (wd.exclusive != p_exclusive) {
  1691. wd.exclusive = p_exclusive;
  1692. reparent_check(p_window);
  1693. }
  1694. }
  1695. Point2i DisplayServerMacOS::window_get_position(WindowID p_window) const {
  1696. _THREAD_SAFE_METHOD_
  1697. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1698. const WindowData &wd = windows[p_window];
  1699. // Use content rect position (without titlebar / window border).
  1700. const NSRect contentRect = [wd.window_view frame];
  1701. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  1702. Point2i pos;
  1703. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  1704. const float scale = screen_get_max_scale();
  1705. pos.x = nsrect.origin.x;
  1706. pos.y = (nsrect.origin.y + nsrect.size.height);
  1707. pos *= scale;
  1708. pos -= _get_screens_origin();
  1709. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1710. // Godot expects a positive value.
  1711. pos.y *= -1;
  1712. return pos;
  1713. }
  1714. Point2i DisplayServerMacOS::window_get_position_with_decorations(WindowID p_window) const {
  1715. _THREAD_SAFE_METHOD_
  1716. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1717. const WindowData &wd = windows[p_window];
  1718. const NSRect nsrect = [wd.window_object frame];
  1719. Point2i pos;
  1720. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  1721. const float scale = screen_get_max_scale();
  1722. pos.x = nsrect.origin.x;
  1723. pos.y = (nsrect.origin.y + nsrect.size.height);
  1724. pos *= scale;
  1725. pos -= _get_screens_origin();
  1726. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1727. // Godot expects a positive value.
  1728. pos.y *= -1;
  1729. return pos;
  1730. }
  1731. void DisplayServerMacOS::window_set_position(const Point2i &p_position, WindowID p_window) {
  1732. _THREAD_SAFE_METHOD_
  1733. ERR_FAIL_COND(!windows.has(p_window));
  1734. WindowData &wd = windows[p_window];
  1735. if (wd.fullscreen) {
  1736. return;
  1737. }
  1738. Point2i position = p_position;
  1739. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1740. // Godot passes a positive value.
  1741. position.y *= -1;
  1742. position += _get_screens_origin();
  1743. position /= screen_get_max_scale();
  1744. // Remove titlebar / window border size.
  1745. const NSRect contentRect = [wd.window_view frame];
  1746. const NSRect windowRect = [wd.window_object frame];
  1747. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  1748. Point2i offset;
  1749. offset.x = (nsrect.origin.x - windowRect.origin.x);
  1750. offset.y = (nsrect.origin.y + nsrect.size.height);
  1751. offset.y -= (windowRect.origin.y + windowRect.size.height);
  1752. [wd.window_object setFrameTopLeftPoint:NSMakePoint(position.x - offset.x, position.y - offset.y)];
  1753. _update_window_style(wd);
  1754. update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  1755. }
  1756. void DisplayServerMacOS::window_set_transient(WindowID p_window, WindowID p_parent) {
  1757. _THREAD_SAFE_METHOD_
  1758. ERR_FAIL_COND(p_window == p_parent);
  1759. ERR_FAIL_COND(!windows.has(p_window));
  1760. WindowData &wd_window = windows[p_window];
  1761. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  1762. ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
  1763. if (p_parent == INVALID_WINDOW_ID) {
  1764. // Remove transient.
  1765. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  1766. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  1767. WindowData &wd_parent = windows[wd_window.transient_parent];
  1768. wd_window.transient_parent = INVALID_WINDOW_ID;
  1769. wd_parent.transient_children.erase(p_window);
  1770. if ([[wd_parent.window_object childWindows] containsObject:wd_window.window_object]) {
  1771. [wd_parent.window_object removeChildWindow:wd_window.window_object];
  1772. }
  1773. [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1774. } else {
  1775. ERR_FAIL_COND(!windows.has(p_parent));
  1776. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  1777. WindowData &wd_parent = windows[p_parent];
  1778. wd_window.transient_parent = p_parent;
  1779. wd_parent.transient_children.insert(p_window);
  1780. reparent_check(p_window);
  1781. }
  1782. }
  1783. void DisplayServerMacOS::window_set_max_size(const Size2i p_size, WindowID p_window) {
  1784. _THREAD_SAFE_METHOD_
  1785. ERR_FAIL_COND(!windows.has(p_window));
  1786. WindowData &wd = windows[p_window];
  1787. if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  1788. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1789. return;
  1790. }
  1791. wd.max_size = p_size;
  1792. if ((wd.max_size != Size2i()) && !wd.fullscreen) {
  1793. Size2i size = wd.max_size / screen_get_max_scale();
  1794. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  1795. } else {
  1796. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  1797. }
  1798. }
  1799. Size2i DisplayServerMacOS::window_get_max_size(WindowID p_window) const {
  1800. _THREAD_SAFE_METHOD_
  1801. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1802. const WindowData &wd = windows[p_window];
  1803. return wd.max_size;
  1804. }
  1805. void DisplayServerMacOS::update_presentation_mode() {
  1806. bool has_fs_windows = false;
  1807. for (const KeyValue<WindowID, WindowData> &wd : windows) {
  1808. if (wd.value.fullscreen) {
  1809. if (wd.value.exclusive_fullscreen) {
  1810. return;
  1811. } else {
  1812. has_fs_windows = true;
  1813. }
  1814. }
  1815. }
  1816. if (has_fs_windows) {
  1817. [NSApp setPresentationOptions:NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock | NSApplicationPresentationFullScreen];
  1818. } else {
  1819. [NSApp setPresentationOptions:NSApplicationPresentationDefault];
  1820. }
  1821. }
  1822. void DisplayServerMacOS::window_set_min_size(const Size2i p_size, WindowID p_window) {
  1823. _THREAD_SAFE_METHOD_
  1824. ERR_FAIL_COND(!windows.has(p_window));
  1825. WindowData &wd = windows[p_window];
  1826. if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  1827. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1828. return;
  1829. }
  1830. wd.min_size = p_size;
  1831. if ((wd.min_size != Size2i()) && !wd.fullscreen) {
  1832. Size2i size = wd.min_size / screen_get_max_scale();
  1833. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  1834. } else {
  1835. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  1836. }
  1837. }
  1838. Size2i DisplayServerMacOS::window_get_min_size(WindowID p_window) const {
  1839. _THREAD_SAFE_METHOD_
  1840. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1841. const WindowData &wd = windows[p_window];
  1842. return wd.min_size;
  1843. }
  1844. void DisplayServerMacOS::window_set_size(const Size2i p_size, WindowID p_window) {
  1845. _THREAD_SAFE_METHOD_
  1846. ERR_FAIL_COND(!windows.has(p_window));
  1847. WindowData &wd = windows[p_window];
  1848. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1849. return;
  1850. }
  1851. Size2i size = p_size / screen_get_max_scale();
  1852. NSPoint top_left;
  1853. NSRect old_frame = [wd.window_object frame];
  1854. top_left.x = old_frame.origin.x;
  1855. top_left.y = NSMaxY(old_frame);
  1856. NSRect new_frame = NSMakeRect(0, 0, MAX(1, size.x), MAX(1, size.y));
  1857. new_frame = [wd.window_object frameRectForContentRect:new_frame];
  1858. new_frame.origin.x = top_left.x;
  1859. new_frame.origin.y = top_left.y - new_frame.size.height;
  1860. [wd.window_object setFrame:new_frame display:YES];
  1861. _update_window_style(wd);
  1862. }
  1863. Size2i DisplayServerMacOS::window_get_size(WindowID p_window) const {
  1864. _THREAD_SAFE_METHOD_
  1865. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1866. const WindowData &wd = windows[p_window];
  1867. return wd.size;
  1868. }
  1869. Size2i DisplayServerMacOS::window_get_size_with_decorations(WindowID p_window) const {
  1870. _THREAD_SAFE_METHOD_
  1871. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1872. const WindowData &wd = windows[p_window];
  1873. NSRect frame = [wd.window_object frame];
  1874. return Size2i(frame.size.width, frame.size.height) * screen_get_max_scale();
  1875. }
  1876. void DisplayServerMacOS::window_set_mode(WindowMode p_mode, WindowID p_window) {
  1877. _THREAD_SAFE_METHOD_
  1878. ERR_FAIL_COND(!windows.has(p_window));
  1879. WindowData &wd = windows[p_window];
  1880. WindowMode old_mode = window_get_mode(p_window);
  1881. if (old_mode == p_mode) {
  1882. return; // Do nothing.
  1883. }
  1884. switch (old_mode) {
  1885. case WINDOW_MODE_WINDOWED: {
  1886. // Do nothing.
  1887. } break;
  1888. case WINDOW_MODE_MINIMIZED: {
  1889. [wd.window_object deminiaturize:nil];
  1890. } break;
  1891. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  1892. case WINDOW_MODE_FULLSCREEN: {
  1893. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN || p_mode == WINDOW_MODE_FULLSCREEN) {
  1894. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  1895. const NSUInteger presentationOptions = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
  1896. [NSApp setPresentationOptions:presentationOptions];
  1897. wd.exclusive_fullscreen = true;
  1898. } else {
  1899. wd.exclusive_fullscreen = false;
  1900. update_presentation_mode();
  1901. }
  1902. return;
  1903. }
  1904. [(NSWindow *)wd.window_object setLevel:NSNormalWindowLevel];
  1905. if (wd.resize_disabled) { // Restore resize disabled.
  1906. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  1907. }
  1908. if (wd.min_size != Size2i()) {
  1909. Size2i size = wd.min_size / screen_get_max_scale();
  1910. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  1911. }
  1912. if (wd.max_size != Size2i()) {
  1913. Size2i size = wd.max_size / screen_get_max_scale();
  1914. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  1915. }
  1916. [wd.window_object toggleFullScreen:nil];
  1917. if (old_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  1918. update_presentation_mode();
  1919. }
  1920. wd.fullscreen = false;
  1921. wd.exclusive_fullscreen = false;
  1922. } break;
  1923. case WINDOW_MODE_MAXIMIZED: {
  1924. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1925. [wd.window_object zoom:nil];
  1926. }
  1927. } break;
  1928. }
  1929. switch (p_mode) {
  1930. case WINDOW_MODE_WINDOWED: {
  1931. // Do nothing.
  1932. } break;
  1933. case WINDOW_MODE_MINIMIZED: {
  1934. [wd.window_object performMiniaturize:nil];
  1935. } break;
  1936. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  1937. case WINDOW_MODE_FULLSCREEN: {
  1938. if (wd.resize_disabled) { // Fullscreen window should be resizable to work.
  1939. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  1940. }
  1941. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  1942. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  1943. [wd.window_object toggleFullScreen:nil];
  1944. wd.fullscreen = true;
  1945. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  1946. const NSUInteger presentationOptions = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
  1947. [NSApp setPresentationOptions:presentationOptions];
  1948. wd.exclusive_fullscreen = true;
  1949. } else {
  1950. wd.exclusive_fullscreen = false;
  1951. update_presentation_mode();
  1952. }
  1953. } break;
  1954. case WINDOW_MODE_MAXIMIZED: {
  1955. if (!NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1956. [wd.window_object zoom:nil];
  1957. }
  1958. } break;
  1959. }
  1960. }
  1961. DisplayServer::WindowMode DisplayServerMacOS::window_get_mode(WindowID p_window) const {
  1962. _THREAD_SAFE_METHOD_
  1963. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  1964. const WindowData &wd = windows[p_window];
  1965. if (wd.fullscreen) { // If fullscreen, it's not in another mode.
  1966. if (wd.exclusive_fullscreen) {
  1967. return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
  1968. } else {
  1969. return WINDOW_MODE_FULLSCREEN;
  1970. }
  1971. }
  1972. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1973. return WINDOW_MODE_MAXIMIZED;
  1974. }
  1975. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  1976. if ([wd.window_object isMiniaturized]) {
  1977. return WINDOW_MODE_MINIMIZED;
  1978. }
  1979. }
  1980. // All other discarded, return windowed.
  1981. return WINDOW_MODE_WINDOWED;
  1982. }
  1983. bool DisplayServerMacOS::window_is_maximize_allowed(WindowID p_window) const {
  1984. return true;
  1985. }
  1986. bool DisplayServerMacOS::window_maximize_on_title_dbl_click() const {
  1987. id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleActionOnDoubleClick"];
  1988. if ([value isKindOfClass:[NSString class]]) {
  1989. return [value isEqualToString:@"Maximize"];
  1990. }
  1991. return false;
  1992. }
  1993. bool DisplayServerMacOS::window_minimize_on_title_dbl_click() const {
  1994. id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleActionOnDoubleClick"];
  1995. if ([value isKindOfClass:[NSString class]]) {
  1996. return [value isEqualToString:@"Minimize"];
  1997. }
  1998. return false;
  1999. }
  2000. void DisplayServerMacOS::window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window) {
  2001. _THREAD_SAFE_METHOD_
  2002. ERR_FAIL_COND(!windows.has(p_window));
  2003. WindowData &wd = windows[p_window];
  2004. float scale = screen_get_max_scale();
  2005. wd.wb_offset = p_offset / scale;
  2006. wd.wb_offset = wd.wb_offset.maxi(12);
  2007. if (wd.window_button_view) {
  2008. [(GodotButtonView *)wd.window_button_view setOffset:NSMakePoint(wd.wb_offset.x, wd.wb_offset.y)];
  2009. }
  2010. }
  2011. Vector3i DisplayServerMacOS::window_get_safe_title_margins(WindowID p_window) const {
  2012. _THREAD_SAFE_METHOD_
  2013. ERR_FAIL_COND_V(!windows.has(p_window), Vector3i());
  2014. const WindowData &wd = windows[p_window];
  2015. if (!wd.window_button_view) {
  2016. return Vector3i();
  2017. }
  2018. float scale = screen_get_max_scale();
  2019. float max_x = [wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width;
  2020. float max_y = [wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height;
  2021. if ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft) {
  2022. return Vector3i(0, max_x * scale, max_y * scale);
  2023. } else {
  2024. return Vector3i(max_x * scale, 0, max_y * scale);
  2025. }
  2026. }
  2027. void DisplayServerMacOS::window_set_custom_window_buttons(WindowData &p_wd, bool p_enabled) {
  2028. if (p_wd.window_button_view) {
  2029. [p_wd.window_button_view removeFromSuperview];
  2030. p_wd.window_button_view = nil;
  2031. }
  2032. if (p_enabled) {
  2033. float cb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowCloseButton] frame]);
  2034. float mb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] frame]);
  2035. bool is_rtl = ([p_wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft);
  2036. float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame);
  2037. [p_wd.window_object setTitleVisibility:NSWindowTitleHidden];
  2038. [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:YES];
  2039. [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  2040. [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:YES];
  2041. p_wd.window_button_view = [[GodotButtonView alloc] initWithFrame:NSZeroRect];
  2042. [p_wd.window_button_view initButtons:window_buttons_spacing offset:NSMakePoint(p_wd.wb_offset.x, p_wd.wb_offset.y) rtl:is_rtl];
  2043. [p_wd.window_view addSubview:p_wd.window_button_view];
  2044. } else {
  2045. [p_wd.window_object setTitleVisibility:NSWindowTitleVisible];
  2046. [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:NO];
  2047. [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:NO];
  2048. [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:NO];
  2049. }
  2050. }
  2051. void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  2052. _THREAD_SAFE_METHOD_
  2053. ERR_FAIL_COND(!windows.has(p_window));
  2054. WindowData &wd = windows[p_window];
  2055. switch (p_flag) {
  2056. case WINDOW_FLAG_RESIZE_DISABLED: {
  2057. wd.resize_disabled = p_enabled;
  2058. if (wd.fullscreen) { // Fullscreen window should be resizable, style will be applied on exiting fullscreen.
  2059. return;
  2060. }
  2061. if (p_enabled) {
  2062. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2063. [[wd.window_object standardWindowButton:NSWindowZoomButton] setEnabled:NO];
  2064. } else {
  2065. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2066. [[wd.window_object standardWindowButton:NSWindowZoomButton] setEnabled:YES];
  2067. }
  2068. } break;
  2069. case WINDOW_FLAG_EXTEND_TO_TITLE: {
  2070. NSRect rect = [wd.window_object frame];
  2071. wd.extend_to_title = p_enabled;
  2072. if (p_enabled) {
  2073. [wd.window_object setTitlebarAppearsTransparent:YES];
  2074. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskFullSizeContentView];
  2075. if (!wd.fullscreen) {
  2076. window_set_custom_window_buttons(wd, true);
  2077. }
  2078. } else {
  2079. [wd.window_object setTitlebarAppearsTransparent:NO];
  2080. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskFullSizeContentView];
  2081. if (!wd.fullscreen) {
  2082. window_set_custom_window_buttons(wd, false);
  2083. }
  2084. }
  2085. [wd.window_object setFrame:rect display:YES];
  2086. send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_TITLEBAR_CHANGE);
  2087. } break;
  2088. case WINDOW_FLAG_BORDERLESS: {
  2089. if (wd.fullscreen) {
  2090. return;
  2091. }
  2092. // OrderOut prevents a lose focus bug with the window.
  2093. bool was_visible = false;
  2094. if ([wd.window_object isVisible]) {
  2095. was_visible = true;
  2096. [wd.window_object orderOut:nil];
  2097. }
  2098. wd.borderless = p_enabled;
  2099. if (p_enabled) {
  2100. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless];
  2101. } else {
  2102. if (wd.layered_window) {
  2103. wd.layered_window = false;
  2104. set_window_per_pixel_transparency_enabled(false, p_window);
  2105. }
  2106. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.extend_to_title ? NSWindowStyleMaskFullSizeContentView : 0) | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2107. // Force update of the window styles.
  2108. NSRect frameRect = [wd.window_object frame];
  2109. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2110. [wd.window_object setFrame:frameRect display:NO];
  2111. }
  2112. _update_window_style(wd);
  2113. if (was_visible || [wd.window_object isVisible]) {
  2114. if ([wd.window_object isMiniaturized]) {
  2115. return;
  2116. } else if (wd.no_focus) {
  2117. [wd.window_object orderFront:nil];
  2118. } else {
  2119. [wd.window_object makeKeyAndOrderFront:nil];
  2120. }
  2121. }
  2122. } break;
  2123. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2124. wd.on_top = p_enabled;
  2125. if (wd.fullscreen) {
  2126. return;
  2127. }
  2128. if (p_enabled) {
  2129. [(NSWindow *)wd.window_object setLevel:NSFloatingWindowLevel];
  2130. } else {
  2131. [(NSWindow *)wd.window_object setLevel:NSNormalWindowLevel];
  2132. }
  2133. } break;
  2134. case WINDOW_FLAG_TRANSPARENT: {
  2135. if (wd.fullscreen) {
  2136. return;
  2137. }
  2138. if (p_enabled) {
  2139. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless]; // Force borderless.
  2140. } else if (!wd.borderless) {
  2141. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.extend_to_title ? NSWindowStyleMaskFullSizeContentView : 0) | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2142. }
  2143. wd.layered_window = p_enabled;
  2144. set_window_per_pixel_transparency_enabled(p_enabled, p_window);
  2145. // Force update of the window styles.
  2146. NSRect frameRect = [wd.window_object frame];
  2147. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2148. [wd.window_object setFrame:frameRect display:NO];
  2149. } break;
  2150. case WINDOW_FLAG_NO_FOCUS: {
  2151. wd.no_focus = p_enabled;
  2152. NSWindow *w = wd.window_object;
  2153. w.excludedFromWindowsMenu = wd.is_popup || wd.no_focus;
  2154. } break;
  2155. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2156. wd.mpass = p_enabled;
  2157. } break;
  2158. case WINDOW_FLAG_POPUP: {
  2159. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  2160. ERR_FAIL_COND_MSG([wd.window_object isVisible] && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  2161. wd.is_popup = p_enabled;
  2162. NSWindow *w = wd.window_object;
  2163. w.excludedFromWindowsMenu = wd.is_popup || wd.no_focus;
  2164. } break;
  2165. default: {
  2166. }
  2167. }
  2168. }
  2169. bool DisplayServerMacOS::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  2170. _THREAD_SAFE_METHOD_
  2171. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2172. const WindowData &wd = windows[p_window];
  2173. switch (p_flag) {
  2174. case WINDOW_FLAG_RESIZE_DISABLED: {
  2175. return wd.resize_disabled;
  2176. } break;
  2177. case WINDOW_FLAG_EXTEND_TO_TITLE: {
  2178. return [wd.window_object styleMask] & NSWindowStyleMaskFullSizeContentView;
  2179. } break;
  2180. case WINDOW_FLAG_BORDERLESS: {
  2181. return [wd.window_object styleMask] == NSWindowStyleMaskBorderless;
  2182. } break;
  2183. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2184. if (wd.fullscreen) {
  2185. return wd.on_top;
  2186. } else {
  2187. return [(NSWindow *)wd.window_object level] == NSFloatingWindowLevel;
  2188. }
  2189. } break;
  2190. case WINDOW_FLAG_TRANSPARENT: {
  2191. return wd.layered_window;
  2192. } break;
  2193. case WINDOW_FLAG_NO_FOCUS: {
  2194. return wd.no_focus;
  2195. } break;
  2196. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2197. return wd.mpass;
  2198. } break;
  2199. case WINDOW_FLAG_POPUP: {
  2200. return wd.is_popup;
  2201. } break;
  2202. default: {
  2203. }
  2204. }
  2205. return false;
  2206. }
  2207. void DisplayServerMacOS::window_request_attention(WindowID p_window) {
  2208. // It's app global, ignore window id.
  2209. [NSApp requestUserAttention:NSCriticalRequest];
  2210. }
  2211. void DisplayServerMacOS::window_move_to_foreground(WindowID p_window) {
  2212. _THREAD_SAFE_METHOD_
  2213. ERR_FAIL_COND(!windows.has(p_window));
  2214. const WindowData &wd = windows[p_window];
  2215. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  2216. if (wd.no_focus || wd.is_popup) {
  2217. [wd.window_object orderFront:nil];
  2218. } else {
  2219. [wd.window_object makeKeyAndOrderFront:nil];
  2220. }
  2221. }
  2222. bool DisplayServerMacOS::window_is_focused(WindowID p_window) const {
  2223. _THREAD_SAFE_METHOD_
  2224. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2225. const WindowData &wd = windows[p_window];
  2226. return wd.focused;
  2227. }
  2228. DisplayServerMacOS::WindowID DisplayServerMacOS::get_focused_window() const {
  2229. return last_focused_window;
  2230. }
  2231. bool DisplayServerMacOS::window_can_draw(WindowID p_window) const {
  2232. return windows[p_window].is_visible;
  2233. }
  2234. bool DisplayServerMacOS::can_any_window_draw() const {
  2235. _THREAD_SAFE_METHOD_
  2236. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2237. if (E.value.is_visible) {
  2238. return true;
  2239. }
  2240. }
  2241. return false;
  2242. }
  2243. void DisplayServerMacOS::window_set_ime_active(const bool p_active, WindowID p_window) {
  2244. _THREAD_SAFE_METHOD_
  2245. ERR_FAIL_COND(!windows.has(p_window));
  2246. WindowData &wd = windows[p_window];
  2247. wd.im_active = p_active;
  2248. if (!p_active) {
  2249. [wd.window_view cancelComposition];
  2250. }
  2251. }
  2252. void DisplayServerMacOS::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  2253. _THREAD_SAFE_METHOD_
  2254. ERR_FAIL_COND(!windows.has(p_window));
  2255. WindowData &wd = windows[p_window];
  2256. wd.im_position = p_pos;
  2257. }
  2258. DisplayServer::WindowID DisplayServerMacOS::get_window_at_screen_position(const Point2i &p_position) const {
  2259. Point2i position = p_position;
  2260. position.y *= -1;
  2261. position += _get_screens_origin();
  2262. position /= screen_get_max_scale();
  2263. NSInteger wnum = [NSWindow windowNumberAtPoint:NSMakePoint(position.x, position.y) belowWindowWithWindowNumber:0 /*topmost*/];
  2264. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2265. if ([E.value.window_object windowNumber] == wnum) {
  2266. return E.key;
  2267. }
  2268. }
  2269. return INVALID_WINDOW_ID;
  2270. }
  2271. int64_t DisplayServerMacOS::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  2272. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  2273. switch (p_handle_type) {
  2274. case DISPLAY_HANDLE: {
  2275. return 0; // Not supported.
  2276. }
  2277. case WINDOW_HANDLE: {
  2278. return (int64_t)windows[p_window].window_object;
  2279. }
  2280. case WINDOW_VIEW: {
  2281. return (int64_t)windows[p_window].window_view;
  2282. }
  2283. #ifdef GLES3_ENABLED
  2284. case OPENGL_CONTEXT: {
  2285. if (gl_manager_legacy) {
  2286. return (int64_t)gl_manager_legacy->get_context(p_window);
  2287. }
  2288. if (gl_manager_angle) {
  2289. return (int64_t)gl_manager_angle->get_context(p_window);
  2290. }
  2291. return 0;
  2292. }
  2293. case EGL_DISPLAY: {
  2294. if (gl_manager_angle) {
  2295. return (int64_t)gl_manager_angle->get_display(p_window);
  2296. }
  2297. return 0;
  2298. }
  2299. case EGL_CONFIG: {
  2300. if (gl_manager_angle) {
  2301. return (int64_t)gl_manager_angle->get_config(p_window);
  2302. }
  2303. return 0;
  2304. }
  2305. #endif
  2306. default: {
  2307. return 0;
  2308. }
  2309. }
  2310. }
  2311. void DisplayServerMacOS::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  2312. _THREAD_SAFE_METHOD_
  2313. ERR_FAIL_COND(!windows.has(p_window));
  2314. windows[p_window].instance_id = p_instance;
  2315. }
  2316. ObjectID DisplayServerMacOS::window_get_attached_instance_id(WindowID p_window) const {
  2317. _THREAD_SAFE_METHOD_
  2318. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  2319. return windows[p_window].instance_id;
  2320. }
  2321. void DisplayServerMacOS::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  2322. #if defined(GLES3_ENABLED)
  2323. if (gl_manager_legacy) {
  2324. gl_manager_legacy->window_make_current(p_window_id);
  2325. }
  2326. if (gl_manager_angle) {
  2327. gl_manager_angle->window_make_current(p_window_id);
  2328. }
  2329. #endif
  2330. }
  2331. void DisplayServerMacOS::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  2332. _THREAD_SAFE_METHOD_
  2333. #if defined(GLES3_ENABLED)
  2334. if (gl_manager_angle) {
  2335. gl_manager_angle->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  2336. }
  2337. if (gl_manager_legacy) {
  2338. gl_manager_legacy->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  2339. }
  2340. #endif
  2341. #if defined(RD_ENABLED)
  2342. if (rendering_context) {
  2343. rendering_context->window_set_vsync_mode(p_window, p_vsync_mode);
  2344. }
  2345. #endif
  2346. }
  2347. DisplayServer::VSyncMode DisplayServerMacOS::window_get_vsync_mode(WindowID p_window) const {
  2348. _THREAD_SAFE_METHOD_
  2349. #if defined(GLES3_ENABLED)
  2350. if (gl_manager_angle) {
  2351. return (gl_manager_angle->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2352. }
  2353. if (gl_manager_legacy) {
  2354. return (gl_manager_legacy->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2355. }
  2356. #endif
  2357. #if defined(RD_ENABLED)
  2358. if (rendering_context) {
  2359. return rendering_context->window_get_vsync_mode(p_window);
  2360. }
  2361. #endif
  2362. return DisplayServer::VSYNC_ENABLED;
  2363. }
  2364. Point2i DisplayServerMacOS::ime_get_selection() const {
  2365. return im_selection;
  2366. }
  2367. String DisplayServerMacOS::ime_get_text() const {
  2368. return im_text;
  2369. }
  2370. void DisplayServerMacOS::cursor_update_shape() {
  2371. _THREAD_SAFE_METHOD_
  2372. if (cursors[cursor_shape] != nullptr) {
  2373. [cursors[cursor_shape] set];
  2374. } else {
  2375. switch (cursor_shape) {
  2376. case CURSOR_ARROW:
  2377. [[NSCursor arrowCursor] set];
  2378. break;
  2379. case CURSOR_IBEAM:
  2380. [[NSCursor IBeamCursor] set];
  2381. break;
  2382. case CURSOR_POINTING_HAND:
  2383. [[NSCursor pointingHandCursor] set];
  2384. break;
  2385. case CURSOR_CROSS:
  2386. [[NSCursor crosshairCursor] set];
  2387. break;
  2388. case CURSOR_WAIT:
  2389. [[NSCursor arrowCursor] set];
  2390. break;
  2391. case CURSOR_BUSY:
  2392. [[NSCursor arrowCursor] set];
  2393. break;
  2394. case CURSOR_DRAG:
  2395. [[NSCursor closedHandCursor] set];
  2396. break;
  2397. case CURSOR_CAN_DROP:
  2398. [[NSCursor openHandCursor] set];
  2399. break;
  2400. case CURSOR_FORBIDDEN:
  2401. [[NSCursor operationNotAllowedCursor] set];
  2402. break;
  2403. case CURSOR_VSIZE:
  2404. [_cursor_from_selector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set];
  2405. break;
  2406. case CURSOR_HSIZE:
  2407. [_cursor_from_selector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set];
  2408. break;
  2409. case CURSOR_BDIAGSIZE:
  2410. [_cursor_from_selector(@selector(_windowResizeNorthEastSouthWestCursor)) set];
  2411. break;
  2412. case CURSOR_FDIAGSIZE:
  2413. [_cursor_from_selector(@selector(_windowResizeNorthWestSouthEastCursor)) set];
  2414. break;
  2415. case CURSOR_MOVE:
  2416. [[NSCursor arrowCursor] set];
  2417. break;
  2418. case CURSOR_VSPLIT:
  2419. [[NSCursor resizeUpDownCursor] set];
  2420. break;
  2421. case CURSOR_HSPLIT:
  2422. [[NSCursor resizeLeftRightCursor] set];
  2423. break;
  2424. case CURSOR_HELP:
  2425. [_cursor_from_selector(@selector(_helpCursor)) set];
  2426. break;
  2427. default: {
  2428. }
  2429. }
  2430. }
  2431. }
  2432. void DisplayServerMacOS::cursor_set_shape(CursorShape p_shape) {
  2433. _THREAD_SAFE_METHOD_
  2434. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2435. if (cursor_shape == p_shape) {
  2436. return;
  2437. }
  2438. cursor_shape = p_shape;
  2439. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  2440. return;
  2441. }
  2442. cursor_update_shape();
  2443. }
  2444. DisplayServerMacOS::CursorShape DisplayServerMacOS::cursor_get_shape() const {
  2445. return cursor_shape;
  2446. }
  2447. void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2448. _THREAD_SAFE_METHOD_
  2449. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2450. if (p_cursor.is_valid()) {
  2451. HashMap<CursorShape, Vector<Variant>>::Iterator cursor_c = cursors_cache.find(p_shape);
  2452. if (cursor_c) {
  2453. if (cursor_c->value[0] == p_cursor && cursor_c->value[1] == p_hotspot) {
  2454. cursor_set_shape(p_shape);
  2455. return;
  2456. }
  2457. cursors_cache.erase(p_shape);
  2458. }
  2459. Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot);
  2460. ERR_FAIL_COND(image.is_null());
  2461. Vector2i texture_size = image->get_size();
  2462. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2463. initWithBitmapDataPlanes:nullptr
  2464. pixelsWide:int(texture_size.width)
  2465. pixelsHigh:int(texture_size.height)
  2466. bitsPerSample:8
  2467. samplesPerPixel:4
  2468. hasAlpha:YES
  2469. isPlanar:NO
  2470. colorSpaceName:NSDeviceRGBColorSpace
  2471. bytesPerRow:int(texture_size.width) * 4
  2472. bitsPerPixel:32];
  2473. ERR_FAIL_NULL(imgrep);
  2474. uint8_t *pixels = [imgrep bitmapData];
  2475. int len = int(texture_size.width * texture_size.height);
  2476. for (int i = 0; i < len; i++) {
  2477. int row_index = floor(i / texture_size.width);
  2478. int column_index = i % int(texture_size.width);
  2479. uint32_t color = image->get_pixel(column_index, row_index).to_argb32();
  2480. uint8_t alpha = (color >> 24) & 0xFF;
  2481. pixels[i * 4 + 0] = ((color >> 16) & 0xFF) * alpha / 255;
  2482. pixels[i * 4 + 1] = ((color >> 8) & 0xFF) * alpha / 255;
  2483. pixels[i * 4 + 2] = ((color) & 0xFF) * alpha / 255;
  2484. pixels[i * 4 + 3] = alpha;
  2485. }
  2486. NSImage *nsimage = [[NSImage alloc] initWithSize:NSMakeSize(texture_size.width, texture_size.height)];
  2487. [nsimage addRepresentation:imgrep];
  2488. NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
  2489. cursors[p_shape] = cursor;
  2490. Vector<Variant> params;
  2491. params.push_back(p_cursor);
  2492. params.push_back(p_hotspot);
  2493. cursors_cache.insert(p_shape, params);
  2494. if (p_shape == cursor_shape) {
  2495. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2496. [cursor set];
  2497. }
  2498. }
  2499. } else {
  2500. // Reset to default system cursor.
  2501. if (cursors[p_shape] != nullptr) {
  2502. cursors[p_shape] = nullptr;
  2503. }
  2504. cursors_cache.erase(p_shape);
  2505. cursor_update_shape();
  2506. }
  2507. }
  2508. bool DisplayServerMacOS::get_swap_cancel_ok() {
  2509. return false;
  2510. }
  2511. int DisplayServerMacOS::keyboard_get_layout_count() const {
  2512. if (keyboard_layout_dirty) {
  2513. const_cast<DisplayServerMacOS *>(this)->_update_keyboard_layouts();
  2514. }
  2515. return kbd_layouts.size();
  2516. }
  2517. void DisplayServerMacOS::keyboard_set_current_layout(int p_index) {
  2518. if (keyboard_layout_dirty) {
  2519. const_cast<DisplayServerMacOS *>(this)->_update_keyboard_layouts();
  2520. }
  2521. ERR_FAIL_INDEX(p_index, kbd_layouts.size());
  2522. NSString *cur_name = [NSString stringWithUTF8String:kbd_layouts[p_index].name.utf8().get_data()];
  2523. NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
  2524. NSArray *list_kbd = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_kbd, false);
  2525. for (NSUInteger i = 0; i < [list_kbd count]; i++) {
  2526. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
  2527. if ([name isEqualToString:cur_name]) {
  2528. TISSelectInputSource((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i]);
  2529. break;
  2530. }
  2531. }
  2532. NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
  2533. NSArray *list_ime = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_ime, false);
  2534. for (NSUInteger i = 0; i < [list_ime count]; i++) {
  2535. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
  2536. if ([name isEqualToString:cur_name]) {
  2537. TISSelectInputSource((__bridge TISInputSourceRef)[list_ime objectAtIndex:i]);
  2538. break;
  2539. }
  2540. }
  2541. }
  2542. int DisplayServerMacOS::keyboard_get_current_layout() const {
  2543. if (keyboard_layout_dirty) {
  2544. const_cast<DisplayServerMacOS *>(this)->_update_keyboard_layouts();
  2545. }
  2546. return current_layout;
  2547. }
  2548. String DisplayServerMacOS::keyboard_get_layout_language(int p_index) const {
  2549. if (keyboard_layout_dirty) {
  2550. const_cast<DisplayServerMacOS *>(this)->_update_keyboard_layouts();
  2551. }
  2552. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2553. return kbd_layouts[p_index].code;
  2554. }
  2555. String DisplayServerMacOS::keyboard_get_layout_name(int p_index) const {
  2556. if (keyboard_layout_dirty) {
  2557. const_cast<DisplayServerMacOS *>(this)->_update_keyboard_layouts();
  2558. }
  2559. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2560. return kbd_layouts[p_index].name;
  2561. }
  2562. Key DisplayServerMacOS::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2563. if (p_keycode == Key::PAUSE || p_keycode == Key::NONE) {
  2564. return p_keycode;
  2565. }
  2566. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2567. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2568. unsigned int macos_keycode = KeyMappingMacOS::unmap_key(keycode_no_mod);
  2569. return (Key)(KeyMappingMacOS::remap_key(macos_keycode, 0, false) | modifiers);
  2570. }
  2571. Key DisplayServerMacOS::keyboard_get_label_from_physical(Key p_keycode) const {
  2572. if (p_keycode == Key::PAUSE || p_keycode == Key::NONE) {
  2573. return p_keycode;
  2574. }
  2575. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2576. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2577. unsigned int macos_keycode = KeyMappingMacOS::unmap_key(keycode_no_mod);
  2578. return (Key)(KeyMappingMacOS::remap_key(macos_keycode, 0, true) | modifiers);
  2579. }
  2580. void DisplayServerMacOS::process_events() {
  2581. ERR_FAIL_COND(!Thread::is_main_thread());
  2582. while (true) {
  2583. NSEvent *event = [NSApp
  2584. nextEventMatchingMask:NSEventMaskAny
  2585. untilDate:[NSDate distantPast]
  2586. inMode:NSDefaultRunLoopMode
  2587. dequeue:YES];
  2588. if (event == nil) {
  2589. break;
  2590. }
  2591. [NSApp sendEvent:event];
  2592. }
  2593. // Process "menu_callback"s.
  2594. while (List<MenuCall>::Element *call_p = deferred_menu_calls.front()) {
  2595. MenuCall call = call_p->get();
  2596. deferred_menu_calls.pop_front(); // Remove before call to avoid infinite loop in case callback is using `process_events` (e.g. EditorProgress).
  2597. Variant ret;
  2598. Callable::CallError ce;
  2599. const Variant *args[1] = { &call.tag };
  2600. call.callback.callp(args, 1, ret, ce);
  2601. if (ce.error != Callable::CallError::CALL_OK) {
  2602. ERR_PRINT(vformat("Failed to execute menu callback: %s.", Variant::get_callable_error_text(call.callback, args, 1, ce)));
  2603. }
  2604. }
  2605. if (!drop_events) {
  2606. _process_key_events();
  2607. Input::get_singleton()->flush_buffered_events();
  2608. }
  2609. _THREAD_SAFE_LOCK_
  2610. for (KeyValue<WindowID, WindowData> &E : windows) {
  2611. WindowData &wd = E.value;
  2612. if (wd.mpass) {
  2613. if (![wd.window_object ignoresMouseEvents]) {
  2614. [wd.window_object setIgnoresMouseEvents:YES];
  2615. }
  2616. } else if (wd.mpath.size() > 0) {
  2617. update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  2618. if (Geometry2D::is_point_in_polygon(wd.mouse_pos, wd.mpath)) {
  2619. if ([wd.window_object ignoresMouseEvents]) {
  2620. [wd.window_object setIgnoresMouseEvents:NO];
  2621. }
  2622. } else {
  2623. if (![wd.window_object ignoresMouseEvents]) {
  2624. [wd.window_object setIgnoresMouseEvents:YES];
  2625. }
  2626. }
  2627. } else {
  2628. if ([wd.window_object ignoresMouseEvents]) {
  2629. [wd.window_object setIgnoresMouseEvents:NO];
  2630. }
  2631. }
  2632. }
  2633. _THREAD_SAFE_UNLOCK_
  2634. }
  2635. void DisplayServerMacOS::force_process_and_drop_events() {
  2636. ERR_FAIL_COND(!Thread::is_main_thread());
  2637. drop_events = true;
  2638. process_events();
  2639. drop_events = false;
  2640. }
  2641. void DisplayServerMacOS::release_rendering_thread() {
  2642. #if defined(GLES3_ENABLED)
  2643. if (gl_manager_angle) {
  2644. gl_manager_angle->release_current();
  2645. }
  2646. if (gl_manager_legacy) {
  2647. gl_manager_legacy->release_current();
  2648. }
  2649. #endif
  2650. }
  2651. void DisplayServerMacOS::swap_buffers() {
  2652. #if defined(GLES3_ENABLED)
  2653. if (gl_manager_angle) {
  2654. gl_manager_angle->swap_buffers();
  2655. }
  2656. if (gl_manager_legacy) {
  2657. gl_manager_legacy->swap_buffers();
  2658. }
  2659. #endif
  2660. }
  2661. void DisplayServerMacOS::set_native_icon(const String &p_filename) {
  2662. _THREAD_SAFE_METHOD_
  2663. Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ);
  2664. ERR_FAIL_COND(f.is_null());
  2665. Vector<uint8_t> data;
  2666. uint64_t len = f->get_length();
  2667. ERR_FAIL_COND_MSG(len < 8, "Error reading icon data."); // "icns" + 32-bit length
  2668. data.resize(len);
  2669. f->get_buffer((uint8_t *)&data.write[0], len);
  2670. @try {
  2671. NSData *icon_data = [[NSData alloc] initWithBytes:&data.write[0] length:len];
  2672. ERR_FAIL_NULL_MSG(icon_data, "Error reading icon data.");
  2673. NSImage *icon = [[NSImage alloc] initWithData:icon_data];
  2674. ERR_FAIL_NULL_MSG(icon, "Error loading icon.");
  2675. [NSApp setApplicationIconImage:icon];
  2676. } @catch (NSException *exception) {
  2677. ERR_FAIL_MSG("NSException: " + String::utf8([exception reason].UTF8String));
  2678. }
  2679. }
  2680. void DisplayServerMacOS::set_icon(const Ref<Image> &p_icon) {
  2681. _THREAD_SAFE_METHOD_
  2682. if (p_icon.is_valid()) {
  2683. ERR_FAIL_COND(p_icon->get_width() <= 0 || p_icon->get_height() <= 0);
  2684. Ref<Image> img = p_icon->duplicate();
  2685. img->convert(Image::FORMAT_RGBA8);
  2686. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2687. initWithBitmapDataPlanes:nullptr
  2688. pixelsWide:img->get_width()
  2689. pixelsHigh:img->get_height()
  2690. bitsPerSample:8
  2691. samplesPerPixel:4
  2692. hasAlpha:YES
  2693. isPlanar:NO
  2694. colorSpaceName:NSDeviceRGBColorSpace
  2695. bytesPerRow:img->get_width() * 4
  2696. bitsPerPixel:32];
  2697. ERR_FAIL_NULL(imgrep);
  2698. uint8_t *pixels = [imgrep bitmapData];
  2699. int len = img->get_width() * img->get_height();
  2700. const uint8_t *r = img->get_data().ptr();
  2701. /* Premultiply the alpha channel */
  2702. for (int i = 0; i < len; i++) {
  2703. uint8_t alpha = r[i * 4 + 3];
  2704. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  2705. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  2706. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  2707. pixels[i * 4 + 3] = alpha;
  2708. }
  2709. NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())];
  2710. ERR_FAIL_NULL(nsimg);
  2711. [nsimg addRepresentation:imgrep];
  2712. [NSApp setApplicationIconImage:nsimg];
  2713. } else {
  2714. [NSApp setApplicationIconImage:nil];
  2715. }
  2716. }
  2717. DisplayServer::IndicatorID DisplayServerMacOS::create_status_indicator(const Ref<Texture2D> &p_icon, const String &p_tooltip, const Callable &p_callback) {
  2718. NSImage *nsimg = nullptr;
  2719. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  2720. Ref<Image> img = p_icon->get_image();
  2721. img = img->duplicate();
  2722. if (img->is_compressed()) {
  2723. img->decompress();
  2724. }
  2725. nsimg = _convert_to_nsimg(img);
  2726. }
  2727. IndicatorData idat;
  2728. NSStatusItem *item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  2729. idat.item = item;
  2730. idat.delegate = [[GodotStatusItemDelegate alloc] init];
  2731. [idat.delegate setCallback:p_callback];
  2732. item.button.image = nsimg;
  2733. item.button.imagePosition = NSImageOnly;
  2734. item.button.imageScaling = NSImageScaleProportionallyUpOrDown;
  2735. item.button.target = idat.delegate;
  2736. item.button.action = @selector(click:);
  2737. [item.button sendActionOn:(NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown)];
  2738. item.button.toolTip = [NSString stringWithUTF8String:p_tooltip.utf8().get_data()];
  2739. IndicatorID iid = indicator_id_counter++;
  2740. indicators[iid] = idat;
  2741. return iid;
  2742. }
  2743. void DisplayServerMacOS::status_indicator_set_icon(IndicatorID p_id, const Ref<Texture2D> &p_icon) {
  2744. ERR_FAIL_COND(!indicators.has(p_id));
  2745. NSImage *nsimg = nullptr;
  2746. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  2747. Ref<Image> img = p_icon->get_image();
  2748. img = img->duplicate();
  2749. if (img->is_compressed()) {
  2750. img->decompress();
  2751. }
  2752. nsimg = _convert_to_nsimg(img);
  2753. }
  2754. NSStatusItem *item = indicators[p_id].item;
  2755. item.button.image = nsimg;
  2756. }
  2757. void DisplayServerMacOS::status_indicator_set_tooltip(IndicatorID p_id, const String &p_tooltip) {
  2758. ERR_FAIL_COND(!indicators.has(p_id));
  2759. NSStatusItem *item = indicators[p_id].item;
  2760. item.button.toolTip = [NSString stringWithUTF8String:p_tooltip.utf8().get_data()];
  2761. }
  2762. void DisplayServerMacOS::status_indicator_set_menu(IndicatorID p_id, const RID &p_menu_rid) {
  2763. ERR_FAIL_COND(!indicators.has(p_id));
  2764. NSStatusItem *item = indicators[p_id].item;
  2765. if (p_menu_rid.is_valid() && native_menu->has_menu(p_menu_rid)) {
  2766. NSMenu *menu = native_menu->get_native_menu_handle(p_menu_rid);
  2767. item.menu = menu;
  2768. } else {
  2769. item.menu = nullptr;
  2770. }
  2771. }
  2772. void DisplayServerMacOS::status_indicator_set_callback(IndicatorID p_id, const Callable &p_callback) {
  2773. ERR_FAIL_COND(!indicators.has(p_id));
  2774. [indicators[p_id].delegate setCallback:p_callback];
  2775. }
  2776. Rect2 DisplayServerMacOS::status_indicator_get_rect(IndicatorID p_id) const {
  2777. ERR_FAIL_COND_V(!indicators.has(p_id), Rect2());
  2778. NSStatusItem *item = indicators[p_id].item;
  2779. NSView *v = item.button;
  2780. const NSRect contentRect = [v frame];
  2781. const NSRect nsrect = [v.window convertRectToScreen:contentRect];
  2782. Rect2 rect;
  2783. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  2784. const float scale = screen_get_max_scale();
  2785. rect.size.x = nsrect.size.width;
  2786. rect.size.y = nsrect.size.height;
  2787. rect.size *= scale;
  2788. rect.position.x = nsrect.origin.x;
  2789. rect.position.y = (nsrect.origin.y + nsrect.size.height);
  2790. rect.position *= scale;
  2791. rect.position -= _get_screens_origin();
  2792. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  2793. // Godot expects a positive value.
  2794. rect.position.y *= -1;
  2795. return rect;
  2796. }
  2797. void DisplayServerMacOS::delete_status_indicator(IndicatorID p_id) {
  2798. ERR_FAIL_COND(!indicators.has(p_id));
  2799. [[NSStatusBar systemStatusBar] removeStatusItem:indicators[p_id].item];
  2800. indicators.erase(p_id);
  2801. }
  2802. bool DisplayServerMacOS::is_window_transparency_available() const {
  2803. #if defined(RD_ENABLED)
  2804. if (rendering_device && !rendering_device->is_composite_alpha_supported()) {
  2805. return false;
  2806. }
  2807. #endif
  2808. return OS::get_singleton()->is_layered_allowed();
  2809. }
  2810. DisplayServer *DisplayServerMacOS::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, int p_screen, Context p_context, Error &r_error) {
  2811. DisplayServer *ds = memnew(DisplayServerMacOS(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_position, p_resolution, p_screen, p_context, r_error));
  2812. if (r_error != OK) {
  2813. if (p_rendering_driver == "vulkan") {
  2814. String executable_command;
  2815. if (OS::get_singleton()->get_bundle_resource_dir() == OS::get_singleton()->get_executable_path().get_base_dir()) {
  2816. executable_command = vformat("\"%s\" --rendering-driver opengl3", OS::get_singleton()->get_executable_path());
  2817. } else {
  2818. executable_command = vformat("open \"%s\" --args --rendering-driver opengl3", OS::get_singleton()->get_bundle_resource_dir().path_join("../..").simplify_path());
  2819. }
  2820. OS::get_singleton()->alert(
  2821. vformat("Your video card drivers seem not to support the required Vulkan version.\n\n"
  2822. "If possible, consider updating your macOS version or using the OpenGL 3 driver.\n\n"
  2823. "You can enable the OpenGL 3 driver by starting the engine from the\n"
  2824. "command line with the command:\n\n %s",
  2825. executable_command),
  2826. "Unable to initialize Vulkan video driver");
  2827. } else {
  2828. OS::get_singleton()->alert(
  2829. "Your video card drivers seem not to support the required OpenGL 3.3 version.\n\n"
  2830. "If possible, consider updating your macOS version.",
  2831. "Unable to initialize OpenGL video driver");
  2832. }
  2833. }
  2834. return ds;
  2835. }
  2836. Vector<String> DisplayServerMacOS::get_rendering_drivers_func() {
  2837. Vector<String> drivers;
  2838. #if defined(VULKAN_ENABLED)
  2839. drivers.push_back("vulkan");
  2840. #endif
  2841. #if defined(METAL_ENABLED)
  2842. drivers.push_back("metal");
  2843. #endif
  2844. #if defined(GLES3_ENABLED)
  2845. drivers.push_back("opengl3");
  2846. drivers.push_back("opengl3_angle");
  2847. #endif
  2848. return drivers;
  2849. }
  2850. void DisplayServerMacOS::register_macos_driver() {
  2851. register_create_function("macos", create_func, get_rendering_drivers_func);
  2852. }
  2853. DisplayServer::WindowID DisplayServerMacOS::window_get_active_popup() const {
  2854. const List<WindowID>::Element *E = popup_list.back();
  2855. if (E) {
  2856. return E->get();
  2857. } else {
  2858. return INVALID_WINDOW_ID;
  2859. }
  2860. }
  2861. void DisplayServerMacOS::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  2862. _THREAD_SAFE_METHOD_
  2863. ERR_FAIL_COND(!windows.has(p_window));
  2864. WindowData &wd = windows[p_window];
  2865. wd.parent_safe_rect = p_rect;
  2866. }
  2867. Rect2i DisplayServerMacOS::window_get_popup_safe_rect(WindowID p_window) const {
  2868. _THREAD_SAFE_METHOD_
  2869. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  2870. const WindowData &wd = windows[p_window];
  2871. return wd.parent_safe_rect;
  2872. }
  2873. void DisplayServerMacOS::popup_open(WindowID p_window) {
  2874. _THREAD_SAFE_METHOD_
  2875. bool has_popup_ancestor = false;
  2876. WindowID transient_root = p_window;
  2877. while (true) {
  2878. WindowID parent = windows[transient_root].transient_parent;
  2879. if (parent == INVALID_WINDOW_ID) {
  2880. break;
  2881. } else {
  2882. transient_root = parent;
  2883. if (windows[parent].is_popup) {
  2884. has_popup_ancestor = true;
  2885. break;
  2886. }
  2887. }
  2888. }
  2889. // Detect tooltips and other similar popups that shouldn't block input to their parent.
  2890. bool ignores_input = window_get_flag(WINDOW_FLAG_NO_FOCUS, p_window) && window_get_flag(WINDOW_FLAG_MOUSE_PASSTHROUGH, p_window);
  2891. WindowData &wd = windows[p_window];
  2892. if (wd.is_popup || (has_popup_ancestor && !ignores_input)) {
  2893. bool was_empty = popup_list.is_empty();
  2894. // Find current popup parent, or root popup if new window is not transient.
  2895. List<WindowID>::Element *C = nullptr;
  2896. List<WindowID>::Element *E = popup_list.back();
  2897. while (E) {
  2898. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  2899. C = E;
  2900. E = E->prev();
  2901. } else {
  2902. break;
  2903. }
  2904. }
  2905. if (C) {
  2906. send_window_event(windows[C->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  2907. }
  2908. if (was_empty && popup_list.is_empty()) {
  2909. // Inform OS that popup was opened, to close other native popups.
  2910. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.beginMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  2911. }
  2912. time_since_popup = OS::get_singleton()->get_ticks_msec();
  2913. popup_list.push_back(p_window);
  2914. }
  2915. }
  2916. void DisplayServerMacOS::popup_close(WindowID p_window) {
  2917. _THREAD_SAFE_METHOD_
  2918. bool was_empty = popup_list.is_empty();
  2919. List<WindowID>::Element *E = popup_list.find(p_window);
  2920. while (E) {
  2921. List<WindowID>::Element *F = E->next();
  2922. WindowID win_id = E->get();
  2923. popup_list.erase(E);
  2924. if (win_id != p_window) {
  2925. // Only request close on related windows, not this window. We are already processing it.
  2926. send_window_event(windows[win_id], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  2927. }
  2928. E = F;
  2929. }
  2930. if (!was_empty && popup_list.is_empty()) {
  2931. // Inform OS that all popups are closed.
  2932. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  2933. }
  2934. }
  2935. bool DisplayServerMacOS::mouse_process_popups(bool p_close) {
  2936. _THREAD_SAFE_METHOD_
  2937. bool was_empty = popup_list.is_empty();
  2938. bool closed = false;
  2939. if (p_close) {
  2940. // Close all popups.
  2941. List<WindowID>::Element *E = popup_list.front();
  2942. if (E) {
  2943. send_window_event(windows[E->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  2944. closed = true;
  2945. }
  2946. if (!was_empty) {
  2947. // Inform OS that all popups are closed.
  2948. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  2949. }
  2950. } else {
  2951. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  2952. if (delta < 250) {
  2953. return false;
  2954. }
  2955. Point2i pos = mouse_get_position();
  2956. List<WindowID>::Element *C = nullptr;
  2957. List<WindowID>::Element *E = popup_list.back();
  2958. // Find top popup to close.
  2959. while (E) {
  2960. // Popup window area.
  2961. Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
  2962. // Area of the parent window, which responsible for opening sub-menu.
  2963. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  2964. if (win_rect.has_point(pos)) {
  2965. break;
  2966. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  2967. break;
  2968. } else {
  2969. C = E;
  2970. E = E->prev();
  2971. }
  2972. }
  2973. if (C) {
  2974. send_window_event(windows[C->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  2975. closed = true;
  2976. }
  2977. if (!was_empty && popup_list.is_empty()) {
  2978. // Inform OS that all popups are closed.
  2979. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  2980. }
  2981. }
  2982. return closed;
  2983. }
  2984. DisplayServerMacOS::DisplayServerMacOS(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i *p_position, const Vector2i &p_resolution, int p_screen, Context p_context, Error &r_error) {
  2985. KeyMappingMacOS::initialize();
  2986. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  2987. r_error = OK;
  2988. memset(cursors, 0, sizeof(cursors));
  2989. event_source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  2990. ERR_FAIL_COND(!event_source);
  2991. CGEventSourceSetLocalEventsSuppressionInterval(event_source, 0.0);
  2992. int screen_count = get_screen_count();
  2993. for (int i = 0; i < screen_count; i++) {
  2994. display_max_scale = fmax(display_max_scale, screen_get_scale(i));
  2995. }
  2996. // Register to be notified on keyboard layout changes.
  2997. CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
  2998. nullptr, _keyboard_layout_changed,
  2999. kTISNotifySelectedKeyboardInputSourceChanged, nullptr,
  3000. CFNotificationSuspensionBehaviorDeliverImmediately);
  3001. // Register to be notified on displays arrangement changes.
  3002. CGDisplayRegisterReconfigurationCallback(_displays_arrangement_changed, nullptr);
  3003. // Init TTS
  3004. bool tts_enabled = GLOBAL_GET("audio/general/text_to_speech");
  3005. if (tts_enabled) {
  3006. tts = [[TTS_MacOS alloc] init];
  3007. }
  3008. native_menu = memnew(NativeMenuMacOS);
  3009. NSMenuItem *menu_item;
  3010. NSString *title;
  3011. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  3012. if (nsappname == nil) {
  3013. nsappname = [[NSProcessInfo processInfo] processName];
  3014. }
  3015. menu_delegate = [[GodotMenuDelegate alloc] init];
  3016. // Setup Dock menu.
  3017. NSMenu *dock_menu = [[NSMenu alloc] initWithTitle:@"_dock"];
  3018. [dock_menu setAutoenablesItems:NO];
  3019. [dock_menu setDelegate:menu_delegate];
  3020. // Setup Apple menu.
  3021. NSMenu *application_menu = [[NSMenu alloc] initWithTitle:@""];
  3022. title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
  3023. [application_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
  3024. [application_menu setAutoenablesItems:NO];
  3025. [application_menu setDelegate:menu_delegate];
  3026. [application_menu addItem:[NSMenuItem separatorItem]];
  3027. menu_item = [application_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3028. menu_item.hidden = YES;
  3029. menu_item.tag = MENU_TAG_START;
  3030. menu_item = [application_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3031. menu_item.hidden = YES;
  3032. menu_item.tag = MENU_TAG_END;
  3033. NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
  3034. menu_item = [application_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
  3035. [application_menu setSubmenu:services forItem:menu_item];
  3036. [NSApp setServicesMenu:services];
  3037. [application_menu addItem:[NSMenuItem separatorItem]];
  3038. title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
  3039. [application_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  3040. menu_item = [application_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  3041. [menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
  3042. [application_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
  3043. [application_menu addItem:[NSMenuItem separatorItem]];
  3044. title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
  3045. [application_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  3046. NSMenu *window_menu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Window", nil)];
  3047. [window_menu addItemWithTitle:NSLocalizedString(@"Minimize", nil) action:@selector(performMiniaturize:) keyEquivalent:@"m"];
  3048. [window_menu addItemWithTitle:NSLocalizedString(@"Zoom", nil) action:@selector(performZoom:) keyEquivalent:@""];
  3049. [window_menu addItem:[NSMenuItem separatorItem]];
  3050. [window_menu addItemWithTitle:NSLocalizedString(@"Bring All to Front", nil) action:@selector(bringAllToFront:) keyEquivalent:@""];
  3051. [window_menu addItem:[NSMenuItem separatorItem]];
  3052. menu_item = [window_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3053. menu_item.hidden = YES;
  3054. menu_item.tag = MENU_TAG_START;
  3055. menu_item = [window_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3056. menu_item.hidden = YES;
  3057. menu_item.tag = MENU_TAG_END;
  3058. NSMenu *help_menu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Help", nil)];
  3059. menu_item = [help_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3060. menu_item.hidden = YES;
  3061. menu_item.tag = MENU_TAG_START;
  3062. menu_item = [help_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3063. menu_item.hidden = YES;
  3064. menu_item.tag = MENU_TAG_END;
  3065. [NSApp setWindowsMenu:window_menu];
  3066. [NSApp setHelpMenu:help_menu];
  3067. // Add items to the menu bar.
  3068. NSMenu *main_menu = [NSApp mainMenu];
  3069. menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  3070. [main_menu setSubmenu:application_menu forItem:menu_item];
  3071. menu_item = [main_menu addItemWithTitle:NSLocalizedString(@"Window", nil) action:nil keyEquivalent:@""];
  3072. [main_menu setSubmenu:window_menu forItem:menu_item];
  3073. menu_item = [main_menu addItemWithTitle:NSLocalizedString(@"Help", nil) action:nil keyEquivalent:@""];
  3074. [main_menu setSubmenu:help_menu forItem:menu_item];
  3075. [main_menu setAutoenablesItems:NO];
  3076. native_menu->_register_system_menus(main_menu, application_menu, window_menu, help_menu, dock_menu);
  3077. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  3078. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  3079. rendering_driver = p_rendering_driver;
  3080. #if defined(RD_ENABLED)
  3081. #if defined(VULKAN_ENABLED)
  3082. if (rendering_driver == "vulkan") {
  3083. rendering_context = memnew(RenderingContextDriverVulkanMacOS);
  3084. }
  3085. #endif
  3086. #if defined(METAL_ENABLED)
  3087. if (rendering_driver == "metal") {
  3088. rendering_context = memnew(RenderingContextDriverMetal);
  3089. }
  3090. #endif
  3091. if (rendering_context) {
  3092. if (rendering_context->initialize() != OK) {
  3093. memdelete(rendering_context);
  3094. rendering_context = nullptr;
  3095. #if defined(GLES3_ENABLED)
  3096. bool fallback_to_opengl3 = GLOBAL_GET("rendering/rendering_device/fallback_to_opengl3");
  3097. if (fallback_to_opengl3 && rendering_driver != "opengl3") {
  3098. WARN_PRINT("Your device seem not to support MoltenVK or Metal, switching to OpenGL 3.");
  3099. rendering_driver = "opengl3";
  3100. OS::get_singleton()->set_current_rendering_method("gl_compatibility");
  3101. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3102. } else
  3103. #endif
  3104. {
  3105. r_error = ERR_CANT_CREATE;
  3106. ERR_FAIL_MSG("Could not initialize " + rendering_driver);
  3107. }
  3108. }
  3109. }
  3110. #endif
  3111. #if defined(GLES3_ENABLED)
  3112. if (rendering_driver == "opengl3_angle") {
  3113. gl_manager_angle = memnew(GLManagerANGLE_MacOS);
  3114. if (gl_manager_angle->initialize() != OK || gl_manager_angle->open_display(nullptr) != OK) {
  3115. memdelete(gl_manager_angle);
  3116. gl_manager_angle = nullptr;
  3117. bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_native");
  3118. if (fallback) {
  3119. #ifdef EGL_STATIC
  3120. WARN_PRINT("Your video card drivers seem not to support GLES3 / ANGLE, switching to native OpenGL.");
  3121. #else
  3122. WARN_PRINT("Your video card drivers seem not to support GLES3 / ANGLE or ANGLE dynamic libraries (libEGL.dylib and libGLESv2.dylib) are missing, switching to native OpenGL.");
  3123. #endif
  3124. rendering_driver = "opengl3";
  3125. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3126. } else {
  3127. r_error = ERR_UNAVAILABLE;
  3128. ERR_FAIL_MSG("Could not initialize ANGLE OpenGL.");
  3129. }
  3130. }
  3131. }
  3132. if (rendering_driver == "opengl3") {
  3133. gl_manager_legacy = memnew(GLManagerLegacy_MacOS);
  3134. if (gl_manager_legacy->initialize() != OK) {
  3135. memdelete(gl_manager_legacy);
  3136. gl_manager_legacy = nullptr;
  3137. r_error = ERR_UNAVAILABLE;
  3138. ERR_FAIL_MSG("Could not initialize native OpenGL.");
  3139. }
  3140. }
  3141. #endif
  3142. Point2i window_position;
  3143. if (p_position != nullptr) {
  3144. window_position = *p_position;
  3145. } else {
  3146. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  3147. p_screen = SCREEN_PRIMARY;
  3148. }
  3149. Rect2i scr_rect = screen_get_usable_rect(p_screen);
  3150. window_position = scr_rect.position + (scr_rect.size - p_resolution) / 2;
  3151. }
  3152. WindowID main_window = _create_window(p_mode, p_vsync_mode, Rect2i(window_position, p_resolution));
  3153. ERR_FAIL_COND(main_window == INVALID_WINDOW_ID);
  3154. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  3155. if (p_flags & (1 << i)) {
  3156. window_set_flag(WindowFlags(i), true, main_window);
  3157. }
  3158. }
  3159. show_window(MAIN_WINDOW_ID);
  3160. force_process_and_drop_events();
  3161. #if defined(GLES3_ENABLED)
  3162. if (rendering_driver == "opengl3") {
  3163. RasterizerGLES3::make_current(true);
  3164. }
  3165. if (rendering_driver == "opengl3_angle") {
  3166. RasterizerGLES3::make_current(false);
  3167. }
  3168. #endif
  3169. #if defined(RD_ENABLED)
  3170. if (rendering_context) {
  3171. rendering_device = memnew(RenderingDevice);
  3172. rendering_device->initialize(rendering_context, MAIN_WINDOW_ID);
  3173. rendering_device->screen_create(MAIN_WINDOW_ID);
  3174. RendererCompositorRD::make_current();
  3175. }
  3176. #endif
  3177. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  3178. }
  3179. DisplayServerMacOS::~DisplayServerMacOS() {
  3180. if (screen_keep_on_assertion) {
  3181. IOPMAssertionRelease(screen_keep_on_assertion);
  3182. screen_keep_on_assertion = kIOPMNullAssertionID;
  3183. }
  3184. // Destroy all status indicators.
  3185. for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E; ++E) {
  3186. [[NSStatusBar systemStatusBar] removeStatusItem:E->value.item];
  3187. }
  3188. // Destroy native menu.
  3189. if (native_menu) {
  3190. memdelete(native_menu);
  3191. native_menu = nullptr;
  3192. }
  3193. // Destroy all windows.
  3194. for (HashMap<WindowID, WindowData>::Iterator E = windows.begin(); E;) {
  3195. HashMap<WindowID, WindowData>::Iterator F = E;
  3196. ++E;
  3197. [F->value.window_object setContentView:nil];
  3198. [F->value.window_object close];
  3199. }
  3200. // Destroy drivers.
  3201. #if defined(GLES3_ENABLED)
  3202. if (gl_manager_legacy) {
  3203. memdelete(gl_manager_legacy);
  3204. gl_manager_legacy = nullptr;
  3205. }
  3206. if (gl_manager_angle) {
  3207. memdelete(gl_manager_angle);
  3208. gl_manager_angle = nullptr;
  3209. }
  3210. #endif
  3211. #if defined(RD_ENABLED)
  3212. if (rendering_device) {
  3213. memdelete(rendering_device);
  3214. rendering_device = nullptr;
  3215. }
  3216. if (rendering_context) {
  3217. memdelete(rendering_context);
  3218. rendering_context = nullptr;
  3219. }
  3220. #endif
  3221. CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), nullptr, kTISNotifySelectedKeyboardInputSourceChanged, nullptr);
  3222. CGDisplayRemoveReconfigurationCallback(_displays_arrangement_changed, nullptr);
  3223. cursors_cache.clear();
  3224. }