display_server_macos.mm 135 KB

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