display_server_macos.mm 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964
  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. mouse_enter_window(get_window_at_screen_position(mouse_get_position()));
  1641. }
  1642. void DisplayServerMacOS::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1643. _THREAD_SAFE_METHOD_
  1644. ERR_FAIL_COND(!windows.has(p_window));
  1645. WindowData &wd = windows[p_window];
  1646. wd.rect_changed_callback = p_callable;
  1647. }
  1648. void DisplayServerMacOS::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1649. _THREAD_SAFE_METHOD_
  1650. ERR_FAIL_COND(!windows.has(p_window));
  1651. WindowData &wd = windows[p_window];
  1652. wd.event_callback = p_callable;
  1653. }
  1654. void DisplayServerMacOS::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1655. _THREAD_SAFE_METHOD_
  1656. ERR_FAIL_COND(!windows.has(p_window));
  1657. WindowData &wd = windows[p_window];
  1658. wd.input_event_callback = p_callable;
  1659. }
  1660. void DisplayServerMacOS::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1661. _THREAD_SAFE_METHOD_
  1662. ERR_FAIL_COND(!windows.has(p_window));
  1663. WindowData &wd = windows[p_window];
  1664. wd.input_text_callback = p_callable;
  1665. }
  1666. void DisplayServerMacOS::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1667. _THREAD_SAFE_METHOD_
  1668. ERR_FAIL_COND(!windows.has(p_window));
  1669. WindowData &wd = windows[p_window];
  1670. wd.drop_files_callback = p_callable;
  1671. }
  1672. void DisplayServerMacOS::window_set_title(const String &p_title, WindowID p_window) {
  1673. _THREAD_SAFE_METHOD_
  1674. ERR_FAIL_COND(!windows.has(p_window));
  1675. WindowData &wd = windows[p_window];
  1676. [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
  1677. }
  1678. Size2i DisplayServerMacOS::window_get_title_size(const String &p_title, WindowID p_window) const {
  1679. _THREAD_SAFE_METHOD_
  1680. Size2i size;
  1681. ERR_FAIL_COND_V(!windows.has(p_window), size);
  1682. const WindowData &wd = windows[p_window];
  1683. if (wd.fullscreen || wd.borderless) {
  1684. return size;
  1685. }
  1686. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  1687. if ([wd.window_object isMiniaturized]) {
  1688. return size;
  1689. }
  1690. }
  1691. float scale = screen_get_max_scale();
  1692. if (wd.window_button_view) {
  1693. size.x = ([wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width);
  1694. size.y = ([wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height);
  1695. } else {
  1696. NSButton *cb = [wd.window_object standardWindowButton:NSWindowCloseButton];
  1697. NSButton *mb = [wd.window_object standardWindowButton:NSWindowMiniaturizeButton];
  1698. float cb_frame = NSMinX([cb frame]);
  1699. float mb_frame = NSMinX([mb frame]);
  1700. bool is_rtl = ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft);
  1701. float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame);
  1702. size.x = window_buttons_spacing * 4;
  1703. size.y = [cb frame].origin.y + [cb frame].size.height;
  1704. }
  1705. NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont titleBarFontOfSize:0], NSFontAttributeName, nil];
  1706. NSSize text_size = [[[NSAttributedString alloc] initWithString:[NSString stringWithUTF8String:p_title.utf8().get_data()] attributes:attributes] size];
  1707. size.x += text_size.width;
  1708. size.y = MAX(size.y, text_size.height);
  1709. return size * scale;
  1710. }
  1711. void DisplayServerMacOS::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1712. _THREAD_SAFE_METHOD_
  1713. ERR_FAIL_COND(!windows.has(p_window));
  1714. WindowData &wd = windows[p_window];
  1715. wd.mpath = p_region;
  1716. }
  1717. int DisplayServerMacOS::window_get_current_screen(WindowID p_window) const {
  1718. _THREAD_SAFE_METHOD_
  1719. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  1720. const WindowData &wd = windows[p_window];
  1721. const NSUInteger index = [[NSScreen screens] indexOfObject:[wd.window_object screen]];
  1722. return (index == NSNotFound) ? 0 : index;
  1723. }
  1724. void DisplayServerMacOS::window_set_current_screen(int p_screen, WindowID p_window) {
  1725. _THREAD_SAFE_METHOD_
  1726. ERR_FAIL_COND(!windows.has(p_window));
  1727. WindowData &wd = windows[p_window];
  1728. if (window_get_current_screen(p_window) == p_screen) {
  1729. return;
  1730. }
  1731. bool was_fullscreen = false;
  1732. if (wd.fullscreen) {
  1733. // Temporary exit fullscreen mode to move window.
  1734. [wd.window_object toggleFullScreen:nil];
  1735. was_fullscreen = true;
  1736. }
  1737. bool was_maximized = false;
  1738. if (!was_fullscreen && NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1739. [wd.window_object zoom:nil];
  1740. was_maximized = true;
  1741. }
  1742. Rect2i srect = screen_get_usable_rect(p_screen);
  1743. Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  1744. Size2i wsize = window_get_size(p_window);
  1745. wpos += srect.position;
  1746. wpos = wpos.clamp(srect.position, srect.position + srect.size - wsize / 3);
  1747. window_set_position(wpos, p_window);
  1748. if (was_maximized) {
  1749. [wd.window_object zoom:nil];
  1750. }
  1751. if (was_fullscreen) {
  1752. // Re-enter fullscreen mode.
  1753. [wd.window_object toggleFullScreen:nil];
  1754. }
  1755. }
  1756. void DisplayServerMacOS::reparent_check(WindowID p_window) {
  1757. ERR_FAIL_COND(!windows.has(p_window));
  1758. WindowData &wd = windows[p_window];
  1759. NSScreen *screen = [wd.window_object screen];
  1760. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1761. WindowData &wd_parent = windows[wd.transient_parent];
  1762. NSScreen *parent_screen = [wd_parent.window_object screen];
  1763. if (parent_screen == screen) {
  1764. if (![[wd_parent.window_object childWindows] containsObject:wd.window_object]) {
  1765. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
  1766. [wd_parent.window_object addChildWindow:wd.window_object ordered:NSWindowAbove];
  1767. }
  1768. } else {
  1769. if ([[wd_parent.window_object childWindows] containsObject:wd.window_object]) {
  1770. [wd_parent.window_object removeChildWindow:wd.window_object];
  1771. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1772. [wd.window_object orderFront:nil];
  1773. }
  1774. }
  1775. }
  1776. for (const WindowID &child : wd.transient_children) {
  1777. WindowData &wd_child = windows[child];
  1778. NSScreen *child_screen = [wd_child.window_object screen];
  1779. if (child_screen == screen) {
  1780. if (![[wd.window_object childWindows] containsObject:wd_child.window_object]) {
  1781. if (wd_child.fullscreen) {
  1782. [wd_child.window_object toggleFullScreen:nil];
  1783. }
  1784. [wd_child.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
  1785. [wd.window_object addChildWindow:wd_child.window_object ordered:NSWindowAbove];
  1786. }
  1787. } else {
  1788. if ([[wd.window_object childWindows] containsObject:wd_child.window_object]) {
  1789. [wd.window_object removeChildWindow:wd_child.window_object];
  1790. [wd_child.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1791. }
  1792. }
  1793. }
  1794. }
  1795. void DisplayServerMacOS::window_set_exclusive(WindowID p_window, bool p_exclusive) {
  1796. _THREAD_SAFE_METHOD_
  1797. ERR_FAIL_COND(!windows.has(p_window));
  1798. WindowData &wd = windows[p_window];
  1799. if (wd.exclusive != p_exclusive) {
  1800. wd.exclusive = p_exclusive;
  1801. reparent_check(p_window);
  1802. }
  1803. }
  1804. Point2i DisplayServerMacOS::window_get_position(WindowID p_window) const {
  1805. _THREAD_SAFE_METHOD_
  1806. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1807. const WindowData &wd = windows[p_window];
  1808. // Use content rect position (without titlebar / window border).
  1809. const NSRect contentRect = [wd.window_view frame];
  1810. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  1811. Point2i pos;
  1812. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  1813. const float scale = screen_get_max_scale();
  1814. pos.x = nsrect.origin.x;
  1815. pos.y = (nsrect.origin.y + nsrect.size.height);
  1816. pos *= scale;
  1817. pos -= _get_screens_origin();
  1818. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1819. // Godot expects a positive value.
  1820. pos.y *= -1;
  1821. return pos;
  1822. }
  1823. Point2i DisplayServerMacOS::window_get_position_with_decorations(WindowID p_window) const {
  1824. _THREAD_SAFE_METHOD_
  1825. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1826. const WindowData &wd = windows[p_window];
  1827. const NSRect nsrect = [wd.window_object frame];
  1828. Point2i pos;
  1829. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  1830. const float scale = screen_get_max_scale();
  1831. pos.x = nsrect.origin.x;
  1832. pos.y = (nsrect.origin.y + nsrect.size.height);
  1833. pos *= scale;
  1834. pos -= _get_screens_origin();
  1835. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1836. // Godot expects a positive value.
  1837. pos.y *= -1;
  1838. return pos;
  1839. }
  1840. void DisplayServerMacOS::window_set_position(const Point2i &p_position, WindowID p_window) {
  1841. _THREAD_SAFE_METHOD_
  1842. ERR_FAIL_COND(!windows.has(p_window));
  1843. WindowData &wd = windows[p_window];
  1844. if (wd.fullscreen) {
  1845. return;
  1846. }
  1847. Point2i position = p_position;
  1848. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1849. // Godot passes a positive value.
  1850. position.y *= -1;
  1851. position += _get_screens_origin();
  1852. position /= screen_get_max_scale();
  1853. // Remove titlebar / window border size.
  1854. const NSRect contentRect = [wd.window_view frame];
  1855. const NSRect windowRect = [wd.window_object frame];
  1856. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  1857. Point2i offset;
  1858. offset.x = (nsrect.origin.x - windowRect.origin.x);
  1859. offset.y = (nsrect.origin.y + nsrect.size.height);
  1860. offset.y -= (windowRect.origin.y + windowRect.size.height);
  1861. [wd.window_object setFrameTopLeftPoint:NSMakePoint(position.x - offset.x, position.y - offset.y)];
  1862. _update_window_style(wd, p_window);
  1863. update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  1864. }
  1865. void DisplayServerMacOS::window_set_transient(WindowID p_window, WindowID p_parent) {
  1866. _THREAD_SAFE_METHOD_
  1867. ERR_FAIL_COND(p_window == p_parent);
  1868. ERR_FAIL_COND(!windows.has(p_window));
  1869. WindowData &wd_window = windows[p_window];
  1870. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  1871. ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
  1872. if (p_parent == INVALID_WINDOW_ID) {
  1873. // Remove transient.
  1874. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  1875. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  1876. WindowData &wd_parent = windows[wd_window.transient_parent];
  1877. wd_window.transient_parent = INVALID_WINDOW_ID;
  1878. wd_parent.transient_children.erase(p_window);
  1879. if ([[wd_parent.window_object childWindows] containsObject:wd_window.window_object]) {
  1880. [wd_parent.window_object removeChildWindow:wd_window.window_object];
  1881. }
  1882. [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1883. } else {
  1884. ERR_FAIL_COND(!windows.has(p_parent));
  1885. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  1886. WindowData &wd_parent = windows[p_parent];
  1887. wd_window.transient_parent = p_parent;
  1888. wd_parent.transient_children.insert(p_window);
  1889. reparent_check(p_window);
  1890. }
  1891. }
  1892. void DisplayServerMacOS::window_set_max_size(const Size2i p_size, WindowID p_window) {
  1893. _THREAD_SAFE_METHOD_
  1894. ERR_FAIL_COND(!windows.has(p_window));
  1895. WindowData &wd = windows[p_window];
  1896. if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  1897. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1898. return;
  1899. }
  1900. wd.max_size = p_size;
  1901. if ((wd.max_size != Size2i()) && !wd.fullscreen) {
  1902. Size2i size = wd.max_size / screen_get_max_scale();
  1903. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  1904. } else {
  1905. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  1906. }
  1907. }
  1908. Size2i DisplayServerMacOS::window_get_max_size(WindowID p_window) const {
  1909. _THREAD_SAFE_METHOD_
  1910. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1911. const WindowData &wd = windows[p_window];
  1912. return wd.max_size;
  1913. }
  1914. void DisplayServerMacOS::update_presentation_mode() {
  1915. bool has_fs_windows = false;
  1916. for (const KeyValue<WindowID, WindowData> &wd : windows) {
  1917. if (wd.value.fullscreen) {
  1918. if (wd.value.exclusive_fullscreen) {
  1919. return;
  1920. } else {
  1921. has_fs_windows = true;
  1922. }
  1923. }
  1924. }
  1925. if (has_fs_windows) {
  1926. [NSApp setPresentationOptions:NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock | NSApplicationPresentationFullScreen];
  1927. } else {
  1928. [NSApp setPresentationOptions:NSApplicationPresentationDefault];
  1929. }
  1930. }
  1931. void DisplayServerMacOS::window_set_min_size(const Size2i p_size, WindowID p_window) {
  1932. _THREAD_SAFE_METHOD_
  1933. ERR_FAIL_COND(!windows.has(p_window));
  1934. WindowData &wd = windows[p_window];
  1935. if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  1936. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1937. return;
  1938. }
  1939. wd.min_size = p_size;
  1940. if ((wd.min_size != Size2i()) && !wd.fullscreen) {
  1941. Size2i size = wd.min_size / screen_get_max_scale();
  1942. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  1943. } else {
  1944. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  1945. }
  1946. }
  1947. Size2i DisplayServerMacOS::window_get_min_size(WindowID p_window) const {
  1948. _THREAD_SAFE_METHOD_
  1949. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1950. const WindowData &wd = windows[p_window];
  1951. return wd.min_size;
  1952. }
  1953. void DisplayServerMacOS::window_set_size(const Size2i p_size, WindowID p_window) {
  1954. _THREAD_SAFE_METHOD_
  1955. ERR_FAIL_COND(!windows.has(p_window));
  1956. WindowData &wd = windows[p_window];
  1957. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1958. return;
  1959. }
  1960. Size2i size = p_size / screen_get_max_scale();
  1961. NSPoint top_left;
  1962. NSRect old_frame = [wd.window_object frame];
  1963. top_left.x = old_frame.origin.x;
  1964. top_left.y = NSMaxY(old_frame);
  1965. NSRect new_frame = NSMakeRect(0, 0, MAX(1, size.x), MAX(1, size.y));
  1966. new_frame = [wd.window_object frameRectForContentRect:new_frame];
  1967. new_frame.origin.x = top_left.x;
  1968. new_frame.origin.y = top_left.y - new_frame.size.height;
  1969. [wd.window_object setFrame:new_frame display:YES];
  1970. _update_window_style(wd, p_window);
  1971. }
  1972. Size2i DisplayServerMacOS::window_get_size(WindowID p_window) const {
  1973. _THREAD_SAFE_METHOD_
  1974. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1975. const WindowData &wd = windows[p_window];
  1976. return wd.size;
  1977. }
  1978. Size2i DisplayServerMacOS::window_get_size_with_decorations(WindowID p_window) const {
  1979. _THREAD_SAFE_METHOD_
  1980. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1981. const WindowData &wd = windows[p_window];
  1982. NSRect frame = [wd.window_object frame];
  1983. return Size2i(frame.size.width, frame.size.height) * screen_get_max_scale();
  1984. }
  1985. void DisplayServerMacOS::window_set_mode(WindowMode p_mode, WindowID p_window) {
  1986. _THREAD_SAFE_METHOD_
  1987. ERR_FAIL_COND(!windows.has(p_window));
  1988. WindowData &wd = windows[p_window];
  1989. WindowMode old_mode = window_get_mode(p_window);
  1990. if (old_mode == p_mode) {
  1991. return; // Do nothing.
  1992. }
  1993. switch (old_mode) {
  1994. case WINDOW_MODE_WINDOWED: {
  1995. // Do nothing.
  1996. } break;
  1997. case WINDOW_MODE_MINIMIZED: {
  1998. [wd.window_object deminiaturize:nil];
  1999. } break;
  2000. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  2001. case WINDOW_MODE_FULLSCREEN: {
  2002. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN || p_mode == WINDOW_MODE_FULLSCREEN) {
  2003. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2004. const NSUInteger presentationOptions = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
  2005. [NSApp setPresentationOptions:presentationOptions];
  2006. wd.exclusive_fullscreen = true;
  2007. } else {
  2008. wd.exclusive_fullscreen = false;
  2009. update_presentation_mode();
  2010. }
  2011. return;
  2012. }
  2013. [(NSWindow *)wd.window_object setLevel:NSNormalWindowLevel];
  2014. if (wd.resize_disabled) { // Restore resize disabled.
  2015. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2016. }
  2017. if (wd.min_size != Size2i()) {
  2018. Size2i size = wd.min_size / screen_get_max_scale();
  2019. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  2020. }
  2021. if (wd.max_size != Size2i()) {
  2022. Size2i size = wd.max_size / screen_get_max_scale();
  2023. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  2024. }
  2025. [wd.window_object toggleFullScreen:nil];
  2026. if (old_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2027. update_presentation_mode();
  2028. }
  2029. wd.fullscreen = false;
  2030. wd.exclusive_fullscreen = false;
  2031. } break;
  2032. case WINDOW_MODE_MAXIMIZED: {
  2033. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  2034. [wd.window_object zoom:nil];
  2035. }
  2036. } break;
  2037. }
  2038. switch (p_mode) {
  2039. case WINDOW_MODE_WINDOWED: {
  2040. // Do nothing.
  2041. } break;
  2042. case WINDOW_MODE_MINIMIZED: {
  2043. [wd.window_object performMiniaturize:nil];
  2044. } break;
  2045. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  2046. case WINDOW_MODE_FULLSCREEN: {
  2047. if (wd.resize_disabled) { // Fullscreen window should be resizable to work.
  2048. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2049. }
  2050. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  2051. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  2052. [wd.window_object toggleFullScreen:nil];
  2053. wd.fullscreen = true;
  2054. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2055. const NSUInteger presentationOptions = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
  2056. [NSApp setPresentationOptions:presentationOptions];
  2057. wd.exclusive_fullscreen = true;
  2058. } else {
  2059. wd.exclusive_fullscreen = false;
  2060. update_presentation_mode();
  2061. }
  2062. } break;
  2063. case WINDOW_MODE_MAXIMIZED: {
  2064. if (!NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  2065. [wd.window_object zoom:nil];
  2066. }
  2067. } break;
  2068. }
  2069. }
  2070. DisplayServer::WindowMode DisplayServerMacOS::window_get_mode(WindowID p_window) const {
  2071. _THREAD_SAFE_METHOD_
  2072. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  2073. const WindowData &wd = windows[p_window];
  2074. if (wd.fullscreen) { // If fullscreen, it's not in another mode.
  2075. if (wd.exclusive_fullscreen) {
  2076. return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
  2077. } else {
  2078. return WINDOW_MODE_FULLSCREEN;
  2079. }
  2080. }
  2081. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  2082. return WINDOW_MODE_MAXIMIZED;
  2083. }
  2084. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  2085. if ([wd.window_object isMiniaturized]) {
  2086. return WINDOW_MODE_MINIMIZED;
  2087. }
  2088. }
  2089. // All other discarded, return windowed.
  2090. return WINDOW_MODE_WINDOWED;
  2091. }
  2092. bool DisplayServerMacOS::window_is_maximize_allowed(WindowID p_window) const {
  2093. return true;
  2094. }
  2095. bool DisplayServerMacOS::window_maximize_on_title_dbl_click() const {
  2096. id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleActionOnDoubleClick"];
  2097. if ([value isKindOfClass:[NSString class]]) {
  2098. return [value isEqualToString:@"Maximize"];
  2099. }
  2100. return false;
  2101. }
  2102. bool DisplayServerMacOS::window_minimize_on_title_dbl_click() const {
  2103. id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleActionOnDoubleClick"];
  2104. if ([value isKindOfClass:[NSString class]]) {
  2105. return [value isEqualToString:@"Minimize"];
  2106. }
  2107. return false;
  2108. }
  2109. void DisplayServerMacOS::window_start_drag(WindowID p_window) {
  2110. _THREAD_SAFE_METHOD_
  2111. ERR_FAIL_COND(!windows.has(p_window));
  2112. WindowData &wd = windows[p_window];
  2113. 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];
  2114. [wd.window_object performWindowDragWithEvent:event];
  2115. }
  2116. void DisplayServerMacOS::window_start_resize(WindowResizeEdge p_edge, WindowID p_window) {
  2117. _THREAD_SAFE_METHOD_
  2118. ERR_FAIL_INDEX(int(p_edge), WINDOW_EDGE_MAX);
  2119. ERR_FAIL_COND(!windows.has(p_window));
  2120. WindowData &wd = windows[p_window];
  2121. wd.edge = p_edge;
  2122. }
  2123. void DisplayServerMacOS::window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window) {
  2124. _THREAD_SAFE_METHOD_
  2125. ERR_FAIL_COND(!windows.has(p_window));
  2126. WindowData &wd = windows[p_window];
  2127. float scale = screen_get_max_scale();
  2128. wd.wb_offset = p_offset / scale;
  2129. wd.wb_offset = wd.wb_offset.maxi(12);
  2130. if (wd.window_button_view) {
  2131. [(GodotButtonView *)wd.window_button_view setOffset:NSMakePoint(wd.wb_offset.x, wd.wb_offset.y)];
  2132. }
  2133. }
  2134. Vector3i DisplayServerMacOS::window_get_safe_title_margins(WindowID p_window) const {
  2135. _THREAD_SAFE_METHOD_
  2136. ERR_FAIL_COND_V(!windows.has(p_window), Vector3i());
  2137. const WindowData &wd = windows[p_window];
  2138. if (!wd.window_button_view) {
  2139. return Vector3i();
  2140. }
  2141. float scale = screen_get_max_scale();
  2142. float max_x = [wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width;
  2143. float max_y = [wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height;
  2144. if ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft) {
  2145. return Vector3i(0, max_x * scale, max_y * scale);
  2146. } else {
  2147. return Vector3i(max_x * scale, 0, max_y * scale);
  2148. }
  2149. }
  2150. void DisplayServerMacOS::window_set_custom_window_buttons(WindowData &p_wd, bool p_enabled) {
  2151. if (p_wd.window_button_view) {
  2152. [p_wd.window_button_view removeFromSuperview];
  2153. p_wd.window_button_view = nil;
  2154. }
  2155. if (p_enabled) {
  2156. float cb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowCloseButton] frame]);
  2157. float mb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] frame]);
  2158. bool is_rtl = ([p_wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft);
  2159. float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame);
  2160. [p_wd.window_object setTitleVisibility:NSWindowTitleHidden];
  2161. [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:YES];
  2162. [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  2163. [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:YES];
  2164. p_wd.window_button_view = [[GodotButtonView alloc] initWithFrame:NSZeroRect];
  2165. [p_wd.window_button_view initButtons:window_buttons_spacing offset:NSMakePoint(p_wd.wb_offset.x, p_wd.wb_offset.y) rtl:is_rtl];
  2166. [p_wd.window_view addSubview:p_wd.window_button_view];
  2167. } else {
  2168. [p_wd.window_object setTitleVisibility:NSWindowTitleVisible];
  2169. [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:NO];
  2170. [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:NO];
  2171. [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:NO];
  2172. }
  2173. }
  2174. void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  2175. _THREAD_SAFE_METHOD_
  2176. ERR_FAIL_COND(!windows.has(p_window));
  2177. WindowData &wd = windows[p_window];
  2178. switch (p_flag) {
  2179. case WINDOW_FLAG_RESIZE_DISABLED: {
  2180. wd.resize_disabled = p_enabled;
  2181. if (wd.fullscreen) { // Fullscreen window should be resizable, style will be applied on exiting fullscreen.
  2182. return;
  2183. }
  2184. if (p_enabled) {
  2185. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2186. [[wd.window_object standardWindowButton:NSWindowZoomButton] setEnabled:NO];
  2187. } else {
  2188. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2189. [[wd.window_object standardWindowButton:NSWindowZoomButton] setEnabled:YES];
  2190. }
  2191. } break;
  2192. case WINDOW_FLAG_EXTEND_TO_TITLE: {
  2193. NSRect rect = [wd.window_object frame];
  2194. wd.extend_to_title = p_enabled;
  2195. if (p_enabled) {
  2196. [wd.window_object setTitlebarAppearsTransparent:YES];
  2197. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskFullSizeContentView];
  2198. if (!wd.fullscreen) {
  2199. window_set_custom_window_buttons(wd, true);
  2200. }
  2201. } else {
  2202. [wd.window_object setTitlebarAppearsTransparent:NO];
  2203. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskFullSizeContentView];
  2204. if (!wd.fullscreen) {
  2205. window_set_custom_window_buttons(wd, false);
  2206. }
  2207. }
  2208. [wd.window_object setFrame:rect display:YES];
  2209. send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_TITLEBAR_CHANGE);
  2210. } break;
  2211. case WINDOW_FLAG_BORDERLESS: {
  2212. if (wd.fullscreen) {
  2213. return;
  2214. }
  2215. // OrderOut prevents a lose focus bug with the window.
  2216. bool was_visible = false;
  2217. if ([wd.window_object isVisible]) {
  2218. was_visible = true;
  2219. [wd.window_object orderOut:nil];
  2220. }
  2221. wd.borderless = p_enabled;
  2222. if (p_enabled) {
  2223. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless];
  2224. } else {
  2225. if (wd.layered_window) {
  2226. wd.layered_window = false;
  2227. set_window_per_pixel_transparency_enabled(false, p_window);
  2228. }
  2229. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.extend_to_title ? NSWindowStyleMaskFullSizeContentView : 0) | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2230. // Force update of the window styles.
  2231. NSRect frameRect = [wd.window_object frame];
  2232. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2233. [wd.window_object setFrame:frameRect display:NO];
  2234. }
  2235. _update_window_style(wd, p_window);
  2236. if (was_visible || [wd.window_object isVisible]) {
  2237. if ([wd.window_object isMiniaturized]) {
  2238. return;
  2239. } else if (wd.no_focus) {
  2240. [wd.window_object orderFront:nil];
  2241. } else {
  2242. [wd.window_object makeKeyAndOrderFront:nil];
  2243. }
  2244. }
  2245. } break;
  2246. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2247. wd.on_top = p_enabled;
  2248. if (wd.fullscreen) {
  2249. return;
  2250. }
  2251. if (p_enabled) {
  2252. [(NSWindow *)wd.window_object setLevel:NSFloatingWindowLevel];
  2253. } else {
  2254. [(NSWindow *)wd.window_object setLevel:NSNormalWindowLevel];
  2255. }
  2256. } break;
  2257. case WINDOW_FLAG_TRANSPARENT: {
  2258. if (wd.fullscreen) {
  2259. return;
  2260. }
  2261. if (p_enabled) {
  2262. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless]; // Force borderless.
  2263. } else if (!wd.borderless) {
  2264. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.extend_to_title ? NSWindowStyleMaskFullSizeContentView : 0) | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2265. }
  2266. wd.layered_window = p_enabled;
  2267. set_window_per_pixel_transparency_enabled(p_enabled, p_window);
  2268. // Force update of the window styles.
  2269. NSRect frameRect = [wd.window_object frame];
  2270. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2271. [wd.window_object setFrame:frameRect display:NO];
  2272. } break;
  2273. case WINDOW_FLAG_NO_FOCUS: {
  2274. wd.no_focus = p_enabled;
  2275. NSWindow *w = wd.window_object;
  2276. w.excludedFromWindowsMenu = wd.is_popup || wd.no_focus;
  2277. } break;
  2278. case WINDOW_FLAG_EXCLUDE_FROM_CAPTURE: {
  2279. if (p_enabled) {
  2280. [wd.window_object setSharingType:NSWindowSharingNone];
  2281. } else {
  2282. [wd.window_object setSharingType:NSWindowSharingReadWrite];
  2283. }
  2284. wd.hide_from_capture = p_enabled;
  2285. } break;
  2286. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2287. wd.mpass = p_enabled;
  2288. } break;
  2289. case WINDOW_FLAG_POPUP: {
  2290. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  2291. ERR_FAIL_COND_MSG([wd.window_object isVisible] && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  2292. wd.is_popup = p_enabled;
  2293. NSWindow *w = wd.window_object;
  2294. w.excludedFromWindowsMenu = wd.is_popup || wd.no_focus;
  2295. } break;
  2296. default: {
  2297. }
  2298. }
  2299. }
  2300. bool DisplayServerMacOS::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  2301. _THREAD_SAFE_METHOD_
  2302. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2303. const WindowData &wd = windows[p_window];
  2304. switch (p_flag) {
  2305. case WINDOW_FLAG_RESIZE_DISABLED: {
  2306. return wd.resize_disabled;
  2307. } break;
  2308. case WINDOW_FLAG_EXTEND_TO_TITLE: {
  2309. return [wd.window_object styleMask] & NSWindowStyleMaskFullSizeContentView;
  2310. } break;
  2311. case WINDOW_FLAG_BORDERLESS: {
  2312. return [wd.window_object styleMask] == NSWindowStyleMaskBorderless;
  2313. } break;
  2314. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2315. return wd.on_top;
  2316. } break;
  2317. case WINDOW_FLAG_TRANSPARENT: {
  2318. return wd.layered_window;
  2319. } break;
  2320. case WINDOW_FLAG_NO_FOCUS: {
  2321. return wd.no_focus;
  2322. } break;
  2323. case WINDOW_FLAG_EXCLUDE_FROM_CAPTURE: {
  2324. return wd.hide_from_capture;
  2325. } break;
  2326. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2327. return wd.mpass;
  2328. } break;
  2329. case WINDOW_FLAG_POPUP: {
  2330. return wd.is_popup;
  2331. } break;
  2332. default: {
  2333. }
  2334. }
  2335. return false;
  2336. }
  2337. void DisplayServerMacOS::window_request_attention(WindowID p_window) {
  2338. // It's app global, ignore window id.
  2339. [NSApp requestUserAttention:NSCriticalRequest];
  2340. }
  2341. void DisplayServerMacOS::window_move_to_foreground(WindowID p_window) {
  2342. _THREAD_SAFE_METHOD_
  2343. ERR_FAIL_COND(!windows.has(p_window));
  2344. const WindowData &wd = windows[p_window];
  2345. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  2346. if (wd.no_focus || wd.is_popup) {
  2347. [wd.window_object orderFront:nil];
  2348. } else {
  2349. [wd.window_object makeKeyAndOrderFront:nil];
  2350. }
  2351. }
  2352. bool DisplayServerMacOS::window_is_focused(WindowID p_window) const {
  2353. _THREAD_SAFE_METHOD_
  2354. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2355. const WindowData &wd = windows[p_window];
  2356. return wd.focused;
  2357. }
  2358. DisplayServerMacOS::WindowID DisplayServerMacOS::get_focused_window() const {
  2359. return last_focused_window;
  2360. }
  2361. bool DisplayServerMacOS::window_can_draw(WindowID p_window) const {
  2362. return windows[p_window].is_visible;
  2363. }
  2364. bool DisplayServerMacOS::can_any_window_draw() const {
  2365. _THREAD_SAFE_METHOD_
  2366. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2367. if (E.value.is_visible) {
  2368. return true;
  2369. }
  2370. }
  2371. return false;
  2372. }
  2373. void DisplayServerMacOS::window_set_ime_active(const bool p_active, WindowID p_window) {
  2374. _THREAD_SAFE_METHOD_
  2375. ERR_FAIL_COND(!windows.has(p_window));
  2376. WindowData &wd = windows[p_window];
  2377. wd.im_active = p_active;
  2378. if (!p_active) {
  2379. [wd.window_view cancelComposition];
  2380. }
  2381. }
  2382. void DisplayServerMacOS::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  2383. _THREAD_SAFE_METHOD_
  2384. ERR_FAIL_COND(!windows.has(p_window));
  2385. WindowData &wd = windows[p_window];
  2386. wd.im_position = p_pos;
  2387. }
  2388. DisplayServer::WindowID DisplayServerMacOS::get_window_at_screen_position(const Point2i &p_position) const {
  2389. Point2i position = p_position;
  2390. position.y *= -1;
  2391. position += _get_screens_origin();
  2392. position /= screen_get_max_scale();
  2393. NSInteger wnum = [NSWindow windowNumberAtPoint:NSMakePoint(position.x, position.y) belowWindowWithWindowNumber:0 /*topmost*/];
  2394. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2395. if ([E.value.window_object windowNumber] == wnum) {
  2396. return E.key;
  2397. }
  2398. }
  2399. return INVALID_WINDOW_ID;
  2400. }
  2401. int64_t DisplayServerMacOS::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  2402. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  2403. switch (p_handle_type) {
  2404. case DISPLAY_HANDLE: {
  2405. return 0; // Not supported.
  2406. }
  2407. case WINDOW_HANDLE: {
  2408. return (int64_t)windows[p_window].window_object;
  2409. }
  2410. case WINDOW_VIEW: {
  2411. return (int64_t)windows[p_window].window_view;
  2412. }
  2413. #ifdef GLES3_ENABLED
  2414. case OPENGL_CONTEXT: {
  2415. if (gl_manager_legacy) {
  2416. return (int64_t)gl_manager_legacy->get_context(p_window);
  2417. }
  2418. if (gl_manager_angle) {
  2419. return (int64_t)gl_manager_angle->get_context(p_window);
  2420. }
  2421. return 0;
  2422. }
  2423. case EGL_DISPLAY: {
  2424. if (gl_manager_angle) {
  2425. return (int64_t)gl_manager_angle->get_display(p_window);
  2426. }
  2427. return 0;
  2428. }
  2429. case EGL_CONFIG: {
  2430. if (gl_manager_angle) {
  2431. return (int64_t)gl_manager_angle->get_config(p_window);
  2432. }
  2433. return 0;
  2434. }
  2435. #endif
  2436. default: {
  2437. return 0;
  2438. }
  2439. }
  2440. }
  2441. void DisplayServerMacOS::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  2442. _THREAD_SAFE_METHOD_
  2443. ERR_FAIL_COND(!windows.has(p_window));
  2444. windows[p_window].instance_id = p_instance;
  2445. }
  2446. ObjectID DisplayServerMacOS::window_get_attached_instance_id(WindowID p_window) const {
  2447. _THREAD_SAFE_METHOD_
  2448. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  2449. return windows[p_window].instance_id;
  2450. }
  2451. void DisplayServerMacOS::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  2452. #if defined(GLES3_ENABLED)
  2453. if (gl_manager_legacy) {
  2454. gl_manager_legacy->window_make_current(p_window_id);
  2455. }
  2456. if (gl_manager_angle) {
  2457. gl_manager_angle->window_make_current(p_window_id);
  2458. }
  2459. #endif
  2460. }
  2461. void DisplayServerMacOS::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  2462. _THREAD_SAFE_METHOD_
  2463. #if defined(GLES3_ENABLED)
  2464. if (gl_manager_angle) {
  2465. gl_manager_angle->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  2466. }
  2467. if (gl_manager_legacy) {
  2468. gl_manager_legacy->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  2469. }
  2470. #endif
  2471. #if defined(RD_ENABLED)
  2472. if (rendering_context) {
  2473. rendering_context->window_set_vsync_mode(p_window, p_vsync_mode);
  2474. }
  2475. #endif
  2476. }
  2477. DisplayServer::VSyncMode DisplayServerMacOS::window_get_vsync_mode(WindowID p_window) const {
  2478. _THREAD_SAFE_METHOD_
  2479. #if defined(GLES3_ENABLED)
  2480. if (gl_manager_angle) {
  2481. return (gl_manager_angle->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2482. }
  2483. if (gl_manager_legacy) {
  2484. return (gl_manager_legacy->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2485. }
  2486. #endif
  2487. #if defined(RD_ENABLED)
  2488. if (rendering_context) {
  2489. return rendering_context->window_get_vsync_mode(p_window);
  2490. }
  2491. #endif
  2492. return DisplayServer::VSYNC_ENABLED;
  2493. }
  2494. Point2i DisplayServerMacOS::ime_get_selection() const {
  2495. return im_selection;
  2496. }
  2497. String DisplayServerMacOS::ime_get_text() const {
  2498. return im_text;
  2499. }
  2500. void DisplayServerMacOS::cursor_update_shape() {
  2501. _THREAD_SAFE_METHOD_
  2502. if (cursors[cursor_shape] != nullptr) {
  2503. [cursors[cursor_shape] set];
  2504. } else {
  2505. switch (cursor_shape) {
  2506. case CURSOR_ARROW:
  2507. [[NSCursor arrowCursor] set];
  2508. break;
  2509. case CURSOR_IBEAM:
  2510. [[NSCursor IBeamCursor] set];
  2511. break;
  2512. case CURSOR_POINTING_HAND:
  2513. [[NSCursor pointingHandCursor] set];
  2514. break;
  2515. case CURSOR_CROSS:
  2516. [[NSCursor crosshairCursor] set];
  2517. break;
  2518. case CURSOR_WAIT:
  2519. [[NSCursor arrowCursor] set];
  2520. break;
  2521. case CURSOR_BUSY:
  2522. [[NSCursor arrowCursor] set];
  2523. break;
  2524. case CURSOR_DRAG:
  2525. [[NSCursor closedHandCursor] set];
  2526. break;
  2527. case CURSOR_CAN_DROP:
  2528. [[NSCursor openHandCursor] set];
  2529. break;
  2530. case CURSOR_FORBIDDEN:
  2531. [[NSCursor operationNotAllowedCursor] set];
  2532. break;
  2533. case CURSOR_VSIZE:
  2534. [_cursor_from_selector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set];
  2535. break;
  2536. case CURSOR_HSIZE:
  2537. [_cursor_from_selector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set];
  2538. break;
  2539. case CURSOR_BDIAGSIZE:
  2540. [_cursor_from_selector(@selector(_windowResizeNorthEastSouthWestCursor)) set];
  2541. break;
  2542. case CURSOR_FDIAGSIZE:
  2543. [_cursor_from_selector(@selector(_windowResizeNorthWestSouthEastCursor)) set];
  2544. break;
  2545. case CURSOR_MOVE:
  2546. [[NSCursor arrowCursor] set];
  2547. break;
  2548. case CURSOR_VSPLIT:
  2549. [[NSCursor resizeUpDownCursor] set];
  2550. break;
  2551. case CURSOR_HSPLIT:
  2552. [[NSCursor resizeLeftRightCursor] set];
  2553. break;
  2554. case CURSOR_HELP:
  2555. [_cursor_from_selector(@selector(_helpCursor)) set];
  2556. break;
  2557. default: {
  2558. }
  2559. }
  2560. }
  2561. }
  2562. void DisplayServerMacOS::cursor_set_shape(CursorShape p_shape) {
  2563. _THREAD_SAFE_METHOD_
  2564. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2565. if (cursor_shape == p_shape) {
  2566. return;
  2567. }
  2568. cursor_shape = p_shape;
  2569. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  2570. return;
  2571. }
  2572. cursor_update_shape();
  2573. }
  2574. DisplayServerMacOS::CursorShape DisplayServerMacOS::cursor_get_shape() const {
  2575. return cursor_shape;
  2576. }
  2577. void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2578. _THREAD_SAFE_METHOD_
  2579. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2580. if (p_cursor.is_valid()) {
  2581. HashMap<CursorShape, Vector<Variant>>::Iterator cursor_c = cursors_cache.find(p_shape);
  2582. if (cursor_c) {
  2583. if (cursor_c->value[0] == p_cursor && cursor_c->value[1] == p_hotspot) {
  2584. cursor_set_shape(p_shape);
  2585. return;
  2586. }
  2587. cursors_cache.erase(p_shape);
  2588. }
  2589. Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot);
  2590. ERR_FAIL_COND(image.is_null());
  2591. Vector2i texture_size = image->get_size();
  2592. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2593. initWithBitmapDataPlanes:nullptr
  2594. pixelsWide:int(texture_size.width)
  2595. pixelsHigh:int(texture_size.height)
  2596. bitsPerSample:8
  2597. samplesPerPixel:4
  2598. hasAlpha:YES
  2599. isPlanar:NO
  2600. colorSpaceName:NSDeviceRGBColorSpace
  2601. bytesPerRow:int(texture_size.width) * 4
  2602. bitsPerPixel:32];
  2603. ERR_FAIL_NULL(imgrep);
  2604. uint8_t *pixels = [imgrep bitmapData];
  2605. int len = int(texture_size.width * texture_size.height);
  2606. for (int i = 0; i < len; i++) {
  2607. int row_index = floor(i / texture_size.width);
  2608. int column_index = i % int(texture_size.width);
  2609. uint32_t color = image->get_pixel(column_index, row_index).to_argb32();
  2610. uint8_t alpha = (color >> 24) & 0xFF;
  2611. pixels[i * 4 + 0] = ((color >> 16) & 0xFF) * alpha / 255;
  2612. pixels[i * 4 + 1] = ((color >> 8) & 0xFF) * alpha / 255;
  2613. pixels[i * 4 + 2] = ((color) & 0xFF) * alpha / 255;
  2614. pixels[i * 4 + 3] = alpha;
  2615. }
  2616. NSImage *nsimage = [[NSImage alloc] initWithSize:NSMakeSize(texture_size.width, texture_size.height)];
  2617. [nsimage addRepresentation:imgrep];
  2618. NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
  2619. cursors[p_shape] = cursor;
  2620. Vector<Variant> params;
  2621. params.push_back(p_cursor);
  2622. params.push_back(p_hotspot);
  2623. cursors_cache.insert(p_shape, params);
  2624. if (p_shape == cursor_shape) {
  2625. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2626. [cursor set];
  2627. }
  2628. }
  2629. } else {
  2630. // Reset to default system cursor.
  2631. if (cursors[p_shape] != nullptr) {
  2632. cursors[p_shape] = nullptr;
  2633. }
  2634. cursors_cache.erase(p_shape);
  2635. cursor_update_shape();
  2636. }
  2637. }
  2638. bool DisplayServerMacOS::get_swap_cancel_ok() {
  2639. return false;
  2640. }
  2641. int DisplayServerMacOS::keyboard_get_layout_count() const {
  2642. if (keyboard_layout_dirty) {
  2643. _update_keyboard_layouts();
  2644. }
  2645. return kbd_layouts.size();
  2646. }
  2647. void DisplayServerMacOS::keyboard_set_current_layout(int p_index) {
  2648. if (keyboard_layout_dirty) {
  2649. _update_keyboard_layouts();
  2650. }
  2651. ERR_FAIL_INDEX(p_index, kbd_layouts.size());
  2652. NSString *cur_name = [NSString stringWithUTF8String:kbd_layouts[p_index].name.utf8().get_data()];
  2653. NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
  2654. NSArray *list_kbd = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_kbd, false);
  2655. for (NSUInteger i = 0; i < [list_kbd count]; i++) {
  2656. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
  2657. if ([name isEqualToString:cur_name]) {
  2658. TISSelectInputSource((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i]);
  2659. break;
  2660. }
  2661. }
  2662. NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
  2663. NSArray *list_ime = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_ime, false);
  2664. for (NSUInteger i = 0; i < [list_ime count]; i++) {
  2665. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
  2666. if ([name isEqualToString:cur_name]) {
  2667. TISSelectInputSource((__bridge TISInputSourceRef)[list_ime objectAtIndex:i]);
  2668. break;
  2669. }
  2670. }
  2671. }
  2672. int DisplayServerMacOS::keyboard_get_current_layout() const {
  2673. if (keyboard_layout_dirty) {
  2674. _update_keyboard_layouts();
  2675. }
  2676. return current_layout;
  2677. }
  2678. String DisplayServerMacOS::keyboard_get_layout_language(int p_index) const {
  2679. if (keyboard_layout_dirty) {
  2680. _update_keyboard_layouts();
  2681. }
  2682. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2683. return kbd_layouts[p_index].code;
  2684. }
  2685. String DisplayServerMacOS::keyboard_get_layout_name(int p_index) const {
  2686. if (keyboard_layout_dirty) {
  2687. _update_keyboard_layouts();
  2688. }
  2689. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2690. return kbd_layouts[p_index].name;
  2691. }
  2692. Key DisplayServerMacOS::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2693. if (p_keycode == Key::PAUSE || p_keycode == Key::NONE) {
  2694. return p_keycode;
  2695. }
  2696. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2697. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2698. unsigned int macos_keycode = KeyMappingMacOS::unmap_key(keycode_no_mod);
  2699. return (Key)(KeyMappingMacOS::remap_key(macos_keycode, 0, false) | modifiers);
  2700. }
  2701. Key DisplayServerMacOS::keyboard_get_label_from_physical(Key p_keycode) const {
  2702. if (p_keycode == Key::PAUSE || p_keycode == Key::NONE) {
  2703. return p_keycode;
  2704. }
  2705. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2706. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2707. unsigned int macos_keycode = KeyMappingMacOS::unmap_key(keycode_no_mod);
  2708. return (Key)(KeyMappingMacOS::remap_key(macos_keycode, 0, true) | modifiers);
  2709. }
  2710. void DisplayServerMacOS::show_emoji_and_symbol_picker() const {
  2711. [[NSApplication sharedApplication] orderFrontCharacterPalette:nil];
  2712. }
  2713. void DisplayServerMacOS::process_events() {
  2714. ERR_FAIL_COND(!Thread::is_main_thread());
  2715. while (true) {
  2716. NSEvent *event = [NSApp
  2717. nextEventMatchingMask:NSEventMaskAny
  2718. untilDate:[NSDate distantPast]
  2719. inMode:NSDefaultRunLoopMode
  2720. dequeue:YES];
  2721. if (event == nil) {
  2722. break;
  2723. }
  2724. [NSApp sendEvent:event];
  2725. }
  2726. // Process "menu_callback"s.
  2727. while (List<MenuCall>::Element *call_p = deferred_menu_calls.front()) {
  2728. MenuCall call = call_p->get();
  2729. deferred_menu_calls.pop_front(); // Remove before call to avoid infinite loop in case callback is using `process_events` (e.g. EditorProgress).
  2730. Variant ret;
  2731. Callable::CallError ce;
  2732. const Variant *args[1] = { &call.tag };
  2733. call.callback.callp(args, 1, ret, ce);
  2734. if (ce.error != Callable::CallError::CALL_OK) {
  2735. ERR_PRINT(vformat("Failed to execute menu callback: %s.", Variant::get_callable_error_text(call.callback, args, 1, ce)));
  2736. }
  2737. }
  2738. if (!drop_events) {
  2739. _process_key_events();
  2740. Input::get_singleton()->flush_buffered_events();
  2741. }
  2742. _THREAD_SAFE_LOCK_
  2743. for (KeyValue<WindowID, WindowData> &E : windows) {
  2744. WindowData &wd = E.value;
  2745. if (wd.mpass) {
  2746. if (![wd.window_object ignoresMouseEvents]) {
  2747. [wd.window_object setIgnoresMouseEvents:YES];
  2748. }
  2749. } else if (wd.mpath.size() > 0) {
  2750. update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  2751. if (Geometry2D::is_point_in_polygon(wd.mouse_pos, wd.mpath)) {
  2752. if ([wd.window_object ignoresMouseEvents]) {
  2753. [wd.window_object setIgnoresMouseEvents:NO];
  2754. }
  2755. } else {
  2756. if (![wd.window_object ignoresMouseEvents]) {
  2757. [wd.window_object setIgnoresMouseEvents:YES];
  2758. }
  2759. }
  2760. } else {
  2761. if ([wd.window_object ignoresMouseEvents]) {
  2762. [wd.window_object setIgnoresMouseEvents:NO];
  2763. }
  2764. }
  2765. }
  2766. _THREAD_SAFE_UNLOCK_
  2767. }
  2768. void DisplayServerMacOS::force_process_and_drop_events() {
  2769. ERR_FAIL_COND(!Thread::is_main_thread());
  2770. drop_events = true;
  2771. process_events();
  2772. drop_events = false;
  2773. }
  2774. void DisplayServerMacOS::release_rendering_thread() {
  2775. #if defined(GLES3_ENABLED)
  2776. if (gl_manager_angle) {
  2777. gl_manager_angle->release_current();
  2778. }
  2779. if (gl_manager_legacy) {
  2780. gl_manager_legacy->release_current();
  2781. }
  2782. #endif
  2783. }
  2784. void DisplayServerMacOS::swap_buffers() {
  2785. #if defined(GLES3_ENABLED)
  2786. if (gl_manager_angle) {
  2787. gl_manager_angle->swap_buffers();
  2788. }
  2789. if (gl_manager_legacy) {
  2790. gl_manager_legacy->swap_buffers();
  2791. }
  2792. #endif
  2793. }
  2794. void DisplayServerMacOS::set_native_icon(const String &p_filename) {
  2795. _THREAD_SAFE_METHOD_
  2796. Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ);
  2797. ERR_FAIL_COND(f.is_null());
  2798. Vector<uint8_t> data;
  2799. uint64_t len = f->get_length();
  2800. ERR_FAIL_COND_MSG(len < 8, "Error reading icon data."); // "icns" + 32-bit length
  2801. data.resize(len);
  2802. f->get_buffer((uint8_t *)&data.write[0], len);
  2803. @try {
  2804. NSData *icon_data = [[NSData alloc] initWithBytes:&data.write[0] length:len];
  2805. ERR_FAIL_NULL_MSG(icon_data, "Error reading icon data.");
  2806. NSImage *icon = [[NSImage alloc] initWithData:icon_data];
  2807. ERR_FAIL_NULL_MSG(icon, "Error loading icon.");
  2808. [NSApp setApplicationIconImage:icon];
  2809. } @catch (NSException *exception) {
  2810. ERR_FAIL_MSG("NSException: " + String::utf8([exception reason].UTF8String));
  2811. }
  2812. }
  2813. void DisplayServerMacOS::set_icon(const Ref<Image> &p_icon) {
  2814. _THREAD_SAFE_METHOD_
  2815. if (p_icon.is_valid()) {
  2816. ERR_FAIL_COND(p_icon->get_width() <= 0 || p_icon->get_height() <= 0);
  2817. Ref<Image> img = p_icon->duplicate();
  2818. img->convert(Image::FORMAT_RGBA8);
  2819. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2820. initWithBitmapDataPlanes:nullptr
  2821. pixelsWide:img->get_width()
  2822. pixelsHigh:img->get_height()
  2823. bitsPerSample:8
  2824. samplesPerPixel:4
  2825. hasAlpha:YES
  2826. isPlanar:NO
  2827. colorSpaceName:NSDeviceRGBColorSpace
  2828. bytesPerRow:img->get_width() * 4
  2829. bitsPerPixel:32];
  2830. ERR_FAIL_NULL(imgrep);
  2831. uint8_t *pixels = [imgrep bitmapData];
  2832. int len = img->get_width() * img->get_height();
  2833. const uint8_t *r = img->get_data().ptr();
  2834. /* Premultiply the alpha channel */
  2835. for (int i = 0; i < len; i++) {
  2836. uint8_t alpha = r[i * 4 + 3];
  2837. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  2838. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  2839. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  2840. pixels[i * 4 + 3] = alpha;
  2841. }
  2842. NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())];
  2843. ERR_FAIL_NULL(nsimg);
  2844. [nsimg addRepresentation:imgrep];
  2845. [NSApp setApplicationIconImage:nsimg];
  2846. } else {
  2847. [NSApp setApplicationIconImage:nil];
  2848. }
  2849. }
  2850. DisplayServer::IndicatorID DisplayServerMacOS::create_status_indicator(const Ref<Texture2D> &p_icon, const String &p_tooltip, const Callable &p_callback) {
  2851. NSImage *nsimg = nullptr;
  2852. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  2853. Ref<Image> img = p_icon->get_image();
  2854. img = img->duplicate();
  2855. if (img->is_compressed()) {
  2856. img->decompress();
  2857. }
  2858. nsimg = _convert_to_nsimg(img);
  2859. }
  2860. IndicatorData idat;
  2861. NSStatusItem *item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  2862. idat.item = item;
  2863. idat.delegate = [[GodotStatusItemDelegate alloc] init];
  2864. [idat.delegate setCallback:p_callback];
  2865. item.button.image = nsimg;
  2866. item.button.imagePosition = NSImageOnly;
  2867. item.button.imageScaling = NSImageScaleProportionallyUpOrDown;
  2868. item.button.target = idat.delegate;
  2869. item.button.action = @selector(click:);
  2870. [item.button sendActionOn:(NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown)];
  2871. item.button.toolTip = [NSString stringWithUTF8String:p_tooltip.utf8().get_data()];
  2872. IndicatorID iid = indicator_id_counter++;
  2873. indicators[iid] = idat;
  2874. return iid;
  2875. }
  2876. void DisplayServerMacOS::status_indicator_set_icon(IndicatorID p_id, const Ref<Texture2D> &p_icon) {
  2877. ERR_FAIL_COND(!indicators.has(p_id));
  2878. NSImage *nsimg = nullptr;
  2879. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  2880. Ref<Image> img = p_icon->get_image();
  2881. img = img->duplicate();
  2882. if (img->is_compressed()) {
  2883. img->decompress();
  2884. }
  2885. nsimg = _convert_to_nsimg(img);
  2886. }
  2887. NSStatusItem *item = indicators[p_id].item;
  2888. item.button.image = nsimg;
  2889. }
  2890. void DisplayServerMacOS::status_indicator_set_tooltip(IndicatorID p_id, const String &p_tooltip) {
  2891. ERR_FAIL_COND(!indicators.has(p_id));
  2892. NSStatusItem *item = indicators[p_id].item;
  2893. item.button.toolTip = [NSString stringWithUTF8String:p_tooltip.utf8().get_data()];
  2894. }
  2895. void DisplayServerMacOS::status_indicator_set_menu(IndicatorID p_id, const RID &p_menu_rid) {
  2896. ERR_FAIL_COND(!indicators.has(p_id));
  2897. NSStatusItem *item = indicators[p_id].item;
  2898. if (p_menu_rid.is_valid() && native_menu->has_menu(p_menu_rid)) {
  2899. NSMenu *menu = native_menu->get_native_menu_handle(p_menu_rid);
  2900. item.menu = menu;
  2901. } else {
  2902. item.menu = nullptr;
  2903. }
  2904. }
  2905. void DisplayServerMacOS::status_indicator_set_callback(IndicatorID p_id, const Callable &p_callback) {
  2906. ERR_FAIL_COND(!indicators.has(p_id));
  2907. [indicators[p_id].delegate setCallback:p_callback];
  2908. }
  2909. Rect2 DisplayServerMacOS::status_indicator_get_rect(IndicatorID p_id) const {
  2910. ERR_FAIL_COND_V(!indicators.has(p_id), Rect2());
  2911. NSStatusItem *item = indicators[p_id].item;
  2912. NSView *v = item.button;
  2913. const NSRect contentRect = [v frame];
  2914. const NSRect nsrect = [v.window convertRectToScreen:contentRect];
  2915. Rect2 rect;
  2916. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  2917. const float scale = screen_get_max_scale();
  2918. rect.size.x = nsrect.size.width;
  2919. rect.size.y = nsrect.size.height;
  2920. rect.size *= scale;
  2921. rect.position.x = nsrect.origin.x;
  2922. rect.position.y = (nsrect.origin.y + nsrect.size.height);
  2923. rect.position *= scale;
  2924. rect.position -= _get_screens_origin();
  2925. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  2926. // Godot expects a positive value.
  2927. rect.position.y *= -1;
  2928. return rect;
  2929. }
  2930. void DisplayServerMacOS::delete_status_indicator(IndicatorID p_id) {
  2931. ERR_FAIL_COND(!indicators.has(p_id));
  2932. [[NSStatusBar systemStatusBar] removeStatusItem:indicators[p_id].item];
  2933. indicators.erase(p_id);
  2934. }
  2935. bool DisplayServerMacOS::is_window_transparency_available() const {
  2936. #if defined(RD_ENABLED)
  2937. if (rendering_device && !rendering_device->is_composite_alpha_supported()) {
  2938. return false;
  2939. }
  2940. #endif
  2941. return OS::get_singleton()->is_layered_allowed();
  2942. }
  2943. 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) {
  2944. 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));
  2945. if (r_error != OK) {
  2946. if (p_rendering_driver == "vulkan") {
  2947. String executable_command;
  2948. if (OS::get_singleton()->get_bundle_resource_dir() == OS::get_singleton()->get_executable_path().get_base_dir()) {
  2949. executable_command = vformat("\"%s\" --rendering-driver opengl3", OS::get_singleton()->get_executable_path());
  2950. } else {
  2951. executable_command = vformat("open \"%s\" --args --rendering-driver opengl3", OS::get_singleton()->get_bundle_resource_dir().path_join("../..").simplify_path());
  2952. }
  2953. OS::get_singleton()->alert(
  2954. vformat("Your video card drivers seem not to support the required Vulkan version.\n\n"
  2955. "If possible, consider updating your macOS version or using the OpenGL 3 driver.\n\n"
  2956. "You can enable the OpenGL 3 driver by starting the engine from the\n"
  2957. "command line with the command:\n\n %s",
  2958. executable_command),
  2959. "Unable to initialize Vulkan video driver");
  2960. } else {
  2961. OS::get_singleton()->alert(
  2962. "Your video card drivers seem not to support the required OpenGL 3.3 version.\n\n"
  2963. "If possible, consider updating your macOS version.",
  2964. "Unable to initialize OpenGL video driver");
  2965. }
  2966. }
  2967. return ds;
  2968. }
  2969. Vector<String> DisplayServerMacOS::get_rendering_drivers_func() {
  2970. Vector<String> drivers;
  2971. #if defined(VULKAN_ENABLED)
  2972. drivers.push_back("vulkan");
  2973. #endif
  2974. #if defined(METAL_ENABLED)
  2975. drivers.push_back("metal");
  2976. #endif
  2977. #if defined(GLES3_ENABLED)
  2978. drivers.push_back("opengl3");
  2979. drivers.push_back("opengl3_angle");
  2980. #endif
  2981. return drivers;
  2982. }
  2983. void DisplayServerMacOS::register_macos_driver() {
  2984. register_create_function("macos", create_func, get_rendering_drivers_func);
  2985. }
  2986. DisplayServer::WindowID DisplayServerMacOS::window_get_active_popup() const {
  2987. const List<WindowID>::Element *E = popup_list.back();
  2988. if (E) {
  2989. return E->get();
  2990. } else {
  2991. return INVALID_WINDOW_ID;
  2992. }
  2993. }
  2994. void DisplayServerMacOS::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  2995. _THREAD_SAFE_METHOD_
  2996. ERR_FAIL_COND(!windows.has(p_window));
  2997. WindowData &wd = windows[p_window];
  2998. wd.parent_safe_rect = p_rect;
  2999. }
  3000. Rect2i DisplayServerMacOS::window_get_popup_safe_rect(WindowID p_window) const {
  3001. _THREAD_SAFE_METHOD_
  3002. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  3003. const WindowData &wd = windows[p_window];
  3004. return wd.parent_safe_rect;
  3005. }
  3006. void DisplayServerMacOS::popup_open(WindowID p_window) {
  3007. _THREAD_SAFE_METHOD_
  3008. bool has_popup_ancestor = false;
  3009. WindowID transient_root = p_window;
  3010. while (true) {
  3011. WindowID parent = windows[transient_root].transient_parent;
  3012. if (parent == INVALID_WINDOW_ID) {
  3013. break;
  3014. } else {
  3015. transient_root = parent;
  3016. if (windows[parent].is_popup) {
  3017. has_popup_ancestor = true;
  3018. break;
  3019. }
  3020. }
  3021. }
  3022. // Detect tooltips and other similar popups that shouldn't block input to their parent.
  3023. bool ignores_input = window_get_flag(WINDOW_FLAG_NO_FOCUS, p_window) && window_get_flag(WINDOW_FLAG_MOUSE_PASSTHROUGH, p_window);
  3024. WindowData &wd = windows[p_window];
  3025. if (wd.is_popup || (has_popup_ancestor && !ignores_input)) {
  3026. bool was_empty = popup_list.is_empty();
  3027. // Find current popup parent, or root popup if new window is not transient.
  3028. List<WindowID>::Element *C = nullptr;
  3029. List<WindowID>::Element *E = popup_list.back();
  3030. while (E) {
  3031. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  3032. C = E;
  3033. E = E->prev();
  3034. } else {
  3035. break;
  3036. }
  3037. }
  3038. if (C) {
  3039. send_window_event(windows[C->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3040. }
  3041. if (was_empty && popup_list.is_empty()) {
  3042. // Inform OS that popup was opened, to close other native popups.
  3043. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.beginMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3044. }
  3045. time_since_popup = OS::get_singleton()->get_ticks_msec();
  3046. popup_list.push_back(p_window);
  3047. }
  3048. }
  3049. void DisplayServerMacOS::popup_close(WindowID p_window) {
  3050. _THREAD_SAFE_METHOD_
  3051. bool was_empty = popup_list.is_empty();
  3052. List<WindowID>::Element *E = popup_list.find(p_window);
  3053. while (E) {
  3054. List<WindowID>::Element *F = E->next();
  3055. WindowID win_id = E->get();
  3056. popup_list.erase(E);
  3057. if (win_id != p_window) {
  3058. // Only request close on related windows, not this window. We are already processing it.
  3059. send_window_event(windows[win_id], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3060. }
  3061. E = F;
  3062. }
  3063. if (!was_empty && popup_list.is_empty()) {
  3064. // Inform OS that all popups are closed.
  3065. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3066. }
  3067. }
  3068. bool DisplayServerMacOS::mouse_process_popups(bool p_close) {
  3069. _THREAD_SAFE_METHOD_
  3070. bool was_empty = popup_list.is_empty();
  3071. bool closed = false;
  3072. if (p_close) {
  3073. // Close all popups.
  3074. List<WindowID>::Element *E = popup_list.front();
  3075. if (E) {
  3076. send_window_event(windows[E->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3077. closed = true;
  3078. }
  3079. if (!was_empty) {
  3080. // Inform OS that all popups are closed.
  3081. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3082. }
  3083. } else {
  3084. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  3085. if (delta < 250) {
  3086. return false;
  3087. }
  3088. Point2i pos = mouse_get_position();
  3089. List<WindowID>::Element *C = nullptr;
  3090. List<WindowID>::Element *E = popup_list.back();
  3091. // Find top popup to close.
  3092. while (E) {
  3093. // Popup window area.
  3094. Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
  3095. // Area of the parent window, which responsible for opening sub-menu.
  3096. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  3097. if (win_rect.has_point(pos)) {
  3098. break;
  3099. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  3100. break;
  3101. } else {
  3102. C = E;
  3103. E = E->prev();
  3104. }
  3105. }
  3106. if (C) {
  3107. send_window_event(windows[C->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3108. closed = true;
  3109. }
  3110. if (!was_empty && popup_list.is_empty()) {
  3111. // Inform OS that all popups are closed.
  3112. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3113. }
  3114. }
  3115. return closed;
  3116. }
  3117. 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) {
  3118. KeyMappingMacOS::initialize();
  3119. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  3120. r_error = OK;
  3121. memset(cursors, 0, sizeof(cursors));
  3122. event_source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  3123. ERR_FAIL_COND(!event_source);
  3124. CGEventSourceSetLocalEventsSuppressionInterval(event_source, 0.0);
  3125. int screen_count = get_screen_count();
  3126. for (int i = 0; i < screen_count; i++) {
  3127. display_max_scale = fmax(display_max_scale, screen_get_scale(i));
  3128. }
  3129. // Register to be notified on keyboard layout changes.
  3130. CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
  3131. nullptr, _keyboard_layout_changed,
  3132. kTISNotifySelectedKeyboardInputSourceChanged, nullptr,
  3133. CFNotificationSuspensionBehaviorDeliverImmediately);
  3134. // Register to be notified on displays arrangement changes.
  3135. CGDisplayRegisterReconfigurationCallback(_displays_arrangement_changed, nullptr);
  3136. // Init TTS
  3137. bool tts_enabled = GLOBAL_GET("audio/general/text_to_speech");
  3138. if (tts_enabled) {
  3139. tts = [[TTS_MacOS alloc] init];
  3140. }
  3141. native_menu = memnew(NativeMenuMacOS);
  3142. NSMenuItem *menu_item;
  3143. NSString *title;
  3144. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  3145. if (nsappname == nil) {
  3146. nsappname = [[NSProcessInfo processInfo] processName];
  3147. }
  3148. menu_delegate = [[GodotMenuDelegate alloc] init];
  3149. // Setup Dock menu.
  3150. NSMenu *dock_menu = [[NSMenu alloc] initWithTitle:@"_dock"];
  3151. [dock_menu setAutoenablesItems:NO];
  3152. [dock_menu setDelegate:menu_delegate];
  3153. // Setup Apple menu.
  3154. NSMenu *application_menu = [[NSMenu alloc] initWithTitle:@""];
  3155. title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
  3156. [application_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
  3157. [application_menu setAutoenablesItems:NO];
  3158. [application_menu setDelegate:menu_delegate];
  3159. [application_menu addItem:[NSMenuItem separatorItem]];
  3160. menu_item = [application_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3161. menu_item.hidden = YES;
  3162. menu_item.tag = MENU_TAG_START;
  3163. menu_item = [application_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3164. menu_item.hidden = YES;
  3165. menu_item.tag = MENU_TAG_END;
  3166. NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
  3167. menu_item = [application_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
  3168. [application_menu setSubmenu:services forItem:menu_item];
  3169. [NSApp setServicesMenu:services];
  3170. [application_menu addItem:[NSMenuItem separatorItem]];
  3171. title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
  3172. [application_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  3173. menu_item = [application_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  3174. [menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
  3175. [application_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
  3176. [application_menu addItem:[NSMenuItem separatorItem]];
  3177. title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
  3178. [application_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  3179. NSMenu *window_menu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Window", nil)];
  3180. [window_menu addItemWithTitle:NSLocalizedString(@"Minimize", nil) action:@selector(performMiniaturize:) keyEquivalent:@"m"];
  3181. [window_menu addItemWithTitle:NSLocalizedString(@"Zoom", nil) action:@selector(performZoom:) keyEquivalent:@""];
  3182. [window_menu addItem:[NSMenuItem separatorItem]];
  3183. [window_menu addItemWithTitle:NSLocalizedString(@"Bring All to Front", nil) action:@selector(bringAllToFront:) keyEquivalent:@""];
  3184. [window_menu addItem:[NSMenuItem separatorItem]];
  3185. menu_item = [window_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3186. menu_item.hidden = YES;
  3187. menu_item.tag = MENU_TAG_START;
  3188. menu_item = [window_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3189. menu_item.hidden = YES;
  3190. menu_item.tag = MENU_TAG_END;
  3191. NSMenu *help_menu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Help", nil)];
  3192. menu_item = [help_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3193. menu_item.hidden = YES;
  3194. menu_item.tag = MENU_TAG_START;
  3195. menu_item = [help_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3196. menu_item.hidden = YES;
  3197. menu_item.tag = MENU_TAG_END;
  3198. [NSApp setWindowsMenu:window_menu];
  3199. [NSApp setHelpMenu:help_menu];
  3200. // Add items to the menu bar.
  3201. NSMenu *main_menu = [NSApp mainMenu];
  3202. menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  3203. [main_menu setSubmenu:application_menu forItem:menu_item];
  3204. menu_item = [main_menu addItemWithTitle:NSLocalizedString(@"Window", nil) action:nil keyEquivalent:@""];
  3205. [main_menu setSubmenu:window_menu forItem:menu_item];
  3206. menu_item = [main_menu addItemWithTitle:NSLocalizedString(@"Help", nil) action:nil keyEquivalent:@""];
  3207. [main_menu setSubmenu:help_menu forItem:menu_item];
  3208. [main_menu setAutoenablesItems:NO];
  3209. native_menu->_register_system_menus(main_menu, application_menu, window_menu, help_menu, dock_menu);
  3210. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  3211. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  3212. rendering_driver = p_rendering_driver;
  3213. #if defined(RD_ENABLED)
  3214. #if defined(VULKAN_ENABLED)
  3215. #if defined(__x86_64__)
  3216. bool fallback_to_vulkan = GLOBAL_GET("rendering/rendering_device/fallback_to_vulkan");
  3217. if (!fallback_to_vulkan) {
  3218. WARN_PRINT("Metal is not supported on Intel Macs, switching to Vulkan.");
  3219. }
  3220. // Metal rendering driver not available on Intel.
  3221. if (rendering_driver == "metal") {
  3222. rendering_driver = "vulkan";
  3223. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3224. }
  3225. #endif
  3226. if (rendering_driver == "vulkan") {
  3227. rendering_context = memnew(RenderingContextDriverVulkanMacOS);
  3228. }
  3229. #endif
  3230. #if defined(METAL_ENABLED)
  3231. if (rendering_driver == "metal") {
  3232. rendering_context = memnew(RenderingContextDriverMetal);
  3233. }
  3234. #endif
  3235. if (rendering_context) {
  3236. if (rendering_context->initialize() != OK) {
  3237. memdelete(rendering_context);
  3238. rendering_context = nullptr;
  3239. #if defined(GLES3_ENABLED)
  3240. bool fallback_to_opengl3 = GLOBAL_GET("rendering/rendering_device/fallback_to_opengl3");
  3241. if (fallback_to_opengl3 && rendering_driver != "opengl3") {
  3242. WARN_PRINT("Your device seem not to support MoltenVK or Metal, switching to OpenGL 3.");
  3243. rendering_driver = "opengl3";
  3244. OS::get_singleton()->set_current_rendering_method("gl_compatibility");
  3245. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3246. } else
  3247. #endif
  3248. {
  3249. r_error = ERR_CANT_CREATE;
  3250. ERR_FAIL_MSG("Could not initialize " + rendering_driver);
  3251. }
  3252. }
  3253. }
  3254. #endif
  3255. #if defined(GLES3_ENABLED)
  3256. if (rendering_driver == "opengl3_angle") {
  3257. gl_manager_angle = memnew(GLManagerANGLE_MacOS);
  3258. if (gl_manager_angle->initialize() != OK || gl_manager_angle->open_display(nullptr) != OK) {
  3259. memdelete(gl_manager_angle);
  3260. gl_manager_angle = nullptr;
  3261. bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_native");
  3262. if (fallback) {
  3263. #ifdef EGL_STATIC
  3264. WARN_PRINT("Your video card drivers seem not to support GLES3 / ANGLE, switching to native OpenGL.");
  3265. #else
  3266. 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.");
  3267. #endif
  3268. rendering_driver = "opengl3";
  3269. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3270. } else {
  3271. r_error = ERR_UNAVAILABLE;
  3272. ERR_FAIL_MSG("Could not initialize ANGLE OpenGL.");
  3273. }
  3274. }
  3275. }
  3276. if (rendering_driver == "opengl3") {
  3277. gl_manager_legacy = memnew(GLManagerLegacy_MacOS);
  3278. if (gl_manager_legacy->initialize() != OK) {
  3279. memdelete(gl_manager_legacy);
  3280. gl_manager_legacy = nullptr;
  3281. r_error = ERR_UNAVAILABLE;
  3282. ERR_FAIL_MSG("Could not initialize native OpenGL.");
  3283. }
  3284. }
  3285. #endif
  3286. Point2i window_position;
  3287. if (p_position != nullptr) {
  3288. window_position = *p_position;
  3289. } else {
  3290. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  3291. p_screen = SCREEN_PRIMARY;
  3292. }
  3293. Rect2i scr_rect = screen_get_usable_rect(p_screen);
  3294. window_position = scr_rect.position + (scr_rect.size - p_resolution) / 2;
  3295. }
  3296. WindowID main_window = _create_window(p_mode, p_vsync_mode, Rect2i(window_position, p_resolution));
  3297. ERR_FAIL_COND(main_window == INVALID_WINDOW_ID);
  3298. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  3299. if (p_flags & (1 << i)) {
  3300. window_set_flag(WindowFlags(i), true, main_window);
  3301. }
  3302. }
  3303. show_window(MAIN_WINDOW_ID);
  3304. force_process_and_drop_events();
  3305. #if defined(GLES3_ENABLED)
  3306. if (rendering_driver == "opengl3") {
  3307. RasterizerGLES3::make_current(true);
  3308. }
  3309. if (rendering_driver == "opengl3_angle") {
  3310. RasterizerGLES3::make_current(false);
  3311. }
  3312. #endif
  3313. #if defined(RD_ENABLED)
  3314. if (rendering_context) {
  3315. rendering_device = memnew(RenderingDevice);
  3316. rendering_device->initialize(rendering_context, MAIN_WINDOW_ID);
  3317. rendering_device->screen_create(MAIN_WINDOW_ID);
  3318. RendererCompositorRD::make_current();
  3319. }
  3320. #endif
  3321. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  3322. }
  3323. DisplayServerMacOS::~DisplayServerMacOS() {
  3324. if (screen_keep_on_assertion) {
  3325. IOPMAssertionRelease(screen_keep_on_assertion);
  3326. screen_keep_on_assertion = kIOPMNullAssertionID;
  3327. }
  3328. // Destroy all status indicators.
  3329. for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E; ++E) {
  3330. [[NSStatusBar systemStatusBar] removeStatusItem:E->value.item];
  3331. }
  3332. // Destroy native menu.
  3333. if (native_menu) {
  3334. memdelete(native_menu);
  3335. native_menu = nullptr;
  3336. }
  3337. // Destroy all windows.
  3338. for (HashMap<WindowID, WindowData>::Iterator E = windows.begin(); E;) {
  3339. HashMap<WindowID, WindowData>::Iterator F = E;
  3340. ++E;
  3341. [F->value.window_object setContentView:nil];
  3342. [F->value.window_object close];
  3343. }
  3344. // Destroy drivers.
  3345. #if defined(GLES3_ENABLED)
  3346. if (gl_manager_legacy) {
  3347. memdelete(gl_manager_legacy);
  3348. gl_manager_legacy = nullptr;
  3349. }
  3350. if (gl_manager_angle) {
  3351. memdelete(gl_manager_angle);
  3352. gl_manager_angle = nullptr;
  3353. }
  3354. #endif
  3355. #if defined(RD_ENABLED)
  3356. if (rendering_device) {
  3357. memdelete(rendering_device);
  3358. rendering_device = nullptr;
  3359. }
  3360. if (rendering_context) {
  3361. memdelete(rendering_context);
  3362. rendering_context = nullptr;
  3363. }
  3364. #endif
  3365. CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), nullptr, kTISNotifySelectedKeyboardInputSourceChanged, nullptr);
  3366. CGDisplayRemoveReconfigurationCallback(_displays_arrangement_changed, nullptr);
  3367. cursors_cache.clear();
  3368. }