display_server_macos.mm 132 KB

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