display_server_macos.mm 127 KB

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