display_server_macos.mm 137 KB

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