display_server_macos.mm 134 KB

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