2
0

display_server_macos.mm 124 KB

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