2
0

display_server_macos.mm 127 KB

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