display_server_macos.mm 133 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973
  1. /**************************************************************************/
  2. /* display_server_macos.mm */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #import "display_server_macos.h"
  31. #import "godot_button_view.h"
  32. #import "godot_content_view.h"
  33. #import "godot_menu_delegate.h"
  34. #import "godot_menu_item.h"
  35. #import "godot_open_save_delegate.h"
  36. #import "godot_status_item.h"
  37. #import "godot_window.h"
  38. #import "godot_window_delegate.h"
  39. #import "key_mapping_macos.h"
  40. #import "os_macos.h"
  41. #import "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 windowBackgroundColor] 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, WindowID p_window_id) {
  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, p_window_id);
  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, WindowID p_window_id) {
  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, p_window_id);
  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, WindowID p_window_id) {
  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. NSWindow *nswindow = nullptr;
  861. if (windows.has(p_window_id) && !windows[p_window_id].is_popup) {
  862. nswindow = windows[p_window_id].window_object;
  863. }
  864. GodotOpenSaveDelegate *panel_delegate = [[GodotOpenSaveDelegate alloc] init];
  865. if (p_root.length() > 0) {
  866. [panel_delegate setRootPath:p_root];
  867. }
  868. Callable callback = p_callback; // Make a copy for async completion handler.
  869. if (p_mode == FILE_DIALOG_MODE_SAVE_FILE) {
  870. NSSavePanel *panel = [NSSavePanel savePanel];
  871. [panel setDirectoryURL:[NSURL fileURLWithPath:url]];
  872. [panel_delegate makeAccessoryView:panel filters:p_filters options:p_options];
  873. [panel setExtensionHidden:YES];
  874. [panel setCanSelectHiddenExtension:YES];
  875. [panel setCanCreateDirectories:YES];
  876. [panel setShowsHiddenFiles:p_show_hidden];
  877. [panel setDelegate:panel_delegate];
  878. if (p_filename != "") {
  879. NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()];
  880. [panel setNameFieldStringValue:fileurl];
  881. }
  882. void (^completion_handler)(NSInteger ret) = ^(NSInteger ret) {
  883. if (ret == NSModalResponseOK) {
  884. // Save bookmark for folder.
  885. if (OS::get_singleton()->is_sandboxed()) {
  886. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  887. bool skip = false;
  888. for (id bookmark in bookmarks) {
  889. NSError *error = nil;
  890. BOOL isStale = NO;
  891. NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  892. if (!error && !isStale && ([[exurl path] compare:[[panel directoryURL] path]] == NSOrderedSame)) {
  893. skip = true;
  894. break;
  895. }
  896. }
  897. if (!skip) {
  898. NSError *error = nil;
  899. NSData *bookmark = [[panel directoryURL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
  900. if (!error) {
  901. NSArray *new_bookmarks = [bookmarks arrayByAddingObject:bookmark];
  902. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  903. }
  904. }
  905. }
  906. // Callback.
  907. Vector<String> files;
  908. String url;
  909. url.parse_utf8([[[panel URL] path] UTF8String]);
  910. files.push_back(url);
  911. if (callback.is_valid()) {
  912. if (p_options_in_cb) {
  913. Variant v_result = true;
  914. Variant v_files = files;
  915. Variant v_index = [panel_delegate getIndex];
  916. Variant v_opt = [panel_delegate getSelection];
  917. Variant ret;
  918. Callable::CallError ce;
  919. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  920. callback.callp(args, 4, ret, ce);
  921. if (ce.error != Callable::CallError::CALL_OK) {
  922. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  923. }
  924. } else {
  925. Variant v_result = true;
  926. Variant v_files = files;
  927. Variant v_index = [panel_delegate getIndex];
  928. Variant ret;
  929. Callable::CallError ce;
  930. const Variant *args[3] = { &v_result, &v_files, &v_index };
  931. callback.callp(args, 3, ret, ce);
  932. if (ce.error != Callable::CallError::CALL_OK) {
  933. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  934. }
  935. }
  936. }
  937. } else {
  938. if (callback.is_valid()) {
  939. if (p_options_in_cb) {
  940. Variant v_result = false;
  941. Variant v_files = Vector<String>();
  942. Variant v_index = [panel_delegate getIndex];
  943. Variant v_opt = [panel_delegate getSelection];
  944. Variant ret;
  945. Callable::CallError ce;
  946. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  947. callback.callp(args, 4, ret, ce);
  948. if (ce.error != Callable::CallError::CALL_OK) {
  949. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  950. }
  951. } else {
  952. Variant v_result = false;
  953. Variant v_files = Vector<String>();
  954. Variant v_index = [panel_delegate getIndex];
  955. Variant ret;
  956. Callable::CallError ce;
  957. const Variant *args[3] = { &v_result, &v_files, &v_index };
  958. callback.callp(args, 3, ret, ce);
  959. if (ce.error != Callable::CallError::CALL_OK) {
  960. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  961. }
  962. }
  963. }
  964. }
  965. if (p_window_id != INVALID_WINDOW_ID) {
  966. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(p_window_id);
  967. }
  968. };
  969. if (nswindow) {
  970. [panel beginSheetModalForWindow:nswindow completionHandler:completion_handler];
  971. } else {
  972. [panel beginWithCompletionHandler:completion_handler];
  973. }
  974. } else {
  975. NSOpenPanel *panel = [NSOpenPanel openPanel];
  976. [panel setDirectoryURL:[NSURL fileURLWithPath:url]];
  977. [panel_delegate makeAccessoryView:panel filters:p_filters options:p_options];
  978. [panel setExtensionHidden:YES];
  979. [panel setCanSelectHiddenExtension:YES];
  980. [panel setCanCreateDirectories:YES];
  981. [panel setCanChooseFiles:(p_mode != FILE_DIALOG_MODE_OPEN_DIR)];
  982. [panel setCanChooseDirectories:(p_mode == FILE_DIALOG_MODE_OPEN_DIR || p_mode == FILE_DIALOG_MODE_OPEN_ANY)];
  983. [panel setShowsHiddenFiles:p_show_hidden];
  984. [panel setDelegate:panel_delegate];
  985. if (p_filename != "") {
  986. NSString *fileurl = [NSString stringWithUTF8String:p_filename.utf8().get_data()];
  987. [panel setNameFieldStringValue:fileurl];
  988. }
  989. [panel setAllowsMultipleSelection:(p_mode == FILE_DIALOG_MODE_OPEN_FILES)];
  990. void (^completion_handler)(NSInteger ret) = ^(NSInteger ret) {
  991. if (ret == NSModalResponseOK) {
  992. // Save bookmark for folder.
  993. NSArray *urls = [(NSOpenPanel *)panel URLs];
  994. if (OS::get_singleton()->is_sandboxed()) {
  995. NSArray *bookmarks = [[NSUserDefaults standardUserDefaults] arrayForKey:@"sec_bookmarks"];
  996. NSMutableArray *new_bookmarks = [bookmarks mutableCopy];
  997. for (NSUInteger i = 0; i != [urls count]; ++i) {
  998. bool skip = false;
  999. for (id bookmark in bookmarks) {
  1000. NSError *error = nil;
  1001. BOOL isStale = NO;
  1002. NSURL *exurl = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error];
  1003. if (!error && !isStale && ([[exurl path] compare:[[urls objectAtIndex:i] path]] == NSOrderedSame)) {
  1004. skip = true;
  1005. break;
  1006. }
  1007. }
  1008. if (!skip) {
  1009. NSError *error = nil;
  1010. NSData *bookmark = [[urls objectAtIndex:i] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
  1011. if (!error) {
  1012. [new_bookmarks addObject:bookmark];
  1013. }
  1014. }
  1015. }
  1016. [[NSUserDefaults standardUserDefaults] setObject:new_bookmarks forKey:@"sec_bookmarks"];
  1017. }
  1018. // Callback.
  1019. Vector<String> files;
  1020. for (NSUInteger i = 0; i != [urls count]; ++i) {
  1021. String url;
  1022. url.parse_utf8([[[urls objectAtIndex:i] path] UTF8String]);
  1023. files.push_back(url);
  1024. }
  1025. if (callback.is_valid()) {
  1026. if (p_options_in_cb) {
  1027. Variant v_result = true;
  1028. Variant v_files = files;
  1029. Variant v_index = [panel_delegate getIndex];
  1030. Variant v_opt = [panel_delegate getSelection];
  1031. Variant ret;
  1032. Callable::CallError ce;
  1033. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  1034. callback.callp(args, 4, ret, ce);
  1035. if (ce.error != Callable::CallError::CALL_OK) {
  1036. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  1037. }
  1038. } else {
  1039. Variant v_result = true;
  1040. Variant v_files = files;
  1041. Variant v_index = [panel_delegate getIndex];
  1042. Variant ret;
  1043. Callable::CallError ce;
  1044. const Variant *args[3] = { &v_result, &v_files, &v_index };
  1045. callback.callp(args, 3, ret, ce);
  1046. if (ce.error != Callable::CallError::CALL_OK) {
  1047. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  1048. }
  1049. }
  1050. }
  1051. } else {
  1052. if (callback.is_valid()) {
  1053. if (p_options_in_cb) {
  1054. Variant v_result = false;
  1055. Variant v_files = Vector<String>();
  1056. Variant v_index = [panel_delegate getIndex];
  1057. Variant v_opt = [panel_delegate getSelection];
  1058. Variant ret;
  1059. Callable::CallError ce;
  1060. const Variant *args[4] = { &v_result, &v_files, &v_index, &v_opt };
  1061. callback.callp(args, 4, ret, ce);
  1062. if (ce.error != Callable::CallError::CALL_OK) {
  1063. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 4, ce)));
  1064. }
  1065. } else {
  1066. Variant v_result = false;
  1067. Variant v_files = Vector<String>();
  1068. Variant v_index = [panel_delegate getIndex];
  1069. Variant ret;
  1070. Callable::CallError ce;
  1071. const Variant *args[3] = { &v_result, &v_files, &v_index };
  1072. callback.callp(args, 3, ret, ce);
  1073. if (ce.error != Callable::CallError::CALL_OK) {
  1074. ERR_PRINT(vformat("Failed to execute file dialog callback: %s.", Variant::get_callable_error_text(callback, args, 3, ce)));
  1075. }
  1076. }
  1077. }
  1078. }
  1079. if (p_window_id != INVALID_WINDOW_ID) {
  1080. callable_mp(DisplayServer::get_singleton(), &DisplayServer::window_move_to_foreground).call_deferred(p_window_id);
  1081. }
  1082. };
  1083. if (nswindow) {
  1084. [panel beginSheetModalForWindow:nswindow completionHandler:completion_handler];
  1085. } else {
  1086. [panel beginWithCompletionHandler:completion_handler];
  1087. }
  1088. }
  1089. return OK;
  1090. }
  1091. void DisplayServerMacOS::beep() const {
  1092. NSBeep();
  1093. }
  1094. Error DisplayServerMacOS::dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) {
  1095. _THREAD_SAFE_METHOD_
  1096. NSAlert *window = [[NSAlert alloc] init];
  1097. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  1098. NSString *ns_description = [NSString stringWithUTF8String:p_description.utf8().get_data()];
  1099. NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 250, 30)];
  1100. [window addButtonWithTitle:@"OK"];
  1101. [window setMessageText:ns_title];
  1102. [window setInformativeText:ns_description];
  1103. [window setAlertStyle:NSAlertStyleInformational];
  1104. [input setStringValue:[NSString stringWithUTF8String:p_partial.utf8().get_data()]];
  1105. [window setAccessoryView:input];
  1106. [window runModal];
  1107. String ret;
  1108. ret.parse_utf8([[input stringValue] UTF8String]);
  1109. if (p_callback.is_valid()) {
  1110. Variant v_result = ret;
  1111. Variant ret;
  1112. Callable::CallError ce;
  1113. const Variant *args[1] = { &v_result };
  1114. p_callback.callp(args, 1, ret, ce);
  1115. if (ce.error != Callable::CallError::CALL_OK) {
  1116. ERR_PRINT(vformat("Failed to execute input dialog callback: %s.", Variant::get_callable_error_text(p_callback, args, 1, ce)));
  1117. }
  1118. }
  1119. return OK;
  1120. }
  1121. void DisplayServerMacOS::_mouse_update_mode() {
  1122. _THREAD_SAFE_METHOD_
  1123. MouseMode wanted_mouse_mode = mouse_mode_override_enabled
  1124. ? mouse_mode_override
  1125. : mouse_mode_base;
  1126. if (wanted_mouse_mode == mouse_mode) {
  1127. return;
  1128. }
  1129. WindowID window_id = _get_focused_window_or_popup();
  1130. if (!windows.has(window_id)) {
  1131. window_id = MAIN_WINDOW_ID;
  1132. }
  1133. WindowData &wd = windows[window_id];
  1134. bool show_cursor = (wanted_mouse_mode == MOUSE_MODE_VISIBLE || wanted_mouse_mode == MOUSE_MODE_CONFINED);
  1135. bool previously_shown = (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED);
  1136. if (show_cursor && !previously_shown) {
  1137. window_id = get_window_at_screen_position(mouse_get_position());
  1138. mouse_enter_window(window_id);
  1139. }
  1140. if (wanted_mouse_mode == MOUSE_MODE_CAPTURED) {
  1141. // Apple Docs state that the display parameter is not used.
  1142. // "This parameter is not used. By default, you may pass kCGDirectMainDisplay."
  1143. // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html
  1144. if (previously_shown) {
  1145. CGDisplayHideCursor(kCGDirectMainDisplay);
  1146. }
  1147. CGAssociateMouseAndMouseCursorPosition(false);
  1148. [wd.window_object setMovable:NO];
  1149. const NSRect contentRect = [wd.window_view frame];
  1150. NSRect pointInWindowRect = NSMakeRect(contentRect.size.width / 2, contentRect.size.height / 2, 0, 0);
  1151. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  1152. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1153. CGWarpMouseCursorPosition(lMouseWarpPos);
  1154. } else if (wanted_mouse_mode == MOUSE_MODE_HIDDEN) {
  1155. if (previously_shown) {
  1156. CGDisplayHideCursor(kCGDirectMainDisplay);
  1157. }
  1158. [wd.window_object setMovable:YES];
  1159. CGAssociateMouseAndMouseCursorPosition(true);
  1160. } else if (wanted_mouse_mode == MOUSE_MODE_CONFINED) {
  1161. CGDisplayShowCursor(kCGDirectMainDisplay);
  1162. [wd.window_object setMovable:NO];
  1163. CGAssociateMouseAndMouseCursorPosition(false);
  1164. } else if (wanted_mouse_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  1165. if (previously_shown) {
  1166. CGDisplayHideCursor(kCGDirectMainDisplay);
  1167. }
  1168. [wd.window_object setMovable:NO];
  1169. CGAssociateMouseAndMouseCursorPosition(false);
  1170. } else { // MOUSE_MODE_VISIBLE
  1171. CGDisplayShowCursor(kCGDirectMainDisplay);
  1172. [wd.window_object setMovable:YES];
  1173. CGAssociateMouseAndMouseCursorPosition(true);
  1174. }
  1175. last_warp = [[NSProcessInfo processInfo] systemUptime];
  1176. ignore_warp = true;
  1177. warp_events.clear();
  1178. mouse_mode = wanted_mouse_mode;
  1179. if (show_cursor) {
  1180. cursor_update_shape();
  1181. }
  1182. }
  1183. void DisplayServerMacOS::mouse_set_mode(MouseMode p_mode) {
  1184. ERR_FAIL_INDEX(p_mode, MouseMode::MOUSE_MODE_MAX);
  1185. if (p_mode == mouse_mode_base) {
  1186. return;
  1187. }
  1188. mouse_mode_base = p_mode;
  1189. _mouse_update_mode();
  1190. }
  1191. DisplayServer::MouseMode DisplayServerMacOS::mouse_get_mode() const {
  1192. return mouse_mode;
  1193. }
  1194. void DisplayServerMacOS::mouse_set_mode_override(MouseMode p_mode) {
  1195. ERR_FAIL_INDEX(p_mode, MouseMode::MOUSE_MODE_MAX);
  1196. if (p_mode == mouse_mode_override) {
  1197. return;
  1198. }
  1199. mouse_mode_override = p_mode;
  1200. _mouse_update_mode();
  1201. }
  1202. DisplayServer::MouseMode DisplayServerMacOS::mouse_get_mode_override() const {
  1203. return mouse_mode_override;
  1204. }
  1205. void DisplayServerMacOS::mouse_set_mode_override_enabled(bool p_override_enabled) {
  1206. if (p_override_enabled == mouse_mode_override_enabled) {
  1207. return;
  1208. }
  1209. mouse_mode_override_enabled = p_override_enabled;
  1210. _mouse_update_mode();
  1211. }
  1212. bool DisplayServerMacOS::mouse_is_mode_override_enabled() const {
  1213. return mouse_mode_override_enabled;
  1214. }
  1215. bool DisplayServerMacOS::update_mouse_wrap(WindowData &p_wd, NSPoint &r_delta, NSPoint &r_mpos, NSTimeInterval p_timestamp) {
  1216. _THREAD_SAFE_METHOD_
  1217. if (ignore_warp) {
  1218. // Discard late events, before warp.
  1219. if (p_timestamp < last_warp) {
  1220. return true;
  1221. }
  1222. ignore_warp = false;
  1223. return true;
  1224. }
  1225. if (mouse_mode == DisplayServer::MOUSE_MODE_CONFINED || mouse_mode == DisplayServer::MOUSE_MODE_CONFINED_HIDDEN) {
  1226. // Discard late events.
  1227. if (p_timestamp < last_warp) {
  1228. return true;
  1229. }
  1230. // Warp affects next event delta, subtract previous warp deltas.
  1231. List<WarpEvent>::Element *F = warp_events.front();
  1232. while (F) {
  1233. if (F->get().timestamp < p_timestamp) {
  1234. List<DisplayServerMacOS::WarpEvent>::Element *E = F;
  1235. r_delta.x -= E->get().delta.x;
  1236. r_delta.y -= E->get().delta.y;
  1237. F = F->next();
  1238. warp_events.erase(E);
  1239. } else {
  1240. F = F->next();
  1241. }
  1242. }
  1243. // Confine mouse position to the window, and update delta.
  1244. NSRect frame = [p_wd.window_view frame];
  1245. NSPoint conf_pos = r_mpos;
  1246. conf_pos.x = CLAMP(conf_pos.x + r_delta.x, 0.f, frame.size.width);
  1247. conf_pos.y = CLAMP(conf_pos.y - r_delta.y, 0.f, frame.size.height);
  1248. r_delta.x = conf_pos.x - r_mpos.x;
  1249. r_delta.y = r_mpos.y - conf_pos.y;
  1250. r_mpos = conf_pos;
  1251. // Move mouse cursor.
  1252. NSRect point_in_window_rect = NSMakeRect(conf_pos.x, conf_pos.y, 0, 0);
  1253. conf_pos = [[p_wd.window_view window] convertRectToScreen:point_in_window_rect].origin;
  1254. conf_pos.y = CGDisplayBounds(CGMainDisplayID()).size.height - conf_pos.y;
  1255. CGWarpMouseCursorPosition(conf_pos);
  1256. // Save warp data.
  1257. last_warp = [[NSProcessInfo processInfo] systemUptime];
  1258. DisplayServerMacOS::WarpEvent ev;
  1259. ev.timestamp = last_warp;
  1260. ev.delta = r_delta;
  1261. warp_events.push_back(ev);
  1262. }
  1263. return false;
  1264. }
  1265. void DisplayServerMacOS::warp_mouse(const Point2i &p_position) {
  1266. _THREAD_SAFE_METHOD_
  1267. if (mouse_mode != MOUSE_MODE_CAPTURED) {
  1268. WindowID window_id = _get_focused_window_or_popup();
  1269. if (!windows.has(window_id)) {
  1270. window_id = MAIN_WINDOW_ID;
  1271. }
  1272. WindowData &wd = windows[window_id];
  1273. // Local point in window coords.
  1274. const NSRect contentRect = [wd.window_view frame];
  1275. const float scale = screen_get_max_scale();
  1276. NSRect pointInWindowRect = NSMakeRect(p_position.x / scale, contentRect.size.height - (p_position.y / scale), scale, scale);
  1277. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  1278. // Point in screen coords.
  1279. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1280. // Do the warping.
  1281. CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
  1282. CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
  1283. CGAssociateMouseAndMouseCursorPosition(false);
  1284. CGWarpMouseCursorPosition(lMouseWarpPos);
  1285. if (mouse_mode != MOUSE_MODE_CONFINED && mouse_mode != MOUSE_MODE_CONFINED_HIDDEN) {
  1286. CGAssociateMouseAndMouseCursorPosition(true);
  1287. }
  1288. }
  1289. }
  1290. Point2i DisplayServerMacOS::mouse_get_position() const {
  1291. _THREAD_SAFE_METHOD_
  1292. const NSPoint mouse_pos = [NSEvent mouseLocation];
  1293. const float scale = screen_get_max_scale();
  1294. for (NSScreen *screen in [NSScreen screens]) {
  1295. NSRect frame = [screen frame];
  1296. if (NSMouseInRect(mouse_pos, frame, NO)) {
  1297. Vector2i pos = Vector2i((int)mouse_pos.x, (int)mouse_pos.y);
  1298. pos *= scale;
  1299. pos -= _get_screens_origin();
  1300. pos.y *= -1;
  1301. return pos;
  1302. }
  1303. }
  1304. return Vector2i();
  1305. }
  1306. BitField<MouseButtonMask> DisplayServerMacOS::mouse_get_button_state() const {
  1307. BitField<MouseButtonMask> last_button_state = 0;
  1308. NSUInteger buttons = [NSEvent pressedMouseButtons];
  1309. if (buttons & (1 << 0)) {
  1310. last_button_state.set_flag(MouseButtonMask::LEFT);
  1311. }
  1312. if (buttons & (1 << 1)) {
  1313. last_button_state.set_flag(MouseButtonMask::RIGHT);
  1314. }
  1315. if (buttons & (1 << 2)) {
  1316. last_button_state.set_flag(MouseButtonMask::MIDDLE);
  1317. }
  1318. if (buttons & (1 << 3)) {
  1319. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON1);
  1320. }
  1321. if (buttons & (1 << 4)) {
  1322. last_button_state.set_flag(MouseButtonMask::MB_XBUTTON2);
  1323. }
  1324. return last_button_state;
  1325. }
  1326. void DisplayServerMacOS::clipboard_set(const String &p_text) {
  1327. _THREAD_SAFE_METHOD_
  1328. NSString *copiedString = [NSString stringWithUTF8String:p_text.utf8().get_data()];
  1329. NSArray *copiedStringArray = [NSArray arrayWithObject:copiedString];
  1330. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1331. [pasteboard clearContents];
  1332. [pasteboard writeObjects:copiedStringArray];
  1333. }
  1334. String DisplayServerMacOS::clipboard_get() const {
  1335. _THREAD_SAFE_METHOD_
  1336. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1337. NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
  1338. NSDictionary *options = [NSDictionary dictionary];
  1339. BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
  1340. if (!ok) {
  1341. return "";
  1342. }
  1343. NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
  1344. NSString *string = [objectsToPaste objectAtIndex:0];
  1345. String ret;
  1346. ret.parse_utf8([string UTF8String]);
  1347. return ret;
  1348. }
  1349. Ref<Image> DisplayServerMacOS::clipboard_get_image() const {
  1350. Ref<Image> image;
  1351. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1352. NSString *result = [pasteboard availableTypeFromArray:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSPasteboardTypePNG, nil]];
  1353. if (!result) {
  1354. return image;
  1355. }
  1356. NSData *data = [pasteboard dataForType:result];
  1357. if (!data) {
  1358. return image;
  1359. }
  1360. NSBitmapImageRep *bitmap = [NSBitmapImageRep imageRepWithData:data];
  1361. NSData *pngData = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
  1362. image.instantiate();
  1363. PNGDriverCommon::png_to_image((const uint8_t *)pngData.bytes, pngData.length, false, image);
  1364. return image;
  1365. }
  1366. bool DisplayServerMacOS::clipboard_has() const {
  1367. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1368. NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
  1369. NSDictionary *options = [NSDictionary dictionary];
  1370. return [pasteboard canReadObjectForClasses:classArray options:options];
  1371. }
  1372. bool DisplayServerMacOS::clipboard_has_image() const {
  1373. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1374. NSString *result = [pasteboard availableTypeFromArray:[NSArray arrayWithObjects:NSPasteboardTypeTIFF, NSPasteboardTypePNG, nil]];
  1375. return result;
  1376. }
  1377. int DisplayServerMacOS::get_screen_count() const {
  1378. _THREAD_SAFE_METHOD_
  1379. NSArray *screenArray = [NSScreen screens];
  1380. return [screenArray count];
  1381. }
  1382. int DisplayServerMacOS::get_primary_screen() const {
  1383. return 0;
  1384. }
  1385. int DisplayServerMacOS::get_keyboard_focus_screen() const {
  1386. const NSUInteger index = [[NSScreen screens] indexOfObject:[NSScreen mainScreen]];
  1387. return (index == NSNotFound) ? 0 : index;
  1388. }
  1389. Point2i DisplayServerMacOS::screen_get_position(int p_screen) const {
  1390. _THREAD_SAFE_METHOD_
  1391. p_screen = _get_screen_index(p_screen);
  1392. Point2i position = _get_native_screen_position(p_screen) - _get_screens_origin();
  1393. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1394. // Godot expects a positive value.
  1395. position.y *= -1;
  1396. return position;
  1397. }
  1398. Size2i DisplayServerMacOS::screen_get_size(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. // Note: Use frame to get the whole screen size.
  1404. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1405. return Size2i(nsrect.size.width, nsrect.size.height) * screen_get_max_scale();
  1406. }
  1407. return Size2i();
  1408. }
  1409. int DisplayServerMacOS::screen_get_dpi(int p_screen) const {
  1410. _THREAD_SAFE_METHOD_
  1411. p_screen = _get_screen_index(p_screen);
  1412. NSArray *screenArray = [NSScreen screens];
  1413. if ((NSUInteger)p_screen < [screenArray count]) {
  1414. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1415. const NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
  1416. const CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1417. float scale = [[screenArray objectAtIndex:p_screen] backingScaleFactor];
  1418. float den2 = (displayPhysicalSize.width / 25.4f) * (displayPhysicalSize.width / 25.4f) + (displayPhysicalSize.height / 25.4f) * (displayPhysicalSize.height / 25.4f);
  1419. if (den2 > 0.0f) {
  1420. return ceil(sqrt(displayPixelSize.width * displayPixelSize.width + displayPixelSize.height * displayPixelSize.height) / sqrt(den2) * scale);
  1421. }
  1422. }
  1423. return 72;
  1424. }
  1425. float DisplayServerMacOS::screen_get_scale(int p_screen) const {
  1426. _THREAD_SAFE_METHOD_
  1427. p_screen = _get_screen_index(p_screen);
  1428. if (OS::get_singleton()->is_hidpi_allowed()) {
  1429. NSArray *screenArray = [NSScreen screens];
  1430. if ((NSUInteger)p_screen < [screenArray count]) {
  1431. if ([[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
  1432. return fmax(1.0, [[screenArray objectAtIndex:p_screen] backingScaleFactor]);
  1433. }
  1434. }
  1435. }
  1436. return 1.f;
  1437. }
  1438. float DisplayServerMacOS::screen_get_max_scale() const {
  1439. _THREAD_SAFE_METHOD_
  1440. // Note: Do not update max display scale on screen configuration change, existing editor windows can't be rescaled on the fly.
  1441. return display_max_scale;
  1442. }
  1443. Rect2i DisplayServerMacOS::screen_get_usable_rect(int p_screen) const {
  1444. _THREAD_SAFE_METHOD_
  1445. p_screen = _get_screen_index(p_screen);
  1446. NSArray *screenArray = [NSScreen screens];
  1447. if ((NSUInteger)p_screen < [screenArray count]) {
  1448. const float scale = screen_get_max_scale();
  1449. NSRect nsrect = [[screenArray objectAtIndex:p_screen] visibleFrame];
  1450. Point2i position = Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * scale - _get_screens_origin();
  1451. position.y *= -1;
  1452. Size2i size = Size2i(nsrect.size.width, nsrect.size.height) * scale;
  1453. return Rect2i(position, size);
  1454. }
  1455. return Rect2i();
  1456. }
  1457. Color DisplayServerMacOS::screen_get_pixel(const Point2i &p_position) const {
  1458. HashSet<CGWindowID> exclude_windows;
  1459. for (HashMap<WindowID, WindowData>::ConstIterator E = windows.begin(); E; ++E) {
  1460. if (E->value.hide_from_capture) {
  1461. exclude_windows.insert([E->value.window_object windowNumber]);
  1462. }
  1463. }
  1464. CFArrayRef on_screen_windows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
  1465. CFMutableArrayRef capture_windows = CFArrayCreateMutableCopy(nullptr, 0, on_screen_windows);
  1466. for (long i = CFArrayGetCount(on_screen_windows) - 1; i >= 0; i--) {
  1467. CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(capture_windows, i);
  1468. if (exclude_windows.has(window)) {
  1469. CFArrayRemoveValueAtIndex(capture_windows, i);
  1470. }
  1471. }
  1472. Point2i position = p_position - Vector2i(1, 1);
  1473. 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.
  1474. position /= screen_get_max_scale();
  1475. Color color;
  1476. CGImageRef image = CGWindowListCreateImageFromArray(CGRectMake(position.x, position.y, 1, 1), capture_windows, kCGWindowListOptionAll);
  1477. if (image) {
  1478. CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
  1479. if (color_space) {
  1480. uint8_t img_data[4];
  1481. CGContextRef context = CGBitmapContextCreate(img_data, 1, 1, 8, 4, color_space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  1482. if (context) {
  1483. CGContextDrawImage(context, CGRectMake(0, 0, 1, 1), image);
  1484. color = Color(img_data[0] / 255.0f, img_data[1] / 255.0f, img_data[2] / 255.0f, img_data[3] / 255.0f);
  1485. CGContextRelease(context);
  1486. }
  1487. CGColorSpaceRelease(color_space);
  1488. }
  1489. CGImageRelease(image);
  1490. }
  1491. return color;
  1492. }
  1493. Ref<Image> DisplayServerMacOS::screen_get_image(int p_screen) const {
  1494. ERR_FAIL_INDEX_V(p_screen, get_screen_count(), Ref<Image>());
  1495. HashSet<CGWindowID> exclude_windows;
  1496. for (HashMap<WindowID, WindowData>::ConstIterator E = windows.begin(); E; ++E) {
  1497. if (E->value.hide_from_capture) {
  1498. exclude_windows.insert([E->value.window_object windowNumber]);
  1499. }
  1500. }
  1501. CFArrayRef on_screen_windows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
  1502. CFMutableArrayRef capture_windows = CFArrayCreateMutableCopy(nullptr, 0, on_screen_windows);
  1503. for (long i = CFArrayGetCount(on_screen_windows) - 1; i >= 0; i--) {
  1504. CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(capture_windows, i);
  1505. if (exclude_windows.has(window)) {
  1506. CFArrayRemoveValueAtIndex(capture_windows, i);
  1507. }
  1508. }
  1509. Point2i position = screen_get_position(p_screen);
  1510. 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.
  1511. position /= screen_get_max_scale();
  1512. Size2i size = screen_get_size(p_screen);
  1513. size /= screen_get_max_scale();
  1514. Ref<Image> img;
  1515. CGImageRef image = CGWindowListCreateImageFromArray(CGRectMake(position.x, position.y, size.width, size.height), capture_windows, kCGWindowListOptionAll);
  1516. if (image) {
  1517. CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
  1518. if (color_space) {
  1519. NSUInteger width = CGImageGetWidth(image);
  1520. NSUInteger height = CGImageGetHeight(image);
  1521. Vector<uint8_t> img_data;
  1522. img_data.resize(height * width * 4);
  1523. CGContextRef context = CGBitmapContextCreate(img_data.ptrw(), width, height, 8, 4 * width, color_space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  1524. if (context) {
  1525. CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
  1526. img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
  1527. CGContextRelease(context);
  1528. img->resize(screen_get_size(p_screen).x, screen_get_size(p_screen).y, Image::INTERPOLATE_NEAREST);
  1529. }
  1530. CGColorSpaceRelease(color_space);
  1531. }
  1532. CGImageRelease(image);
  1533. }
  1534. return img;
  1535. }
  1536. Ref<Image> DisplayServerMacOS::screen_get_image_rect(const Rect2i &p_rect) const {
  1537. HashSet<CGWindowID> exclude_windows;
  1538. for (HashMap<WindowID, WindowData>::ConstIterator E = windows.begin(); E; ++E) {
  1539. if (E->value.hide_from_capture) {
  1540. exclude_windows.insert([E->value.window_object windowNumber]);
  1541. }
  1542. }
  1543. CFArrayRef on_screen_windows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
  1544. CFMutableArrayRef capture_windows = CFArrayCreateMutableCopy(nullptr, 0, on_screen_windows);
  1545. for (long i = CFArrayGetCount(on_screen_windows) - 1; i >= 0; i--) {
  1546. CGWindowID window = (CGWindowID)(uintptr_t)CFArrayGetValueAtIndex(capture_windows, i);
  1547. if (exclude_windows.has(window)) {
  1548. CFArrayRemoveValueAtIndex(capture_windows, i);
  1549. }
  1550. }
  1551. Point2i position = p_rect.position;
  1552. 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.
  1553. position /= screen_get_max_scale();
  1554. Size2i size = p_rect.size;
  1555. size /= screen_get_max_scale();
  1556. Ref<Image> img;
  1557. CGImageRef image = CGWindowListCreateImageFromArray(CGRectMake(position.x, position.y, size.width, size.height), capture_windows, kCGWindowListOptionAll);
  1558. if (image) {
  1559. CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB();
  1560. if (color_space) {
  1561. NSUInteger width = CGImageGetWidth(image);
  1562. NSUInteger height = CGImageGetHeight(image);
  1563. Vector<uint8_t> img_data;
  1564. img_data.resize_zeroed(height * width * 4);
  1565. CGContextRef context = CGBitmapContextCreate(img_data.ptrw(), width, height, 8, 4 * width, color_space, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
  1566. if (context) {
  1567. CGContextDrawImage(context, CGRectMake(0, 0, width, height), image);
  1568. img = Image::create_from_data(width, height, false, Image::FORMAT_RGBA8, img_data);
  1569. CGContextRelease(context);
  1570. img->resize(p_rect.size.x, p_rect.size.y, Image::INTERPOLATE_NEAREST);
  1571. }
  1572. CGColorSpaceRelease(color_space);
  1573. }
  1574. CGImageRelease(image);
  1575. }
  1576. return img;
  1577. }
  1578. float DisplayServerMacOS::screen_get_refresh_rate(int p_screen) const {
  1579. _THREAD_SAFE_METHOD_
  1580. p_screen = _get_screen_index(p_screen);
  1581. NSArray *screenArray = [NSScreen screens];
  1582. if ((NSUInteger)p_screen < [screenArray count]) {
  1583. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1584. const CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1585. const double displayRefreshRate = CGDisplayModeGetRefreshRate(displayMode);
  1586. return (float)displayRefreshRate;
  1587. }
  1588. ERR_PRINT("An error occurred while trying to get the screen refresh rate.");
  1589. return SCREEN_REFRESH_RATE_FALLBACK;
  1590. }
  1591. bool DisplayServerMacOS::screen_is_kept_on() const {
  1592. return (screen_keep_on_assertion);
  1593. }
  1594. void DisplayServerMacOS::screen_set_keep_on(bool p_enable) {
  1595. if (screen_keep_on_assertion) {
  1596. IOPMAssertionRelease(screen_keep_on_assertion);
  1597. screen_keep_on_assertion = kIOPMNullAssertionID;
  1598. }
  1599. if (p_enable) {
  1600. String app_name_string = GLOBAL_GET("application/config/name");
  1601. NSString *name = [NSString stringWithUTF8String:(app_name_string.is_empty() ? "Godot Engine" : app_name_string.utf8().get_data())];
  1602. NSString *reason = @"Godot Engine running with display/window/energy_saving/keep_screen_on = true";
  1603. IOPMAssertionCreateWithDescription(kIOPMAssertPreventUserIdleDisplaySleep, (__bridge CFStringRef)name, (__bridge CFStringRef)reason, (__bridge CFStringRef)reason, nullptr, 0, nullptr, &screen_keep_on_assertion);
  1604. }
  1605. }
  1606. Vector<DisplayServer::WindowID> DisplayServerMacOS::get_window_list() const {
  1607. _THREAD_SAFE_METHOD_
  1608. Vector<int> ret;
  1609. for (const KeyValue<WindowID, WindowData> &E : windows) {
  1610. ret.push_back(E.key);
  1611. }
  1612. return ret;
  1613. }
  1614. 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) {
  1615. _THREAD_SAFE_METHOD_
  1616. WindowID id = _create_window(p_mode, p_vsync_mode, p_rect);
  1617. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  1618. if (p_flags & (1 << i)) {
  1619. window_set_flag(WindowFlags(i), true, id);
  1620. }
  1621. }
  1622. #ifdef RD_ENABLED
  1623. if (rendering_device) {
  1624. rendering_device->screen_create(id);
  1625. }
  1626. #endif
  1627. window_set_exclusive(id, p_exclusive);
  1628. if (p_transient_parent != INVALID_WINDOW_ID) {
  1629. window_set_transient(id, p_transient_parent);
  1630. }
  1631. return id;
  1632. }
  1633. void DisplayServerMacOS::show_window(WindowID p_id) {
  1634. WindowData &wd = windows[p_id];
  1635. popup_open(p_id);
  1636. if ([wd.window_object isMiniaturized]) {
  1637. return;
  1638. } else if (wd.no_focus) {
  1639. [wd.window_object orderFront:nil];
  1640. } else {
  1641. [wd.window_object makeKeyAndOrderFront:nil];
  1642. }
  1643. }
  1644. void DisplayServerMacOS::delete_sub_window(WindowID p_id) {
  1645. _THREAD_SAFE_METHOD_
  1646. ERR_FAIL_COND(!windows.has(p_id));
  1647. ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted");
  1648. WindowData &wd = windows[p_id];
  1649. [wd.window_object setContentView:nil];
  1650. [wd.window_object close];
  1651. }
  1652. void DisplayServerMacOS::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1653. _THREAD_SAFE_METHOD_
  1654. ERR_FAIL_COND(!windows.has(p_window));
  1655. WindowData &wd = windows[p_window];
  1656. wd.rect_changed_callback = p_callable;
  1657. }
  1658. void DisplayServerMacOS::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1659. _THREAD_SAFE_METHOD_
  1660. ERR_FAIL_COND(!windows.has(p_window));
  1661. WindowData &wd = windows[p_window];
  1662. wd.event_callback = p_callable;
  1663. }
  1664. void DisplayServerMacOS::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1665. _THREAD_SAFE_METHOD_
  1666. ERR_FAIL_COND(!windows.has(p_window));
  1667. WindowData &wd = windows[p_window];
  1668. wd.input_event_callback = p_callable;
  1669. }
  1670. void DisplayServerMacOS::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1671. _THREAD_SAFE_METHOD_
  1672. ERR_FAIL_COND(!windows.has(p_window));
  1673. WindowData &wd = windows[p_window];
  1674. wd.input_text_callback = p_callable;
  1675. }
  1676. void DisplayServerMacOS::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1677. _THREAD_SAFE_METHOD_
  1678. ERR_FAIL_COND(!windows.has(p_window));
  1679. WindowData &wd = windows[p_window];
  1680. wd.drop_files_callback = p_callable;
  1681. }
  1682. void DisplayServerMacOS::window_set_title(const String &p_title, WindowID p_window) {
  1683. _THREAD_SAFE_METHOD_
  1684. ERR_FAIL_COND(!windows.has(p_window));
  1685. WindowData &wd = windows[p_window];
  1686. [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
  1687. }
  1688. Size2i DisplayServerMacOS::window_get_title_size(const String &p_title, WindowID p_window) const {
  1689. _THREAD_SAFE_METHOD_
  1690. Size2i size;
  1691. ERR_FAIL_COND_V(!windows.has(p_window), size);
  1692. const WindowData &wd = windows[p_window];
  1693. if (wd.fullscreen || wd.borderless) {
  1694. return size;
  1695. }
  1696. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  1697. if ([wd.window_object isMiniaturized]) {
  1698. return size;
  1699. }
  1700. }
  1701. float scale = screen_get_max_scale();
  1702. if (wd.window_button_view) {
  1703. size.x = ([wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width);
  1704. size.y = ([wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height);
  1705. } else {
  1706. NSButton *cb = [wd.window_object standardWindowButton:NSWindowCloseButton];
  1707. NSButton *mb = [wd.window_object standardWindowButton:NSWindowMiniaturizeButton];
  1708. float cb_frame = NSMinX([cb frame]);
  1709. float mb_frame = NSMinX([mb frame]);
  1710. bool is_rtl = ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft);
  1711. float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame);
  1712. size.x = window_buttons_spacing * 4;
  1713. size.y = [cb frame].origin.y + [cb frame].size.height;
  1714. }
  1715. NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont titleBarFontOfSize:0], NSFontAttributeName, nil];
  1716. NSSize text_size = [[[NSAttributedString alloc] initWithString:[NSString stringWithUTF8String:p_title.utf8().get_data()] attributes:attributes] size];
  1717. size.x += text_size.width;
  1718. size.y = MAX(size.y, text_size.height);
  1719. return size * scale;
  1720. }
  1721. void DisplayServerMacOS::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1722. _THREAD_SAFE_METHOD_
  1723. ERR_FAIL_COND(!windows.has(p_window));
  1724. WindowData &wd = windows[p_window];
  1725. wd.mpath = p_region;
  1726. }
  1727. int DisplayServerMacOS::window_get_current_screen(WindowID p_window) const {
  1728. _THREAD_SAFE_METHOD_
  1729. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  1730. const WindowData &wd = windows[p_window];
  1731. const NSUInteger index = [[NSScreen screens] indexOfObject:[wd.window_object screen]];
  1732. return (index == NSNotFound) ? 0 : index;
  1733. }
  1734. void DisplayServerMacOS::window_set_current_screen(int p_screen, WindowID p_window) {
  1735. _THREAD_SAFE_METHOD_
  1736. ERR_FAIL_COND(!windows.has(p_window));
  1737. WindowData &wd = windows[p_window];
  1738. if (window_get_current_screen(p_window) == p_screen) {
  1739. return;
  1740. }
  1741. bool was_fullscreen = false;
  1742. if (wd.fullscreen) {
  1743. // Temporary exit fullscreen mode to move window.
  1744. [wd.window_object toggleFullScreen:nil];
  1745. was_fullscreen = true;
  1746. }
  1747. bool was_maximized = false;
  1748. if (!was_fullscreen && NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1749. [wd.window_object zoom:nil];
  1750. was_maximized = true;
  1751. }
  1752. Rect2i srect = screen_get_usable_rect(p_screen);
  1753. Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  1754. Size2i wsize = window_get_size(p_window);
  1755. wpos += srect.position;
  1756. wpos = wpos.clamp(srect.position, srect.position + srect.size - wsize / 3);
  1757. window_set_position(wpos, p_window);
  1758. if (was_maximized) {
  1759. [wd.window_object zoom:nil];
  1760. }
  1761. if (was_fullscreen) {
  1762. // Re-enter fullscreen mode.
  1763. [wd.window_object toggleFullScreen:nil];
  1764. }
  1765. }
  1766. void DisplayServerMacOS::reparent_check(WindowID p_window) {
  1767. ERR_FAIL_COND(!windows.has(p_window));
  1768. WindowData &wd = windows[p_window];
  1769. NSScreen *screen = [wd.window_object screen];
  1770. if (wd.transient_parent != INVALID_WINDOW_ID) {
  1771. WindowData &wd_parent = windows[wd.transient_parent];
  1772. NSScreen *parent_screen = [wd_parent.window_object screen];
  1773. if (parent_screen == screen) {
  1774. if (![[wd_parent.window_object childWindows] containsObject:wd.window_object]) {
  1775. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
  1776. [wd_parent.window_object addChildWindow:wd.window_object ordered:NSWindowAbove];
  1777. }
  1778. } else {
  1779. if ([[wd_parent.window_object childWindows] containsObject:wd.window_object]) {
  1780. [wd_parent.window_object removeChildWindow:wd.window_object];
  1781. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1782. [wd.window_object orderFront:nil];
  1783. }
  1784. }
  1785. }
  1786. for (const WindowID &child : wd.transient_children) {
  1787. WindowData &wd_child = windows[child];
  1788. NSScreen *child_screen = [wd_child.window_object screen];
  1789. if (child_screen == screen) {
  1790. if (![[wd.window_object childWindows] containsObject:wd_child.window_object]) {
  1791. if (wd_child.fullscreen) {
  1792. [wd_child.window_object toggleFullScreen:nil];
  1793. }
  1794. [wd_child.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenAuxiliary];
  1795. [wd.window_object addChildWindow:wd_child.window_object ordered:NSWindowAbove];
  1796. }
  1797. } else {
  1798. if ([[wd.window_object childWindows] containsObject:wd_child.window_object]) {
  1799. [wd.window_object removeChildWindow:wd_child.window_object];
  1800. [wd_child.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1801. }
  1802. }
  1803. }
  1804. }
  1805. void DisplayServerMacOS::window_set_exclusive(WindowID p_window, bool p_exclusive) {
  1806. _THREAD_SAFE_METHOD_
  1807. ERR_FAIL_COND(!windows.has(p_window));
  1808. WindowData &wd = windows[p_window];
  1809. if (wd.exclusive != p_exclusive) {
  1810. wd.exclusive = p_exclusive;
  1811. reparent_check(p_window);
  1812. }
  1813. }
  1814. Point2i DisplayServerMacOS::window_get_position(WindowID p_window) const {
  1815. _THREAD_SAFE_METHOD_
  1816. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1817. const WindowData &wd = windows[p_window];
  1818. // Use content rect position (without titlebar / window border).
  1819. const NSRect contentRect = [wd.window_view frame];
  1820. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  1821. Point2i pos;
  1822. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  1823. const float scale = screen_get_max_scale();
  1824. pos.x = nsrect.origin.x;
  1825. pos.y = (nsrect.origin.y + nsrect.size.height);
  1826. pos *= scale;
  1827. pos -= _get_screens_origin();
  1828. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1829. // Godot expects a positive value.
  1830. pos.y *= -1;
  1831. return pos;
  1832. }
  1833. Point2i DisplayServerMacOS::window_get_position_with_decorations(WindowID p_window) const {
  1834. _THREAD_SAFE_METHOD_
  1835. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  1836. const WindowData &wd = windows[p_window];
  1837. const NSRect nsrect = [wd.window_object frame];
  1838. Point2i pos;
  1839. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  1840. const float scale = screen_get_max_scale();
  1841. pos.x = nsrect.origin.x;
  1842. pos.y = (nsrect.origin.y + nsrect.size.height);
  1843. pos *= scale;
  1844. pos -= _get_screens_origin();
  1845. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1846. // Godot expects a positive value.
  1847. pos.y *= -1;
  1848. return pos;
  1849. }
  1850. void DisplayServerMacOS::window_set_position(const Point2i &p_position, WindowID p_window) {
  1851. _THREAD_SAFE_METHOD_
  1852. ERR_FAIL_COND(!windows.has(p_window));
  1853. WindowData &wd = windows[p_window];
  1854. if (wd.fullscreen) {
  1855. return;
  1856. }
  1857. Point2i position = p_position;
  1858. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  1859. // Godot passes a positive value.
  1860. position.y *= -1;
  1861. position += _get_screens_origin();
  1862. position /= screen_get_max_scale();
  1863. // Remove titlebar / window border size.
  1864. const NSRect contentRect = [wd.window_view frame];
  1865. const NSRect windowRect = [wd.window_object frame];
  1866. const NSRect nsrect = [wd.window_object convertRectToScreen:contentRect];
  1867. Point2i offset;
  1868. offset.x = (nsrect.origin.x - windowRect.origin.x);
  1869. offset.y = (nsrect.origin.y + nsrect.size.height);
  1870. offset.y -= (windowRect.origin.y + windowRect.size.height);
  1871. [wd.window_object setFrameTopLeftPoint:NSMakePoint(position.x - offset.x, position.y - offset.y)];
  1872. _update_window_style(wd, p_window);
  1873. update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  1874. }
  1875. void DisplayServerMacOS::window_set_transient(WindowID p_window, WindowID p_parent) {
  1876. _THREAD_SAFE_METHOD_
  1877. ERR_FAIL_COND(p_window == p_parent);
  1878. ERR_FAIL_COND(!windows.has(p_window));
  1879. WindowData &wd_window = windows[p_window];
  1880. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  1881. ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
  1882. if (p_parent == INVALID_WINDOW_ID) {
  1883. // Remove transient.
  1884. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  1885. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  1886. WindowData &wd_parent = windows[wd_window.transient_parent];
  1887. wd_window.transient_parent = INVALID_WINDOW_ID;
  1888. wd_parent.transient_children.erase(p_window);
  1889. if ([[wd_parent.window_object childWindows] containsObject:wd_window.window_object]) {
  1890. [wd_parent.window_object removeChildWindow:wd_window.window_object];
  1891. }
  1892. [wd_window.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  1893. } else {
  1894. ERR_FAIL_COND(!windows.has(p_parent));
  1895. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  1896. WindowData &wd_parent = windows[p_parent];
  1897. wd_window.transient_parent = p_parent;
  1898. wd_parent.transient_children.insert(p_window);
  1899. reparent_check(p_window);
  1900. }
  1901. }
  1902. void DisplayServerMacOS::window_set_max_size(const Size2i p_size, WindowID p_window) {
  1903. _THREAD_SAFE_METHOD_
  1904. ERR_FAIL_COND(!windows.has(p_window));
  1905. WindowData &wd = windows[p_window];
  1906. if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  1907. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  1908. return;
  1909. }
  1910. wd.max_size = p_size;
  1911. if ((wd.max_size != Size2i()) && !wd.fullscreen) {
  1912. Size2i size = wd.max_size / screen_get_max_scale();
  1913. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  1914. } else {
  1915. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  1916. }
  1917. }
  1918. Size2i DisplayServerMacOS::window_get_max_size(WindowID p_window) const {
  1919. _THREAD_SAFE_METHOD_
  1920. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1921. const WindowData &wd = windows[p_window];
  1922. return wd.max_size;
  1923. }
  1924. void DisplayServerMacOS::update_presentation_mode() {
  1925. bool has_fs_windows = false;
  1926. for (const KeyValue<WindowID, WindowData> &wd : windows) {
  1927. if (wd.value.fullscreen) {
  1928. if (wd.value.exclusive_fullscreen) {
  1929. return;
  1930. } else {
  1931. has_fs_windows = true;
  1932. }
  1933. }
  1934. }
  1935. if (has_fs_windows) {
  1936. [NSApp setPresentationOptions:NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock | NSApplicationPresentationFullScreen];
  1937. } else {
  1938. [NSApp setPresentationOptions:NSApplicationPresentationDefault];
  1939. }
  1940. }
  1941. void DisplayServerMacOS::window_set_min_size(const Size2i p_size, WindowID p_window) {
  1942. _THREAD_SAFE_METHOD_
  1943. ERR_FAIL_COND(!windows.has(p_window));
  1944. WindowData &wd = windows[p_window];
  1945. if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  1946. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  1947. return;
  1948. }
  1949. wd.min_size = p_size;
  1950. if ((wd.min_size != Size2i()) && !wd.fullscreen) {
  1951. Size2i size = wd.min_size / screen_get_max_scale();
  1952. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  1953. } else {
  1954. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  1955. }
  1956. }
  1957. Size2i DisplayServerMacOS::window_get_min_size(WindowID p_window) const {
  1958. _THREAD_SAFE_METHOD_
  1959. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1960. const WindowData &wd = windows[p_window];
  1961. return wd.min_size;
  1962. }
  1963. void DisplayServerMacOS::window_set_size(const Size2i p_size, WindowID p_window) {
  1964. _THREAD_SAFE_METHOD_
  1965. ERR_FAIL_COND(!windows.has(p_window));
  1966. WindowData &wd = windows[p_window];
  1967. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  1968. return;
  1969. }
  1970. Size2i size = p_size / screen_get_max_scale();
  1971. NSPoint top_left;
  1972. NSRect old_frame = [wd.window_object frame];
  1973. top_left.x = old_frame.origin.x;
  1974. top_left.y = NSMaxY(old_frame);
  1975. NSRect new_frame = NSMakeRect(0, 0, MAX(1, size.x), MAX(1, size.y));
  1976. new_frame = [wd.window_object frameRectForContentRect:new_frame];
  1977. new_frame.origin.x = top_left.x;
  1978. new_frame.origin.y = top_left.y - new_frame.size.height;
  1979. [wd.window_object setFrame:new_frame display:YES];
  1980. _update_window_style(wd, p_window);
  1981. }
  1982. Size2i DisplayServerMacOS::window_get_size(WindowID p_window) const {
  1983. _THREAD_SAFE_METHOD_
  1984. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1985. const WindowData &wd = windows[p_window];
  1986. return wd.size;
  1987. }
  1988. Size2i DisplayServerMacOS::window_get_size_with_decorations(WindowID p_window) const {
  1989. _THREAD_SAFE_METHOD_
  1990. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  1991. const WindowData &wd = windows[p_window];
  1992. NSRect frame = [wd.window_object frame];
  1993. return Size2i(frame.size.width, frame.size.height) * screen_get_max_scale();
  1994. }
  1995. void DisplayServerMacOS::window_set_mode(WindowMode p_mode, WindowID p_window) {
  1996. _THREAD_SAFE_METHOD_
  1997. ERR_FAIL_COND(!windows.has(p_window));
  1998. WindowData &wd = windows[p_window];
  1999. WindowMode old_mode = window_get_mode(p_window);
  2000. if (old_mode == p_mode) {
  2001. return; // Do nothing.
  2002. }
  2003. switch (old_mode) {
  2004. case WINDOW_MODE_WINDOWED: {
  2005. // Do nothing.
  2006. } break;
  2007. case WINDOW_MODE_MINIMIZED: {
  2008. [wd.window_object deminiaturize:nil];
  2009. } break;
  2010. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  2011. case WINDOW_MODE_FULLSCREEN: {
  2012. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN || p_mode == WINDOW_MODE_FULLSCREEN) {
  2013. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2014. const NSUInteger presentationOptions = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
  2015. [NSApp setPresentationOptions:presentationOptions];
  2016. wd.exclusive_fullscreen = true;
  2017. } else {
  2018. wd.exclusive_fullscreen = false;
  2019. update_presentation_mode();
  2020. }
  2021. return;
  2022. }
  2023. [(NSWindow *)wd.window_object setLevel:NSNormalWindowLevel];
  2024. if (wd.resize_disabled) { // Restore resize disabled.
  2025. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2026. }
  2027. if (wd.min_size != Size2i()) {
  2028. Size2i size = wd.min_size / screen_get_max_scale();
  2029. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  2030. }
  2031. if (wd.max_size != Size2i()) {
  2032. Size2i size = wd.max_size / screen_get_max_scale();
  2033. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  2034. }
  2035. [wd.window_object toggleFullScreen:nil];
  2036. if (old_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2037. update_presentation_mode();
  2038. }
  2039. wd.fullscreen = false;
  2040. wd.exclusive_fullscreen = false;
  2041. } break;
  2042. case WINDOW_MODE_MAXIMIZED: {
  2043. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  2044. [wd.window_object zoom:nil];
  2045. }
  2046. } break;
  2047. }
  2048. switch (p_mode) {
  2049. case WINDOW_MODE_WINDOWED: {
  2050. // Do nothing.
  2051. } break;
  2052. case WINDOW_MODE_MINIMIZED: {
  2053. [wd.window_object performMiniaturize:nil];
  2054. } break;
  2055. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  2056. case WINDOW_MODE_FULLSCREEN: {
  2057. if (wd.resize_disabled) { // Fullscreen window should be resizable to work.
  2058. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2059. }
  2060. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  2061. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  2062. [wd.window_object toggleFullScreen:nil];
  2063. wd.fullscreen = true;
  2064. if (p_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN) {
  2065. const NSUInteger presentationOptions = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar;
  2066. [NSApp setPresentationOptions:presentationOptions];
  2067. wd.exclusive_fullscreen = true;
  2068. } else {
  2069. wd.exclusive_fullscreen = false;
  2070. update_presentation_mode();
  2071. }
  2072. } break;
  2073. case WINDOW_MODE_MAXIMIZED: {
  2074. if (!NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  2075. [wd.window_object zoom:nil];
  2076. }
  2077. } break;
  2078. }
  2079. }
  2080. DisplayServer::WindowMode DisplayServerMacOS::window_get_mode(WindowID p_window) const {
  2081. _THREAD_SAFE_METHOD_
  2082. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  2083. const WindowData &wd = windows[p_window];
  2084. if (wd.fullscreen) { // If fullscreen, it's not in another mode.
  2085. if (wd.exclusive_fullscreen) {
  2086. return WINDOW_MODE_EXCLUSIVE_FULLSCREEN;
  2087. } else {
  2088. return WINDOW_MODE_FULLSCREEN;
  2089. }
  2090. }
  2091. if (NSEqualRects([wd.window_object frame], [[wd.window_object screen] visibleFrame])) {
  2092. return WINDOW_MODE_MAXIMIZED;
  2093. }
  2094. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  2095. if ([wd.window_object isMiniaturized]) {
  2096. return WINDOW_MODE_MINIMIZED;
  2097. }
  2098. }
  2099. // All other discarded, return windowed.
  2100. return WINDOW_MODE_WINDOWED;
  2101. }
  2102. bool DisplayServerMacOS::window_is_maximize_allowed(WindowID p_window) const {
  2103. return true;
  2104. }
  2105. bool DisplayServerMacOS::window_maximize_on_title_dbl_click() const {
  2106. id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleActionOnDoubleClick"];
  2107. if ([value isKindOfClass:[NSString class]]) {
  2108. return [value isEqualToString:@"Maximize"];
  2109. }
  2110. return false;
  2111. }
  2112. bool DisplayServerMacOS::window_minimize_on_title_dbl_click() const {
  2113. id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleActionOnDoubleClick"];
  2114. if ([value isKindOfClass:[NSString class]]) {
  2115. return [value isEqualToString:@"Minimize"];
  2116. }
  2117. return false;
  2118. }
  2119. void DisplayServerMacOS::window_start_drag(WindowID p_window) {
  2120. _THREAD_SAFE_METHOD_
  2121. ERR_FAIL_COND(!windows.has(p_window));
  2122. WindowData &wd = windows[p_window];
  2123. 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];
  2124. [wd.window_object performWindowDragWithEvent:event];
  2125. }
  2126. void DisplayServerMacOS::window_start_resize(WindowResizeEdge p_edge, WindowID p_window) {
  2127. _THREAD_SAFE_METHOD_
  2128. ERR_FAIL_INDEX(int(p_edge), WINDOW_EDGE_MAX);
  2129. ERR_FAIL_COND(!windows.has(p_window));
  2130. WindowData &wd = windows[p_window];
  2131. wd.edge = p_edge;
  2132. }
  2133. void DisplayServerMacOS::window_set_window_buttons_offset(const Vector2i &p_offset, WindowID p_window) {
  2134. _THREAD_SAFE_METHOD_
  2135. ERR_FAIL_COND(!windows.has(p_window));
  2136. WindowData &wd = windows[p_window];
  2137. float scale = screen_get_max_scale();
  2138. wd.wb_offset = p_offset / scale;
  2139. wd.wb_offset = wd.wb_offset.maxi(12);
  2140. if (wd.window_button_view) {
  2141. [(GodotButtonView *)wd.window_button_view setOffset:NSMakePoint(wd.wb_offset.x, wd.wb_offset.y)];
  2142. }
  2143. }
  2144. Vector3i DisplayServerMacOS::window_get_safe_title_margins(WindowID p_window) const {
  2145. _THREAD_SAFE_METHOD_
  2146. ERR_FAIL_COND_V(!windows.has(p_window), Vector3i());
  2147. const WindowData &wd = windows[p_window];
  2148. if (!wd.window_button_view) {
  2149. return Vector3i();
  2150. }
  2151. float scale = screen_get_max_scale();
  2152. float max_x = [wd.window_button_view getOffset].x + [wd.window_button_view frame].size.width;
  2153. float max_y = [wd.window_button_view getOffset].y + [wd.window_button_view frame].size.height;
  2154. if ([wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft) {
  2155. return Vector3i(0, max_x * scale, max_y * scale);
  2156. } else {
  2157. return Vector3i(max_x * scale, 0, max_y * scale);
  2158. }
  2159. }
  2160. void DisplayServerMacOS::window_set_custom_window_buttons(WindowData &p_wd, bool p_enabled) {
  2161. if (p_wd.window_button_view) {
  2162. [p_wd.window_button_view removeFromSuperview];
  2163. p_wd.window_button_view = nil;
  2164. }
  2165. if (p_enabled) {
  2166. float cb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowCloseButton] frame]);
  2167. float mb_frame = NSMinX([[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] frame]);
  2168. bool is_rtl = ([p_wd.window_object windowTitlebarLayoutDirection] == NSUserInterfaceLayoutDirectionRightToLeft);
  2169. float window_buttons_spacing = (is_rtl) ? (cb_frame - mb_frame) : (mb_frame - cb_frame);
  2170. [p_wd.window_object setTitleVisibility:NSWindowTitleHidden];
  2171. [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:YES];
  2172. [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:YES];
  2173. [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:YES];
  2174. p_wd.window_button_view = [[GodotButtonView alloc] initWithFrame:NSZeroRect];
  2175. [p_wd.window_button_view initButtons:window_buttons_spacing offset:NSMakePoint(p_wd.wb_offset.x, p_wd.wb_offset.y) rtl:is_rtl];
  2176. [p_wd.window_view addSubview:p_wd.window_button_view];
  2177. } else {
  2178. [p_wd.window_object setTitleVisibility:NSWindowTitleVisible];
  2179. [[p_wd.window_object standardWindowButton:NSWindowZoomButton] setHidden:NO];
  2180. [[p_wd.window_object standardWindowButton:NSWindowMiniaturizeButton] setHidden:NO];
  2181. [[p_wd.window_object standardWindowButton:NSWindowCloseButton] setHidden:NO];
  2182. }
  2183. }
  2184. void DisplayServerMacOS::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  2185. _THREAD_SAFE_METHOD_
  2186. ERR_FAIL_COND(!windows.has(p_window));
  2187. WindowData &wd = windows[p_window];
  2188. switch (p_flag) {
  2189. case WINDOW_FLAG_RESIZE_DISABLED: {
  2190. wd.resize_disabled = p_enabled;
  2191. if (wd.fullscreen) { // Fullscreen window should be resizable, style will be applied on exiting fullscreen.
  2192. return;
  2193. }
  2194. if (p_enabled) {
  2195. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2196. [[wd.window_object standardWindowButton:NSWindowZoomButton] setEnabled:NO];
  2197. } else {
  2198. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2199. [[wd.window_object standardWindowButton:NSWindowZoomButton] setEnabled:YES];
  2200. }
  2201. } break;
  2202. case WINDOW_FLAG_EXTEND_TO_TITLE: {
  2203. NSRect rect = [wd.window_object frame];
  2204. wd.extend_to_title = p_enabled;
  2205. if (p_enabled) {
  2206. [wd.window_object setTitlebarAppearsTransparent:YES];
  2207. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskFullSizeContentView];
  2208. if (!wd.fullscreen) {
  2209. window_set_custom_window_buttons(wd, true);
  2210. }
  2211. } else {
  2212. [wd.window_object setTitlebarAppearsTransparent:NO];
  2213. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskFullSizeContentView];
  2214. if (!wd.fullscreen) {
  2215. window_set_custom_window_buttons(wd, false);
  2216. }
  2217. }
  2218. [wd.window_object setFrame:rect display:YES];
  2219. send_window_event(wd, DisplayServerMacOS::WINDOW_EVENT_TITLEBAR_CHANGE);
  2220. } break;
  2221. case WINDOW_FLAG_BORDERLESS: {
  2222. if (wd.fullscreen) {
  2223. return;
  2224. }
  2225. // OrderOut prevents a lose focus bug with the window.
  2226. bool was_visible = false;
  2227. if ([wd.window_object isVisible]) {
  2228. was_visible = true;
  2229. [wd.window_object orderOut:nil];
  2230. }
  2231. wd.borderless = p_enabled;
  2232. if (p_enabled) {
  2233. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless];
  2234. } else {
  2235. if (wd.layered_window) {
  2236. wd.layered_window = false;
  2237. set_window_per_pixel_transparency_enabled(false, p_window);
  2238. }
  2239. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.extend_to_title ? NSWindowStyleMaskFullSizeContentView : 0) | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2240. // Force update of the window styles.
  2241. NSRect frameRect = [wd.window_object frame];
  2242. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2243. [wd.window_object setFrame:frameRect display:NO];
  2244. }
  2245. _update_window_style(wd, p_window);
  2246. if (was_visible || [wd.window_object isVisible]) {
  2247. if ([wd.window_object isMiniaturized]) {
  2248. return;
  2249. } else if (wd.no_focus) {
  2250. [wd.window_object orderFront:nil];
  2251. } else {
  2252. [wd.window_object makeKeyAndOrderFront:nil];
  2253. }
  2254. }
  2255. } break;
  2256. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2257. wd.on_top = p_enabled;
  2258. if (wd.fullscreen) {
  2259. return;
  2260. }
  2261. if (p_enabled) {
  2262. [(NSWindow *)wd.window_object setLevel:NSFloatingWindowLevel];
  2263. } else {
  2264. [(NSWindow *)wd.window_object setLevel:NSNormalWindowLevel];
  2265. }
  2266. } break;
  2267. case WINDOW_FLAG_TRANSPARENT: {
  2268. if (wd.fullscreen) {
  2269. return;
  2270. }
  2271. if (p_enabled) {
  2272. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless]; // Force borderless.
  2273. } else if (!wd.borderless) {
  2274. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.extend_to_title ? NSWindowStyleMaskFullSizeContentView : 0) | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2275. }
  2276. wd.layered_window = p_enabled;
  2277. set_window_per_pixel_transparency_enabled(p_enabled, p_window);
  2278. // Force update of the window styles.
  2279. NSRect frameRect = [wd.window_object frame];
  2280. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2281. [wd.window_object setFrame:frameRect display:NO];
  2282. } break;
  2283. case WINDOW_FLAG_NO_FOCUS: {
  2284. wd.no_focus = p_enabled;
  2285. NSWindow *w = wd.window_object;
  2286. w.excludedFromWindowsMenu = wd.is_popup || wd.no_focus;
  2287. } break;
  2288. case WINDOW_FLAG_EXCLUDE_FROM_CAPTURE: {
  2289. if (p_enabled) {
  2290. [wd.window_object setSharingType:NSWindowSharingNone];
  2291. } else {
  2292. [wd.window_object setSharingType:NSWindowSharingReadWrite];
  2293. }
  2294. wd.hide_from_capture = p_enabled;
  2295. } break;
  2296. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2297. wd.mpass = p_enabled;
  2298. } break;
  2299. case WINDOW_FLAG_POPUP: {
  2300. ERR_FAIL_COND_MSG(p_window == MAIN_WINDOW_ID, "Main window can't be popup.");
  2301. ERR_FAIL_COND_MSG([wd.window_object isVisible] && (wd.is_popup != p_enabled), "Popup flag can't changed while window is opened.");
  2302. wd.is_popup = p_enabled;
  2303. NSWindow *w = wd.window_object;
  2304. w.excludedFromWindowsMenu = wd.is_popup || wd.no_focus;
  2305. } break;
  2306. default: {
  2307. }
  2308. }
  2309. }
  2310. bool DisplayServerMacOS::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  2311. _THREAD_SAFE_METHOD_
  2312. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2313. const WindowData &wd = windows[p_window];
  2314. switch (p_flag) {
  2315. case WINDOW_FLAG_RESIZE_DISABLED: {
  2316. return wd.resize_disabled;
  2317. } break;
  2318. case WINDOW_FLAG_EXTEND_TO_TITLE: {
  2319. return [wd.window_object styleMask] & NSWindowStyleMaskFullSizeContentView;
  2320. } break;
  2321. case WINDOW_FLAG_BORDERLESS: {
  2322. return [wd.window_object styleMask] == NSWindowStyleMaskBorderless;
  2323. } break;
  2324. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2325. return wd.on_top;
  2326. } break;
  2327. case WINDOW_FLAG_TRANSPARENT: {
  2328. return wd.layered_window;
  2329. } break;
  2330. case WINDOW_FLAG_NO_FOCUS: {
  2331. return wd.no_focus;
  2332. } break;
  2333. case WINDOW_FLAG_EXCLUDE_FROM_CAPTURE: {
  2334. return wd.hide_from_capture;
  2335. } break;
  2336. case WINDOW_FLAG_MOUSE_PASSTHROUGH: {
  2337. return wd.mpass;
  2338. } break;
  2339. case WINDOW_FLAG_POPUP: {
  2340. return wd.is_popup;
  2341. } break;
  2342. default: {
  2343. }
  2344. }
  2345. return false;
  2346. }
  2347. void DisplayServerMacOS::window_request_attention(WindowID p_window) {
  2348. // It's app global, ignore window id.
  2349. [NSApp requestUserAttention:NSCriticalRequest];
  2350. }
  2351. void DisplayServerMacOS::window_move_to_foreground(WindowID p_window) {
  2352. _THREAD_SAFE_METHOD_
  2353. ERR_FAIL_COND(!windows.has(p_window));
  2354. const WindowData &wd = windows[p_window];
  2355. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  2356. if (wd.no_focus || wd.is_popup) {
  2357. [wd.window_object orderFront:nil];
  2358. } else {
  2359. [wd.window_object makeKeyAndOrderFront:nil];
  2360. }
  2361. }
  2362. bool DisplayServerMacOS::window_is_focused(WindowID p_window) const {
  2363. _THREAD_SAFE_METHOD_
  2364. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2365. const WindowData &wd = windows[p_window];
  2366. return wd.focused;
  2367. }
  2368. DisplayServerMacOS::WindowID DisplayServerMacOS::get_focused_window() const {
  2369. return last_focused_window;
  2370. }
  2371. bool DisplayServerMacOS::window_can_draw(WindowID p_window) const {
  2372. return windows[p_window].is_visible;
  2373. }
  2374. bool DisplayServerMacOS::can_any_window_draw() const {
  2375. _THREAD_SAFE_METHOD_
  2376. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2377. if (E.value.is_visible) {
  2378. return true;
  2379. }
  2380. }
  2381. return false;
  2382. }
  2383. void DisplayServerMacOS::window_set_ime_active(const bool p_active, WindowID p_window) {
  2384. _THREAD_SAFE_METHOD_
  2385. ERR_FAIL_COND(!windows.has(p_window));
  2386. WindowData &wd = windows[p_window];
  2387. wd.im_active = p_active;
  2388. if (!p_active) {
  2389. [wd.window_view cancelComposition];
  2390. }
  2391. }
  2392. void DisplayServerMacOS::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  2393. _THREAD_SAFE_METHOD_
  2394. ERR_FAIL_COND(!windows.has(p_window));
  2395. WindowData &wd = windows[p_window];
  2396. wd.im_position = p_pos;
  2397. }
  2398. DisplayServer::WindowID DisplayServerMacOS::get_window_at_screen_position(const Point2i &p_position) const {
  2399. Point2i position = p_position;
  2400. position.y *= -1;
  2401. position += _get_screens_origin();
  2402. position /= screen_get_max_scale();
  2403. NSInteger wnum = [NSWindow windowNumberAtPoint:NSMakePoint(position.x, position.y) belowWindowWithWindowNumber:0 /*topmost*/];
  2404. for (const KeyValue<WindowID, WindowData> &E : windows) {
  2405. if ([E.value.window_object windowNumber] == wnum) {
  2406. return E.key;
  2407. }
  2408. }
  2409. return INVALID_WINDOW_ID;
  2410. }
  2411. int64_t DisplayServerMacOS::window_get_native_handle(HandleType p_handle_type, WindowID p_window) const {
  2412. ERR_FAIL_COND_V(!windows.has(p_window), 0);
  2413. switch (p_handle_type) {
  2414. case DISPLAY_HANDLE: {
  2415. return 0; // Not supported.
  2416. }
  2417. case WINDOW_HANDLE: {
  2418. return (int64_t)windows[p_window].window_object;
  2419. }
  2420. case WINDOW_VIEW: {
  2421. return (int64_t)windows[p_window].window_view;
  2422. }
  2423. #ifdef GLES3_ENABLED
  2424. case OPENGL_CONTEXT: {
  2425. if (gl_manager_legacy) {
  2426. return (int64_t)gl_manager_legacy->get_context(p_window);
  2427. }
  2428. if (gl_manager_angle) {
  2429. return (int64_t)gl_manager_angle->get_context(p_window);
  2430. }
  2431. return 0;
  2432. }
  2433. case EGL_DISPLAY: {
  2434. if (gl_manager_angle) {
  2435. return (int64_t)gl_manager_angle->get_display(p_window);
  2436. }
  2437. return 0;
  2438. }
  2439. case EGL_CONFIG: {
  2440. if (gl_manager_angle) {
  2441. return (int64_t)gl_manager_angle->get_config(p_window);
  2442. }
  2443. return 0;
  2444. }
  2445. #endif
  2446. default: {
  2447. return 0;
  2448. }
  2449. }
  2450. }
  2451. void DisplayServerMacOS::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  2452. _THREAD_SAFE_METHOD_
  2453. ERR_FAIL_COND(!windows.has(p_window));
  2454. windows[p_window].instance_id = p_instance;
  2455. }
  2456. ObjectID DisplayServerMacOS::window_get_attached_instance_id(WindowID p_window) const {
  2457. _THREAD_SAFE_METHOD_
  2458. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  2459. return windows[p_window].instance_id;
  2460. }
  2461. void DisplayServerMacOS::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  2462. #if defined(GLES3_ENABLED)
  2463. if (gl_manager_legacy) {
  2464. gl_manager_legacy->window_make_current(p_window_id);
  2465. }
  2466. if (gl_manager_angle) {
  2467. gl_manager_angle->window_make_current(p_window_id);
  2468. }
  2469. #endif
  2470. }
  2471. void DisplayServerMacOS::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  2472. _THREAD_SAFE_METHOD_
  2473. #if defined(GLES3_ENABLED)
  2474. if (gl_manager_angle) {
  2475. gl_manager_angle->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  2476. }
  2477. if (gl_manager_legacy) {
  2478. gl_manager_legacy->set_use_vsync(p_vsync_mode != DisplayServer::VSYNC_DISABLED);
  2479. }
  2480. #endif
  2481. #if defined(RD_ENABLED)
  2482. if (rendering_context) {
  2483. rendering_context->window_set_vsync_mode(p_window, p_vsync_mode);
  2484. }
  2485. #endif
  2486. }
  2487. DisplayServer::VSyncMode DisplayServerMacOS::window_get_vsync_mode(WindowID p_window) const {
  2488. _THREAD_SAFE_METHOD_
  2489. #if defined(GLES3_ENABLED)
  2490. if (gl_manager_angle) {
  2491. return (gl_manager_angle->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2492. }
  2493. if (gl_manager_legacy) {
  2494. return (gl_manager_legacy->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2495. }
  2496. #endif
  2497. #if defined(RD_ENABLED)
  2498. if (rendering_context) {
  2499. return rendering_context->window_get_vsync_mode(p_window);
  2500. }
  2501. #endif
  2502. return DisplayServer::VSYNC_ENABLED;
  2503. }
  2504. Point2i DisplayServerMacOS::ime_get_selection() const {
  2505. return im_selection;
  2506. }
  2507. String DisplayServerMacOS::ime_get_text() const {
  2508. return im_text;
  2509. }
  2510. void DisplayServerMacOS::cursor_update_shape() {
  2511. _THREAD_SAFE_METHOD_
  2512. if (cursors[cursor_shape] != nullptr) {
  2513. [cursors[cursor_shape] set];
  2514. } else {
  2515. switch (cursor_shape) {
  2516. case CURSOR_ARROW:
  2517. [[NSCursor arrowCursor] set];
  2518. break;
  2519. case CURSOR_IBEAM:
  2520. [[NSCursor IBeamCursor] set];
  2521. break;
  2522. case CURSOR_POINTING_HAND:
  2523. [[NSCursor pointingHandCursor] set];
  2524. break;
  2525. case CURSOR_CROSS:
  2526. [[NSCursor crosshairCursor] set];
  2527. break;
  2528. case CURSOR_WAIT:
  2529. [[NSCursor arrowCursor] set];
  2530. break;
  2531. case CURSOR_BUSY:
  2532. [[NSCursor arrowCursor] set];
  2533. break;
  2534. case CURSOR_DRAG:
  2535. [[NSCursor closedHandCursor] set];
  2536. break;
  2537. case CURSOR_CAN_DROP:
  2538. [[NSCursor openHandCursor] set];
  2539. break;
  2540. case CURSOR_FORBIDDEN:
  2541. [[NSCursor operationNotAllowedCursor] set];
  2542. break;
  2543. case CURSOR_VSIZE:
  2544. [_cursor_from_selector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set];
  2545. break;
  2546. case CURSOR_HSIZE:
  2547. [_cursor_from_selector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set];
  2548. break;
  2549. case CURSOR_BDIAGSIZE:
  2550. [_cursor_from_selector(@selector(_windowResizeNorthEastSouthWestCursor)) set];
  2551. break;
  2552. case CURSOR_FDIAGSIZE:
  2553. [_cursor_from_selector(@selector(_windowResizeNorthWestSouthEastCursor)) set];
  2554. break;
  2555. case CURSOR_MOVE:
  2556. [[NSCursor arrowCursor] set];
  2557. break;
  2558. case CURSOR_VSPLIT:
  2559. [[NSCursor resizeUpDownCursor] set];
  2560. break;
  2561. case CURSOR_HSPLIT:
  2562. [[NSCursor resizeLeftRightCursor] set];
  2563. break;
  2564. case CURSOR_HELP:
  2565. [_cursor_from_selector(@selector(_helpCursor)) set];
  2566. break;
  2567. default: {
  2568. }
  2569. }
  2570. }
  2571. }
  2572. void DisplayServerMacOS::cursor_set_shape(CursorShape p_shape) {
  2573. _THREAD_SAFE_METHOD_
  2574. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2575. if (cursor_shape == p_shape) {
  2576. return;
  2577. }
  2578. cursor_shape = p_shape;
  2579. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  2580. return;
  2581. }
  2582. cursor_update_shape();
  2583. }
  2584. DisplayServerMacOS::CursorShape DisplayServerMacOS::cursor_get_shape() const {
  2585. return cursor_shape;
  2586. }
  2587. void DisplayServerMacOS::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2588. _THREAD_SAFE_METHOD_
  2589. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2590. if (p_cursor.is_valid()) {
  2591. HashMap<CursorShape, Vector<Variant>>::Iterator cursor_c = cursors_cache.find(p_shape);
  2592. if (cursor_c) {
  2593. if (cursor_c->value[0] == p_cursor && cursor_c->value[1] == p_hotspot) {
  2594. cursor_set_shape(p_shape);
  2595. return;
  2596. }
  2597. cursors_cache.erase(p_shape);
  2598. }
  2599. Ref<Image> image = _get_cursor_image_from_resource(p_cursor, p_hotspot);
  2600. ERR_FAIL_COND(image.is_null());
  2601. Vector2i texture_size = image->get_size();
  2602. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2603. initWithBitmapDataPlanes:nullptr
  2604. pixelsWide:int(texture_size.width)
  2605. pixelsHigh:int(texture_size.height)
  2606. bitsPerSample:8
  2607. samplesPerPixel:4
  2608. hasAlpha:YES
  2609. isPlanar:NO
  2610. colorSpaceName:NSDeviceRGBColorSpace
  2611. bytesPerRow:int(texture_size.width) * 4
  2612. bitsPerPixel:32];
  2613. ERR_FAIL_NULL(imgrep);
  2614. uint8_t *pixels = [imgrep bitmapData];
  2615. int len = int(texture_size.width * texture_size.height);
  2616. for (int i = 0; i < len; i++) {
  2617. int row_index = floor(i / texture_size.width);
  2618. int column_index = i % int(texture_size.width);
  2619. uint32_t color = image->get_pixel(column_index, row_index).to_argb32();
  2620. uint8_t alpha = (color >> 24) & 0xFF;
  2621. pixels[i * 4 + 0] = ((color >> 16) & 0xFF) * alpha / 255;
  2622. pixels[i * 4 + 1] = ((color >> 8) & 0xFF) * alpha / 255;
  2623. pixels[i * 4 + 2] = ((color) & 0xFF) * alpha / 255;
  2624. pixels[i * 4 + 3] = alpha;
  2625. }
  2626. NSImage *nsimage = [[NSImage alloc] initWithSize:NSMakeSize(texture_size.width, texture_size.height)];
  2627. [nsimage addRepresentation:imgrep];
  2628. NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
  2629. cursors[p_shape] = cursor;
  2630. Vector<Variant> params;
  2631. params.push_back(p_cursor);
  2632. params.push_back(p_hotspot);
  2633. cursors_cache.insert(p_shape, params);
  2634. if (p_shape == cursor_shape) {
  2635. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2636. [cursor set];
  2637. }
  2638. }
  2639. } else {
  2640. // Reset to default system cursor.
  2641. if (cursors[p_shape] != nullptr) {
  2642. cursors[p_shape] = nullptr;
  2643. }
  2644. cursors_cache.erase(p_shape);
  2645. cursor_update_shape();
  2646. }
  2647. }
  2648. bool DisplayServerMacOS::get_swap_cancel_ok() {
  2649. return false;
  2650. }
  2651. int DisplayServerMacOS::keyboard_get_layout_count() const {
  2652. if (keyboard_layout_dirty) {
  2653. _update_keyboard_layouts();
  2654. }
  2655. return kbd_layouts.size();
  2656. }
  2657. void DisplayServerMacOS::keyboard_set_current_layout(int p_index) {
  2658. if (keyboard_layout_dirty) {
  2659. _update_keyboard_layouts();
  2660. }
  2661. ERR_FAIL_INDEX(p_index, kbd_layouts.size());
  2662. NSString *cur_name = [NSString stringWithUTF8String:kbd_layouts[p_index].name.utf8().get_data()];
  2663. NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
  2664. NSArray *list_kbd = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_kbd, false);
  2665. for (NSUInteger i = 0; i < [list_kbd count]; i++) {
  2666. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
  2667. if ([name isEqualToString:cur_name]) {
  2668. TISSelectInputSource((__bridge TISInputSourceRef)[list_kbd objectAtIndex:i]);
  2669. break;
  2670. }
  2671. }
  2672. NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
  2673. NSArray *list_ime = (__bridge NSArray *)TISCreateInputSourceList((__bridge CFDictionaryRef)filter_ime, false);
  2674. for (NSUInteger i = 0; i < [list_ime count]; i++) {
  2675. NSString *name = (__bridge NSString *)TISGetInputSourceProperty((__bridge TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
  2676. if ([name isEqualToString:cur_name]) {
  2677. TISSelectInputSource((__bridge TISInputSourceRef)[list_ime objectAtIndex:i]);
  2678. break;
  2679. }
  2680. }
  2681. }
  2682. int DisplayServerMacOS::keyboard_get_current_layout() const {
  2683. if (keyboard_layout_dirty) {
  2684. _update_keyboard_layouts();
  2685. }
  2686. return current_layout;
  2687. }
  2688. String DisplayServerMacOS::keyboard_get_layout_language(int p_index) const {
  2689. if (keyboard_layout_dirty) {
  2690. _update_keyboard_layouts();
  2691. }
  2692. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2693. return kbd_layouts[p_index].code;
  2694. }
  2695. String DisplayServerMacOS::keyboard_get_layout_name(int p_index) const {
  2696. if (keyboard_layout_dirty) {
  2697. _update_keyboard_layouts();
  2698. }
  2699. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2700. return kbd_layouts[p_index].name;
  2701. }
  2702. Key DisplayServerMacOS::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2703. if (p_keycode == Key::PAUSE || p_keycode == Key::NONE) {
  2704. return p_keycode;
  2705. }
  2706. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2707. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2708. unsigned int macos_keycode = KeyMappingMacOS::unmap_key(keycode_no_mod);
  2709. return (Key)(KeyMappingMacOS::remap_key(macos_keycode, 0, false) | modifiers);
  2710. }
  2711. Key DisplayServerMacOS::keyboard_get_label_from_physical(Key p_keycode) const {
  2712. if (p_keycode == Key::PAUSE || p_keycode == Key::NONE) {
  2713. return p_keycode;
  2714. }
  2715. Key modifiers = p_keycode & KeyModifierMask::MODIFIER_MASK;
  2716. Key keycode_no_mod = p_keycode & KeyModifierMask::CODE_MASK;
  2717. unsigned int macos_keycode = KeyMappingMacOS::unmap_key(keycode_no_mod);
  2718. return (Key)(KeyMappingMacOS::remap_key(macos_keycode, 0, true) | modifiers);
  2719. }
  2720. void DisplayServerMacOS::show_emoji_and_symbol_picker() const {
  2721. [[NSApplication sharedApplication] orderFrontCharacterPalette:nil];
  2722. }
  2723. void DisplayServerMacOS::process_events() {
  2724. ERR_FAIL_COND(!Thread::is_main_thread());
  2725. while (true) {
  2726. NSEvent *event = [NSApp
  2727. nextEventMatchingMask:NSEventMaskAny
  2728. untilDate:[NSDate distantPast]
  2729. inMode:NSDefaultRunLoopMode
  2730. dequeue:YES];
  2731. if (event == nil) {
  2732. break;
  2733. }
  2734. [NSApp sendEvent:event];
  2735. }
  2736. // Process "menu_callback"s.
  2737. while (List<MenuCall>::Element *call_p = deferred_menu_calls.front()) {
  2738. MenuCall call = call_p->get();
  2739. deferred_menu_calls.pop_front(); // Remove before call to avoid infinite loop in case callback is using `process_events` (e.g. EditorProgress).
  2740. Variant ret;
  2741. Callable::CallError ce;
  2742. const Variant *args[1] = { &call.tag };
  2743. call.callback.callp(args, 1, ret, ce);
  2744. if (ce.error != Callable::CallError::CALL_OK) {
  2745. ERR_PRINT(vformat("Failed to execute menu callback: %s.", Variant::get_callable_error_text(call.callback, args, 1, ce)));
  2746. }
  2747. }
  2748. if (!drop_events) {
  2749. _process_key_events();
  2750. Input::get_singleton()->flush_buffered_events();
  2751. }
  2752. _THREAD_SAFE_LOCK_
  2753. for (KeyValue<WindowID, WindowData> &E : windows) {
  2754. WindowData &wd = E.value;
  2755. if (wd.mpass) {
  2756. if (![wd.window_object ignoresMouseEvents]) {
  2757. [wd.window_object setIgnoresMouseEvents:YES];
  2758. }
  2759. } else if (wd.mpath.size() > 0) {
  2760. update_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  2761. if (Geometry2D::is_point_in_polygon(wd.mouse_pos, wd.mpath)) {
  2762. if ([wd.window_object ignoresMouseEvents]) {
  2763. [wd.window_object setIgnoresMouseEvents:NO];
  2764. }
  2765. } else {
  2766. if (![wd.window_object ignoresMouseEvents]) {
  2767. [wd.window_object setIgnoresMouseEvents:YES];
  2768. }
  2769. }
  2770. } else {
  2771. if ([wd.window_object ignoresMouseEvents]) {
  2772. [wd.window_object setIgnoresMouseEvents:NO];
  2773. }
  2774. }
  2775. }
  2776. _THREAD_SAFE_UNLOCK_
  2777. }
  2778. void DisplayServerMacOS::force_process_and_drop_events() {
  2779. ERR_FAIL_COND(!Thread::is_main_thread());
  2780. drop_events = true;
  2781. process_events();
  2782. drop_events = false;
  2783. }
  2784. void DisplayServerMacOS::release_rendering_thread() {
  2785. #if defined(GLES3_ENABLED)
  2786. if (gl_manager_angle) {
  2787. gl_manager_angle->release_current();
  2788. }
  2789. if (gl_manager_legacy) {
  2790. gl_manager_legacy->release_current();
  2791. }
  2792. #endif
  2793. }
  2794. void DisplayServerMacOS::swap_buffers() {
  2795. #if defined(GLES3_ENABLED)
  2796. if (gl_manager_angle) {
  2797. gl_manager_angle->swap_buffers();
  2798. }
  2799. if (gl_manager_legacy) {
  2800. gl_manager_legacy->swap_buffers();
  2801. }
  2802. #endif
  2803. }
  2804. void DisplayServerMacOS::set_native_icon(const String &p_filename) {
  2805. _THREAD_SAFE_METHOD_
  2806. Ref<FileAccess> f = FileAccess::open(p_filename, FileAccess::READ);
  2807. ERR_FAIL_COND(f.is_null());
  2808. Vector<uint8_t> data;
  2809. uint64_t len = f->get_length();
  2810. ERR_FAIL_COND_MSG(len < 8, "Error reading icon data."); // "icns" + 32-bit length
  2811. data.resize(len);
  2812. f->get_buffer((uint8_t *)&data.write[0], len);
  2813. @try {
  2814. NSData *icon_data = [[NSData alloc] initWithBytes:&data.write[0] length:len];
  2815. ERR_FAIL_NULL_MSG(icon_data, "Error reading icon data.");
  2816. NSImage *icon = [[NSImage alloc] initWithData:icon_data];
  2817. ERR_FAIL_NULL_MSG(icon, "Error loading icon.");
  2818. [NSApp setApplicationIconImage:icon];
  2819. } @catch (NSException *exception) {
  2820. ERR_FAIL_MSG("NSException: " + String::utf8([exception reason].UTF8String));
  2821. }
  2822. }
  2823. void DisplayServerMacOS::set_icon(const Ref<Image> &p_icon) {
  2824. _THREAD_SAFE_METHOD_
  2825. if (p_icon.is_valid()) {
  2826. ERR_FAIL_COND(p_icon->get_width() <= 0 || p_icon->get_height() <= 0);
  2827. Ref<Image> img = p_icon->duplicate();
  2828. img->convert(Image::FORMAT_RGBA8);
  2829. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2830. initWithBitmapDataPlanes:nullptr
  2831. pixelsWide:img->get_width()
  2832. pixelsHigh:img->get_height()
  2833. bitsPerSample:8
  2834. samplesPerPixel:4
  2835. hasAlpha:YES
  2836. isPlanar:NO
  2837. colorSpaceName:NSDeviceRGBColorSpace
  2838. bytesPerRow:img->get_width() * 4
  2839. bitsPerPixel:32];
  2840. ERR_FAIL_NULL(imgrep);
  2841. uint8_t *pixels = [imgrep bitmapData];
  2842. int len = img->get_width() * img->get_height();
  2843. const uint8_t *r = img->get_data().ptr();
  2844. /* Premultiply the alpha channel */
  2845. for (int i = 0; i < len; i++) {
  2846. uint8_t alpha = r[i * 4 + 3];
  2847. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  2848. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  2849. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  2850. pixels[i * 4 + 3] = alpha;
  2851. }
  2852. NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())];
  2853. ERR_FAIL_NULL(nsimg);
  2854. [nsimg addRepresentation:imgrep];
  2855. [NSApp setApplicationIconImage:nsimg];
  2856. } else {
  2857. [NSApp setApplicationIconImage:nil];
  2858. }
  2859. }
  2860. DisplayServer::IndicatorID DisplayServerMacOS::create_status_indicator(const Ref<Texture2D> &p_icon, const String &p_tooltip, const Callable &p_callback) {
  2861. NSImage *nsimg = nullptr;
  2862. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  2863. Ref<Image> img = p_icon->get_image();
  2864. img = img->duplicate();
  2865. if (img->is_compressed()) {
  2866. img->decompress();
  2867. }
  2868. nsimg = _convert_to_nsimg(img);
  2869. }
  2870. IndicatorData idat;
  2871. NSStatusItem *item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  2872. idat.item = item;
  2873. idat.delegate = [[GodotStatusItemDelegate alloc] init];
  2874. [idat.delegate setCallback:p_callback];
  2875. item.button.image = nsimg;
  2876. item.button.imagePosition = NSImageOnly;
  2877. item.button.imageScaling = NSImageScaleProportionallyUpOrDown;
  2878. item.button.target = idat.delegate;
  2879. item.button.action = @selector(click:);
  2880. [item.button sendActionOn:(NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown)];
  2881. item.button.toolTip = [NSString stringWithUTF8String:p_tooltip.utf8().get_data()];
  2882. IndicatorID iid = indicator_id_counter++;
  2883. indicators[iid] = idat;
  2884. return iid;
  2885. }
  2886. void DisplayServerMacOS::status_indicator_set_icon(IndicatorID p_id, const Ref<Texture2D> &p_icon) {
  2887. ERR_FAIL_COND(!indicators.has(p_id));
  2888. NSImage *nsimg = nullptr;
  2889. if (p_icon.is_valid() && p_icon->get_width() > 0 && p_icon->get_height() > 0 && p_icon->get_image().is_valid()) {
  2890. Ref<Image> img = p_icon->get_image();
  2891. img = img->duplicate();
  2892. if (img->is_compressed()) {
  2893. img->decompress();
  2894. }
  2895. nsimg = _convert_to_nsimg(img);
  2896. }
  2897. NSStatusItem *item = indicators[p_id].item;
  2898. item.button.image = nsimg;
  2899. }
  2900. void DisplayServerMacOS::status_indicator_set_tooltip(IndicatorID p_id, const String &p_tooltip) {
  2901. ERR_FAIL_COND(!indicators.has(p_id));
  2902. NSStatusItem *item = indicators[p_id].item;
  2903. item.button.toolTip = [NSString stringWithUTF8String:p_tooltip.utf8().get_data()];
  2904. }
  2905. void DisplayServerMacOS::status_indicator_set_menu(IndicatorID p_id, const RID &p_menu_rid) {
  2906. ERR_FAIL_COND(!indicators.has(p_id));
  2907. NSStatusItem *item = indicators[p_id].item;
  2908. if (p_menu_rid.is_valid() && native_menu->has_menu(p_menu_rid)) {
  2909. NSMenu *menu = native_menu->get_native_menu_handle(p_menu_rid);
  2910. item.menu = menu;
  2911. } else {
  2912. item.menu = nullptr;
  2913. }
  2914. }
  2915. void DisplayServerMacOS::status_indicator_set_callback(IndicatorID p_id, const Callable &p_callback) {
  2916. ERR_FAIL_COND(!indicators.has(p_id));
  2917. [indicators[p_id].delegate setCallback:p_callback];
  2918. }
  2919. Rect2 DisplayServerMacOS::status_indicator_get_rect(IndicatorID p_id) const {
  2920. ERR_FAIL_COND_V(!indicators.has(p_id), Rect2());
  2921. NSStatusItem *item = indicators[p_id].item;
  2922. NSView *v = item.button;
  2923. const NSRect contentRect = [v frame];
  2924. const NSRect nsrect = [v.window convertRectToScreen:contentRect];
  2925. Rect2 rect;
  2926. // Return the position of the top-left corner, for macOS the y starts at the bottom.
  2927. const float scale = screen_get_max_scale();
  2928. rect.size.x = nsrect.size.width;
  2929. rect.size.y = nsrect.size.height;
  2930. rect.size *= scale;
  2931. rect.position.x = nsrect.origin.x;
  2932. rect.position.y = (nsrect.origin.y + nsrect.size.height);
  2933. rect.position *= scale;
  2934. rect.position -= _get_screens_origin();
  2935. // macOS native y-coordinate relative to _get_screens_origin() is negative,
  2936. // Godot expects a positive value.
  2937. rect.position.y *= -1;
  2938. return rect;
  2939. }
  2940. void DisplayServerMacOS::delete_status_indicator(IndicatorID p_id) {
  2941. ERR_FAIL_COND(!indicators.has(p_id));
  2942. [[NSStatusBar systemStatusBar] removeStatusItem:indicators[p_id].item];
  2943. indicators.erase(p_id);
  2944. }
  2945. bool DisplayServerMacOS::is_window_transparency_available() const {
  2946. #if defined(RD_ENABLED)
  2947. if (rendering_device && !rendering_device->is_composite_alpha_supported()) {
  2948. return false;
  2949. }
  2950. #endif
  2951. return OS::get_singleton()->is_layered_allowed();
  2952. }
  2953. 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) {
  2954. 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));
  2955. if (r_error != OK) {
  2956. if (p_rendering_driver == "vulkan") {
  2957. String executable_command;
  2958. if (OS::get_singleton()->get_bundle_resource_dir() == OS::get_singleton()->get_executable_path().get_base_dir()) {
  2959. executable_command = vformat("\"%s\" --rendering-driver opengl3", OS::get_singleton()->get_executable_path());
  2960. } else {
  2961. executable_command = vformat("open \"%s\" --args --rendering-driver opengl3", OS::get_singleton()->get_bundle_resource_dir().path_join("../..").simplify_path());
  2962. }
  2963. OS::get_singleton()->alert(
  2964. vformat("Your video card drivers seem not to support the required Vulkan version.\n\n"
  2965. "If possible, consider updating your macOS version or using the OpenGL 3 driver.\n\n"
  2966. "You can enable the OpenGL 3 driver by starting the engine from the\n"
  2967. "command line with the command:\n\n %s",
  2968. executable_command),
  2969. "Unable to initialize Vulkan video driver");
  2970. } else {
  2971. OS::get_singleton()->alert(
  2972. "Your video card drivers seem not to support the required OpenGL 3.3 version.\n\n"
  2973. "If possible, consider updating your macOS version.",
  2974. "Unable to initialize OpenGL video driver");
  2975. }
  2976. }
  2977. return ds;
  2978. }
  2979. Vector<String> DisplayServerMacOS::get_rendering_drivers_func() {
  2980. Vector<String> drivers;
  2981. #if defined(VULKAN_ENABLED)
  2982. drivers.push_back("vulkan");
  2983. #endif
  2984. #if defined(METAL_ENABLED)
  2985. drivers.push_back("metal");
  2986. #endif
  2987. #if defined(GLES3_ENABLED)
  2988. drivers.push_back("opengl3");
  2989. drivers.push_back("opengl3_angle");
  2990. #endif
  2991. return drivers;
  2992. }
  2993. void DisplayServerMacOS::register_macos_driver() {
  2994. register_create_function("macos", create_func, get_rendering_drivers_func);
  2995. }
  2996. DisplayServer::WindowID DisplayServerMacOS::window_get_active_popup() const {
  2997. const List<WindowID>::Element *E = popup_list.back();
  2998. if (E) {
  2999. return E->get();
  3000. } else {
  3001. return INVALID_WINDOW_ID;
  3002. }
  3003. }
  3004. void DisplayServerMacOS::window_set_popup_safe_rect(WindowID p_window, const Rect2i &p_rect) {
  3005. _THREAD_SAFE_METHOD_
  3006. ERR_FAIL_COND(!windows.has(p_window));
  3007. WindowData &wd = windows[p_window];
  3008. wd.parent_safe_rect = p_rect;
  3009. }
  3010. Rect2i DisplayServerMacOS::window_get_popup_safe_rect(WindowID p_window) const {
  3011. _THREAD_SAFE_METHOD_
  3012. ERR_FAIL_COND_V(!windows.has(p_window), Rect2i());
  3013. const WindowData &wd = windows[p_window];
  3014. return wd.parent_safe_rect;
  3015. }
  3016. void DisplayServerMacOS::popup_open(WindowID p_window) {
  3017. _THREAD_SAFE_METHOD_
  3018. bool has_popup_ancestor = false;
  3019. WindowID transient_root = p_window;
  3020. while (true) {
  3021. WindowID parent = windows[transient_root].transient_parent;
  3022. if (parent == INVALID_WINDOW_ID) {
  3023. break;
  3024. } else {
  3025. transient_root = parent;
  3026. if (windows[parent].is_popup) {
  3027. has_popup_ancestor = true;
  3028. break;
  3029. }
  3030. }
  3031. }
  3032. // Detect tooltips and other similar popups that shouldn't block input to their parent.
  3033. bool ignores_input = window_get_flag(WINDOW_FLAG_NO_FOCUS, p_window) && window_get_flag(WINDOW_FLAG_MOUSE_PASSTHROUGH, p_window);
  3034. WindowData &wd = windows[p_window];
  3035. if (wd.is_popup || (has_popup_ancestor && !ignores_input)) {
  3036. bool was_empty = popup_list.is_empty();
  3037. // Find current popup parent, or root popup if new window is not transient.
  3038. List<WindowID>::Element *C = nullptr;
  3039. List<WindowID>::Element *E = popup_list.back();
  3040. while (E) {
  3041. if (wd.transient_parent != E->get() || wd.transient_parent == INVALID_WINDOW_ID) {
  3042. C = E;
  3043. E = E->prev();
  3044. } else {
  3045. break;
  3046. }
  3047. }
  3048. if (C) {
  3049. send_window_event(windows[C->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3050. }
  3051. if (was_empty && popup_list.is_empty()) {
  3052. // Inform OS that popup was opened, to close other native popups.
  3053. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.beginMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3054. }
  3055. time_since_popup = OS::get_singleton()->get_ticks_msec();
  3056. popup_list.push_back(p_window);
  3057. }
  3058. }
  3059. void DisplayServerMacOS::popup_close(WindowID p_window) {
  3060. _THREAD_SAFE_METHOD_
  3061. bool was_empty = popup_list.is_empty();
  3062. List<WindowID>::Element *E = popup_list.find(p_window);
  3063. while (E) {
  3064. List<WindowID>::Element *F = E->next();
  3065. WindowID win_id = E->get();
  3066. popup_list.erase(E);
  3067. if (win_id != p_window) {
  3068. // Only request close on related windows, not this window. We are already processing it.
  3069. send_window_event(windows[win_id], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3070. }
  3071. E = F;
  3072. }
  3073. if (!was_empty && popup_list.is_empty()) {
  3074. // Inform OS that all popups are closed.
  3075. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3076. }
  3077. }
  3078. bool DisplayServerMacOS::mouse_process_popups(bool p_close) {
  3079. _THREAD_SAFE_METHOD_
  3080. bool was_empty = popup_list.is_empty();
  3081. bool closed = false;
  3082. if (p_close) {
  3083. // Close all popups.
  3084. List<WindowID>::Element *E = popup_list.front();
  3085. if (E) {
  3086. send_window_event(windows[E->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3087. closed = true;
  3088. }
  3089. if (!was_empty) {
  3090. // Inform OS that all popups are closed.
  3091. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3092. }
  3093. } else {
  3094. uint64_t delta = OS::get_singleton()->get_ticks_msec() - time_since_popup;
  3095. if (delta < 250) {
  3096. return false;
  3097. }
  3098. Point2i pos = mouse_get_position();
  3099. List<WindowID>::Element *C = nullptr;
  3100. List<WindowID>::Element *E = popup_list.back();
  3101. // Find top popup to close.
  3102. while (E) {
  3103. // Popup window area.
  3104. Rect2i win_rect = Rect2i(window_get_position_with_decorations(E->get()), window_get_size_with_decorations(E->get()));
  3105. // Area of the parent window, which responsible for opening sub-menu.
  3106. Rect2i safe_rect = window_get_popup_safe_rect(E->get());
  3107. if (win_rect.has_point(pos)) {
  3108. break;
  3109. } else if (safe_rect != Rect2i() && safe_rect.has_point(pos)) {
  3110. break;
  3111. } else {
  3112. C = E;
  3113. E = E->prev();
  3114. }
  3115. }
  3116. if (C) {
  3117. send_window_event(windows[C->get()], DisplayServerMacOS::WINDOW_EVENT_CLOSE_REQUEST);
  3118. closed = true;
  3119. }
  3120. if (!was_empty && popup_list.is_empty()) {
  3121. // Inform OS that all popups are closed.
  3122. [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification" object:@"org.godotengine.godot.popup_window"];
  3123. }
  3124. }
  3125. return closed;
  3126. }
  3127. 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) {
  3128. KeyMappingMacOS::initialize();
  3129. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  3130. r_error = OK;
  3131. memset(cursors, 0, sizeof(cursors));
  3132. event_source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  3133. ERR_FAIL_COND(!event_source);
  3134. CGEventSourceSetLocalEventsSuppressionInterval(event_source, 0.0);
  3135. int screen_count = get_screen_count();
  3136. for (int i = 0; i < screen_count; i++) {
  3137. display_max_scale = fmax(display_max_scale, screen_get_scale(i));
  3138. }
  3139. // Register to be notified on keyboard layout changes.
  3140. CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
  3141. nullptr, _keyboard_layout_changed,
  3142. kTISNotifySelectedKeyboardInputSourceChanged, nullptr,
  3143. CFNotificationSuspensionBehaviorDeliverImmediately);
  3144. // Register to be notified on displays arrangement changes.
  3145. CGDisplayRegisterReconfigurationCallback(_displays_arrangement_changed, nullptr);
  3146. // Init TTS
  3147. bool tts_enabled = GLOBAL_GET("audio/general/text_to_speech");
  3148. if (tts_enabled) {
  3149. tts = [[TTS_MacOS alloc] init];
  3150. }
  3151. native_menu = memnew(NativeMenuMacOS);
  3152. NSMenuItem *menu_item;
  3153. NSString *title;
  3154. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  3155. if (nsappname == nil) {
  3156. nsappname = [[NSProcessInfo processInfo] processName];
  3157. }
  3158. menu_delegate = [[GodotMenuDelegate alloc] init];
  3159. // Setup Dock menu.
  3160. NSMenu *dock_menu = [[NSMenu alloc] initWithTitle:@"_dock"];
  3161. [dock_menu setAutoenablesItems:NO];
  3162. [dock_menu setDelegate:menu_delegate];
  3163. // Setup Apple menu.
  3164. NSMenu *application_menu = [[NSMenu alloc] initWithTitle:@""];
  3165. title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
  3166. [application_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
  3167. [application_menu setAutoenablesItems:NO];
  3168. [application_menu setDelegate:menu_delegate];
  3169. [application_menu addItem:[NSMenuItem separatorItem]];
  3170. menu_item = [application_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3171. menu_item.hidden = YES;
  3172. menu_item.tag = MENU_TAG_START;
  3173. menu_item = [application_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3174. menu_item.hidden = YES;
  3175. menu_item.tag = MENU_TAG_END;
  3176. NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
  3177. menu_item = [application_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
  3178. [application_menu setSubmenu:services forItem:menu_item];
  3179. [NSApp setServicesMenu:services];
  3180. [application_menu addItem:[NSMenuItem separatorItem]];
  3181. title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
  3182. [application_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  3183. menu_item = [application_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  3184. [menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
  3185. [application_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
  3186. [application_menu addItem:[NSMenuItem separatorItem]];
  3187. title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
  3188. [application_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  3189. NSMenu *window_menu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Window", nil)];
  3190. [window_menu addItemWithTitle:NSLocalizedString(@"Minimize", nil) action:@selector(performMiniaturize:) keyEquivalent:@"m"];
  3191. [window_menu addItemWithTitle:NSLocalizedString(@"Zoom", nil) action:@selector(performZoom:) keyEquivalent:@""];
  3192. [window_menu addItem:[NSMenuItem separatorItem]];
  3193. [window_menu addItemWithTitle:NSLocalizedString(@"Bring All to Front", nil) action:@selector(bringAllToFront:) keyEquivalent:@""];
  3194. [window_menu addItem:[NSMenuItem separatorItem]];
  3195. menu_item = [window_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3196. menu_item.hidden = YES;
  3197. menu_item.tag = MENU_TAG_START;
  3198. menu_item = [window_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3199. menu_item.hidden = YES;
  3200. menu_item.tag = MENU_TAG_END;
  3201. NSMenu *help_menu = [[NSMenu alloc] initWithTitle:NSLocalizedString(@"Help", nil)];
  3202. menu_item = [help_menu addItemWithTitle:@"_start_" action:nil keyEquivalent:@""];
  3203. menu_item.hidden = YES;
  3204. menu_item.tag = MENU_TAG_START;
  3205. menu_item = [help_menu addItemWithTitle:@"_end_" action:nil keyEquivalent:@""];
  3206. menu_item.hidden = YES;
  3207. menu_item.tag = MENU_TAG_END;
  3208. [NSApp setWindowsMenu:window_menu];
  3209. [NSApp setHelpMenu:help_menu];
  3210. // Add items to the menu bar.
  3211. NSMenu *main_menu = [NSApp mainMenu];
  3212. menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  3213. [main_menu setSubmenu:application_menu forItem:menu_item];
  3214. menu_item = [main_menu addItemWithTitle:NSLocalizedString(@"Window", nil) action:nil keyEquivalent:@""];
  3215. [main_menu setSubmenu:window_menu forItem:menu_item];
  3216. menu_item = [main_menu addItemWithTitle:NSLocalizedString(@"Help", nil) action:nil keyEquivalent:@""];
  3217. [main_menu setSubmenu:help_menu forItem:menu_item];
  3218. [main_menu setAutoenablesItems:NO];
  3219. native_menu->_register_system_menus(main_menu, application_menu, window_menu, help_menu, dock_menu);
  3220. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  3221. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  3222. rendering_driver = p_rendering_driver;
  3223. #if defined(RD_ENABLED)
  3224. #if defined(VULKAN_ENABLED)
  3225. #if defined(__x86_64__)
  3226. bool fallback_to_vulkan = GLOBAL_GET("rendering/rendering_device/fallback_to_vulkan");
  3227. if (!fallback_to_vulkan) {
  3228. WARN_PRINT("Metal is not supported on Intel Macs, switching to Vulkan.");
  3229. }
  3230. // Metal rendering driver not available on Intel.
  3231. if (rendering_driver == "metal") {
  3232. rendering_driver = "vulkan";
  3233. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3234. }
  3235. #endif
  3236. if (rendering_driver == "vulkan") {
  3237. rendering_context = memnew(RenderingContextDriverVulkanMacOS);
  3238. }
  3239. #endif
  3240. #if defined(METAL_ENABLED)
  3241. if (rendering_driver == "metal") {
  3242. rendering_context = memnew(RenderingContextDriverMetal);
  3243. }
  3244. #endif
  3245. if (rendering_context) {
  3246. if (rendering_context->initialize() != OK) {
  3247. memdelete(rendering_context);
  3248. rendering_context = nullptr;
  3249. #if defined(GLES3_ENABLED)
  3250. bool fallback_to_opengl3 = GLOBAL_GET("rendering/rendering_device/fallback_to_opengl3");
  3251. if (fallback_to_opengl3 && rendering_driver != "opengl3") {
  3252. WARN_PRINT("Your device seem not to support MoltenVK or Metal, switching to OpenGL 3.");
  3253. rendering_driver = "opengl3";
  3254. OS::get_singleton()->set_current_rendering_method("gl_compatibility");
  3255. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3256. } else
  3257. #endif
  3258. {
  3259. r_error = ERR_CANT_CREATE;
  3260. ERR_FAIL_MSG("Could not initialize " + rendering_driver);
  3261. }
  3262. }
  3263. }
  3264. #endif
  3265. #if defined(GLES3_ENABLED)
  3266. if (rendering_driver == "opengl3_angle") {
  3267. gl_manager_angle = memnew(GLManagerANGLE_MacOS);
  3268. if (gl_manager_angle->initialize() != OK || gl_manager_angle->open_display(nullptr) != OK) {
  3269. memdelete(gl_manager_angle);
  3270. gl_manager_angle = nullptr;
  3271. bool fallback = GLOBAL_GET("rendering/gl_compatibility/fallback_to_native");
  3272. if (fallback) {
  3273. #ifdef EGL_STATIC
  3274. WARN_PRINT("Your video card drivers seem not to support GLES3 / ANGLE, switching to native OpenGL.");
  3275. #else
  3276. 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.");
  3277. #endif
  3278. rendering_driver = "opengl3";
  3279. OS::get_singleton()->set_current_rendering_driver_name(rendering_driver);
  3280. } else {
  3281. r_error = ERR_UNAVAILABLE;
  3282. ERR_FAIL_MSG("Could not initialize ANGLE OpenGL.");
  3283. }
  3284. }
  3285. }
  3286. if (rendering_driver == "opengl3") {
  3287. gl_manager_legacy = memnew(GLManagerLegacy_MacOS);
  3288. if (gl_manager_legacy->initialize() != OK) {
  3289. memdelete(gl_manager_legacy);
  3290. gl_manager_legacy = nullptr;
  3291. r_error = ERR_UNAVAILABLE;
  3292. ERR_FAIL_MSG("Could not initialize native OpenGL.");
  3293. }
  3294. }
  3295. #endif
  3296. Point2i window_position;
  3297. if (p_position != nullptr) {
  3298. window_position = *p_position;
  3299. } else {
  3300. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  3301. p_screen = SCREEN_PRIMARY;
  3302. }
  3303. Rect2i scr_rect = screen_get_usable_rect(p_screen);
  3304. window_position = scr_rect.position + (scr_rect.size - p_resolution) / 2;
  3305. }
  3306. WindowID main_window = _create_window(p_mode, p_vsync_mode, Rect2i(window_position, p_resolution));
  3307. ERR_FAIL_COND(main_window == INVALID_WINDOW_ID);
  3308. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  3309. if (p_flags & (1 << i)) {
  3310. window_set_flag(WindowFlags(i), true, main_window);
  3311. }
  3312. }
  3313. show_window(MAIN_WINDOW_ID);
  3314. force_process_and_drop_events();
  3315. #if defined(GLES3_ENABLED)
  3316. if (rendering_driver == "opengl3") {
  3317. RasterizerGLES3::make_current(true);
  3318. }
  3319. if (rendering_driver == "opengl3_angle") {
  3320. RasterizerGLES3::make_current(false);
  3321. }
  3322. #endif
  3323. #if defined(RD_ENABLED)
  3324. if (rendering_context) {
  3325. rendering_device = memnew(RenderingDevice);
  3326. rendering_device->initialize(rendering_context, MAIN_WINDOW_ID);
  3327. rendering_device->screen_create(MAIN_WINDOW_ID);
  3328. RendererCompositorRD::make_current();
  3329. }
  3330. #endif
  3331. screen_set_keep_on(GLOBAL_GET("display/window/energy_saving/keep_screen_on"));
  3332. }
  3333. DisplayServerMacOS::~DisplayServerMacOS() {
  3334. if (screen_keep_on_assertion) {
  3335. IOPMAssertionRelease(screen_keep_on_assertion);
  3336. screen_keep_on_assertion = kIOPMNullAssertionID;
  3337. }
  3338. // Destroy all status indicators.
  3339. for (HashMap<IndicatorID, IndicatorData>::Iterator E = indicators.begin(); E; ++E) {
  3340. [[NSStatusBar systemStatusBar] removeStatusItem:E->value.item];
  3341. }
  3342. // Destroy native menu.
  3343. if (native_menu) {
  3344. memdelete(native_menu);
  3345. native_menu = nullptr;
  3346. }
  3347. // Destroy all windows.
  3348. for (HashMap<WindowID, WindowData>::Iterator E = windows.begin(); E;) {
  3349. HashMap<WindowID, WindowData>::Iterator F = E;
  3350. ++E;
  3351. [F->value.window_object setContentView:nil];
  3352. [F->value.window_object close];
  3353. }
  3354. // Destroy drivers.
  3355. #if defined(GLES3_ENABLED)
  3356. if (gl_manager_legacy) {
  3357. memdelete(gl_manager_legacy);
  3358. gl_manager_legacy = nullptr;
  3359. }
  3360. if (gl_manager_angle) {
  3361. memdelete(gl_manager_angle);
  3362. gl_manager_angle = nullptr;
  3363. }
  3364. #endif
  3365. #if defined(RD_ENABLED)
  3366. if (rendering_device) {
  3367. memdelete(rendering_device);
  3368. rendering_device = nullptr;
  3369. }
  3370. if (rendering_context) {
  3371. memdelete(rendering_context);
  3372. rendering_context = nullptr;
  3373. }
  3374. #endif
  3375. CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), nullptr, kTISNotifySelectedKeyboardInputSourceChanged, nullptr);
  3376. CGDisplayRemoveReconfigurationCallback(_displays_arrangement_changed, nullptr);
  3377. cursors_cache.clear();
  3378. }