2
0

display_server_osx.mm 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865
  1. /*************************************************************************/
  2. /* display_server_osx.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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_osx.h"
  31. #include "os_osx.h"
  32. #include "core/io/marshalls.h"
  33. #include "core/math/geometry_2d.h"
  34. #include "core/os/keyboard.h"
  35. #include "main/main.h"
  36. #include "scene/resources/texture.h"
  37. #include <Carbon/Carbon.h>
  38. #include <Cocoa/Cocoa.h>
  39. #include <IOKit/IOCFPlugIn.h>
  40. #include <IOKit/IOKitLib.h>
  41. #include <IOKit/hid/IOHIDKeys.h>
  42. #include <IOKit/hid/IOHIDLib.h>
  43. #if defined(GLES3_ENABLED)
  44. #include "drivers/gles3/rasterizer_gles3.h"
  45. #import <AppKit/NSOpenGLView.h>
  46. #endif
  47. #if defined(VULKAN_ENABLED)
  48. #include "servers/rendering/renderer_rd/renderer_compositor_rd.h"
  49. #include <QuartzCore/CAMetalLayer.h>
  50. #endif
  51. #ifndef NSAppKitVersionNumber10_14
  52. #define NSAppKitVersionNumber10_14 1671
  53. #endif
  54. #define DS_OSX ((DisplayServerOSX *)(DisplayServerOSX::get_singleton()))
  55. static bool ignore_momentum_scroll = false;
  56. static void _get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> r_state) {
  57. r_state->set_shift_pressed((p_osx_state & NSEventModifierFlagShift));
  58. r_state->set_ctrl_pressed((p_osx_state & NSEventModifierFlagControl));
  59. r_state->set_alt_pressed((p_osx_state & NSEventModifierFlagOption));
  60. r_state->set_meta_pressed((p_osx_state & NSEventModifierFlagCommand));
  61. }
  62. static Vector2i _get_mouse_pos(DisplayServerOSX::WindowData &p_wd, NSPoint p_locationInWindow) {
  63. const NSRect contentRect = [p_wd.window_view frame];
  64. const float scale = DS_OSX->screen_get_max_scale();
  65. p_wd.mouse_pos.x = p_locationInWindow.x * scale;
  66. p_wd.mouse_pos.y = (contentRect.size.height - p_locationInWindow.y) * scale;
  67. DS_OSX->last_mouse_pos = p_wd.mouse_pos;
  68. Input::get_singleton()->set_mouse_position(p_wd.mouse_pos);
  69. return p_wd.mouse_pos;
  70. }
  71. static void _push_to_key_event_buffer(const DisplayServerOSX::KeyEvent &p_event) {
  72. Vector<DisplayServerOSX::KeyEvent> &buffer = DS_OSX->key_event_buffer;
  73. if (DS_OSX->key_event_pos >= buffer.size()) {
  74. buffer.resize(1 + DS_OSX->key_event_pos);
  75. }
  76. buffer.write[DS_OSX->key_event_pos++] = p_event;
  77. }
  78. static NSCursor *_cursorFromSelector(SEL selector, SEL fallback = nil) {
  79. if ([NSCursor respondsToSelector:selector]) {
  80. id object = [NSCursor performSelector:selector];
  81. if ([object isKindOfClass:[NSCursor class]]) {
  82. return object;
  83. }
  84. }
  85. if (fallback) {
  86. // Fallback should be a reasonable default, no need to check.
  87. return [NSCursor performSelector:fallback];
  88. }
  89. return [NSCursor arrowCursor];
  90. }
  91. /*************************************************************************/
  92. /* GlobalMenuItem */
  93. /*************************************************************************/
  94. @interface GlobalMenuItem : NSObject {
  95. @public
  96. Callable callback;
  97. Variant meta;
  98. bool checkable;
  99. }
  100. @end
  101. @implementation GlobalMenuItem
  102. @end
  103. /*************************************************************************/
  104. /* GodotWindowDelegate */
  105. /*************************************************************************/
  106. @interface GodotWindowDelegate : NSObject {
  107. DisplayServerOSX::WindowID window_id;
  108. }
  109. - (void)windowWillClose:(NSNotification *)notification;
  110. - (void)setWindowID:(DisplayServerOSX::WindowID)wid;
  111. @end
  112. @implementation GodotWindowDelegate
  113. - (void)setWindowID:(DisplayServerOSX::WindowID)wid {
  114. window_id = wid;
  115. }
  116. - (BOOL)windowShouldClose:(id)sender {
  117. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  118. return YES;
  119. }
  120. DS_OSX->_send_window_event(DS_OSX->windows[window_id], DisplayServerOSX::WINDOW_EVENT_CLOSE_REQUEST);
  121. return NO;
  122. }
  123. - (void)windowWillClose:(NSNotification *)notification {
  124. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  125. return;
  126. }
  127. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  128. while (wd.transient_children.size()) {
  129. DS_OSX->window_set_transient(wd.transient_children.front()->get(), DisplayServerOSX::INVALID_WINDOW_ID);
  130. }
  131. if (wd.transient_parent != DisplayServerOSX::INVALID_WINDOW_ID) {
  132. DisplayServerOSX::WindowData &pwd = DS_OSX->windows[wd.transient_parent];
  133. [pwd.window_object makeKeyAndOrderFront:nil]; // Move focus back to parent.
  134. DS_OSX->window_set_transient(window_id, DisplayServerOSX::INVALID_WINDOW_ID);
  135. } else if ((window_id != DisplayServerOSX::MAIN_WINDOW_ID) && (DS_OSX->windows.size() == 1)) {
  136. DisplayServerOSX::WindowData &pwd = DS_OSX->windows[DisplayServerOSX::MAIN_WINDOW_ID];
  137. [pwd.window_object makeKeyAndOrderFront:nil]; // Move focus back to main window if there is no parent or other windows left.
  138. }
  139. #if defined(GLES3_ENABLED)
  140. if (DS_OSX->rendering_driver == "opengl3") {
  141. DS_OSX->gl_manager->window_destroy(window_id);
  142. }
  143. #endif
  144. #ifdef VULKAN_ENABLED
  145. if (DS_OSX->rendering_driver == "vulkan") {
  146. DS_OSX->context_vulkan->window_destroy(window_id);
  147. }
  148. #endif
  149. DS_OSX->windows.erase(window_id);
  150. }
  151. - (void)windowDidEnterFullScreen:(NSNotification *)notification {
  152. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  153. return;
  154. }
  155. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  156. wd.fullscreen = true;
  157. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  158. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  159. // Force window resize event.
  160. [self windowDidResize:notification];
  161. }
  162. - (void)windowDidExitFullScreen:(NSNotification *)notification {
  163. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  164. return;
  165. }
  166. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  167. wd.fullscreen = false;
  168. const float scale = DS_OSX->screen_get_max_scale();
  169. if (wd.min_size != Size2i()) {
  170. Size2i size = wd.min_size / scale;
  171. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  172. }
  173. if (wd.max_size != Size2i()) {
  174. Size2i size = wd.max_size / scale;
  175. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  176. }
  177. if (wd.resize_disabled) {
  178. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  179. }
  180. if (wd.on_top) {
  181. [wd.window_object setLevel:NSFloatingWindowLevel];
  182. }
  183. // Force window resize event.
  184. [self windowDidResize:notification];
  185. }
  186. - (void)windowDidChangeBackingProperties:(NSNotification *)notification {
  187. if (!DisplayServerOSX::get_singleton()) {
  188. return;
  189. }
  190. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  191. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  192. CGFloat newBackingScaleFactor = [wd.window_object backingScaleFactor];
  193. CGFloat oldBackingScaleFactor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
  194. if (newBackingScaleFactor != oldBackingScaleFactor) {
  195. //Set new display scale and window size
  196. const float scale = DS_OSX->screen_get_max_scale();
  197. const NSRect contentRect = [wd.window_view frame];
  198. wd.size.width = contentRect.size.width * scale;
  199. wd.size.height = contentRect.size.height * scale;
  200. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_DPI_CHANGE);
  201. CALayer *layer = [wd.window_view layer];
  202. if (layer) {
  203. layer.contentsScale = scale;
  204. }
  205. //Force window resize event
  206. [self windowDidResize:notification];
  207. }
  208. }
  209. - (void)windowDidResize:(NSNotification *)notification {
  210. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  211. return;
  212. }
  213. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  214. const NSRect contentRect = [wd.window_view frame];
  215. const float scale = DS_OSX->screen_get_max_scale();
  216. wd.size.width = contentRect.size.width * scale;
  217. wd.size.height = contentRect.size.height * scale;
  218. CALayer *layer = [wd.window_view layer];
  219. if (layer) {
  220. layer.contentsScale = scale;
  221. }
  222. #if defined(GLES3_ENABLED)
  223. if (DS_OSX->rendering_driver == "opengl3") {
  224. DS_OSX->gl_manager->window_resize(window_id, wd.size.width, wd.size.height);
  225. }
  226. #endif
  227. #if defined(VULKAN_ENABLED)
  228. if (DS_OSX->rendering_driver == "vulkan") {
  229. DS_OSX->context_vulkan->window_resize(window_id, wd.size.width, wd.size.height);
  230. }
  231. #endif
  232. if (!wd.rect_changed_callback.is_null()) {
  233. Variant size = Rect2i(DS_OSX->window_get_position(window_id), DS_OSX->window_get_size(window_id));
  234. Variant *sizep = &size;
  235. Variant ret;
  236. Callable::CallError ce;
  237. wd.rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
  238. }
  239. }
  240. - (void)windowDidMove:(NSNotification *)notification {
  241. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  242. return;
  243. }
  244. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  245. DS_OSX->_release_pressed_events();
  246. if (!wd.rect_changed_callback.is_null()) {
  247. Variant size = Rect2i(DS_OSX->window_get_position(window_id), DS_OSX->window_get_size(window_id));
  248. Variant *sizep = &size;
  249. Variant ret;
  250. Callable::CallError ce;
  251. wd.rect_changed_callback.call((const Variant **)&sizep, 1, ret, ce);
  252. }
  253. }
  254. - (void)windowDidBecomeKey:(NSNotification *)notification {
  255. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  256. return;
  257. }
  258. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  259. if (DS_OSX->mouse_mode == DisplayServer::MOUSE_MODE_CAPTURED) {
  260. const NSRect contentRect = [wd.window_view frame];
  261. NSRect pointInWindowRect = NSMakeRect(contentRect.size.width / 2, contentRect.size.height / 2, 0, 0);
  262. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  263. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  264. CGWarpMouseCursorPosition(lMouseWarpPos);
  265. } else {
  266. _get_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  267. Input::get_singleton()->set_mouse_position(wd.mouse_pos);
  268. }
  269. DS_OSX->window_focused = true;
  270. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_IN);
  271. }
  272. - (void)windowDidResignKey:(NSNotification *)notification {
  273. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  274. return;
  275. }
  276. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  277. DS_OSX->window_focused = false;
  278. DS_OSX->_release_pressed_events();
  279. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT);
  280. }
  281. - (void)windowDidMiniaturize:(NSNotification *)notification {
  282. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  283. return;
  284. }
  285. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  286. DS_OSX->window_focused = false;
  287. DS_OSX->_release_pressed_events();
  288. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_OUT);
  289. }
  290. - (void)windowDidDeminiaturize:(NSNotification *)notification {
  291. if (!DS_OSX || !DS_OSX->windows.has(window_id)) {
  292. return;
  293. }
  294. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  295. DS_OSX->window_focused = true;
  296. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_FOCUS_IN);
  297. }
  298. @end
  299. /*************************************************************************/
  300. /* GodotContentView */
  301. /*************************************************************************/
  302. #if defined(GLES3_ENABLED)
  303. @interface GodotContentView : NSOpenGLView <NSTextInputClient> {
  304. #else
  305. @interface GodotContentView : NSView <NSTextInputClient> {
  306. #endif
  307. DisplayServerOSX::WindowID window_id;
  308. NSTrackingArea *trackingArea;
  309. NSMutableAttributedString *markedText;
  310. bool imeInputEventInProgress;
  311. }
  312. - (void)cancelComposition;
  313. - (CALayer *)makeBackingLayer;
  314. - (BOOL)wantsUpdateLayer;
  315. - (void)updateLayer;
  316. - (void)setWindowID:(DisplayServerOSX::WindowID)wid;
  317. @end
  318. @implementation GodotContentView
  319. - (void)setWindowID:(DisplayServerOSX::WindowID)wid {
  320. window_id = wid;
  321. }
  322. + (void)initialize {
  323. if (self == [GodotContentView class]) {
  324. // nothing left to do here at the moment..
  325. }
  326. }
  327. - (CALayer *)makeBackingLayer {
  328. #if defined(VULKAN_ENABLED)
  329. if (DS_OSX->rendering_driver == "vulkan") {
  330. CALayer *layer = [[CAMetalLayer class] layer];
  331. return layer;
  332. }
  333. #endif
  334. return [super makeBackingLayer];
  335. }
  336. - (void)updateLayer {
  337. #if defined(GLES3_ENABLED)
  338. if (DS_OSX->rendering_driver == "opengl3") {
  339. DS_OSX->gl_manager->window_update(window_id);
  340. }
  341. #endif
  342. #if defined(VULKAN_ENABLED)
  343. if (DS_OSX->rendering_driver == "vulkan") {
  344. [super updateLayer];
  345. }
  346. #endif
  347. }
  348. - (BOOL)wantsUpdateLayer {
  349. return YES;
  350. }
  351. - (id)init {
  352. self = [super init];
  353. trackingArea = nil;
  354. imeInputEventInProgress = false;
  355. [self updateTrackingAreas];
  356. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
  357. [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
  358. #else
  359. [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
  360. #endif
  361. markedText = [[NSMutableAttributedString alloc] init];
  362. return self;
  363. }
  364. - (void)dealloc {
  365. [trackingArea release];
  366. [markedText release];
  367. [super dealloc];
  368. }
  369. static const NSRange kEmptyRange = { NSNotFound, 0 };
  370. - (BOOL)hasMarkedText {
  371. return (markedText.length > 0);
  372. }
  373. - (NSRange)markedRange {
  374. return NSMakeRange(0, markedText.length);
  375. }
  376. - (NSRange)selectedRange {
  377. return kEmptyRange;
  378. }
  379. - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
  380. if ([aString isKindOfClass:[NSAttributedString class]]) {
  381. [markedText initWithAttributedString:aString];
  382. } else {
  383. [markedText initWithString:aString];
  384. }
  385. if (markedText.length == 0) {
  386. [self unmarkText];
  387. return;
  388. }
  389. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  390. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  391. if (wd.im_active) {
  392. imeInputEventInProgress = true;
  393. DS_OSX->im_text.parse_utf8([[markedText mutableString] UTF8String]);
  394. DS_OSX->im_selection = Point2i(selectedRange.location, selectedRange.length);
  395. OS_OSX::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  396. }
  397. }
  398. - (void)doCommandBySelector:(SEL)aSelector {
  399. if ([self respondsToSelector:aSelector]) {
  400. [self performSelector:aSelector];
  401. }
  402. }
  403. - (void)unmarkText {
  404. imeInputEventInProgress = false;
  405. [[markedText mutableString] setString:@""];
  406. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  407. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  408. if (wd.im_active) {
  409. DS_OSX->im_text = String();
  410. DS_OSX->im_selection = Point2i();
  411. OS_OSX::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_OS_IME_UPDATE);
  412. }
  413. }
  414. - (NSArray *)validAttributesForMarkedText {
  415. return [NSArray array];
  416. }
  417. - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  418. return nil;
  419. }
  420. - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
  421. return 0;
  422. }
  423. - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  424. ERR_FAIL_COND_V(!DS_OSX->windows.has(window_id), NSMakeRect(0, 0, 0, 0));
  425. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  426. const NSRect contentRect = [wd.window_view frame];
  427. const float scale = DS_OSX->screen_get_max_scale();
  428. NSRect pointInWindowRect = NSMakeRect(wd.im_position.x / scale, contentRect.size.height - (wd.im_position.y / scale) - 1, 0, 0);
  429. NSPoint pointOnScreen = [wd.window_object convertRectToScreen:pointInWindowRect].origin;
  430. return NSMakeRect(pointOnScreen.x, pointOnScreen.y, 0, 0);
  431. }
  432. - (void)cancelComposition {
  433. [self unmarkText];
  434. NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
  435. [currentInputContext discardMarkedText];
  436. }
  437. - (void)insertText:(id)aString {
  438. [self insertText:aString replacementRange:NSMakeRange(0, 0)];
  439. }
  440. - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
  441. NSEvent *event = [NSApp currentEvent];
  442. NSString *characters;
  443. if ([aString isKindOfClass:[NSAttributedString class]]) {
  444. characters = [aString string];
  445. } else {
  446. characters = (NSString *)aString;
  447. }
  448. NSCharacterSet *ctrlChars = [NSCharacterSet controlCharacterSet];
  449. NSCharacterSet *wsnlChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
  450. if ([characters rangeOfCharacterFromSet:ctrlChars].length && [characters rangeOfCharacterFromSet:wsnlChars].length == 0) {
  451. NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
  452. [currentInputContext discardMarkedText];
  453. [self cancelComposition];
  454. return;
  455. }
  456. Char16String text;
  457. text.resize([characters length] + 1);
  458. [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
  459. String u32text;
  460. u32text.parse_utf16(text.ptr(), text.length());
  461. for (int i = 0; i < u32text.length(); i++) {
  462. const char32_t codepoint = u32text[i];
  463. if ((codepoint & 0xFF00) == 0xF700) {
  464. continue;
  465. }
  466. DisplayServerOSX::KeyEvent ke;
  467. ke.window_id = window_id;
  468. ke.osx_state = [event modifierFlags];
  469. ke.pressed = true;
  470. ke.echo = false;
  471. ke.raw = false; // IME input event
  472. ke.keycode = KEY_NONE;
  473. ke.physical_keycode = 0;
  474. ke.unicode = codepoint;
  475. _push_to_key_event_buffer(ke);
  476. }
  477. [self cancelComposition];
  478. }
  479. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  480. return NSDragOperationCopy;
  481. }
  482. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  483. return NSDragOperationCopy;
  484. }
  485. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  486. ERR_FAIL_COND_V(!DS_OSX->windows.has(window_id), NO);
  487. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  488. if (!wd.drop_files_callback.is_null()) {
  489. Vector<String> files;
  490. NSPasteboard *pboard = [sender draggingPasteboard];
  491. #if MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
  492. NSArray *items = pboard.pasteboardItems;
  493. for (NSPasteboardItem *item in items) {
  494. NSString *path = [item stringForType:NSPasteboardTypeFileURL];
  495. NSString *ns = [NSURL URLWithString:path].path;
  496. char *utfs = strdup([ns UTF8String]);
  497. String ret;
  498. ret.parse_utf8(utfs);
  499. free(utfs);
  500. files.push_back(ret);
  501. }
  502. #else
  503. NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
  504. for (NSString *ns in filenames) {
  505. char *utfs = strdup([ns UTF8String]);
  506. String ret;
  507. ret.parse_utf8(utfs);
  508. free(utfs);
  509. files.push_back(ret);
  510. }
  511. #endif
  512. Variant v = files;
  513. Variant *vp = &v;
  514. Variant ret;
  515. Callable::CallError ce;
  516. wd.drop_files_callback.call((const Variant **)&vp, 1, ret, ce);
  517. }
  518. return NO;
  519. }
  520. - (BOOL)isOpaque {
  521. return YES;
  522. }
  523. - (BOOL)canBecomeKeyView {
  524. if (DS_OSX->windows.has(window_id)) {
  525. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  526. if (wd.no_focus) {
  527. return NO;
  528. }
  529. }
  530. return YES;
  531. }
  532. - (BOOL)acceptsFirstResponder {
  533. return YES;
  534. }
  535. - (void)cursorUpdate:(NSEvent *)event {
  536. DisplayServer::CursorShape p_shape = DS_OSX->cursor_shape;
  537. DS_OSX->cursor_shape = DisplayServer::CURSOR_MAX;
  538. DS_OSX->cursor_set_shape(p_shape);
  539. }
  540. static void _mouseDownEvent(DisplayServer::WindowID window_id, NSEvent *event, MouseButton index, MouseButton mask, bool pressed) {
  541. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  542. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  543. if (pressed) {
  544. DS_OSX->last_button_state |= mask;
  545. } else {
  546. DS_OSX->last_button_state &= (MouseButton)~mask;
  547. }
  548. Ref<InputEventMouseButton> mb;
  549. mb.instantiate();
  550. mb->set_window_id(window_id);
  551. const Vector2 pos = _get_mouse_pos(wd, [event locationInWindow]);
  552. _get_key_modifier_state([event modifierFlags], mb);
  553. mb->set_button_index(index);
  554. mb->set_pressed(pressed);
  555. mb->set_position(pos);
  556. mb->set_global_position(pos);
  557. mb->set_button_mask(DS_OSX->last_button_state);
  558. if (index == MOUSE_BUTTON_LEFT && pressed) {
  559. mb->set_double_click([event clickCount] == 2);
  560. }
  561. Input::get_singleton()->parse_input_event(mb);
  562. }
  563. - (void)mouseDown:(NSEvent *)event {
  564. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  565. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  566. if (([event modifierFlags] & NSEventModifierFlagControl)) {
  567. wd.mouse_down_control = true;
  568. _mouseDownEvent(window_id, event, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MASK_RIGHT, true);
  569. } else {
  570. wd.mouse_down_control = false;
  571. _mouseDownEvent(window_id, event, MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MASK_LEFT, true);
  572. }
  573. }
  574. - (void)mouseDragged:(NSEvent *)event {
  575. [self mouseMoved:event];
  576. }
  577. - (void)mouseUp:(NSEvent *)event {
  578. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  579. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  580. if (wd.mouse_down_control) {
  581. _mouseDownEvent(window_id, event, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MASK_RIGHT, false);
  582. } else {
  583. _mouseDownEvent(window_id, event, MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MASK_LEFT, false);
  584. }
  585. }
  586. - (void)mouseMoved:(NSEvent *)event {
  587. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  588. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  589. NSPoint delta = NSMakePoint([event deltaX], [event deltaY]);
  590. NSPoint mpos = [event locationInWindow];
  591. if (DS_OSX->ignore_warp) {
  592. // Discard late events, before warp
  593. if (([event timestamp]) < DS_OSX->last_warp) {
  594. return;
  595. }
  596. DS_OSX->ignore_warp = false;
  597. return;
  598. }
  599. if (DS_OSX->mouse_mode == DisplayServer::MOUSE_MODE_CONFINED || DS_OSX->mouse_mode == DisplayServer::MOUSE_MODE_CONFINED_HIDDEN) {
  600. // Discard late events
  601. if (([event timestamp]) < DS_OSX->last_warp) {
  602. return;
  603. }
  604. // Warp affects next event delta, subtract previous warp deltas
  605. List<DisplayServerOSX::WarpEvent>::Element *F = DS_OSX->warp_events.front();
  606. while (F) {
  607. if (F->get().timestamp < [event timestamp]) {
  608. List<DisplayServerOSX::WarpEvent>::Element *E = F;
  609. delta.x -= E->get().delta.x;
  610. delta.y -= E->get().delta.y;
  611. F = F->next();
  612. DS_OSX->warp_events.erase(E);
  613. } else {
  614. F = F->next();
  615. }
  616. }
  617. // Confine mouse position to the window, and update delta
  618. NSRect frame = [wd.window_object frame];
  619. NSPoint conf_pos = mpos;
  620. conf_pos.x = CLAMP(conf_pos.x + delta.x, 0.f, frame.size.width);
  621. conf_pos.y = CLAMP(conf_pos.y - delta.y, 0.f, frame.size.height);
  622. delta.x = conf_pos.x - mpos.x;
  623. delta.y = mpos.y - conf_pos.y;
  624. mpos = conf_pos;
  625. // Move mouse cursor
  626. NSRect pointInWindowRect = NSMakeRect(conf_pos.x, conf_pos.y, 0, 0);
  627. conf_pos = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  628. conf_pos.y = CGDisplayBounds(CGMainDisplayID()).size.height - conf_pos.y;
  629. CGWarpMouseCursorPosition(conf_pos);
  630. // Save warp data
  631. DS_OSX->last_warp = [[NSProcessInfo processInfo] systemUptime];
  632. DisplayServerOSX::WarpEvent ev;
  633. ev.timestamp = DS_OSX->last_warp;
  634. ev.delta = delta;
  635. DS_OSX->warp_events.push_back(ev);
  636. }
  637. Ref<InputEventMouseMotion> mm;
  638. mm.instantiate();
  639. mm->set_window_id(window_id);
  640. mm->set_button_mask(DS_OSX->last_button_state);
  641. const Vector2i pos = _get_mouse_pos(wd, mpos);
  642. mm->set_position(pos);
  643. mm->set_pressure([event pressure]);
  644. if ([event subtype] == NSEventSubtypeTabletPoint) {
  645. const NSPoint p = [event tilt];
  646. mm->set_tilt(Vector2(p.x, p.y));
  647. }
  648. mm->set_global_position(pos);
  649. mm->set_speed(Input::get_singleton()->get_last_mouse_speed());
  650. const Vector2i relativeMotion = Vector2i(delta.x, delta.y) * DS_OSX->screen_get_max_scale();
  651. mm->set_relative(relativeMotion);
  652. _get_key_modifier_state([event modifierFlags], mm);
  653. Input::get_singleton()->set_mouse_position(wd.mouse_pos);
  654. Input::get_singleton()->parse_input_event(mm);
  655. }
  656. - (void)rightMouseDown:(NSEvent *)event {
  657. _mouseDownEvent(window_id, event, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MASK_RIGHT, true);
  658. }
  659. - (void)rightMouseDragged:(NSEvent *)event {
  660. [self mouseMoved:event];
  661. }
  662. - (void)rightMouseUp:(NSEvent *)event {
  663. _mouseDownEvent(window_id, event, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_MASK_RIGHT, false);
  664. }
  665. - (void)otherMouseDown:(NSEvent *)event {
  666. if ((int)[event buttonNumber] == 2) {
  667. _mouseDownEvent(window_id, event, MOUSE_BUTTON_MIDDLE, MOUSE_BUTTON_MASK_MIDDLE, true);
  668. } else if ((int)[event buttonNumber] == 3) {
  669. _mouseDownEvent(window_id, event, MOUSE_BUTTON_XBUTTON1, MOUSE_BUTTON_MASK_XBUTTON1, true);
  670. } else if ((int)[event buttonNumber] == 4) {
  671. _mouseDownEvent(window_id, event, MOUSE_BUTTON_XBUTTON2, MOUSE_BUTTON_MASK_XBUTTON2, true);
  672. } else {
  673. return;
  674. }
  675. }
  676. - (void)otherMouseDragged:(NSEvent *)event {
  677. [self mouseMoved:event];
  678. }
  679. - (void)otherMouseUp:(NSEvent *)event {
  680. if ((int)[event buttonNumber] == 2) {
  681. _mouseDownEvent(window_id, event, MOUSE_BUTTON_MIDDLE, MOUSE_BUTTON_MASK_MIDDLE, false);
  682. } else if ((int)[event buttonNumber] == 3) {
  683. _mouseDownEvent(window_id, event, MOUSE_BUTTON_XBUTTON1, MOUSE_BUTTON_MASK_XBUTTON1, false);
  684. } else if ((int)[event buttonNumber] == 4) {
  685. _mouseDownEvent(window_id, event, MOUSE_BUTTON_XBUTTON2, MOUSE_BUTTON_MASK_XBUTTON2, false);
  686. } else {
  687. return;
  688. }
  689. }
  690. - (void)mouseExited:(NSEvent *)event {
  691. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  692. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  693. if (DS_OSX->mouse_mode != DisplayServer::MOUSE_MODE_CAPTURED) {
  694. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_MOUSE_EXIT);
  695. }
  696. }
  697. - (void)mouseEntered:(NSEvent *)event {
  698. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  699. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  700. if (DS_OSX->mouse_mode != DisplayServer::MOUSE_MODE_CAPTURED) {
  701. DS_OSX->_send_window_event(wd, DisplayServerOSX::WINDOW_EVENT_MOUSE_ENTER);
  702. }
  703. DisplayServer::CursorShape p_shape = DS_OSX->cursor_shape;
  704. DS_OSX->cursor_shape = DisplayServer::CURSOR_MAX;
  705. DS_OSX->cursor_set_shape(p_shape);
  706. }
  707. - (void)magnifyWithEvent:(NSEvent *)event {
  708. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  709. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  710. Ref<InputEventMagnifyGesture> ev;
  711. ev.instantiate();
  712. ev->set_window_id(window_id);
  713. _get_key_modifier_state([event modifierFlags], ev);
  714. ev->set_position(_get_mouse_pos(wd, [event locationInWindow]));
  715. ev->set_factor([event magnification] + 1.0);
  716. Input::get_singleton()->parse_input_event(ev);
  717. }
  718. - (void)viewDidChangeBackingProperties {
  719. // nothing left to do here
  720. }
  721. - (void)updateTrackingAreas {
  722. if (trackingArea != nil) {
  723. [self removeTrackingArea:trackingArea];
  724. [trackingArea release];
  725. }
  726. NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited | NSTrackingActiveInKeyWindow | NSTrackingCursorUpdate | NSTrackingInVisibleRect;
  727. trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
  728. [self addTrackingArea:trackingArea];
  729. [super updateTrackingAreas];
  730. }
  731. static bool isNumpadKey(unsigned int key) {
  732. static const unsigned int table[] = {
  733. 0x41, /* kVK_ANSI_KeypadDecimal */
  734. 0x43, /* kVK_ANSI_KeypadMultiply */
  735. 0x45, /* kVK_ANSI_KeypadPlus */
  736. 0x47, /* kVK_ANSI_KeypadClear */
  737. 0x4b, /* kVK_ANSI_KeypadDivide */
  738. 0x4c, /* kVK_ANSI_KeypadEnter */
  739. 0x4e, /* kVK_ANSI_KeypadMinus */
  740. 0x51, /* kVK_ANSI_KeypadEquals */
  741. 0x52, /* kVK_ANSI_Keypad0 */
  742. 0x53, /* kVK_ANSI_Keypad1 */
  743. 0x54, /* kVK_ANSI_Keypad2 */
  744. 0x55, /* kVK_ANSI_Keypad3 */
  745. 0x56, /* kVK_ANSI_Keypad4 */
  746. 0x57, /* kVK_ANSI_Keypad5 */
  747. 0x58, /* kVK_ANSI_Keypad6 */
  748. 0x59, /* kVK_ANSI_Keypad7 */
  749. 0x5b, /* kVK_ANSI_Keypad8 */
  750. 0x5c, /* kVK_ANSI_Keypad9 */
  751. 0x5f, /* kVK_JIS_KeypadComma */
  752. 0x00
  753. };
  754. for (int i = 0; table[i] != 0; i++) {
  755. if (key == table[i]) {
  756. return true;
  757. }
  758. }
  759. return false;
  760. }
  761. // Keyboard symbol translation table
  762. static const Key _osx_to_godot_table[128] = {
  763. /* 00 */ KEY_A,
  764. /* 01 */ KEY_S,
  765. /* 02 */ KEY_D,
  766. /* 03 */ KEY_F,
  767. /* 04 */ KEY_H,
  768. /* 05 */ KEY_G,
  769. /* 06 */ KEY_Z,
  770. /* 07 */ KEY_X,
  771. /* 08 */ KEY_C,
  772. /* 09 */ KEY_V,
  773. /* 0a */ KEY_SECTION, /* ISO Section */
  774. /* 0b */ KEY_B,
  775. /* 0c */ KEY_Q,
  776. /* 0d */ KEY_W,
  777. /* 0e */ KEY_E,
  778. /* 0f */ KEY_R,
  779. /* 10 */ KEY_Y,
  780. /* 11 */ KEY_T,
  781. /* 12 */ KEY_1,
  782. /* 13 */ KEY_2,
  783. /* 14 */ KEY_3,
  784. /* 15 */ KEY_4,
  785. /* 16 */ KEY_6,
  786. /* 17 */ KEY_5,
  787. /* 18 */ KEY_EQUAL,
  788. /* 19 */ KEY_9,
  789. /* 1a */ KEY_7,
  790. /* 1b */ KEY_MINUS,
  791. /* 1c */ KEY_8,
  792. /* 1d */ KEY_0,
  793. /* 1e */ KEY_BRACERIGHT,
  794. /* 1f */ KEY_O,
  795. /* 20 */ KEY_U,
  796. /* 21 */ KEY_BRACELEFT,
  797. /* 22 */ KEY_I,
  798. /* 23 */ KEY_P,
  799. /* 24 */ KEY_ENTER,
  800. /* 25 */ KEY_L,
  801. /* 26 */ KEY_J,
  802. /* 27 */ KEY_APOSTROPHE,
  803. /* 28 */ KEY_K,
  804. /* 29 */ KEY_SEMICOLON,
  805. /* 2a */ KEY_BACKSLASH,
  806. /* 2b */ KEY_COMMA,
  807. /* 2c */ KEY_SLASH,
  808. /* 2d */ KEY_N,
  809. /* 2e */ KEY_M,
  810. /* 2f */ KEY_PERIOD,
  811. /* 30 */ KEY_TAB,
  812. /* 31 */ KEY_SPACE,
  813. /* 32 */ KEY_QUOTELEFT,
  814. /* 33 */ KEY_BACKSPACE,
  815. /* 34 */ KEY_UNKNOWN,
  816. /* 35 */ KEY_ESCAPE,
  817. /* 36 */ KEY_META,
  818. /* 37 */ KEY_META,
  819. /* 38 */ KEY_SHIFT,
  820. /* 39 */ KEY_CAPSLOCK,
  821. /* 3a */ KEY_ALT,
  822. /* 3b */ KEY_CTRL,
  823. /* 3c */ KEY_SHIFT,
  824. /* 3d */ KEY_ALT,
  825. /* 3e */ KEY_CTRL,
  826. /* 3f */ KEY_UNKNOWN, /* Function */
  827. /* 40 */ KEY_UNKNOWN, /* F17 */
  828. /* 41 */ KEY_KP_PERIOD,
  829. /* 42 */ KEY_UNKNOWN,
  830. /* 43 */ KEY_KP_MULTIPLY,
  831. /* 44 */ KEY_UNKNOWN,
  832. /* 45 */ KEY_KP_ADD,
  833. /* 46 */ KEY_UNKNOWN,
  834. /* 47 */ KEY_NUMLOCK, /* Really KeypadClear... */
  835. /* 48 */ KEY_VOLUMEUP, /* VolumeUp */
  836. /* 49 */ KEY_VOLUMEDOWN, /* VolumeDown */
  837. /* 4a */ KEY_VOLUMEMUTE, /* Mute */
  838. /* 4b */ KEY_KP_DIVIDE,
  839. /* 4c */ KEY_KP_ENTER,
  840. /* 4d */ KEY_UNKNOWN,
  841. /* 4e */ KEY_KP_SUBTRACT,
  842. /* 4f */ KEY_UNKNOWN, /* F18 */
  843. /* 50 */ KEY_UNKNOWN, /* F19 */
  844. /* 51 */ KEY_EQUAL, /* KeypadEqual */
  845. /* 52 */ KEY_KP_0,
  846. /* 53 */ KEY_KP_1,
  847. /* 54 */ KEY_KP_2,
  848. /* 55 */ KEY_KP_3,
  849. /* 56 */ KEY_KP_4,
  850. /* 57 */ KEY_KP_5,
  851. /* 58 */ KEY_KP_6,
  852. /* 59 */ KEY_KP_7,
  853. /* 5a */ KEY_UNKNOWN, /* F20 */
  854. /* 5b */ KEY_KP_8,
  855. /* 5c */ KEY_KP_9,
  856. /* 5d */ KEY_YEN, /* JIS Yen */
  857. /* 5e */ KEY_UNDERSCORE, /* JIS Underscore */
  858. /* 5f */ KEY_COMMA, /* JIS KeypadComma */
  859. /* 60 */ KEY_F5,
  860. /* 61 */ KEY_F6,
  861. /* 62 */ KEY_F7,
  862. /* 63 */ KEY_F3,
  863. /* 64 */ KEY_F8,
  864. /* 65 */ KEY_F9,
  865. /* 66 */ KEY_UNKNOWN, /* JIS Eisu */
  866. /* 67 */ KEY_F11,
  867. /* 68 */ KEY_UNKNOWN, /* JIS Kana */
  868. /* 69 */ KEY_F13,
  869. /* 6a */ KEY_F16,
  870. /* 6b */ KEY_F14,
  871. /* 6c */ KEY_UNKNOWN,
  872. /* 6d */ KEY_F10,
  873. /* 6e */ KEY_MENU,
  874. /* 6f */ KEY_F12,
  875. /* 70 */ KEY_UNKNOWN,
  876. /* 71 */ KEY_F15,
  877. /* 72 */ KEY_INSERT, /* Really Help... */
  878. /* 73 */ KEY_HOME,
  879. /* 74 */ KEY_PAGEUP,
  880. /* 75 */ KEY_DELETE,
  881. /* 76 */ KEY_F4,
  882. /* 77 */ KEY_END,
  883. /* 78 */ KEY_F2,
  884. /* 79 */ KEY_PAGEDOWN,
  885. /* 7a */ KEY_F1,
  886. /* 7b */ KEY_LEFT,
  887. /* 7c */ KEY_RIGHT,
  888. /* 7d */ KEY_DOWN,
  889. /* 7e */ KEY_UP,
  890. /* 7f */ KEY_UNKNOWN,
  891. };
  892. // Translates a OS X keycode to a Godot keycode
  893. static Key translateKey(unsigned int key) {
  894. if (key >= 128) {
  895. return KEY_UNKNOWN;
  896. }
  897. return _osx_to_godot_table[key];
  898. }
  899. // Translates a Godot keycode back to a OSX keycode
  900. static unsigned int unmapKey(Key key) {
  901. for (int i = 0; i <= 126; i++) {
  902. if (_osx_to_godot_table[i] == key) {
  903. return i;
  904. }
  905. }
  906. return 127;
  907. }
  908. struct _KeyCodeMap {
  909. UniChar kchar;
  910. Key kcode;
  911. };
  912. static const _KeyCodeMap _keycodes[55] = {
  913. { '`', KEY_QUOTELEFT },
  914. { '~', KEY_ASCIITILDE },
  915. { '0', KEY_0 },
  916. { '1', KEY_1 },
  917. { '2', KEY_2 },
  918. { '3', KEY_3 },
  919. { '4', KEY_4 },
  920. { '5', KEY_5 },
  921. { '6', KEY_6 },
  922. { '7', KEY_7 },
  923. { '8', KEY_8 },
  924. { '9', KEY_9 },
  925. { '-', KEY_MINUS },
  926. { '_', KEY_UNDERSCORE },
  927. { '=', KEY_EQUAL },
  928. { '+', KEY_PLUS },
  929. { 'q', KEY_Q },
  930. { 'w', KEY_W },
  931. { 'e', KEY_E },
  932. { 'r', KEY_R },
  933. { 't', KEY_T },
  934. { 'y', KEY_Y },
  935. { 'u', KEY_U },
  936. { 'i', KEY_I },
  937. { 'o', KEY_O },
  938. { 'p', KEY_P },
  939. { '[', KEY_BRACELEFT },
  940. { ']', KEY_BRACERIGHT },
  941. { '{', KEY_BRACELEFT },
  942. { '}', KEY_BRACERIGHT },
  943. { 'a', KEY_A },
  944. { 's', KEY_S },
  945. { 'd', KEY_D },
  946. { 'f', KEY_F },
  947. { 'g', KEY_G },
  948. { 'h', KEY_H },
  949. { 'j', KEY_J },
  950. { 'k', KEY_K },
  951. { 'l', KEY_L },
  952. { ';', KEY_SEMICOLON },
  953. { ':', KEY_COLON },
  954. { '\'', KEY_APOSTROPHE },
  955. { '\"', KEY_QUOTEDBL },
  956. { '\\', KEY_BACKSLASH },
  957. { '#', KEY_NUMBERSIGN },
  958. { 'z', KEY_Z },
  959. { 'x', KEY_X },
  960. { 'c', KEY_C },
  961. { 'v', KEY_V },
  962. { 'b', KEY_B },
  963. { 'n', KEY_N },
  964. { 'm', KEY_M },
  965. { ',', KEY_COMMA },
  966. { '.', KEY_PERIOD },
  967. { '/', KEY_SLASH }
  968. };
  969. static Key remapKey(unsigned int key, unsigned int state) {
  970. if (isNumpadKey(key)) {
  971. return translateKey(key);
  972. }
  973. TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
  974. if (!currentKeyboard) {
  975. return translateKey(key);
  976. }
  977. CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
  978. if (!layoutData) {
  979. return translateKey(key);
  980. }
  981. const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
  982. UInt32 keysDown = 0;
  983. UniChar chars[4];
  984. UniCharCount realLength;
  985. OSStatus err = UCKeyTranslate(keyboardLayout,
  986. key,
  987. kUCKeyActionDisplay,
  988. (state >> 8) & 0xFF,
  989. LMGetKbdType(),
  990. kUCKeyTranslateNoDeadKeysBit,
  991. &keysDown,
  992. sizeof(chars) / sizeof(chars[0]),
  993. &realLength,
  994. chars);
  995. if (err != noErr) {
  996. return translateKey(key);
  997. }
  998. for (unsigned int i = 0; i < 55; i++) {
  999. if (_keycodes[i].kchar == chars[0]) {
  1000. return _keycodes[i].kcode;
  1001. }
  1002. }
  1003. return translateKey(key);
  1004. }
  1005. - (void)keyDown:(NSEvent *)event {
  1006. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  1007. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  1008. ignore_momentum_scroll = true;
  1009. // Ignore all input if IME input is in progress
  1010. if (!imeInputEventInProgress) {
  1011. NSString *characters = [event characters];
  1012. NSUInteger length = [characters length];
  1013. if (!wd.im_active && length > 0 && keycode_has_unicode(remapKey([event keyCode], [event modifierFlags]))) {
  1014. // Fallback unicode character handler used if IME is not active
  1015. Char16String text;
  1016. text.resize([characters length] + 1);
  1017. [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
  1018. String u32text;
  1019. u32text.parse_utf16(text.ptr(), text.length());
  1020. for (int i = 0; i < u32text.length(); i++) {
  1021. const char32_t codepoint = u32text[i];
  1022. DisplayServerOSX::KeyEvent ke;
  1023. ke.window_id = window_id;
  1024. ke.osx_state = [event modifierFlags];
  1025. ke.pressed = true;
  1026. ke.echo = [event isARepeat];
  1027. ke.keycode = remapKey([event keyCode], [event modifierFlags]);
  1028. ke.physical_keycode = translateKey([event keyCode]);
  1029. ke.raw = true;
  1030. ke.unicode = codepoint;
  1031. _push_to_key_event_buffer(ke);
  1032. }
  1033. } else {
  1034. DisplayServerOSX::KeyEvent ke;
  1035. ke.window_id = window_id;
  1036. ke.osx_state = [event modifierFlags];
  1037. ke.pressed = true;
  1038. ke.echo = [event isARepeat];
  1039. ke.keycode = remapKey([event keyCode], [event modifierFlags]);
  1040. ke.physical_keycode = translateKey([event keyCode]);
  1041. ke.raw = false;
  1042. ke.unicode = 0;
  1043. _push_to_key_event_buffer(ke);
  1044. }
  1045. }
  1046. // Pass events to IME handler
  1047. if (wd.im_active) {
  1048. [self interpretKeyEvents:[NSArray arrayWithObject:event]];
  1049. }
  1050. }
  1051. - (void)flagsChanged:(NSEvent *)event {
  1052. ignore_momentum_scroll = true;
  1053. // Ignore all input if IME input is in progress
  1054. if (!imeInputEventInProgress) {
  1055. DisplayServerOSX::KeyEvent ke;
  1056. ke.window_id = window_id;
  1057. ke.echo = false;
  1058. ke.raw = true;
  1059. int key = [event keyCode];
  1060. int mod = [event modifierFlags];
  1061. if (key == 0x36 || key == 0x37) {
  1062. if (mod & NSEventModifierFlagCommand) {
  1063. mod &= ~NSEventModifierFlagCommand;
  1064. ke.pressed = true;
  1065. } else {
  1066. ke.pressed = false;
  1067. }
  1068. } else if (key == 0x38 || key == 0x3c) {
  1069. if (mod & NSEventModifierFlagShift) {
  1070. mod &= ~NSEventModifierFlagShift;
  1071. ke.pressed = true;
  1072. } else {
  1073. ke.pressed = false;
  1074. }
  1075. } else if (key == 0x3a || key == 0x3d) {
  1076. if (mod & NSEventModifierFlagOption) {
  1077. mod &= ~NSEventModifierFlagOption;
  1078. ke.pressed = true;
  1079. } else {
  1080. ke.pressed = false;
  1081. }
  1082. } else if (key == 0x3b || key == 0x3e) {
  1083. if (mod & NSEventModifierFlagControl) {
  1084. mod &= ~NSEventModifierFlagControl;
  1085. ke.pressed = true;
  1086. } else {
  1087. ke.pressed = false;
  1088. }
  1089. } else {
  1090. return;
  1091. }
  1092. ke.osx_state = mod;
  1093. ke.keycode = remapKey(key, mod);
  1094. ke.physical_keycode = translateKey(key);
  1095. ke.unicode = 0;
  1096. _push_to_key_event_buffer(ke);
  1097. }
  1098. }
  1099. - (void)keyUp:(NSEvent *)event {
  1100. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  1101. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  1102. // Ignore all input if IME input is in progress
  1103. if (!imeInputEventInProgress) {
  1104. NSString *characters = [event characters];
  1105. NSUInteger length = [characters length];
  1106. // Fallback unicode character handler used if IME is not active
  1107. if (!wd.im_active && length > 0 && keycode_has_unicode(remapKey([event keyCode], [event modifierFlags]))) {
  1108. Char16String text;
  1109. text.resize([characters length] + 1);
  1110. [characters getCharacters:(unichar *)text.ptrw() range:NSMakeRange(0, [characters length])];
  1111. String u32text;
  1112. u32text.parse_utf16(text.ptr(), text.length());
  1113. for (int i = 0; i < u32text.length(); i++) {
  1114. const char32_t codepoint = u32text[i];
  1115. DisplayServerOSX::KeyEvent ke;
  1116. ke.window_id = window_id;
  1117. ke.osx_state = [event modifierFlags];
  1118. ke.pressed = false;
  1119. ke.echo = [event isARepeat];
  1120. ke.keycode = remapKey([event keyCode], [event modifierFlags]);
  1121. ke.physical_keycode = translateKey([event keyCode]);
  1122. ke.raw = true;
  1123. ke.unicode = codepoint;
  1124. _push_to_key_event_buffer(ke);
  1125. }
  1126. } else {
  1127. DisplayServerOSX::KeyEvent ke;
  1128. ke.window_id = window_id;
  1129. ke.osx_state = [event modifierFlags];
  1130. ke.pressed = false;
  1131. ke.echo = [event isARepeat];
  1132. ke.keycode = remapKey([event keyCode], [event modifierFlags]);
  1133. ke.physical_keycode = translateKey([event keyCode]);
  1134. ke.raw = true;
  1135. ke.unicode = 0;
  1136. _push_to_key_event_buffer(ke);
  1137. }
  1138. }
  1139. }
  1140. inline void sendScrollEvent(DisplayServer::WindowID window_id, MouseButton button, double factor, int modifierFlags) {
  1141. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  1142. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  1143. MouseButton mask = MouseButton(1 << (button - 1));
  1144. Ref<InputEventMouseButton> sc;
  1145. sc.instantiate();
  1146. sc->set_window_id(window_id);
  1147. _get_key_modifier_state(modifierFlags, sc);
  1148. sc->set_button_index(button);
  1149. sc->set_factor(factor);
  1150. sc->set_pressed(true);
  1151. sc->set_position(wd.mouse_pos);
  1152. sc->set_global_position(wd.mouse_pos);
  1153. DS_OSX->last_button_state |= (MouseButton)mask;
  1154. sc->set_button_mask(DS_OSX->last_button_state);
  1155. Input::get_singleton()->parse_input_event(sc);
  1156. sc.instantiate();
  1157. sc->set_window_id(window_id);
  1158. sc->set_button_index(button);
  1159. sc->set_factor(factor);
  1160. sc->set_pressed(false);
  1161. sc->set_position(wd.mouse_pos);
  1162. sc->set_global_position(wd.mouse_pos);
  1163. DS_OSX->last_button_state &= (MouseButton)~mask;
  1164. sc->set_button_mask(DS_OSX->last_button_state);
  1165. Input::get_singleton()->parse_input_event(sc);
  1166. }
  1167. inline void sendPanEvent(DisplayServer::WindowID window_id, double dx, double dy, int modifierFlags) {
  1168. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  1169. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  1170. Ref<InputEventPanGesture> pg;
  1171. pg.instantiate();
  1172. pg->set_window_id(window_id);
  1173. _get_key_modifier_state(modifierFlags, pg);
  1174. pg->set_position(wd.mouse_pos);
  1175. pg->set_delta(Vector2(-dx, -dy));
  1176. Input::get_singleton()->parse_input_event(pg);
  1177. }
  1178. - (void)scrollWheel:(NSEvent *)event {
  1179. ERR_FAIL_COND(!DS_OSX->windows.has(window_id));
  1180. DisplayServerOSX::WindowData &wd = DS_OSX->windows[window_id];
  1181. double deltaX, deltaY;
  1182. _get_mouse_pos(wd, [event locationInWindow]);
  1183. deltaX = [event scrollingDeltaX];
  1184. deltaY = [event scrollingDeltaY];
  1185. if ([event hasPreciseScrollingDeltas]) {
  1186. deltaX *= 0.03;
  1187. deltaY *= 0.03;
  1188. }
  1189. if ([event momentumPhase] != NSEventPhaseNone) {
  1190. if (ignore_momentum_scroll) {
  1191. return;
  1192. }
  1193. } else {
  1194. ignore_momentum_scroll = false;
  1195. }
  1196. if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
  1197. sendPanEvent(window_id, deltaX, deltaY, [event modifierFlags]);
  1198. } else {
  1199. if (fabs(deltaX)) {
  1200. sendScrollEvent(window_id, 0 > deltaX ? MOUSE_BUTTON_WHEEL_RIGHT : MOUSE_BUTTON_WHEEL_LEFT, fabs(deltaX * 0.3), [event modifierFlags]);
  1201. }
  1202. if (fabs(deltaY)) {
  1203. sendScrollEvent(window_id, 0 < deltaY ? MOUSE_BUTTON_WHEEL_UP : MOUSE_BUTTON_WHEEL_DOWN, fabs(deltaY * 0.3), [event modifierFlags]);
  1204. }
  1205. }
  1206. }
  1207. @end
  1208. /*************************************************************************/
  1209. /* GodotWindow */
  1210. /*************************************************************************/
  1211. @interface GodotWindow : NSWindow {
  1212. }
  1213. @end
  1214. @implementation GodotWindow
  1215. - (BOOL)canBecomeKeyWindow {
  1216. // Required for NSBorderlessWindowMask windows
  1217. for (Map<DisplayServer::WindowID, DisplayServerOSX::WindowData>::Element *E = DS_OSX->windows.front(); E; E = E->next()) {
  1218. if (E->get().window_object == self) {
  1219. if (E->get().no_focus) {
  1220. return NO;
  1221. }
  1222. }
  1223. }
  1224. return YES;
  1225. }
  1226. - (BOOL)canBecomeMainWindow {
  1227. // Required for NSBorderlessWindowMask windows
  1228. for (Map<DisplayServer::WindowID, DisplayServerOSX::WindowData>::Element *E = DS_OSX->windows.front(); E; E = E->next()) {
  1229. if (E->get().window_object == self) {
  1230. if (E->get().no_focus) {
  1231. return NO;
  1232. }
  1233. }
  1234. }
  1235. return YES;
  1236. }
  1237. @end
  1238. /*************************************************************************/
  1239. /* DisplayServerOSX */
  1240. /*************************************************************************/
  1241. bool DisplayServerOSX::has_feature(Feature p_feature) const {
  1242. switch (p_feature) {
  1243. case FEATURE_GLOBAL_MENU:
  1244. case FEATURE_SUBWINDOWS:
  1245. //case FEATURE_TOUCHSCREEN:
  1246. case FEATURE_MOUSE:
  1247. case FEATURE_MOUSE_WARP:
  1248. case FEATURE_CLIPBOARD:
  1249. case FEATURE_CURSOR_SHAPE:
  1250. case FEATURE_CUSTOM_CURSOR_SHAPE:
  1251. case FEATURE_NATIVE_DIALOG:
  1252. //case FEATURE_CONSOLE_WINDOW:
  1253. case FEATURE_IME:
  1254. case FEATURE_WINDOW_TRANSPARENCY:
  1255. case FEATURE_HIDPI:
  1256. case FEATURE_ICON:
  1257. case FEATURE_NATIVE_ICON:
  1258. //case FEATURE_KEEP_SCREEN_ON:
  1259. case FEATURE_SWAP_BUFFERS:
  1260. return true;
  1261. default: {
  1262. }
  1263. }
  1264. return false;
  1265. }
  1266. String DisplayServerOSX::get_name() const {
  1267. return "OSX";
  1268. }
  1269. const NSMenu *DisplayServerOSX::_get_menu_root(const String &p_menu_root) const {
  1270. const NSMenu *menu = nullptr;
  1271. if (p_menu_root == "") {
  1272. // Main menu.x
  1273. menu = [NSApp mainMenu];
  1274. } else if (p_menu_root.to_lower() == "_dock") {
  1275. // macOS dock menu.
  1276. menu = dock_menu;
  1277. } else {
  1278. // Submenu.
  1279. if (submenu.has(p_menu_root)) {
  1280. menu = submenu[p_menu_root];
  1281. }
  1282. }
  1283. if (menu == apple_menu) {
  1284. // Do not allow to change Apple menu.
  1285. return nullptr;
  1286. }
  1287. return menu;
  1288. }
  1289. NSMenu *DisplayServerOSX::_get_menu_root(const String &p_menu_root) {
  1290. NSMenu *menu = nullptr;
  1291. if (p_menu_root == "") {
  1292. // Main menu.
  1293. menu = [NSApp mainMenu];
  1294. } else if (p_menu_root.to_lower() == "_dock") {
  1295. // macOS dock menu.
  1296. menu = dock_menu;
  1297. } else {
  1298. // Submenu.
  1299. if (!submenu.has(p_menu_root)) {
  1300. NSMenu *n_menu = [[NSMenu alloc] initWithTitle:[NSString stringWithUTF8String:p_menu_root.utf8().get_data()]];
  1301. submenu[p_menu_root] = n_menu;
  1302. }
  1303. menu = submenu[p_menu_root];
  1304. }
  1305. if (menu == apple_menu) {
  1306. // Do not allow to change Apple menu.
  1307. return nullptr;
  1308. }
  1309. return menu;
  1310. }
  1311. void DisplayServerOSX::global_menu_add_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag) {
  1312. _THREAD_SAFE_METHOD_
  1313. NSMenu *menu = _get_menu_root(p_menu_root);
  1314. if (menu) {
  1315. NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
  1316. GlobalMenuItem *obj = [[[GlobalMenuItem alloc] init] autorelease];
  1317. obj->callback = p_callback;
  1318. obj->meta = p_tag;
  1319. obj->checkable = false;
  1320. [menu_item setRepresentedObject:obj];
  1321. }
  1322. }
  1323. void DisplayServerOSX::global_menu_add_check_item(const String &p_menu_root, const String &p_label, const Callable &p_callback, const Variant &p_tag) {
  1324. _THREAD_SAFE_METHOD_
  1325. NSMenu *menu = _get_menu_root(p_menu_root);
  1326. if (menu) {
  1327. NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:@selector(globalMenuCallback:) keyEquivalent:@""];
  1328. GlobalMenuItem *obj = [[[GlobalMenuItem alloc] init] autorelease];
  1329. obj->callback = p_callback;
  1330. obj->meta = p_tag;
  1331. obj->checkable = true;
  1332. [menu_item setRepresentedObject:obj];
  1333. }
  1334. }
  1335. void DisplayServerOSX::global_menu_add_submenu_item(const String &p_menu_root, const String &p_label, const String &p_submenu) {
  1336. _THREAD_SAFE_METHOD_
  1337. NSMenu *menu = _get_menu_root(p_menu_root);
  1338. NSMenu *sub_menu = _get_menu_root(p_submenu);
  1339. if (menu && sub_menu) {
  1340. if (sub_menu == menu) {
  1341. ERR_PRINT("Can't set submenu to self!");
  1342. return;
  1343. }
  1344. if ([sub_menu supermenu]) {
  1345. ERR_PRINT("Can't set submenu to menu that is already a submenu of some other menu!");
  1346. return;
  1347. }
  1348. NSMenuItem *menu_item = [menu addItemWithTitle:[NSString stringWithUTF8String:p_label.utf8().get_data()] action:nil keyEquivalent:@""];
  1349. [menu setSubmenu:sub_menu forItem:menu_item];
  1350. }
  1351. }
  1352. void DisplayServerOSX::global_menu_add_separator(const String &p_menu_root) {
  1353. _THREAD_SAFE_METHOD_
  1354. NSMenu *menu = _get_menu_root(p_menu_root);
  1355. if (menu) {
  1356. [menu addItem:[NSMenuItem separatorItem]];
  1357. }
  1358. }
  1359. bool DisplayServerOSX::global_menu_is_item_checked(const String &p_menu_root, int p_idx) const {
  1360. _THREAD_SAFE_METHOD_
  1361. const NSMenu *menu = _get_menu_root(p_menu_root);
  1362. if (menu) {
  1363. const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1364. if (menu_item) {
  1365. return ([menu_item state] == NSControlStateValueOn);
  1366. }
  1367. }
  1368. return false;
  1369. }
  1370. bool DisplayServerOSX::global_menu_is_item_checkable(const String &p_menu_root, int p_idx) const {
  1371. _THREAD_SAFE_METHOD_
  1372. const NSMenu *menu = _get_menu_root(p_menu_root);
  1373. if (menu) {
  1374. const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1375. if (menu_item) {
  1376. GlobalMenuItem *obj = [menu_item representedObject];
  1377. if (obj) {
  1378. return obj->checkable;
  1379. }
  1380. }
  1381. }
  1382. return false;
  1383. }
  1384. Callable DisplayServerOSX::global_menu_get_item_callback(const String &p_menu_root, int p_idx) {
  1385. _THREAD_SAFE_METHOD_
  1386. const NSMenu *menu = _get_menu_root(p_menu_root);
  1387. if (menu) {
  1388. const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1389. if (menu_item) {
  1390. GlobalMenuItem *obj = [menu_item representedObject];
  1391. if (obj) {
  1392. return obj->callback;
  1393. }
  1394. }
  1395. }
  1396. return Callable();
  1397. }
  1398. Variant DisplayServerOSX::global_menu_get_item_tag(const String &p_menu_root, int p_idx) {
  1399. _THREAD_SAFE_METHOD_
  1400. const NSMenu *menu = _get_menu_root(p_menu_root);
  1401. if (menu) {
  1402. const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1403. if (menu_item) {
  1404. GlobalMenuItem *obj = [menu_item representedObject];
  1405. if (obj) {
  1406. return obj->meta;
  1407. }
  1408. }
  1409. }
  1410. return Variant();
  1411. }
  1412. String DisplayServerOSX::global_menu_get_item_text(const String &p_menu_root, int p_idx) {
  1413. _THREAD_SAFE_METHOD_
  1414. const NSMenu *menu = _get_menu_root(p_menu_root);
  1415. if (menu) {
  1416. const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1417. if (menu_item) {
  1418. char *utfs = strdup([[menu_item title] UTF8String]);
  1419. String ret;
  1420. ret.parse_utf8(utfs);
  1421. free(utfs);
  1422. return ret;
  1423. }
  1424. }
  1425. return String();
  1426. }
  1427. String DisplayServerOSX::global_menu_get_item_submenu(const String &p_menu_root, int p_idx) {
  1428. _THREAD_SAFE_METHOD_
  1429. const NSMenu *menu = _get_menu_root(p_menu_root);
  1430. if (menu) {
  1431. const NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1432. if (menu_item) {
  1433. const NSMenu *sub_menu = [menu_item submenu];
  1434. if (sub_menu) {
  1435. for (Map<String, NSMenu *>::Element *E = submenu.front(); E; E = E->next()) {
  1436. if (E->get() == sub_menu)
  1437. return E->key();
  1438. }
  1439. }
  1440. }
  1441. }
  1442. return String();
  1443. }
  1444. void DisplayServerOSX::global_menu_set_item_checked(const String &p_menu_root, int p_idx, bool p_checked) {
  1445. _THREAD_SAFE_METHOD_
  1446. NSMenu *menu = _get_menu_root(p_menu_root);
  1447. if (menu) {
  1448. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
  1449. return;
  1450. }
  1451. NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1452. if (menu_item) {
  1453. if (p_checked) {
  1454. [menu_item setState:NSControlStateValueOn];
  1455. } else {
  1456. [menu_item setState:NSControlStateValueOff];
  1457. }
  1458. }
  1459. }
  1460. }
  1461. void DisplayServerOSX::global_menu_set_item_checkable(const String &p_menu_root, int p_idx, bool p_checkable) {
  1462. _THREAD_SAFE_METHOD_
  1463. NSMenu *menu = _get_menu_root(p_menu_root);
  1464. if (menu) {
  1465. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
  1466. return;
  1467. }
  1468. NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1469. if (menu_item) {
  1470. GlobalMenuItem *obj = [menu_item representedObject];
  1471. obj->checkable = p_checkable;
  1472. }
  1473. }
  1474. }
  1475. void DisplayServerOSX::global_menu_set_item_callback(const String &p_menu_root, int p_idx, const Callable &p_callback) {
  1476. _THREAD_SAFE_METHOD_
  1477. NSMenu *menu = _get_menu_root(p_menu_root);
  1478. if (menu) {
  1479. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
  1480. return;
  1481. }
  1482. NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1483. if (menu_item) {
  1484. GlobalMenuItem *obj = [menu_item representedObject];
  1485. obj->callback = p_callback;
  1486. }
  1487. }
  1488. }
  1489. void DisplayServerOSX::global_menu_set_item_tag(const String &p_menu_root, int p_idx, const Variant &p_tag) {
  1490. _THREAD_SAFE_METHOD_
  1491. NSMenu *menu = _get_menu_root(p_menu_root);
  1492. if (menu) {
  1493. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
  1494. return;
  1495. }
  1496. NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1497. if (menu_item) {
  1498. GlobalMenuItem *obj = [menu_item representedObject];
  1499. obj->meta = p_tag;
  1500. }
  1501. }
  1502. }
  1503. void DisplayServerOSX::global_menu_set_item_text(const String &p_menu_root, int p_idx, const String &p_text) {
  1504. _THREAD_SAFE_METHOD_
  1505. NSMenu *menu = _get_menu_root(p_menu_root);
  1506. if (menu) {
  1507. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
  1508. return;
  1509. }
  1510. NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1511. if (menu_item) {
  1512. [menu_item setTitle:[NSString stringWithUTF8String:p_text.utf8().get_data()]];
  1513. }
  1514. }
  1515. }
  1516. void DisplayServerOSX::global_menu_set_item_submenu(const String &p_menu_root, int p_idx, const String &p_submenu) {
  1517. _THREAD_SAFE_METHOD_
  1518. NSMenu *menu = _get_menu_root(p_menu_root);
  1519. NSMenu *sub_menu = _get_menu_root(p_submenu);
  1520. if (menu && sub_menu) {
  1521. if (sub_menu == menu) {
  1522. ERR_PRINT("Can't set submenu to self!");
  1523. return;
  1524. }
  1525. if ([sub_menu supermenu]) {
  1526. ERR_PRINT("Can't set submenu to menu that is already a submenu of some other menu!");
  1527. return;
  1528. }
  1529. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not edit Apple menu.
  1530. return;
  1531. }
  1532. NSMenuItem *menu_item = [menu itemAtIndex:p_idx];
  1533. if (menu_item) {
  1534. [menu setSubmenu:sub_menu forItem:menu_item];
  1535. }
  1536. }
  1537. }
  1538. int DisplayServerOSX::global_menu_get_item_count(const String &p_menu_root) const {
  1539. _THREAD_SAFE_METHOD_
  1540. const NSMenu *menu = _get_menu_root(p_menu_root);
  1541. if (menu) {
  1542. return [menu numberOfItems];
  1543. } else {
  1544. return 0;
  1545. }
  1546. }
  1547. void DisplayServerOSX::global_menu_remove_item(const String &p_menu_root, int p_idx) {
  1548. _THREAD_SAFE_METHOD_
  1549. NSMenu *menu = _get_menu_root(p_menu_root);
  1550. if (menu) {
  1551. if ((menu == [NSApp mainMenu]) && (p_idx == 0)) { // Do not delete Apple menu.
  1552. return;
  1553. }
  1554. [menu removeItemAtIndex:p_idx];
  1555. }
  1556. }
  1557. void DisplayServerOSX::global_menu_clear(const String &p_menu_root) {
  1558. _THREAD_SAFE_METHOD_
  1559. NSMenu *menu = _get_menu_root(p_menu_root);
  1560. if (menu) {
  1561. [menu removeAllItems];
  1562. // Restore Apple menu.
  1563. if (menu == [NSApp mainMenu]) {
  1564. NSMenuItem *menu_item = [menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  1565. [menu setSubmenu:apple_menu forItem:menu_item];
  1566. }
  1567. }
  1568. }
  1569. Error DisplayServerOSX::dialog_show(String p_title, String p_description, Vector<String> p_buttons, const Callable &p_callback) {
  1570. _THREAD_SAFE_METHOD_
  1571. NSAlert *window = [[NSAlert alloc] init];
  1572. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  1573. NSString *ns_description = [NSString stringWithUTF8String:p_description.utf8().get_data()];
  1574. for (int i = 0; i < p_buttons.size(); i++) {
  1575. NSString *ns_button = [NSString stringWithUTF8String:p_buttons[i].utf8().get_data()];
  1576. [window addButtonWithTitle:ns_button];
  1577. }
  1578. [window setMessageText:ns_title];
  1579. [window setInformativeText:ns_description];
  1580. [window setAlertStyle:NSAlertStyleInformational];
  1581. int button_pressed;
  1582. NSInteger ret = [window runModal];
  1583. if (ret == NSAlertFirstButtonReturn) {
  1584. button_pressed = 0;
  1585. } else if (ret == NSAlertSecondButtonReturn) {
  1586. button_pressed = 1;
  1587. } else if (ret == NSAlertThirdButtonReturn) {
  1588. button_pressed = 2;
  1589. } else {
  1590. button_pressed = 2 + (ret - NSAlertThirdButtonReturn);
  1591. }
  1592. if (!p_callback.is_null()) {
  1593. Variant button = button_pressed;
  1594. Variant *buttonp = &button;
  1595. Variant ret;
  1596. Callable::CallError ce;
  1597. p_callback.call((const Variant **)&buttonp, 1, ret, ce);
  1598. }
  1599. [window release];
  1600. return OK;
  1601. }
  1602. Error DisplayServerOSX::dialog_input_text(String p_title, String p_description, String p_partial, const Callable &p_callback) {
  1603. _THREAD_SAFE_METHOD_
  1604. NSAlert *window = [[NSAlert alloc] init];
  1605. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  1606. NSString *ns_description = [NSString stringWithUTF8String:p_description.utf8().get_data()];
  1607. NSTextField *input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 250, 30)];
  1608. [window addButtonWithTitle:@"OK"];
  1609. [window setMessageText:ns_title];
  1610. [window setInformativeText:ns_description];
  1611. [window setAlertStyle:NSAlertStyleInformational];
  1612. [input setStringValue:[NSString stringWithUTF8String:p_partial.utf8().get_data()]];
  1613. [window setAccessoryView:input];
  1614. [window runModal];
  1615. char *utfs = strdup([[input stringValue] UTF8String]);
  1616. String ret;
  1617. ret.parse_utf8(utfs);
  1618. free(utfs);
  1619. if (!p_callback.is_null()) {
  1620. Variant text = ret;
  1621. Variant *textp = &text;
  1622. Variant ret;
  1623. Callable::CallError ce;
  1624. p_callback.call((const Variant **)&textp, 1, ret, ce);
  1625. }
  1626. [window release];
  1627. return OK;
  1628. }
  1629. void DisplayServerOSX::mouse_set_mode(MouseMode p_mode) {
  1630. _THREAD_SAFE_METHOD_
  1631. if (p_mode == mouse_mode) {
  1632. return;
  1633. }
  1634. if (p_mode == MOUSE_MODE_CAPTURED) {
  1635. // Apple Docs state that the display parameter is not used.
  1636. // "This parameter is not used. By default, you may pass kCGDirectMainDisplay."
  1637. // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html
  1638. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1639. CGDisplayHideCursor(kCGDirectMainDisplay);
  1640. }
  1641. CGAssociateMouseAndMouseCursorPosition(false);
  1642. WindowData &wd = windows[MAIN_WINDOW_ID];
  1643. const NSRect contentRect = [wd.window_view frame];
  1644. NSRect pointInWindowRect = NSMakeRect(contentRect.size.width / 2, contentRect.size.height / 2, 0, 0);
  1645. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  1646. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1647. CGWarpMouseCursorPosition(lMouseWarpPos);
  1648. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  1649. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1650. CGDisplayHideCursor(kCGDirectMainDisplay);
  1651. }
  1652. CGAssociateMouseAndMouseCursorPosition(true);
  1653. } else if (p_mode == MOUSE_MODE_CONFINED) {
  1654. CGDisplayShowCursor(kCGDirectMainDisplay);
  1655. CGAssociateMouseAndMouseCursorPosition(false);
  1656. } else if (p_mode == MOUSE_MODE_CONFINED_HIDDEN) {
  1657. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1658. CGDisplayHideCursor(kCGDirectMainDisplay);
  1659. }
  1660. CGAssociateMouseAndMouseCursorPosition(false);
  1661. } else { // MOUSE_MODE_VISIBLE
  1662. CGDisplayShowCursor(kCGDirectMainDisplay);
  1663. CGAssociateMouseAndMouseCursorPosition(true);
  1664. }
  1665. last_warp = [[NSProcessInfo processInfo] systemUptime];
  1666. ignore_warp = true;
  1667. warp_events.clear();
  1668. mouse_mode = p_mode;
  1669. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  1670. CursorShape p_shape = cursor_shape;
  1671. cursor_shape = DisplayServer::CURSOR_MAX;
  1672. cursor_set_shape(p_shape);
  1673. }
  1674. }
  1675. DisplayServer::MouseMode DisplayServerOSX::mouse_get_mode() const {
  1676. return mouse_mode;
  1677. }
  1678. void DisplayServerOSX::mouse_warp_to_position(const Point2i &p_to) {
  1679. _THREAD_SAFE_METHOD_
  1680. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1681. last_mouse_pos = p_to;
  1682. } else {
  1683. WindowData &wd = windows[MAIN_WINDOW_ID];
  1684. //local point in window coords
  1685. const NSRect contentRect = [wd.window_view frame];
  1686. const float scale = screen_get_max_scale();
  1687. NSRect pointInWindowRect = NSMakeRect(p_to.x / scale, contentRect.size.height - (p_to.y / scale - 1), 0, 0);
  1688. NSPoint pointOnScreen = [[wd.window_view window] convertRectToScreen:pointInWindowRect].origin;
  1689. //point in scren coords
  1690. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1691. //do the warping
  1692. CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
  1693. CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
  1694. CGAssociateMouseAndMouseCursorPosition(false);
  1695. CGWarpMouseCursorPosition(lMouseWarpPos);
  1696. if (mouse_mode != MOUSE_MODE_CONFINED && mouse_mode != MOUSE_MODE_CONFINED_HIDDEN) {
  1697. CGAssociateMouseAndMouseCursorPosition(true);
  1698. }
  1699. }
  1700. }
  1701. Point2i DisplayServerOSX::mouse_get_position() const {
  1702. return last_mouse_pos;
  1703. }
  1704. Point2i DisplayServerOSX::mouse_get_absolute_position() const {
  1705. _THREAD_SAFE_METHOD_
  1706. const NSPoint mouse_pos = [NSEvent mouseLocation];
  1707. const float scale = screen_get_max_scale();
  1708. for (NSScreen *screen in [NSScreen screens]) {
  1709. NSRect frame = [screen frame];
  1710. if (NSMouseInRect(mouse_pos, frame, NO)) {
  1711. return Vector2i((int)mouse_pos.x, (int)-mouse_pos.y) * scale + _get_screens_origin();
  1712. }
  1713. }
  1714. return Vector2i();
  1715. }
  1716. MouseButton DisplayServerOSX::mouse_get_button_state() const {
  1717. return last_button_state;
  1718. }
  1719. void DisplayServerOSX::clipboard_set(const String &p_text) {
  1720. _THREAD_SAFE_METHOD_
  1721. NSString *copiedString = [NSString stringWithUTF8String:p_text.utf8().get_data()];
  1722. NSArray *copiedStringArray = [NSArray arrayWithObject:copiedString];
  1723. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1724. [pasteboard clearContents];
  1725. [pasteboard writeObjects:copiedStringArray];
  1726. }
  1727. String DisplayServerOSX::clipboard_get() const {
  1728. _THREAD_SAFE_METHOD_
  1729. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1730. NSArray *classArray = [NSArray arrayWithObject:[NSString class]];
  1731. NSDictionary *options = [NSDictionary dictionary];
  1732. BOOL ok = [pasteboard canReadObjectForClasses:classArray options:options];
  1733. if (!ok) {
  1734. return "";
  1735. }
  1736. NSArray *objectsToPaste = [pasteboard readObjectsForClasses:classArray options:options];
  1737. NSString *string = [objectsToPaste objectAtIndex:0];
  1738. char *utfs = strdup([string UTF8String]);
  1739. String ret;
  1740. ret.parse_utf8(utfs);
  1741. free(utfs);
  1742. return ret;
  1743. }
  1744. int DisplayServerOSX::get_screen_count() const {
  1745. _THREAD_SAFE_METHOD_
  1746. NSArray *screenArray = [NSScreen screens];
  1747. return [screenArray count];
  1748. }
  1749. // Returns the native top-left screen coordinate of the smallest rectangle
  1750. // that encompasses all screens. Needed in get_screen_position(),
  1751. // window_get_position, and window_set_position()
  1752. // to convert between OS X native screen coordinates and the ones expected by Godot
  1753. static bool displays_arrangement_dirty = true;
  1754. static bool displays_scale_dirty = true;
  1755. static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
  1756. displays_arrangement_dirty = true;
  1757. displays_scale_dirty = true;
  1758. }
  1759. Point2i DisplayServerOSX::_get_screens_origin() const {
  1760. static Point2i origin;
  1761. if (displays_arrangement_dirty) {
  1762. origin = Point2i();
  1763. for (int i = 0; i < get_screen_count(); i++) {
  1764. Point2i position = _get_native_screen_position(i);
  1765. if (position.x < origin.x) {
  1766. origin.x = position.x;
  1767. }
  1768. if (position.y > origin.y) {
  1769. origin.y = position.y;
  1770. }
  1771. }
  1772. displays_arrangement_dirty = false;
  1773. }
  1774. return origin;
  1775. }
  1776. Point2i DisplayServerOSX::_get_native_screen_position(int p_screen) const {
  1777. NSArray *screenArray = [NSScreen screens];
  1778. if ((NSUInteger)p_screen < [screenArray count]) {
  1779. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1780. // Return the top-left corner of the screen, for OS X the y starts at the bottom
  1781. return Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * screen_get_max_scale();
  1782. }
  1783. return Point2i();
  1784. }
  1785. Point2i DisplayServerOSX::screen_get_position(int p_screen) const {
  1786. _THREAD_SAFE_METHOD_
  1787. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  1788. p_screen = window_get_current_screen();
  1789. }
  1790. Point2i position = _get_native_screen_position(p_screen) - _get_screens_origin();
  1791. // OS X native y-coordinate relative to _get_screens_origin() is negative,
  1792. // Godot expects a positive value
  1793. position.y *= -1;
  1794. return position;
  1795. }
  1796. Size2i DisplayServerOSX::screen_get_size(int p_screen) const {
  1797. _THREAD_SAFE_METHOD_
  1798. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  1799. p_screen = window_get_current_screen();
  1800. }
  1801. NSArray *screenArray = [NSScreen screens];
  1802. if ((NSUInteger)p_screen < [screenArray count]) {
  1803. // Note: Use frame to get the whole screen size
  1804. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1805. return Size2i(nsrect.size.width, nsrect.size.height) * screen_get_max_scale();
  1806. }
  1807. return Size2i();
  1808. }
  1809. int DisplayServerOSX::screen_get_dpi(int p_screen) const {
  1810. _THREAD_SAFE_METHOD_
  1811. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  1812. p_screen = window_get_current_screen();
  1813. }
  1814. NSArray *screenArray = [NSScreen screens];
  1815. if ((NSUInteger)p_screen < [screenArray count]) {
  1816. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1817. const NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
  1818. const CGSize displayPhysicalSize = CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1819. float scale = [[screenArray objectAtIndex:p_screen] backingScaleFactor];
  1820. float den2 = (displayPhysicalSize.width / 25.4f) * (displayPhysicalSize.width / 25.4f) + (displayPhysicalSize.height / 25.4f) * (displayPhysicalSize.height / 25.4f);
  1821. if (den2 > 0.0f) {
  1822. return ceil(sqrt(displayPixelSize.width * displayPixelSize.width + displayPixelSize.height * displayPixelSize.height) / sqrt(den2) * scale);
  1823. }
  1824. }
  1825. return 72;
  1826. }
  1827. float DisplayServerOSX::screen_get_scale(int p_screen) const {
  1828. _THREAD_SAFE_METHOD_
  1829. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  1830. p_screen = window_get_current_screen();
  1831. }
  1832. if (OS::get_singleton()->is_hidpi_allowed()) {
  1833. NSArray *screenArray = [NSScreen screens];
  1834. if ((NSUInteger)p_screen < [screenArray count]) {
  1835. if ([[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
  1836. return fmax(1.0, [[screenArray objectAtIndex:p_screen] backingScaleFactor]);
  1837. }
  1838. }
  1839. }
  1840. return 1.f;
  1841. }
  1842. float DisplayServerOSX::screen_get_max_scale() const {
  1843. _THREAD_SAFE_METHOD_
  1844. static float scale = 1.f;
  1845. if (displays_scale_dirty) {
  1846. int screen_count = get_screen_count();
  1847. for (int i = 0; i < screen_count; i++) {
  1848. scale = fmax(scale, screen_get_scale(i));
  1849. }
  1850. displays_scale_dirty = false;
  1851. }
  1852. return scale;
  1853. }
  1854. Rect2i DisplayServerOSX::screen_get_usable_rect(int p_screen) const {
  1855. _THREAD_SAFE_METHOD_
  1856. if (p_screen == SCREEN_OF_MAIN_WINDOW) {
  1857. p_screen = window_get_current_screen();
  1858. }
  1859. NSArray *screenArray = [NSScreen screens];
  1860. if ((NSUInteger)p_screen < [screenArray count]) {
  1861. const float scale = screen_get_max_scale();
  1862. NSRect nsrect = [[screenArray objectAtIndex:p_screen] visibleFrame];
  1863. Point2i position = Point2i(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * scale - _get_screens_origin();
  1864. position.y *= -1;
  1865. Size2i size = Size2i(nsrect.size.width, nsrect.size.height) * scale;
  1866. return Rect2i(position, size);
  1867. }
  1868. return Rect2i();
  1869. }
  1870. Vector<DisplayServer::WindowID> DisplayServerOSX::get_window_list() const {
  1871. _THREAD_SAFE_METHOD_
  1872. Vector<int> ret;
  1873. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  1874. ret.push_back(E->key());
  1875. }
  1876. return ret;
  1877. }
  1878. DisplayServer::WindowID DisplayServerOSX::create_sub_window(WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Rect2i &p_rect) {
  1879. _THREAD_SAFE_METHOD_
  1880. WindowID id = _create_window(p_mode, p_vsync_mode, p_rect);
  1881. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  1882. if (p_flags & (1 << i)) {
  1883. window_set_flag(WindowFlags(i), true, id);
  1884. }
  1885. }
  1886. return id;
  1887. }
  1888. void DisplayServerOSX::show_window(WindowID p_id) {
  1889. WindowData &wd = windows[p_id];
  1890. if (wd.no_focus) {
  1891. [wd.window_object orderFront:nil];
  1892. } else {
  1893. [wd.window_object makeKeyAndOrderFront:nil];
  1894. }
  1895. }
  1896. void DisplayServerOSX::_send_window_event(const WindowData &wd, WindowEvent p_event) {
  1897. _THREAD_SAFE_METHOD_
  1898. if (!wd.event_callback.is_null()) {
  1899. Variant event = int(p_event);
  1900. Variant *eventp = &event;
  1901. Variant ret;
  1902. Callable::CallError ce;
  1903. wd.event_callback.call((const Variant **)&eventp, 1, ret, ce);
  1904. }
  1905. }
  1906. DisplayServerOSX::WindowID DisplayServerOSX::_find_window_id(id p_window) {
  1907. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  1908. if (E->get().window_object == p_window) {
  1909. return E->key();
  1910. }
  1911. }
  1912. return INVALID_WINDOW_ID;
  1913. }
  1914. void DisplayServerOSX::_update_window(WindowData p_wd) {
  1915. bool borderless_full = false;
  1916. if (p_wd.borderless) {
  1917. NSRect frameRect = [p_wd.window_object frame];
  1918. NSRect screenRect = [[p_wd.window_object screen] frame];
  1919. // Check if our window covers up the screen
  1920. if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
  1921. frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
  1922. borderless_full = true;
  1923. }
  1924. }
  1925. if (borderless_full) {
  1926. // If the window covers up the screen set the level to above the main menu and hide on deactivate
  1927. [p_wd.window_object setLevel:NSMainMenuWindowLevel + 1];
  1928. [p_wd.window_object setHidesOnDeactivate:YES];
  1929. } else {
  1930. // Reset these when our window is not a borderless window that covers up the screen
  1931. if (p_wd.on_top && !p_wd.fullscreen) {
  1932. [p_wd.window_object setLevel:NSFloatingWindowLevel];
  1933. } else {
  1934. [p_wd.window_object setLevel:NSNormalWindowLevel];
  1935. }
  1936. [p_wd.window_object setHidesOnDeactivate:NO];
  1937. }
  1938. }
  1939. void DisplayServerOSX::delete_sub_window(WindowID p_id) {
  1940. _THREAD_SAFE_METHOD_
  1941. ERR_FAIL_COND(!windows.has(p_id));
  1942. ERR_FAIL_COND_MSG(p_id == MAIN_WINDOW_ID, "Main window can't be deleted");
  1943. WindowData &wd = windows[p_id];
  1944. [wd.window_object setContentView:nil];
  1945. [wd.window_object close];
  1946. }
  1947. void DisplayServerOSX::window_set_title(const String &p_title, WindowID p_window) {
  1948. _THREAD_SAFE_METHOD_
  1949. ERR_FAIL_COND(!windows.has(p_window));
  1950. WindowData &wd = windows[p_window];
  1951. [wd.window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
  1952. }
  1953. void DisplayServerOSX::window_set_mouse_passthrough(const Vector<Vector2> &p_region, WindowID p_window) {
  1954. _THREAD_SAFE_METHOD_
  1955. ERR_FAIL_COND(!windows.has(p_window));
  1956. WindowData &wd = windows[p_window];
  1957. wd.mpath = p_region;
  1958. }
  1959. void DisplayServerOSX::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  1960. _THREAD_SAFE_METHOD_
  1961. ERR_FAIL_COND(!windows.has(p_window));
  1962. WindowData &wd = windows[p_window];
  1963. wd.rect_changed_callback = p_callable;
  1964. }
  1965. void DisplayServerOSX::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  1966. _THREAD_SAFE_METHOD_
  1967. ERR_FAIL_COND(!windows.has(p_window));
  1968. WindowData &wd = windows[p_window];
  1969. wd.event_callback = p_callable;
  1970. }
  1971. void DisplayServerOSX::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  1972. _THREAD_SAFE_METHOD_
  1973. ERR_FAIL_COND(!windows.has(p_window));
  1974. WindowData &wd = windows[p_window];
  1975. wd.input_event_callback = p_callable;
  1976. }
  1977. void DisplayServerOSX::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  1978. _THREAD_SAFE_METHOD_
  1979. ERR_FAIL_COND(!windows.has(p_window));
  1980. WindowData &wd = windows[p_window];
  1981. wd.input_text_callback = p_callable;
  1982. }
  1983. void DisplayServerOSX::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  1984. _THREAD_SAFE_METHOD_
  1985. ERR_FAIL_COND(!windows.has(p_window));
  1986. WindowData &wd = windows[p_window];
  1987. wd.drop_files_callback = p_callable;
  1988. }
  1989. int DisplayServerOSX::window_get_current_screen(WindowID p_window) const {
  1990. _THREAD_SAFE_METHOD_
  1991. ERR_FAIL_COND_V(!windows.has(p_window), -1);
  1992. const WindowData &wd = windows[p_window];
  1993. const NSUInteger index = [[NSScreen screens] indexOfObject:[wd.window_object screen]];
  1994. return (index == NSNotFound) ? 0 : index;
  1995. }
  1996. void DisplayServerOSX::window_set_current_screen(int p_screen, WindowID p_window) {
  1997. _THREAD_SAFE_METHOD_
  1998. Point2i wpos = window_get_position(p_window) - screen_get_position(window_get_current_screen(p_window));
  1999. window_set_position(wpos + screen_get_position(p_screen), p_window);
  2000. }
  2001. void DisplayServerOSX::window_set_transient(WindowID p_window, WindowID p_parent) {
  2002. _THREAD_SAFE_METHOD_
  2003. ERR_FAIL_COND(p_window == p_parent);
  2004. ERR_FAIL_COND(!windows.has(p_window));
  2005. WindowData &wd_window = windows[p_window];
  2006. ERR_FAIL_COND(wd_window.transient_parent == p_parent);
  2007. ERR_FAIL_COND_MSG(wd_window.on_top, "Windows with the 'on top' can't become transient.");
  2008. if (p_parent == INVALID_WINDOW_ID) {
  2009. //remove transient
  2010. ERR_FAIL_COND(wd_window.transient_parent == INVALID_WINDOW_ID);
  2011. ERR_FAIL_COND(!windows.has(wd_window.transient_parent));
  2012. WindowData &wd_parent = windows[wd_window.transient_parent];
  2013. wd_window.transient_parent = INVALID_WINDOW_ID;
  2014. wd_parent.transient_children.erase(p_window);
  2015. [wd_parent.window_object removeChildWindow:wd_window.window_object];
  2016. } else {
  2017. ERR_FAIL_COND(!windows.has(p_parent));
  2018. ERR_FAIL_COND_MSG(wd_window.transient_parent != INVALID_WINDOW_ID, "Window already has a transient parent");
  2019. WindowData &wd_parent = windows[p_parent];
  2020. wd_window.transient_parent = p_parent;
  2021. wd_parent.transient_children.insert(p_window);
  2022. [wd_parent.window_object addChildWindow:wd_window.window_object ordered:NSWindowAbove];
  2023. }
  2024. }
  2025. Point2i DisplayServerOSX::window_get_position(WindowID p_window) const {
  2026. _THREAD_SAFE_METHOD_
  2027. ERR_FAIL_COND_V(!windows.has(p_window), Point2i());
  2028. const WindowData &wd = windows[p_window];
  2029. NSRect nsrect = [wd.window_object frame];
  2030. Point2i pos;
  2031. // Return the position of the top-left corner, for OS X the y starts at the bottom
  2032. const float scale = screen_get_max_scale();
  2033. pos.x = nsrect.origin.x;
  2034. pos.y = (nsrect.origin.y + nsrect.size.height);
  2035. pos *= scale;
  2036. pos -= _get_screens_origin();
  2037. // OS X native y-coordinate relative to _get_screens_origin() is negative,
  2038. // Godot expects a positive value
  2039. pos.y *= -1;
  2040. return pos;
  2041. }
  2042. void DisplayServerOSX::window_set_position(const Point2i &p_position, WindowID p_window) {
  2043. _THREAD_SAFE_METHOD_
  2044. ERR_FAIL_COND(!windows.has(p_window));
  2045. WindowData &wd = windows[p_window];
  2046. Point2i position = p_position;
  2047. // OS X native y-coordinate relative to _get_screens_origin() is negative,
  2048. // Godot passes a positive value
  2049. position.y *= -1;
  2050. position += _get_screens_origin();
  2051. position /= screen_get_max_scale();
  2052. [wd.window_object setFrameTopLeftPoint:NSMakePoint(position.x, position.y)];
  2053. _update_window(wd);
  2054. _get_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  2055. }
  2056. void DisplayServerOSX::window_set_max_size(const Size2i p_size, WindowID p_window) {
  2057. _THREAD_SAFE_METHOD_
  2058. ERR_FAIL_COND(!windows.has(p_window));
  2059. WindowData &wd = windows[p_window];
  2060. if ((p_size != Size2i()) && ((p_size.x < wd.min_size.x) || (p_size.y < wd.min_size.y))) {
  2061. ERR_PRINT("Maximum window size can't be smaller than minimum window size!");
  2062. return;
  2063. }
  2064. wd.max_size = p_size;
  2065. if ((wd.max_size != Size2i()) && !wd.fullscreen) {
  2066. Size2i size = wd.max_size / screen_get_max_scale();
  2067. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  2068. } else {
  2069. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  2070. }
  2071. }
  2072. Size2i DisplayServerOSX::window_get_max_size(WindowID p_window) const {
  2073. _THREAD_SAFE_METHOD_
  2074. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  2075. const WindowData &wd = windows[p_window];
  2076. return wd.max_size;
  2077. }
  2078. void DisplayServerOSX::window_set_min_size(const Size2i p_size, WindowID p_window) {
  2079. _THREAD_SAFE_METHOD_
  2080. ERR_FAIL_COND(!windows.has(p_window));
  2081. WindowData &wd = windows[p_window];
  2082. if ((p_size != Size2i()) && (wd.max_size != Size2i()) && ((p_size.x > wd.max_size.x) || (p_size.y > wd.max_size.y))) {
  2083. ERR_PRINT("Minimum window size can't be larger than maximum window size!");
  2084. return;
  2085. }
  2086. wd.min_size = p_size;
  2087. if ((wd.min_size != Size2i()) && !wd.fullscreen) {
  2088. Size2i size = wd.min_size / screen_get_max_scale();
  2089. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  2090. } else {
  2091. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  2092. }
  2093. }
  2094. Size2i DisplayServerOSX::window_get_min_size(WindowID p_window) const {
  2095. _THREAD_SAFE_METHOD_
  2096. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  2097. const WindowData &wd = windows[p_window];
  2098. return wd.min_size;
  2099. }
  2100. void DisplayServerOSX::window_set_size(const Size2i p_size, WindowID p_window) {
  2101. _THREAD_SAFE_METHOD_
  2102. ERR_FAIL_COND(!windows.has(p_window));
  2103. WindowData &wd = windows[p_window];
  2104. Size2i size = p_size / screen_get_max_scale();
  2105. NSPoint top_left;
  2106. NSRect old_frame = [wd.window_object frame];
  2107. top_left.x = old_frame.origin.x;
  2108. top_left.y = NSMaxY(old_frame);
  2109. NSRect new_frame = NSMakeRect(0, 0, size.x, size.y);
  2110. new_frame = [wd.window_object frameRectForContentRect:new_frame];
  2111. new_frame.origin.x = top_left.x;
  2112. new_frame.origin.y = top_left.y - new_frame.size.height;
  2113. [wd.window_object setFrame:new_frame display:YES];
  2114. _update_window(wd);
  2115. }
  2116. Size2i DisplayServerOSX::window_get_size(WindowID p_window) const {
  2117. _THREAD_SAFE_METHOD_
  2118. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  2119. const WindowData &wd = windows[p_window];
  2120. return wd.size;
  2121. }
  2122. Size2i DisplayServerOSX::window_get_real_size(WindowID p_window) const {
  2123. _THREAD_SAFE_METHOD_
  2124. ERR_FAIL_COND_V(!windows.has(p_window), Size2i());
  2125. const WindowData &wd = windows[p_window];
  2126. NSRect frame = [wd.window_object frame];
  2127. return Size2i(frame.size.width, frame.size.height) * screen_get_max_scale();
  2128. }
  2129. bool DisplayServerOSX::window_is_maximize_allowed(WindowID p_window) const {
  2130. return true;
  2131. }
  2132. void DisplayServerOSX::_set_window_per_pixel_transparency_enabled(bool p_enabled, WindowID p_window) {
  2133. ERR_FAIL_COND(!windows.has(p_window));
  2134. WindowData &wd = windows[p_window];
  2135. if (!OS_OSX::get_singleton()->is_layered_allowed()) {
  2136. return;
  2137. }
  2138. if (wd.layered_window != p_enabled) {
  2139. if (p_enabled) {
  2140. [wd.window_object setBackgroundColor:[NSColor clearColor]];
  2141. [wd.window_object setOpaque:NO];
  2142. [wd.window_object setHasShadow:NO];
  2143. CALayer *layer = [wd.window_view layer];
  2144. if (layer) {
  2145. [layer setOpaque:NO];
  2146. }
  2147. #if defined(VULKAN_ENABLED)
  2148. if (rendering_driver == "vulkan") {
  2149. //TODO - implement transparency for Vulkan
  2150. }
  2151. #endif
  2152. #if defined(GLES3_ENABLED)
  2153. if (rendering_driver == "opengl3") {
  2154. //TODO - reimplement OpenGLES
  2155. }
  2156. #endif
  2157. wd.layered_window = true;
  2158. } else {
  2159. [wd.window_object setBackgroundColor:[NSColor colorWithCalibratedWhite:1 alpha:1]];
  2160. [wd.window_object setOpaque:YES];
  2161. [wd.window_object setHasShadow:YES];
  2162. CALayer *layer = [wd.window_view layer];
  2163. if (layer) {
  2164. [layer setOpaque:YES];
  2165. }
  2166. #if defined(VULKAN_ENABLED)
  2167. if (rendering_driver == "vulkan") {
  2168. //TODO - implement transparency for Vulkan
  2169. }
  2170. #endif
  2171. #if defined(GLES3_ENABLED)
  2172. if (rendering_driver == "opengl3") {
  2173. //TODO - reimplement OpenGLES
  2174. }
  2175. #endif
  2176. wd.layered_window = false;
  2177. }
  2178. #if defined(GLES3_ENABLED)
  2179. if (rendering_driver == "opengl3") {
  2180. //TODO - reimplement OpenGLES
  2181. }
  2182. #endif
  2183. #if defined(VULKAN_ENABLED)
  2184. if (rendering_driver == "vulkan") {
  2185. //TODO - implement transparency for Vulkan
  2186. }
  2187. #endif
  2188. NSRect frameRect = [wd.window_object frame];
  2189. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:YES];
  2190. [wd.window_object setFrame:frameRect display:YES];
  2191. }
  2192. }
  2193. void DisplayServerOSX::window_set_mode(WindowMode p_mode, WindowID p_window) {
  2194. _THREAD_SAFE_METHOD_
  2195. ERR_FAIL_COND(!windows.has(p_window));
  2196. WindowData &wd = windows[p_window];
  2197. WindowMode old_mode = window_get_mode(p_window);
  2198. if (old_mode == p_mode) {
  2199. return; // do nothing
  2200. }
  2201. switch (old_mode) {
  2202. case WINDOW_MODE_WINDOWED: {
  2203. //do nothing
  2204. } break;
  2205. case WINDOW_MODE_MINIMIZED: {
  2206. [wd.window_object deminiaturize:nil];
  2207. } break;
  2208. case WINDOW_MODE_FULLSCREEN: {
  2209. [wd.window_object setLevel:NSNormalWindowLevel];
  2210. if (wd.layered_window) {
  2211. _set_window_per_pixel_transparency_enabled(true, p_window);
  2212. }
  2213. if (wd.resize_disabled) { //restore resize disabled
  2214. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2215. }
  2216. if (wd.min_size != Size2i()) {
  2217. Size2i size = wd.min_size / screen_get_max_scale();
  2218. [wd.window_object setContentMinSize:NSMakeSize(size.x, size.y)];
  2219. }
  2220. if (wd.max_size != Size2i()) {
  2221. Size2i size = wd.max_size / screen_get_max_scale();
  2222. [wd.window_object setContentMaxSize:NSMakeSize(size.x, size.y)];
  2223. }
  2224. [wd.window_object toggleFullScreen:nil];
  2225. wd.fullscreen = false;
  2226. } break;
  2227. case WINDOW_MODE_MAXIMIZED: {
  2228. if ([wd.window_object isZoomed]) {
  2229. [wd.window_object zoom:nil];
  2230. }
  2231. } break;
  2232. }
  2233. switch (p_mode) {
  2234. case WINDOW_MODE_WINDOWED: {
  2235. //do nothing
  2236. } break;
  2237. case WINDOW_MODE_MINIMIZED: {
  2238. [wd.window_object performMiniaturize:nil];
  2239. } break;
  2240. case WINDOW_MODE_FULLSCREEN: {
  2241. if (wd.layered_window)
  2242. _set_window_per_pixel_transparency_enabled(false, p_window);
  2243. if (wd.resize_disabled) //fullscreen window should be resizable to work
  2244. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2245. [wd.window_object setContentMinSize:NSMakeSize(0, 0)];
  2246. [wd.window_object setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
  2247. [wd.window_object toggleFullScreen:nil];
  2248. wd.fullscreen = true;
  2249. } break;
  2250. case WINDOW_MODE_MAXIMIZED: {
  2251. if (![wd.window_object isZoomed]) {
  2252. [wd.window_object zoom:nil];
  2253. }
  2254. } break;
  2255. }
  2256. }
  2257. DisplayServer::WindowMode DisplayServerOSX::window_get_mode(WindowID p_window) const {
  2258. _THREAD_SAFE_METHOD_
  2259. ERR_FAIL_COND_V(!windows.has(p_window), WINDOW_MODE_WINDOWED);
  2260. const WindowData &wd = windows[p_window];
  2261. if (wd.fullscreen) { //if fullscreen, it's not in another mode
  2262. return WINDOW_MODE_FULLSCREEN;
  2263. }
  2264. if ([wd.window_object isZoomed] && !wd.resize_disabled) {
  2265. return WINDOW_MODE_MAXIMIZED;
  2266. }
  2267. if ([wd.window_object respondsToSelector:@selector(isMiniaturized)]) {
  2268. if ([wd.window_object isMiniaturized]) {
  2269. return WINDOW_MODE_MINIMIZED;
  2270. }
  2271. }
  2272. // all other discarded, return windowed.
  2273. return WINDOW_MODE_WINDOWED;
  2274. }
  2275. void DisplayServerOSX::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  2276. _THREAD_SAFE_METHOD_
  2277. ERR_FAIL_COND(!windows.has(p_window));
  2278. WindowData &wd = windows[p_window];
  2279. switch (p_flag) {
  2280. case WINDOW_FLAG_RESIZE_DISABLED: {
  2281. wd.resize_disabled = p_enabled;
  2282. if (wd.fullscreen) { //fullscreen window should be resizable, style will be applied on exiting fs
  2283. return;
  2284. }
  2285. if (p_enabled) {
  2286. [wd.window_object setStyleMask:[wd.window_object styleMask] & ~NSWindowStyleMaskResizable];
  2287. } else {
  2288. [wd.window_object setStyleMask:[wd.window_object styleMask] | NSWindowStyleMaskResizable];
  2289. }
  2290. } break;
  2291. case WINDOW_FLAG_BORDERLESS: {
  2292. // OrderOut prevents a lose focus bug with the window
  2293. if ([wd.window_object isVisible]) {
  2294. [wd.window_object orderOut:nil];
  2295. }
  2296. wd.borderless = p_enabled;
  2297. if (p_enabled) {
  2298. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless];
  2299. } else {
  2300. if (wd.layered_window)
  2301. _set_window_per_pixel_transparency_enabled(false, p_window);
  2302. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2303. // Force update of the window styles
  2304. NSRect frameRect = [wd.window_object frame];
  2305. [wd.window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  2306. [wd.window_object setFrame:frameRect display:NO];
  2307. }
  2308. _update_window(wd);
  2309. if ([wd.window_object isVisible]) {
  2310. if (wd.no_focus) {
  2311. [wd.window_object orderFront:nil];
  2312. } else {
  2313. [wd.window_object makeKeyAndOrderFront:nil];
  2314. }
  2315. }
  2316. } break;
  2317. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2318. wd.on_top = p_enabled;
  2319. if (wd.fullscreen) {
  2320. return;
  2321. }
  2322. if (p_enabled) {
  2323. [wd.window_object setLevel:NSFloatingWindowLevel];
  2324. } else {
  2325. [wd.window_object setLevel:NSNormalWindowLevel];
  2326. }
  2327. } break;
  2328. case WINDOW_FLAG_TRANSPARENT: {
  2329. wd.layered_window = p_enabled;
  2330. if (p_enabled) {
  2331. [wd.window_object setStyleMask:NSWindowStyleMaskBorderless]; // force borderless
  2332. } else if (!wd.borderless) {
  2333. [wd.window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (wd.resize_disabled ? 0 : NSWindowStyleMaskResizable)];
  2334. }
  2335. _set_window_per_pixel_transparency_enabled(p_enabled, p_window);
  2336. } break;
  2337. case WINDOW_FLAG_NO_FOCUS: {
  2338. wd.no_focus = p_enabled;
  2339. } break;
  2340. default: {
  2341. }
  2342. }
  2343. }
  2344. bool DisplayServerOSX::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  2345. _THREAD_SAFE_METHOD_
  2346. ERR_FAIL_COND_V(!windows.has(p_window), false);
  2347. const WindowData &wd = windows[p_window];
  2348. switch (p_flag) {
  2349. case WINDOW_FLAG_RESIZE_DISABLED: {
  2350. return wd.resize_disabled;
  2351. } break;
  2352. case WINDOW_FLAG_BORDERLESS: {
  2353. return [wd.window_object styleMask] == NSWindowStyleMaskBorderless;
  2354. } break;
  2355. case WINDOW_FLAG_ALWAYS_ON_TOP: {
  2356. if (wd.fullscreen) {
  2357. return wd.on_top;
  2358. } else {
  2359. return [wd.window_object level] == NSFloatingWindowLevel;
  2360. }
  2361. } break;
  2362. case WINDOW_FLAG_TRANSPARENT: {
  2363. return wd.layered_window;
  2364. } break;
  2365. case WINDOW_FLAG_NO_FOCUS: {
  2366. return wd.no_focus;
  2367. } break;
  2368. default: {
  2369. }
  2370. }
  2371. return false;
  2372. }
  2373. void DisplayServerOSX::window_request_attention(WindowID p_window) {
  2374. // It's app global, ignore window id.
  2375. [NSApp requestUserAttention:NSCriticalRequest];
  2376. }
  2377. void DisplayServerOSX::window_move_to_foreground(WindowID p_window) {
  2378. _THREAD_SAFE_METHOD_
  2379. ERR_FAIL_COND(!windows.has(p_window));
  2380. const WindowData &wd = windows[p_window];
  2381. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  2382. if (wd.no_focus) {
  2383. [wd.window_object orderFront:nil];
  2384. } else {
  2385. [wd.window_object makeKeyAndOrderFront:nil];
  2386. }
  2387. }
  2388. bool DisplayServerOSX::window_can_draw(WindowID p_window) const {
  2389. return window_get_mode(p_window) != WINDOW_MODE_MINIMIZED;
  2390. }
  2391. bool DisplayServerOSX::can_any_window_draw() const {
  2392. _THREAD_SAFE_METHOD_
  2393. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  2394. if (window_get_mode(E->key()) != WINDOW_MODE_MINIMIZED) {
  2395. return true;
  2396. }
  2397. }
  2398. return false;
  2399. }
  2400. void DisplayServerOSX::window_set_ime_active(const bool p_active, WindowID p_window) {
  2401. _THREAD_SAFE_METHOD_
  2402. ERR_FAIL_COND(!windows.has(p_window));
  2403. WindowData &wd = windows[p_window];
  2404. wd.im_active = p_active;
  2405. if (!p_active) {
  2406. [wd.window_view cancelComposition];
  2407. }
  2408. }
  2409. void DisplayServerOSX::window_set_ime_position(const Point2i &p_pos, WindowID p_window) {
  2410. _THREAD_SAFE_METHOD_
  2411. ERR_FAIL_COND(!windows.has(p_window));
  2412. WindowData &wd = windows[p_window];
  2413. wd.im_position = p_pos;
  2414. }
  2415. bool DisplayServerOSX::get_swap_cancel_ok() {
  2416. return false;
  2417. }
  2418. void DisplayServerOSX::cursor_set_shape(CursorShape p_shape) {
  2419. _THREAD_SAFE_METHOD_
  2420. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  2421. if (cursor_shape == p_shape) {
  2422. return;
  2423. }
  2424. if (mouse_mode != MOUSE_MODE_VISIBLE && mouse_mode != MOUSE_MODE_CONFINED) {
  2425. cursor_shape = p_shape;
  2426. return;
  2427. }
  2428. if (cursors[p_shape] != nullptr) {
  2429. [cursors[p_shape] set];
  2430. } else {
  2431. switch (p_shape) {
  2432. case CURSOR_ARROW:
  2433. [[NSCursor arrowCursor] set];
  2434. break;
  2435. case CURSOR_IBEAM:
  2436. [[NSCursor IBeamCursor] set];
  2437. break;
  2438. case CURSOR_POINTING_HAND:
  2439. [[NSCursor pointingHandCursor] set];
  2440. break;
  2441. case CURSOR_CROSS:
  2442. [[NSCursor crosshairCursor] set];
  2443. break;
  2444. case CURSOR_WAIT:
  2445. [[NSCursor arrowCursor] set];
  2446. break;
  2447. case CURSOR_BUSY:
  2448. [[NSCursor arrowCursor] set];
  2449. break;
  2450. case CURSOR_DRAG:
  2451. [[NSCursor closedHandCursor] set];
  2452. break;
  2453. case CURSOR_CAN_DROP:
  2454. [[NSCursor openHandCursor] set];
  2455. break;
  2456. case CURSOR_FORBIDDEN:
  2457. [[NSCursor operationNotAllowedCursor] set];
  2458. break;
  2459. case CURSOR_VSIZE:
  2460. [_cursorFromSelector(@selector(_windowResizeNorthSouthCursor), @selector(resizeUpDownCursor)) set];
  2461. break;
  2462. case CURSOR_HSIZE:
  2463. [_cursorFromSelector(@selector(_windowResizeEastWestCursor), @selector(resizeLeftRightCursor)) set];
  2464. break;
  2465. case CURSOR_BDIAGSIZE:
  2466. [_cursorFromSelector(@selector(_windowResizeNorthEastSouthWestCursor)) set];
  2467. break;
  2468. case CURSOR_FDIAGSIZE:
  2469. [_cursorFromSelector(@selector(_windowResizeNorthWestSouthEastCursor)) set];
  2470. break;
  2471. case CURSOR_MOVE:
  2472. [[NSCursor arrowCursor] set];
  2473. break;
  2474. case CURSOR_VSPLIT:
  2475. [[NSCursor resizeUpDownCursor] set];
  2476. break;
  2477. case CURSOR_HSPLIT:
  2478. [[NSCursor resizeLeftRightCursor] set];
  2479. break;
  2480. case CURSOR_HELP:
  2481. [_cursorFromSelector(@selector(_helpCursor)) set];
  2482. break;
  2483. default: {
  2484. }
  2485. }
  2486. }
  2487. cursor_shape = p_shape;
  2488. }
  2489. DisplayServerOSX::CursorShape DisplayServerOSX::cursor_get_shape() const {
  2490. return cursor_shape;
  2491. }
  2492. void DisplayServerOSX::cursor_set_custom_image(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  2493. _THREAD_SAFE_METHOD_
  2494. if (p_cursor.is_valid()) {
  2495. Map<CursorShape, Vector<Variant>>::Element *cursor_c = cursors_cache.find(p_shape);
  2496. if (cursor_c) {
  2497. if (cursor_c->get()[0] == p_cursor && cursor_c->get()[1] == p_hotspot) {
  2498. cursor_set_shape(p_shape);
  2499. return;
  2500. }
  2501. cursors_cache.erase(p_shape);
  2502. }
  2503. Ref<Texture2D> texture = p_cursor;
  2504. Ref<AtlasTexture> atlas_texture = p_cursor;
  2505. Ref<Image> image;
  2506. Size2 texture_size;
  2507. Rect2 atlas_rect;
  2508. if (texture.is_valid()) {
  2509. image = texture->get_image();
  2510. }
  2511. if (!image.is_valid() && atlas_texture.is_valid()) {
  2512. texture = atlas_texture->get_atlas();
  2513. atlas_rect.size.width = texture->get_width();
  2514. atlas_rect.size.height = texture->get_height();
  2515. atlas_rect.position.x = atlas_texture->get_region().position.x;
  2516. atlas_rect.position.y = atlas_texture->get_region().position.y;
  2517. texture_size.width = atlas_texture->get_region().size.x;
  2518. texture_size.height = atlas_texture->get_region().size.y;
  2519. } else if (image.is_valid()) {
  2520. texture_size.width = texture->get_width();
  2521. texture_size.height = texture->get_height();
  2522. }
  2523. ERR_FAIL_COND(!texture.is_valid());
  2524. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  2525. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  2526. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  2527. image = texture->get_image();
  2528. ERR_FAIL_COND(!image.is_valid());
  2529. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2530. initWithBitmapDataPlanes:nullptr
  2531. pixelsWide:int(texture_size.width)
  2532. pixelsHigh:int(texture_size.height)
  2533. bitsPerSample:8
  2534. samplesPerPixel:4
  2535. hasAlpha:YES
  2536. isPlanar:NO
  2537. colorSpaceName:NSDeviceRGBColorSpace
  2538. bytesPerRow:int(texture_size.width) * 4
  2539. bitsPerPixel:32];
  2540. ERR_FAIL_COND(imgrep == nil);
  2541. uint8_t *pixels = [imgrep bitmapData];
  2542. int len = int(texture_size.width * texture_size.height);
  2543. for (int i = 0; i < len; i++) {
  2544. int row_index = floor(i / texture_size.width) + atlas_rect.position.y;
  2545. int column_index = (i % int(texture_size.width)) + atlas_rect.position.x;
  2546. if (atlas_texture.is_valid()) {
  2547. column_index = MIN(column_index, atlas_rect.size.width - 1);
  2548. row_index = MIN(row_index, atlas_rect.size.height - 1);
  2549. }
  2550. uint32_t color = image->get_pixel(column_index, row_index).to_argb32();
  2551. uint8_t alpha = (color >> 24) & 0xFF;
  2552. pixels[i * 4 + 0] = ((color >> 16) & 0xFF) * alpha / 255;
  2553. pixels[i * 4 + 1] = ((color >> 8) & 0xFF) * alpha / 255;
  2554. pixels[i * 4 + 2] = ((color)&0xFF) * alpha / 255;
  2555. pixels[i * 4 + 3] = alpha;
  2556. }
  2557. NSImage *nsimage = [[NSImage alloc] initWithSize:NSMakeSize(texture_size.width, texture_size.height)];
  2558. [nsimage addRepresentation:imgrep];
  2559. NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
  2560. [cursors[p_shape] release];
  2561. cursors[p_shape] = cursor;
  2562. Vector<Variant> params;
  2563. params.push_back(p_cursor);
  2564. params.push_back(p_hotspot);
  2565. cursors_cache.insert(p_shape, params);
  2566. if (p_shape == cursor_shape) {
  2567. if (mouse_mode == MOUSE_MODE_VISIBLE || mouse_mode == MOUSE_MODE_CONFINED) {
  2568. [cursor set];
  2569. }
  2570. }
  2571. [imgrep release];
  2572. [nsimage release];
  2573. } else {
  2574. // Reset to default system cursor
  2575. if (cursors[p_shape] != nullptr) {
  2576. [cursors[p_shape] release];
  2577. cursors[p_shape] = nullptr;
  2578. }
  2579. CursorShape c = cursor_shape;
  2580. cursor_shape = CURSOR_MAX;
  2581. cursor_set_shape(c);
  2582. cursors_cache.erase(p_shape);
  2583. }
  2584. }
  2585. struct LayoutInfo {
  2586. String name;
  2587. String code;
  2588. };
  2589. static Vector<LayoutInfo> kbd_layouts;
  2590. static int current_layout = 0;
  2591. static bool keyboard_layout_dirty = true;
  2592. static void keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
  2593. kbd_layouts.clear();
  2594. current_layout = 0;
  2595. keyboard_layout_dirty = true;
  2596. }
  2597. void _update_keyboard_layouts() {
  2598. @autoreleasepool {
  2599. TISInputSourceRef cur_source = TISCopyCurrentKeyboardInputSource();
  2600. NSString *cur_name = (NSString *)TISGetInputSourceProperty(cur_source, kTISPropertyLocalizedName);
  2601. CFRelease(cur_source);
  2602. // Enum IME layouts
  2603. NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
  2604. NSArray *list_ime = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_ime, false);
  2605. for (NSUInteger i = 0; i < [list_ime count]; i++) {
  2606. LayoutInfo ly;
  2607. NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
  2608. ly.name.parse_utf8([name UTF8String]);
  2609. NSArray *langs = (NSArray *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyInputSourceLanguages);
  2610. ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
  2611. kbd_layouts.push_back(ly);
  2612. if ([name isEqualToString:cur_name]) {
  2613. current_layout = kbd_layouts.size() - 1;
  2614. }
  2615. }
  2616. [list_ime release];
  2617. // Enum plain keyboard layouts
  2618. NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
  2619. NSArray *list_kbd = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_kbd, false);
  2620. for (NSUInteger i = 0; i < [list_kbd count]; i++) {
  2621. LayoutInfo ly;
  2622. NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
  2623. ly.name.parse_utf8([name UTF8String]);
  2624. NSArray *langs = (NSArray *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyInputSourceLanguages);
  2625. ly.code.parse_utf8([(NSString *)[langs objectAtIndex:0] UTF8String]);
  2626. kbd_layouts.push_back(ly);
  2627. if ([name isEqualToString:cur_name]) {
  2628. current_layout = kbd_layouts.size() - 1;
  2629. }
  2630. }
  2631. [list_kbd release];
  2632. }
  2633. keyboard_layout_dirty = false;
  2634. }
  2635. int DisplayServerOSX::keyboard_get_layout_count() const {
  2636. if (keyboard_layout_dirty) {
  2637. _update_keyboard_layouts();
  2638. }
  2639. return kbd_layouts.size();
  2640. }
  2641. void DisplayServerOSX::keyboard_set_current_layout(int p_index) {
  2642. if (keyboard_layout_dirty) {
  2643. _update_keyboard_layouts();
  2644. }
  2645. ERR_FAIL_INDEX(p_index, kbd_layouts.size());
  2646. NSString *cur_name = [NSString stringWithUTF8String:kbd_layouts[p_index].name.utf8().get_data()];
  2647. NSDictionary *filter_kbd = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardLayout };
  2648. NSArray *list_kbd = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_kbd, false);
  2649. for (NSUInteger i = 0; i < [list_kbd count]; i++) {
  2650. NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_kbd objectAtIndex:i], kTISPropertyLocalizedName);
  2651. if ([name isEqualToString:cur_name]) {
  2652. TISSelectInputSource((TISInputSourceRef)[list_kbd objectAtIndex:i]);
  2653. break;
  2654. }
  2655. }
  2656. [list_kbd release];
  2657. NSDictionary *filter_ime = @{ (NSString *)kTISPropertyInputSourceType : (NSString *)kTISTypeKeyboardInputMode };
  2658. NSArray *list_ime = (NSArray *)TISCreateInputSourceList((CFDictionaryRef)filter_ime, false);
  2659. for (NSUInteger i = 0; i < [list_ime count]; i++) {
  2660. NSString *name = (NSString *)TISGetInputSourceProperty((TISInputSourceRef)[list_ime objectAtIndex:i], kTISPropertyLocalizedName);
  2661. if ([name isEqualToString:cur_name]) {
  2662. TISSelectInputSource((TISInputSourceRef)[list_ime objectAtIndex:i]);
  2663. break;
  2664. }
  2665. }
  2666. [list_ime release];
  2667. }
  2668. int DisplayServerOSX::keyboard_get_current_layout() const {
  2669. if (keyboard_layout_dirty) {
  2670. _update_keyboard_layouts();
  2671. }
  2672. return current_layout;
  2673. }
  2674. String DisplayServerOSX::keyboard_get_layout_language(int p_index) const {
  2675. if (keyboard_layout_dirty) {
  2676. _update_keyboard_layouts();
  2677. }
  2678. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2679. return kbd_layouts[p_index].code;
  2680. }
  2681. String DisplayServerOSX::keyboard_get_layout_name(int p_index) const {
  2682. if (keyboard_layout_dirty) {
  2683. _update_keyboard_layouts();
  2684. }
  2685. ERR_FAIL_INDEX_V(p_index, kbd_layouts.size(), "");
  2686. return kbd_layouts[p_index].name;
  2687. }
  2688. Key DisplayServerOSX::keyboard_get_keycode_from_physical(Key p_keycode) const {
  2689. if (p_keycode == KEY_PAUSE) {
  2690. return p_keycode;
  2691. }
  2692. unsigned int modifiers = p_keycode & KEY_MODIFIER_MASK;
  2693. unsigned int keycode_no_mod = p_keycode & KEY_CODE_MASK;
  2694. unsigned int osx_keycode = unmapKey((Key)keycode_no_mod);
  2695. return (Key)(remapKey(osx_keycode, 0) | modifiers);
  2696. }
  2697. void DisplayServerOSX::_push_input(const Ref<InputEvent> &p_event) {
  2698. Ref<InputEvent> ev = p_event;
  2699. Input::get_singleton()->parse_input_event(ev);
  2700. }
  2701. void DisplayServerOSX::_release_pressed_events() {
  2702. _THREAD_SAFE_METHOD_
  2703. if (Input::get_singleton()) {
  2704. Input::get_singleton()->release_pressed_events();
  2705. }
  2706. }
  2707. NSMenu *DisplayServerOSX::_get_dock_menu() const {
  2708. return dock_menu;
  2709. }
  2710. void DisplayServerOSX::_menu_callback(id p_sender) {
  2711. if (![p_sender representedObject]) {
  2712. return;
  2713. }
  2714. GlobalMenuItem *value = [p_sender representedObject];
  2715. if (value) {
  2716. if (value->checkable) {
  2717. if ([p_sender state] == NSControlStateValueOff) {
  2718. [p_sender setState:NSControlStateValueOn];
  2719. } else {
  2720. [p_sender setState:NSControlStateValueOff];
  2721. }
  2722. }
  2723. if (value->callback != Callable()) {
  2724. Variant tag = value->meta;
  2725. Variant *tagp = &tag;
  2726. Variant ret;
  2727. Callable::CallError ce;
  2728. value->callback.call((const Variant **)&tagp, 1, ret, ce);
  2729. }
  2730. }
  2731. }
  2732. void DisplayServerOSX::_send_event(NSEvent *p_event) {
  2733. // special case handling of command-period, which is traditionally a special
  2734. // shortcut in macOS and doesn't arrive at our regular keyDown handler.
  2735. if ([p_event type] == NSEventTypeKeyDown) {
  2736. if (([p_event modifierFlags] & NSEventModifierFlagCommand) && [p_event keyCode] == 0x2f) {
  2737. Ref<InputEventKey> k;
  2738. k.instantiate();
  2739. _get_key_modifier_state([p_event modifierFlags], k);
  2740. k->set_window_id(DisplayServerOSX::INVALID_WINDOW_ID);
  2741. k->set_pressed(true);
  2742. k->set_keycode(KEY_PERIOD);
  2743. k->set_physical_keycode(KEY_PERIOD);
  2744. k->set_echo([p_event isARepeat]);
  2745. Input::get_singleton()->parse_input_event(k);
  2746. }
  2747. }
  2748. }
  2749. void DisplayServerOSX::_process_key_events() {
  2750. Ref<InputEventKey> k;
  2751. for (int i = 0; i < key_event_pos; i++) {
  2752. const KeyEvent &ke = key_event_buffer[i];
  2753. if (ke.raw) {
  2754. // Non IME input - no composite characters, pass events as is
  2755. k.instantiate();
  2756. k->set_window_id(ke.window_id);
  2757. _get_key_modifier_state(ke.osx_state, k);
  2758. k->set_pressed(ke.pressed);
  2759. k->set_echo(ke.echo);
  2760. k->set_keycode(ke.keycode);
  2761. k->set_physical_keycode((Key)ke.physical_keycode);
  2762. k->set_unicode(ke.unicode);
  2763. _push_input(k);
  2764. } else {
  2765. // IME input
  2766. if ((i == 0 && ke.keycode == 0) || (i > 0 && key_event_buffer[i - 1].keycode == 0)) {
  2767. k.instantiate();
  2768. k->set_window_id(ke.window_id);
  2769. _get_key_modifier_state(ke.osx_state, k);
  2770. k->set_pressed(ke.pressed);
  2771. k->set_echo(ke.echo);
  2772. k->set_keycode(KEY_NONE);
  2773. k->set_physical_keycode(KEY_NONE);
  2774. k->set_unicode(ke.unicode);
  2775. _push_input(k);
  2776. }
  2777. if (ke.keycode != 0) {
  2778. k.instantiate();
  2779. k->set_window_id(ke.window_id);
  2780. _get_key_modifier_state(ke.osx_state, k);
  2781. k->set_pressed(ke.pressed);
  2782. k->set_echo(ke.echo);
  2783. k->set_keycode(ke.keycode);
  2784. k->set_physical_keycode((Key)ke.physical_keycode);
  2785. if (i + 1 < key_event_pos && key_event_buffer[i + 1].keycode == 0) {
  2786. k->set_unicode(key_event_buffer[i + 1].unicode);
  2787. }
  2788. _push_input(k);
  2789. }
  2790. }
  2791. }
  2792. key_event_pos = 0;
  2793. }
  2794. void DisplayServerOSX::process_events() {
  2795. _THREAD_SAFE_METHOD_
  2796. while (true) {
  2797. NSEvent *event = [NSApp
  2798. nextEventMatchingMask:NSEventMaskAny
  2799. untilDate:[NSDate distantPast]
  2800. inMode:NSDefaultRunLoopMode
  2801. dequeue:YES];
  2802. if (event == nil) {
  2803. break;
  2804. }
  2805. [NSApp sendEvent:event];
  2806. }
  2807. if (!drop_events) {
  2808. _process_key_events();
  2809. Input::get_singleton()->flush_buffered_events();
  2810. }
  2811. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  2812. WindowData &wd = E->get();
  2813. if (wd.mpath.size() > 0) {
  2814. const Vector2 mpos = _get_mouse_pos(wd, [wd.window_object mouseLocationOutsideOfEventStream]);
  2815. if (Geometry2D::is_point_in_polygon(mpos, wd.mpath)) {
  2816. if ([wd.window_object ignoresMouseEvents]) {
  2817. [wd.window_object setIgnoresMouseEvents:NO];
  2818. }
  2819. } else {
  2820. if (![wd.window_object ignoresMouseEvents]) {
  2821. [wd.window_object setIgnoresMouseEvents:YES];
  2822. }
  2823. }
  2824. } else {
  2825. if ([wd.window_object ignoresMouseEvents]) {
  2826. [wd.window_object setIgnoresMouseEvents:NO];
  2827. }
  2828. }
  2829. }
  2830. [autoreleasePool drain];
  2831. autoreleasePool = [[NSAutoreleasePool alloc] init];
  2832. }
  2833. void DisplayServerOSX::force_process_and_drop_events() {
  2834. _THREAD_SAFE_METHOD_
  2835. drop_events = true;
  2836. process_events();
  2837. drop_events = false;
  2838. }
  2839. void DisplayServerOSX::set_native_icon(const String &p_filename) {
  2840. _THREAD_SAFE_METHOD_
  2841. FileAccess *f = FileAccess::open(p_filename, FileAccess::READ);
  2842. ERR_FAIL_COND(!f);
  2843. Vector<uint8_t> data;
  2844. uint64_t len = f->get_length();
  2845. data.resize(len);
  2846. f->get_buffer((uint8_t *)&data.write[0], len);
  2847. memdelete(f);
  2848. NSData *icon_data = [[[NSData alloc] initWithBytes:&data.write[0] length:len] autorelease];
  2849. ERR_FAIL_COND_MSG(!icon_data, "Error reading icon data.");
  2850. NSImage *icon = [[[NSImage alloc] initWithData:icon_data] autorelease];
  2851. ERR_FAIL_COND_MSG(!icon, "Error loading icon.");
  2852. [NSApp setApplicationIconImage:icon];
  2853. }
  2854. void DisplayServerOSX::set_icon(const Ref<Image> &p_icon) {
  2855. _THREAD_SAFE_METHOD_
  2856. Ref<Image> img = p_icon;
  2857. img = img->duplicate();
  2858. img->convert(Image::FORMAT_RGBA8);
  2859. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  2860. initWithBitmapDataPlanes:nullptr
  2861. pixelsWide:img->get_width()
  2862. pixelsHigh:img->get_height()
  2863. bitsPerSample:8
  2864. samplesPerPixel:4
  2865. hasAlpha:YES
  2866. isPlanar:NO
  2867. colorSpaceName:NSDeviceRGBColorSpace
  2868. bytesPerRow:img->get_width() * 4
  2869. bitsPerPixel:32];
  2870. ERR_FAIL_COND(imgrep == nil);
  2871. uint8_t *pixels = [imgrep bitmapData];
  2872. int len = img->get_width() * img->get_height();
  2873. const uint8_t *r = img->get_data().ptr();
  2874. /* Premultiply the alpha channel */
  2875. for (int i = 0; i < len; i++) {
  2876. uint8_t alpha = r[i * 4 + 3];
  2877. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  2878. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  2879. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  2880. pixels[i * 4 + 3] = alpha;
  2881. }
  2882. NSImage *nsimg = [[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())];
  2883. ERR_FAIL_COND(nsimg == nil);
  2884. [nsimg addRepresentation:imgrep];
  2885. [NSApp setApplicationIconImage:nsimg];
  2886. [imgrep release];
  2887. [nsimg release];
  2888. }
  2889. void DisplayServerOSX::window_set_vsync_mode(DisplayServer::VSyncMode p_vsync_mode, WindowID p_window) {
  2890. _THREAD_SAFE_METHOD_
  2891. #if defined(GLES3_ENABLED)
  2892. if (rendering_driver == "opengl3") {
  2893. gl_manager->swap_buffers();
  2894. }
  2895. #endif
  2896. #if defined(VULKAN_ENABLED)
  2897. if (rendering_driver == "vulkan") {
  2898. context_vulkan->set_vsync_mode(p_window, p_vsync_mode);
  2899. }
  2900. #endif
  2901. }
  2902. DisplayServer::VSyncMode DisplayServerOSX::window_get_vsync_mode(WindowID p_window) const {
  2903. _THREAD_SAFE_METHOD_
  2904. #if defined(GLES3_ENABLED)
  2905. if (rendering_driver == "opengl3") {
  2906. return (gl_manager->is_using_vsync() ? DisplayServer::VSyncMode::VSYNC_ENABLED : DisplayServer::VSyncMode::VSYNC_DISABLED);
  2907. }
  2908. #endif
  2909. #if defined(VULKAN_ENABLED)
  2910. if (rendering_driver == "vulkan") {
  2911. return context_vulkan->get_vsync_mode(p_window);
  2912. }
  2913. #endif
  2914. return DisplayServer::VSYNC_ENABLED;
  2915. }
  2916. Vector<String> DisplayServerOSX::get_rendering_drivers_func() {
  2917. Vector<String> drivers;
  2918. #if defined(VULKAN_ENABLED)
  2919. drivers.push_back("vulkan");
  2920. #endif
  2921. #if defined(GLES3_ENABLED)
  2922. drivers.push_back("opengl3");
  2923. #endif
  2924. return drivers;
  2925. }
  2926. void DisplayServerOSX::gl_window_make_current(DisplayServer::WindowID p_window_id) {
  2927. #if defined(GLES3_ENABLED)
  2928. gl_manager->window_make_current(p_window_id);
  2929. #endif
  2930. }
  2931. Point2i DisplayServerOSX::ime_get_selection() const {
  2932. return im_selection;
  2933. }
  2934. String DisplayServerOSX::ime_get_text() const {
  2935. return im_text;
  2936. }
  2937. DisplayServer::WindowID DisplayServerOSX::get_window_at_screen_position(const Point2i &p_position) const {
  2938. Point2i position = p_position;
  2939. position.y *= -1;
  2940. position += _get_screens_origin();
  2941. position /= screen_get_max_scale();
  2942. NSInteger wnum = [NSWindow windowNumberAtPoint:NSMakePoint(position.x, position.y) belowWindowWithWindowNumber:0 /*topmost*/];
  2943. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  2944. if ([E->get().window_object windowNumber] == wnum) {
  2945. return E->key();
  2946. }
  2947. }
  2948. return INVALID_WINDOW_ID;
  2949. }
  2950. void DisplayServerOSX::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  2951. _THREAD_SAFE_METHOD_
  2952. ERR_FAIL_COND(!windows.has(p_window));
  2953. windows[p_window].instance_id = p_instance;
  2954. }
  2955. ObjectID DisplayServerOSX::window_get_attached_instance_id(WindowID p_window) const {
  2956. _THREAD_SAFE_METHOD_
  2957. ERR_FAIL_COND_V(!windows.has(p_window), ObjectID());
  2958. return windows[p_window].instance_id;
  2959. }
  2960. DisplayServer *DisplayServerOSX::create_func(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  2961. DisplayServer *ds = memnew(DisplayServerOSX(p_rendering_driver, p_mode, p_vsync_mode, p_flags, p_resolution, r_error));
  2962. if (r_error != OK) {
  2963. OS::get_singleton()->alert("Your video card driver does not support any of the supported Vulkan or OpenGL versions.", "Unable to initialize Video driver");
  2964. }
  2965. return ds;
  2966. }
  2967. DisplayServerOSX::WindowID DisplayServerOSX::_create_window(WindowMode p_mode, VSyncMode p_vsync_mode, const Rect2i &p_rect) {
  2968. WindowID id;
  2969. const float scale = screen_get_max_scale();
  2970. {
  2971. WindowData wd;
  2972. wd.window_delegate = [[GodotWindowDelegate alloc] init];
  2973. ERR_FAIL_COND_V_MSG(wd.window_delegate == nil, INVALID_WINDOW_ID, "Can't create a window delegate");
  2974. [wd.window_delegate setWindowID:window_id_counter];
  2975. Point2i position = p_rect.position;
  2976. // OS X native y-coordinate relative to _get_screens_origin() is negative,
  2977. // Godot passes a positive value
  2978. position.y *= -1;
  2979. position += _get_screens_origin();
  2980. // initWithContentRect uses bottom-left corner of the window’s frame as origin.
  2981. wd.window_object = [[GodotWindow alloc]
  2982. initWithContentRect:NSMakeRect(position.x / scale, (position.y - p_rect.size.height) / scale, p_rect.size.width / scale, p_rect.size.height / scale)
  2983. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
  2984. backing:NSBackingStoreBuffered
  2985. defer:NO];
  2986. ERR_FAIL_COND_V_MSG(wd.window_object == nil, INVALID_WINDOW_ID, "Can't create a window");
  2987. wd.window_view = [[GodotContentView alloc] init];
  2988. ERR_FAIL_COND_V_MSG(wd.window_view == nil, INVALID_WINDOW_ID, "Can't create a window view");
  2989. [wd.window_view setWindowID:window_id_counter];
  2990. [wd.window_view setWantsLayer:TRUE];
  2991. [wd.window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  2992. [wd.window_object setContentView:wd.window_view];
  2993. [wd.window_object setDelegate:wd.window_delegate];
  2994. [wd.window_object setAcceptsMouseMovedEvents:YES];
  2995. [wd.window_object setRestorable:NO];
  2996. if ([wd.window_object respondsToSelector:@selector(setTabbingMode:)]) {
  2997. [wd.window_object setTabbingMode:NSWindowTabbingModeDisallowed];
  2998. }
  2999. CALayer *layer = [wd.window_view layer];
  3000. if (layer) {
  3001. layer.contentsScale = scale;
  3002. }
  3003. #if defined(VULKAN_ENABLED)
  3004. if (rendering_driver == "vulkan") {
  3005. if (context_vulkan) {
  3006. Error err = context_vulkan->window_create(window_id_counter, p_vsync_mode, wd.window_view, p_rect.size.width, p_rect.size.height);
  3007. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create a Vulkan context");
  3008. }
  3009. }
  3010. #endif
  3011. #if defined(GLES3_ENABLED)
  3012. if (rendering_driver == "opengl3") {
  3013. if (gl_manager) {
  3014. Error err = gl_manager->window_create(window_id_counter, wd.window_view, p_rect.size.width, p_rect.size.height);
  3015. ERR_FAIL_COND_V_MSG(err != OK, INVALID_WINDOW_ID, "Can't create an OpenGL context");
  3016. }
  3017. }
  3018. #endif
  3019. id = window_id_counter++;
  3020. windows[id] = wd;
  3021. }
  3022. WindowData &wd = windows[id];
  3023. window_set_mode(p_mode, id);
  3024. const NSRect contentRect = [wd.window_view frame];
  3025. wd.size.width = contentRect.size.width * scale;
  3026. wd.size.height = contentRect.size.height * scale;
  3027. CALayer *layer = [wd.window_view layer];
  3028. if (layer) {
  3029. layer.contentsScale = scale;
  3030. }
  3031. #if defined(GLES3_ENABLED)
  3032. if (rendering_driver == "opengl3") {
  3033. gl_manager->window_resize(id, wd.size.width, wd.size.height);
  3034. }
  3035. #endif
  3036. #if defined(VULKAN_ENABLED)
  3037. if (rendering_driver == "vulkan") {
  3038. context_vulkan->window_resize(id, wd.size.width, wd.size.height);
  3039. }
  3040. #endif
  3041. return id;
  3042. }
  3043. void DisplayServerOSX::_dispatch_input_events(const Ref<InputEvent> &p_event) {
  3044. ((DisplayServerOSX *)(get_singleton()))->_dispatch_input_event(p_event);
  3045. }
  3046. void DisplayServerOSX::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  3047. _THREAD_SAFE_METHOD_
  3048. if (!in_dispatch_input_event) {
  3049. in_dispatch_input_event = true;
  3050. Variant ev = p_event;
  3051. Variant *evp = &ev;
  3052. Variant ret;
  3053. Callable::CallError ce;
  3054. Ref<InputEventFromWindow> event_from_window = p_event;
  3055. if (event_from_window.is_valid() && event_from_window->get_window_id() != INVALID_WINDOW_ID) {
  3056. //send to a window
  3057. if (windows.has(event_from_window->get_window_id())) {
  3058. Callable callable = windows[event_from_window->get_window_id()].input_event_callback;
  3059. if (callable.is_null()) {
  3060. return;
  3061. }
  3062. callable.call((const Variant **)&evp, 1, ret, ce);
  3063. }
  3064. } else {
  3065. //send to all windows
  3066. for (Map<WindowID, WindowData>::Element *E = windows.front(); E; E = E->next()) {
  3067. Callable callable = E->get().input_event_callback;
  3068. if (callable.is_null()) {
  3069. continue;
  3070. }
  3071. callable.call((const Variant **)&evp, 1, ret, ce);
  3072. }
  3073. }
  3074. in_dispatch_input_event = false;
  3075. }
  3076. }
  3077. void DisplayServerOSX::release_rendering_thread() {
  3078. }
  3079. void DisplayServerOSX::make_rendering_thread() {
  3080. }
  3081. void DisplayServerOSX::swap_buffers() {
  3082. #if defined(GLES3_ENABLED)
  3083. gl_manager->swap_buffers();
  3084. #endif
  3085. }
  3086. void DisplayServerOSX::console_set_visible(bool p_enabled) {
  3087. //TODO - open terminal and redirect
  3088. }
  3089. bool DisplayServerOSX::is_console_visible() const {
  3090. return isatty(STDIN_FILENO);
  3091. }
  3092. DisplayServerOSX::DisplayServerOSX(const String &p_rendering_driver, WindowMode p_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Vector2i &p_resolution, Error &r_error) {
  3093. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_events);
  3094. r_error = OK;
  3095. drop_events = false;
  3096. memset(cursors, 0, sizeof(cursors));
  3097. cursor_shape = CURSOR_ARROW;
  3098. key_event_pos = 0;
  3099. mouse_mode = MOUSE_MODE_VISIBLE;
  3100. autoreleasePool = [[NSAutoreleasePool alloc] init];
  3101. eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  3102. ERR_FAIL_COND(!eventSource);
  3103. CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0);
  3104. keyboard_layout_dirty = true;
  3105. displays_arrangement_dirty = true;
  3106. displays_scale_dirty = true;
  3107. // Register to be notified on keyboard layout changes
  3108. CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
  3109. nullptr, keyboard_layout_changed,
  3110. kTISNotifySelectedKeyboardInputSourceChanged, nullptr,
  3111. CFNotificationSuspensionBehaviorDeliverImmediately);
  3112. // Register to be notified on displays arrangement changes
  3113. CGDisplayRegisterReconfigurationCallback(displays_arrangement_changed, nullptr);
  3114. NSMenuItem *menu_item;
  3115. NSString *title;
  3116. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  3117. if (nsappname == nil) {
  3118. nsappname = [[NSProcessInfo processInfo] processName];
  3119. }
  3120. // Setup Dock menu
  3121. dock_menu = [[NSMenu alloc] initWithTitle:@"_dock"];
  3122. // Setup Apple menu
  3123. apple_menu = [[[NSMenu alloc] initWithTitle:@""] autorelease];
  3124. title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
  3125. [apple_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
  3126. [apple_menu addItem:[NSMenuItem separatorItem]];
  3127. NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
  3128. menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
  3129. [apple_menu setSubmenu:services forItem:menu_item];
  3130. [NSApp setServicesMenu:services];
  3131. [services release];
  3132. [apple_menu addItem:[NSMenuItem separatorItem]];
  3133. title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
  3134. [apple_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  3135. menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  3136. [menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
  3137. [apple_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
  3138. [apple_menu addItem:[NSMenuItem separatorItem]];
  3139. title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
  3140. [apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  3141. // Add items to the menu bar
  3142. NSMenu *main_menu = [NSApp mainMenu];
  3143. menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  3144. [main_menu setSubmenu:apple_menu forItem:menu_item];
  3145. //!!!!!!!!!!!!!!!!!!!!!!!!!!
  3146. //TODO - do Vulkan and OpenGL support checks, driver selection and fallback
  3147. rendering_driver = p_rendering_driver;
  3148. #if defined(GLES3_ENABLED)
  3149. if (rendering_driver == "opengl3") {
  3150. GLManager_OSX::ContextType opengl_api_type = GLManager_OSX::GLES_3_0_COMPATIBLE;
  3151. gl_manager = memnew(GLManager_OSX(opengl_api_type));
  3152. if (gl_manager->initialize() != OK) {
  3153. memdelete(gl_manager);
  3154. gl_manager = nullptr;
  3155. r_error = ERR_UNAVAILABLE;
  3156. ERR_FAIL_MSG("Could not initialize OpenGL");
  3157. return;
  3158. }
  3159. }
  3160. #endif
  3161. #if defined(VULKAN_ENABLED)
  3162. if (rendering_driver == "vulkan") {
  3163. context_vulkan = memnew(VulkanContextOSX);
  3164. if (context_vulkan->initialize() != OK) {
  3165. memdelete(context_vulkan);
  3166. context_vulkan = nullptr;
  3167. r_error = ERR_CANT_CREATE;
  3168. ERR_FAIL_MSG("Could not initialize Vulkan");
  3169. }
  3170. }
  3171. #endif
  3172. Point2i window_position(
  3173. screen_get_position(0).x + (screen_get_size(0).width - p_resolution.width) / 2,
  3174. screen_get_position(0).y + (screen_get_size(0).height - p_resolution.height) / 2);
  3175. WindowID main_window = _create_window(p_mode, p_vsync_mode, Rect2i(window_position, p_resolution));
  3176. ERR_FAIL_COND(main_window == INVALID_WINDOW_ID);
  3177. for (int i = 0; i < WINDOW_FLAG_MAX; i++) {
  3178. if (p_flags & (1 << i)) {
  3179. window_set_flag(WindowFlags(i), true, main_window);
  3180. }
  3181. }
  3182. show_window(MAIN_WINDOW_ID);
  3183. #if defined(GLES3_ENABLED)
  3184. if (rendering_driver == "opengl3") {
  3185. RasterizerGLES3::make_current();
  3186. }
  3187. #endif
  3188. #if defined(VULKAN_ENABLED)
  3189. if (rendering_driver == "vulkan") {
  3190. rendering_device_vulkan = memnew(RenderingDeviceVulkan);
  3191. rendering_device_vulkan->initialize(context_vulkan);
  3192. RendererCompositorRD::make_current();
  3193. }
  3194. #endif
  3195. }
  3196. DisplayServerOSX::~DisplayServerOSX() {
  3197. if (dock_menu) {
  3198. [dock_menu release];
  3199. }
  3200. for (Map<String, NSMenu *>::Element *E = submenu.front(); E; E = E->next()) {
  3201. [E->get() release];
  3202. }
  3203. //destroy all windows
  3204. for (Map<WindowID, WindowData>::Element *E = windows.front(); E;) {
  3205. Map<WindowID, WindowData>::Element *F = E;
  3206. E = E->next();
  3207. [F->get().window_object setContentView:nil];
  3208. [F->get().window_object close];
  3209. }
  3210. //destroy drivers
  3211. #if defined(GLES3_ENABLED)
  3212. if (gl_manager) {
  3213. memdelete(gl_manager);
  3214. gl_manager = nullptr;
  3215. }
  3216. #endif
  3217. #if defined(VULKAN_ENABLED)
  3218. if (rendering_device_vulkan) {
  3219. rendering_device_vulkan->finalize();
  3220. memdelete(rendering_device_vulkan);
  3221. rendering_device_vulkan = nullptr;
  3222. }
  3223. if (context_vulkan) {
  3224. memdelete(context_vulkan);
  3225. context_vulkan = nullptr;
  3226. }
  3227. #endif
  3228. CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), nullptr, kTISNotifySelectedKeyboardInputSourceChanged, nullptr);
  3229. CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, nullptr);
  3230. cursors_cache.clear();
  3231. }
  3232. void DisplayServerOSX::register_osx_driver() {
  3233. register_create_function("osx", create_func, get_rendering_drivers_func);
  3234. }