display_server_macos.mm 116 KB

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