display_server_macos.mm 128 KB

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