display_server_macos.mm 151 KB

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