display_server_osx.mm 112 KB

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