display_server_macos.mm 137 KB

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