display_server_macos.mm 140 KB

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