display_server_macos.mm 133 KB

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