cocoa_window.m 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150
  1. //========================================================================
  2. // GLFW 3.4 macOS - www.glfw.org
  3. //------------------------------------------------------------------------
  4. // Copyright (c) 2009-2019 Camilla Löwy <elmindreda@glfw.org>
  5. //
  6. // This software is provided 'as-is', without any express or implied
  7. // warranty. In no event will the authors be held liable for any damages
  8. // arising from the use of this software.
  9. //
  10. // Permission is granted to anyone to use this software for any purpose,
  11. // including commercial applications, and to alter it and redistribute it
  12. // freely, subject to the following restrictions:
  13. //
  14. // 1. The origin of this software must not be misrepresented; you must not
  15. // claim that you wrote the original software. If you use this software
  16. // in a product, an acknowledgment in the product documentation would
  17. // be appreciated but is not required.
  18. //
  19. // 2. Altered source versions must be plainly marked as such, and must not
  20. // be misrepresented as being the original software.
  21. //
  22. // 3. This notice may not be removed or altered from any source
  23. // distribution.
  24. //
  25. //========================================================================
  26. // It is fine to use C99 in this file because it will not be built with VS
  27. //========================================================================
  28. #include "../kitty/monotonic.h"
  29. #include "glfw3.h"
  30. #include "internal.h"
  31. #include <Availability.h>
  32. #import <CoreServices/CoreServices.h>
  33. #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
  34. #include <float.h>
  35. #include <string.h>
  36. #define debug debug_rendering
  37. static const char*
  38. polymorphic_string_as_utf8(id string) {
  39. if (string == nil) return "(nil)";
  40. NSString* characters;
  41. if ([string isKindOfClass:[NSAttributedString class]])
  42. characters = [string string];
  43. else
  44. characters = (NSString*) string;
  45. return [characters UTF8String];
  46. }
  47. static uint32_t
  48. vk_code_to_functional_key_code(uint8_t key_code) { // {{{
  49. switch(key_code) {
  50. /* start vk to functional (auto generated by gen-key-constants.py do not edit) */
  51. case 0x35: return GLFW_FKEY_ESCAPE;
  52. case 0x24: return GLFW_FKEY_ENTER;
  53. case 0x30: return GLFW_FKEY_TAB;
  54. case 0x33: return GLFW_FKEY_BACKSPACE;
  55. case 0x72: return GLFW_FKEY_INSERT;
  56. case 0x75: return GLFW_FKEY_DELETE;
  57. case 0x7b: return GLFW_FKEY_LEFT;
  58. case 0x7c: return GLFW_FKEY_RIGHT;
  59. case 0x7e: return GLFW_FKEY_UP;
  60. case 0x7d: return GLFW_FKEY_DOWN;
  61. case 0x74: return GLFW_FKEY_PAGE_UP;
  62. case 0x79: return GLFW_FKEY_PAGE_DOWN;
  63. case 0x73: return GLFW_FKEY_HOME;
  64. case 0x77: return GLFW_FKEY_END;
  65. case 0x39: return GLFW_FKEY_CAPS_LOCK;
  66. case 0x47: return GLFW_FKEY_NUM_LOCK;
  67. case 0x6e: return GLFW_FKEY_MENU;
  68. case 0x7a: return GLFW_FKEY_F1;
  69. case 0x78: return GLFW_FKEY_F2;
  70. case 0x63: return GLFW_FKEY_F3;
  71. case 0x76: return GLFW_FKEY_F4;
  72. case 0x60: return GLFW_FKEY_F5;
  73. case 0x61: return GLFW_FKEY_F6;
  74. case 0x62: return GLFW_FKEY_F7;
  75. case 0x64: return GLFW_FKEY_F8;
  76. case 0x65: return GLFW_FKEY_F9;
  77. case 0x6d: return GLFW_FKEY_F10;
  78. case 0x67: return GLFW_FKEY_F11;
  79. case 0x6f: return GLFW_FKEY_F12;
  80. case 0x69: return GLFW_FKEY_F13;
  81. case 0x6b: return GLFW_FKEY_F14;
  82. case 0x71: return GLFW_FKEY_F15;
  83. case 0x6a: return GLFW_FKEY_F16;
  84. case 0x40: return GLFW_FKEY_F17;
  85. case 0x4f: return GLFW_FKEY_F18;
  86. case 0x50: return GLFW_FKEY_F19;
  87. case 0x5a: return GLFW_FKEY_F20;
  88. case 0x52: return GLFW_FKEY_KP_0;
  89. case 0x53: return GLFW_FKEY_KP_1;
  90. case 0x54: return GLFW_FKEY_KP_2;
  91. case 0x55: return GLFW_FKEY_KP_3;
  92. case 0x56: return GLFW_FKEY_KP_4;
  93. case 0x57: return GLFW_FKEY_KP_5;
  94. case 0x58: return GLFW_FKEY_KP_6;
  95. case 0x59: return GLFW_FKEY_KP_7;
  96. case 0x5b: return GLFW_FKEY_KP_8;
  97. case 0x5c: return GLFW_FKEY_KP_9;
  98. case 0x41: return GLFW_FKEY_KP_DECIMAL;
  99. case 0x4b: return GLFW_FKEY_KP_DIVIDE;
  100. case 0x43: return GLFW_FKEY_KP_MULTIPLY;
  101. case 0x4e: return GLFW_FKEY_KP_SUBTRACT;
  102. case 0x45: return GLFW_FKEY_KP_ADD;
  103. case 0x4c: return GLFW_FKEY_KP_ENTER;
  104. case 0x51: return GLFW_FKEY_KP_EQUAL;
  105. case 0x38: return GLFW_FKEY_LEFT_SHIFT;
  106. case 0x3b: return GLFW_FKEY_LEFT_CONTROL;
  107. case 0x3a: return GLFW_FKEY_LEFT_ALT;
  108. case 0x37: return GLFW_FKEY_LEFT_SUPER;
  109. case 0x3c: return GLFW_FKEY_RIGHT_SHIFT;
  110. case 0x3e: return GLFW_FKEY_RIGHT_CONTROL;
  111. case 0x3d: return GLFW_FKEY_RIGHT_ALT;
  112. case 0x36: return GLFW_FKEY_RIGHT_SUPER;
  113. /* end vk to functional */
  114. default:
  115. return 0;
  116. }
  117. } // }}}
  118. static uint32_t
  119. vk_code_to_unicode(uint8_t key_code) { // {{{
  120. switch(key_code) {
  121. /* start vk to unicode (auto generated by gen-key-constants.py do not edit) */
  122. case 0x0: return 0x61;
  123. case 0x1: return 0x73;
  124. case 0x2: return 0x64;
  125. case 0x3: return 0x66;
  126. case 0x4: return 0x68;
  127. case 0x5: return 0x67;
  128. case 0x6: return 0x7a;
  129. case 0x7: return 0x78;
  130. case 0x8: return 0x63;
  131. case 0x9: return 0x76;
  132. case 0xb: return 0x62;
  133. case 0xc: return 0x71;
  134. case 0xd: return 0x77;
  135. case 0xe: return 0x65;
  136. case 0xf: return 0x72;
  137. case 0x10: return 0x79;
  138. case 0x11: return 0x74;
  139. case 0x12: return 0x31;
  140. case 0x13: return 0x32;
  141. case 0x14: return 0x33;
  142. case 0x15: return 0x34;
  143. case 0x16: return 0x36;
  144. case 0x17: return 0x35;
  145. case 0x18: return 0x3d;
  146. case 0x19: return 0x39;
  147. case 0x1a: return 0x37;
  148. case 0x1b: return 0x2d;
  149. case 0x1c: return 0x38;
  150. case 0x1d: return 0x30;
  151. case 0x1e: return 0x5d;
  152. case 0x1f: return 0x6f;
  153. case 0x20: return 0x75;
  154. case 0x21: return 0x5b;
  155. case 0x22: return 0x69;
  156. case 0x23: return 0x70;
  157. case 0x25: return 0x6c;
  158. case 0x26: return 0x6a;
  159. case 0x27: return 0x27;
  160. case 0x28: return 0x6b;
  161. case 0x29: return 0x3b;
  162. case 0x2a: return 0x5c;
  163. case 0x2b: return 0x2c;
  164. case 0x2c: return 0x2f;
  165. case 0x2d: return 0x6e;
  166. case 0x2e: return 0x6d;
  167. case 0x2f: return 0x2e;
  168. case 0x31: return 0x20;
  169. case 0x32: return 0x60;
  170. /* end vk to unicode */
  171. default:
  172. return 0;
  173. }
  174. } // }}}
  175. static uint32_t
  176. mac_ucode_to_functional(uint32_t key_code) { // {{{
  177. switch(key_code) {
  178. /* start macu to functional (auto generated by gen-key-constants.py do not edit) */
  179. case NSCarriageReturnCharacter: return GLFW_FKEY_ENTER;
  180. case NSTabCharacter: return GLFW_FKEY_TAB;
  181. case NSBackspaceCharacter: return GLFW_FKEY_BACKSPACE;
  182. case NSInsertFunctionKey: return GLFW_FKEY_INSERT;
  183. case NSDeleteFunctionKey: return GLFW_FKEY_DELETE;
  184. case NSLeftArrowFunctionKey: return GLFW_FKEY_LEFT;
  185. case NSRightArrowFunctionKey: return GLFW_FKEY_RIGHT;
  186. case NSUpArrowFunctionKey: return GLFW_FKEY_UP;
  187. case NSDownArrowFunctionKey: return GLFW_FKEY_DOWN;
  188. case NSPageUpFunctionKey: return GLFW_FKEY_PAGE_UP;
  189. case NSPageDownFunctionKey: return GLFW_FKEY_PAGE_DOWN;
  190. case NSHomeFunctionKey: return GLFW_FKEY_HOME;
  191. case NSEndFunctionKey: return GLFW_FKEY_END;
  192. case NSScrollLockFunctionKey: return GLFW_FKEY_SCROLL_LOCK;
  193. case NSClearLineFunctionKey: return GLFW_FKEY_NUM_LOCK;
  194. case NSPrintScreenFunctionKey: return GLFW_FKEY_PRINT_SCREEN;
  195. case NSPauseFunctionKey: return GLFW_FKEY_PAUSE;
  196. case NSMenuFunctionKey: return GLFW_FKEY_MENU;
  197. case NSF1FunctionKey: return GLFW_FKEY_F1;
  198. case NSF2FunctionKey: return GLFW_FKEY_F2;
  199. case NSF3FunctionKey: return GLFW_FKEY_F3;
  200. case NSF4FunctionKey: return GLFW_FKEY_F4;
  201. case NSF5FunctionKey: return GLFW_FKEY_F5;
  202. case NSF6FunctionKey: return GLFW_FKEY_F6;
  203. case NSF7FunctionKey: return GLFW_FKEY_F7;
  204. case NSF8FunctionKey: return GLFW_FKEY_F8;
  205. case NSF9FunctionKey: return GLFW_FKEY_F9;
  206. case NSF10FunctionKey: return GLFW_FKEY_F10;
  207. case NSF11FunctionKey: return GLFW_FKEY_F11;
  208. case NSF12FunctionKey: return GLFW_FKEY_F12;
  209. case NSF13FunctionKey: return GLFW_FKEY_F13;
  210. case NSF14FunctionKey: return GLFW_FKEY_F14;
  211. case NSF15FunctionKey: return GLFW_FKEY_F15;
  212. case NSF16FunctionKey: return GLFW_FKEY_F16;
  213. case NSF17FunctionKey: return GLFW_FKEY_F17;
  214. case NSF18FunctionKey: return GLFW_FKEY_F18;
  215. case NSF19FunctionKey: return GLFW_FKEY_F19;
  216. case NSF20FunctionKey: return GLFW_FKEY_F20;
  217. case NSF21FunctionKey: return GLFW_FKEY_F21;
  218. case NSF22FunctionKey: return GLFW_FKEY_F22;
  219. case NSF23FunctionKey: return GLFW_FKEY_F23;
  220. case NSF24FunctionKey: return GLFW_FKEY_F24;
  221. case NSF25FunctionKey: return GLFW_FKEY_F25;
  222. case NSF26FunctionKey: return GLFW_FKEY_F26;
  223. case NSF27FunctionKey: return GLFW_FKEY_F27;
  224. case NSF28FunctionKey: return GLFW_FKEY_F28;
  225. case NSF29FunctionKey: return GLFW_FKEY_F29;
  226. case NSF30FunctionKey: return GLFW_FKEY_F30;
  227. case NSF31FunctionKey: return GLFW_FKEY_F31;
  228. case NSF32FunctionKey: return GLFW_FKEY_F32;
  229. case NSF33FunctionKey: return GLFW_FKEY_F33;
  230. case NSF34FunctionKey: return GLFW_FKEY_F34;
  231. case NSF35FunctionKey: return GLFW_FKEY_F35;
  232. case NSEnterCharacter: return GLFW_FKEY_KP_ENTER;
  233. /* end macu to functional */
  234. default:
  235. return 0;
  236. }
  237. } // }}}
  238. static bool
  239. is_surrogate(UniChar uc) { return (uc - 0xd800u) < 2048u; }
  240. static uint32_t
  241. get_first_codepoint(UniChar *utf16, UniCharCount num) {
  242. if (!num) return 0;
  243. if (!is_surrogate(*utf16)) return *utf16;
  244. if (CFStringIsSurrogateHighCharacter(*utf16) && num > 1 && CFStringIsSurrogateLowCharacter(utf16[1])) return CFStringGetLongCharacterForSurrogatePair(utf16[0], utf16[1]);
  245. return 0;
  246. }
  247. static bool
  248. is_pua_char(uint32_t ch) {
  249. return (0xE000 <= ch && ch <= 0xF8FF) || (0xF0000 <= ch && ch <= 0xFFFFF) || (0x100000 <= ch && ch <= 0x10FFFF);
  250. }
  251. uint32_t
  252. vk_to_unicode_key_with_current_layout(uint16_t keycode)
  253. {
  254. UInt32 dead_key_state = 0;
  255. UniChar characters[256];
  256. UniCharCount character_count = 0;
  257. uint32_t ans = vk_code_to_functional_key_code(keycode);
  258. if (ans) return ans;
  259. if (UCKeyTranslate([(NSData*) _glfw.ns.unicodeData bytes],
  260. keycode,
  261. kUCKeyActionDisplay,
  262. 0,
  263. LMGetKbdType(),
  264. kUCKeyTranslateNoDeadKeysBit,
  265. &dead_key_state,
  266. arraysz(characters),
  267. &character_count,
  268. characters) == noErr) {
  269. uint32_t cp = get_first_codepoint(characters, character_count);
  270. if (cp) {
  271. if (cp < 32 || (0xF700 <= cp && cp <= 0xF8FF)) return mac_ucode_to_functional(cp);
  272. if (cp >= 32 && !is_pua_char(cp)) return cp;
  273. }
  274. }
  275. return vk_code_to_unicode(keycode);
  276. }
  277. // Returns the style mask corresponding to the window settings
  278. //
  279. static NSUInteger getStyleMask(_GLFWwindow* window)
  280. {
  281. NSUInteger styleMask = NSWindowStyleMaskMiniaturizable;
  282. if (window->ns.titlebar_hidden) styleMask |= NSWindowStyleMaskFullSizeContentView;
  283. if (window->monitor || !window->decorated) {
  284. styleMask |= NSWindowStyleMaskBorderless;
  285. } else {
  286. styleMask |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable;
  287. }
  288. if (window->resizable) styleMask |= NSWindowStyleMaskResizable;
  289. return styleMask;
  290. }
  291. static void
  292. requestRenderFrame(_GLFWwindow *w, GLFWcocoarenderframefun callback) {
  293. if (!callback) {
  294. w->ns.renderFrameRequested = false;
  295. w->ns.renderFrameCallback = NULL;
  296. return;
  297. }
  298. w->ns.renderFrameCallback = callback;
  299. w->ns.renderFrameRequested = true;
  300. _glfwRequestRenderFrame(w);
  301. }
  302. void
  303. _glfwRestartDisplayLinks(void) {
  304. _GLFWwindow* window;
  305. for (window = _glfw.windowListHead; window; window = window->next) {
  306. if (window->ns.renderFrameRequested && window->ns.renderFrameCallback) {
  307. requestRenderFrame(window, window->ns.renderFrameCallback);
  308. }
  309. }
  310. }
  311. // Returns whether the cursor is in the content area of the specified window
  312. //
  313. static bool cursorInContentArea(_GLFWwindow* window)
  314. {
  315. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  316. return [window->ns.view mouse:pos inRect:[window->ns.view frame]];
  317. }
  318. // Hides the cursor if not already hidden
  319. //
  320. static void hideCursor(_GLFWwindow* window UNUSED)
  321. {
  322. if (!_glfw.ns.cursorHidden)
  323. {
  324. [NSCursor hide];
  325. _glfw.ns.cursorHidden = true;
  326. }
  327. }
  328. // Shows the cursor if not already shown
  329. //
  330. static void showCursor(_GLFWwindow* window UNUSED)
  331. {
  332. if (_glfw.ns.cursorHidden)
  333. {
  334. [NSCursor unhide];
  335. _glfw.ns.cursorHidden = false;
  336. }
  337. }
  338. // Updates the cursor image according to its cursor mode
  339. //
  340. static void updateCursorImage(_GLFWwindow* window)
  341. {
  342. if (window->cursorMode == GLFW_CURSOR_NORMAL)
  343. {
  344. showCursor(window);
  345. if (window->cursor)
  346. [(NSCursor*) window->cursor->ns.object set];
  347. else
  348. [[NSCursor arrowCursor] set];
  349. }
  350. else
  351. hideCursor(window);
  352. }
  353. // Apply chosen cursor mode to a focused window
  354. //
  355. static void updateCursorMode(_GLFWwindow* window)
  356. {
  357. if (window->cursorMode == GLFW_CURSOR_DISABLED)
  358. {
  359. _glfw.ns.disabledCursorWindow = window;
  360. _glfwPlatformGetCursorPos(window,
  361. &_glfw.ns.restoreCursorPosX,
  362. &_glfw.ns.restoreCursorPosY);
  363. _glfwCenterCursorInContentArea(window);
  364. CGAssociateMouseAndMouseCursorPosition(false);
  365. }
  366. else if (_glfw.ns.disabledCursorWindow == window)
  367. {
  368. _glfw.ns.disabledCursorWindow = NULL;
  369. CGAssociateMouseAndMouseCursorPosition(true);
  370. _glfwPlatformSetCursorPos(window,
  371. _glfw.ns.restoreCursorPosX,
  372. _glfw.ns.restoreCursorPosY);
  373. }
  374. if (cursorInContentArea(window))
  375. updateCursorImage(window);
  376. }
  377. // Make the specified window and its video mode active on its monitor
  378. //
  379. static void acquireMonitor(_GLFWwindow* window)
  380. {
  381. _glfwSetVideoModeNS(window->monitor, &window->videoMode);
  382. const CGRect bounds = CGDisplayBounds(window->monitor->ns.displayID);
  383. const NSRect frame = NSMakeRect(bounds.origin.x,
  384. _glfwTransformYNS(bounds.origin.y + bounds.size.height - 1),
  385. bounds.size.width,
  386. bounds.size.height);
  387. [window->ns.object setFrame:frame display:YES];
  388. _glfwInputMonitorWindow(window->monitor, window);
  389. }
  390. // Remove the window and restore the original video mode
  391. //
  392. static void releaseMonitor(_GLFWwindow* window)
  393. {
  394. if (window->monitor->window != window)
  395. return;
  396. _glfwInputMonitorWindow(window->monitor, NULL);
  397. _glfwRestoreVideoModeNS(window->monitor);
  398. }
  399. // Translates macOS key modifiers into GLFW ones
  400. //
  401. static int
  402. translateFlags(NSUInteger flags)
  403. {
  404. int mods = 0;
  405. if (flags & NSEventModifierFlagShift)
  406. mods |= GLFW_MOD_SHIFT;
  407. if (flags & NSEventModifierFlagControl)
  408. mods |= GLFW_MOD_CONTROL;
  409. if (flags & NSEventModifierFlagOption)
  410. mods |= GLFW_MOD_ALT;
  411. if (flags & NSEventModifierFlagCommand)
  412. mods |= GLFW_MOD_SUPER;
  413. if (flags & NSEventModifierFlagCapsLock)
  414. mods |= GLFW_MOD_CAPS_LOCK;
  415. return mods;
  416. }
  417. static const char*
  418. format_mods(int mods) {
  419. static char buf[128];
  420. char *p = buf, *s;
  421. #define pr(x) p += snprintf(p, sizeof(buf) - (p - buf) - 1, x)
  422. pr("mods: ");
  423. s = p;
  424. if (mods & GLFW_MOD_CONTROL) pr("ctrl+");
  425. if (mods & GLFW_MOD_ALT) pr("alt+");
  426. if (mods & GLFW_MOD_SHIFT) pr("shift+");
  427. if (mods & GLFW_MOD_SUPER) pr("super+");
  428. if (mods & GLFW_MOD_CAPS_LOCK) pr("capslock+");
  429. if (mods & GLFW_MOD_NUM_LOCK) pr("numlock+");
  430. if (p == s) pr("none");
  431. else p--;
  432. pr(" ");
  433. #undef pr
  434. return buf;
  435. }
  436. static const char*
  437. format_text(const char *src) {
  438. static char buf[256];
  439. char *p = buf;
  440. const char *last_char = buf + sizeof(buf) - 1;
  441. if (!src[0]) return "<none>";
  442. while (*src) {
  443. int num = snprintf(p, sizeof(buf) - (p - buf), "0x%x ", (unsigned char)*(src++));
  444. if (num < 0) return "<error>";
  445. if (p + num >= last_char) break;
  446. p += num;
  447. }
  448. if (p != buf) *(--p) = 0;
  449. return buf;
  450. }
  451. static const char*
  452. safe_name_for_keycode(unsigned int keycode) {
  453. const char *ans = _glfwPlatformGetNativeKeyName(keycode);
  454. if (!ans) return "<noname>";
  455. if ((1 <= ans[0] && ans[0] <= 31) || ans[0] == 127) ans = "<cc>";
  456. return ans;
  457. }
  458. // Translates a macOS keycode to a GLFW keycode
  459. //
  460. static uint32_t
  461. translateKey(uint16_t vk_key, bool apply_keymap)
  462. {
  463. if (apply_keymap) return vk_to_unicode_key_with_current_layout(vk_key);
  464. uint32_t ans = vk_code_to_functional_key_code(vk_key);
  465. if (!ans) ans = vk_code_to_unicode(vk_key);
  466. return ans;
  467. }
  468. static NSRect
  469. get_window_size_without_border_in_logical_pixels(_GLFWwindow *window) {
  470. return [window->ns.object contentRectForFrameRect:[window->ns.object frame]];
  471. }
  472. // Defines a constant for empty ranges in NSTextInputClient
  473. //
  474. static const NSRange kEmptyRange = { NSNotFound, 0 };
  475. // Delegate for window related notifications {{{
  476. @interface GLFWWindowDelegate : NSObject
  477. {
  478. _GLFWwindow* window;
  479. }
  480. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow;
  481. - (void)request_delayed_cursor_update:(id)sender;
  482. @end
  483. @implementation GLFWWindowDelegate
  484. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow
  485. {
  486. self = [super init];
  487. if (self != nil)
  488. window = initWindow;
  489. return self;
  490. }
  491. - (BOOL)windowShouldClose:(id)sender
  492. {
  493. (void)sender;
  494. _glfwInputWindowCloseRequest(window);
  495. return NO;
  496. }
  497. - (void)windowDidResize:(NSNotification *)notification
  498. {
  499. (void)notification;
  500. if (window->context.client != GLFW_NO_API)
  501. [window->context.nsgl.object update];
  502. if (_glfw.ns.disabledCursorWindow == window)
  503. _glfwCenterCursorInContentArea(window);
  504. const int maximized = [window->ns.object isZoomed];
  505. if (window->ns.maximized != maximized)
  506. {
  507. window->ns.maximized = maximized;
  508. _glfwInputWindowMaximize(window, maximized);
  509. }
  510. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  511. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  512. if (fbRect.size.width != window->ns.fbWidth ||
  513. fbRect.size.height != window->ns.fbHeight)
  514. {
  515. window->ns.fbWidth = (int)fbRect.size.width;
  516. window->ns.fbHeight = (int)fbRect.size.height;
  517. _glfwInputFramebufferSize(window, (int)fbRect.size.width, (int)fbRect.size.height);
  518. }
  519. if (contentRect.size.width != window->ns.width ||
  520. contentRect.size.height != window->ns.height)
  521. {
  522. window->ns.width = (int)contentRect.size.width;
  523. window->ns.height = (int)contentRect.size.height;
  524. _glfwInputWindowSize(window, (int)contentRect.size.width, (int)contentRect.size.height);
  525. }
  526. if (window->ns.resizeCallback) window->ns.resizeCallback((GLFWwindow*)window);
  527. }
  528. - (void)windowDidMove:(NSNotification *)notification
  529. {
  530. (void)notification;
  531. if (window->context.client != GLFW_NO_API)
  532. [window->context.nsgl.object update];
  533. if (_glfw.ns.disabledCursorWindow == window)
  534. _glfwCenterCursorInContentArea(window);
  535. int x, y;
  536. _glfwPlatformGetWindowPos(window, &x, &y);
  537. _glfwInputWindowPos(window, x, y);
  538. }
  539. - (void)windowDidChangeOcclusionState:(NSNotification *)notification
  540. {
  541. (void)notification;
  542. _glfwInputWindowOcclusion(window, !([window->ns.object occlusionState] & NSWindowOcclusionStateVisible));
  543. }
  544. - (void)windowDidMiniaturize:(NSNotification *)notification
  545. {
  546. (void)notification;
  547. if (window->monitor)
  548. releaseMonitor(window);
  549. _glfwInputWindowIconify(window, true);
  550. }
  551. - (void)windowDidDeminiaturize:(NSNotification *)notification
  552. {
  553. (void)notification;
  554. if (window->monitor)
  555. acquireMonitor(window);
  556. _glfwInputWindowIconify(window, false);
  557. }
  558. - (void)windowDidBecomeKey:(NSNotification *)notification
  559. {
  560. (void)notification;
  561. if (_glfw.ns.disabledCursorWindow == window)
  562. _glfwCenterCursorInContentArea(window);
  563. _glfwInputWindowFocus(window, true);
  564. updateCursorMode(window);
  565. if (window->cursorMode == GLFW_CURSOR_HIDDEN) hideCursor(window);
  566. if (_glfw.ns.disabledCursorWindow != window && cursorInContentArea(window))
  567. {
  568. double x = 0, y = 0;
  569. _glfwPlatformGetCursorPos(window, &x, &y);
  570. _glfwInputCursorPos(window, x, y);
  571. }
  572. // macOS will send a delayed event to update the cursor to arrow after switching desktops.
  573. // So we need to delay and update the cursor once after that.
  574. [self performSelector:@selector(request_delayed_cursor_update:) withObject:nil afterDelay:0.3];
  575. }
  576. - (void)windowDidResignKey:(NSNotification *)notification
  577. {
  578. (void)notification;
  579. if (window->monitor && window->autoIconify)
  580. _glfwPlatformIconifyWindow(window);
  581. showCursor(window);
  582. _glfwInputWindowFocus(window, false);
  583. // IME is cancelled when losing the focus
  584. if ([window->ns.view hasMarkedText]) {
  585. [[window->ns.view inputContext] discardMarkedText];
  586. [window->ns.view unmarkText];
  587. GLFWkeyevent dummy = {.action = GLFW_RELEASE, .ime_state = GLFW_IME_PREEDIT_CHANGED};
  588. _glfwInputKeyboard(window, &dummy);
  589. _glfw.ns.text[0] = 0;
  590. }
  591. }
  592. - (void)windowDidChangeScreen:(NSNotification *)notification
  593. {
  594. (void)notification;
  595. if (window->ns.renderFrameRequested && window->ns.renderFrameCallback) {
  596. // Ensure that if the window changed its monitor, CVDisplayLink
  597. // is running for the new monitor
  598. requestRenderFrame(window, window->ns.renderFrameCallback);
  599. }
  600. }
  601. - (void)request_delayed_cursor_update:(id)sender
  602. {
  603. (void)sender;
  604. if (window) window->ns.delayed_cursor_update_requested = true;
  605. }
  606. - (void)windowWillEnterFullScreen:(NSNotification *)notification
  607. {
  608. (void)notification;
  609. if (window) window->ns.in_fullscreen_transition = true;
  610. }
  611. - (void)windowDidEnterFullScreen:(NSNotification *)notification
  612. {
  613. (void)notification;
  614. if (window) window->ns.in_fullscreen_transition = false;
  615. [self performSelector:@selector(request_delayed_cursor_update:) withObject:nil afterDelay:0.3];
  616. }
  617. - (void)windowWillExitFullScreen:(NSNotification *)notification
  618. {
  619. (void)notification;
  620. if (window) window->ns.in_fullscreen_transition = true;
  621. }
  622. - (void)windowDidExitFullScreen:(NSNotification *)notification
  623. {
  624. (void)notification;
  625. if (window) window->ns.in_fullscreen_transition = false;
  626. [self performSelector:@selector(request_delayed_cursor_update:) withObject:nil afterDelay:0.3];
  627. }
  628. @end // }}}
  629. // Text input context class for the GLFW content view {{{
  630. @interface GLFWTextInputContext : NSTextInputContext
  631. @end
  632. @implementation GLFWTextInputContext
  633. - (void)doCommandBySelector:(SEL)selector
  634. {
  635. // interpretKeyEvents: May call insertText: or doCommandBySelector:.
  636. // With the default macOS keybindings, pressing certain key combinations
  637. // (e.g. Ctrl+/, Ctrl+Cmd+Down/Left/Right) will produce a beep sound.
  638. debug_key("\n\tTextInputCtx: doCommandBySelector: (%s)\n", [NSStringFromSelector(selector) UTF8String]);
  639. }
  640. @end // }}}
  641. // Content view class for the GLFW window {{{
  642. @interface GLFWContentView : NSView <NSTextInputClient>
  643. {
  644. _GLFWwindow* window;
  645. NSTrackingArea* trackingArea;
  646. GLFWTextInputContext* input_context;
  647. NSMutableAttributedString* markedText;
  648. NSRect markedRect;
  649. bool marked_text_cleared_by_insert;
  650. int in_key_handler;
  651. NSString *input_source_at_last_key_event;
  652. }
  653. - (void) removeGLFWWindow;
  654. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow;
  655. @end
  656. @implementation GLFWContentView
  657. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow
  658. {
  659. self = [super init];
  660. if (self != nil)
  661. {
  662. window = initWindow;
  663. trackingArea = nil;
  664. input_context = [[GLFWTextInputContext alloc] initWithClient:self];
  665. markedText = [[NSMutableAttributedString alloc] init];
  666. markedRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
  667. input_source_at_last_key_event = nil;
  668. in_key_handler = 0;
  669. [self updateTrackingAreas];
  670. [self registerForDraggedTypes:@[NSPasteboardTypeFileURL, NSPasteboardTypeString]];
  671. }
  672. return self;
  673. }
  674. - (void)dealloc
  675. {
  676. [trackingArea release];
  677. [markedText release];
  678. if (input_source_at_last_key_event) [input_source_at_last_key_event release];
  679. [input_context release];
  680. [super dealloc];
  681. }
  682. - (void) removeGLFWWindow
  683. {
  684. window = NULL;
  685. }
  686. - (_GLFWwindow*)glfwWindow {
  687. return window;
  688. }
  689. - (BOOL)isOpaque
  690. {
  691. return window && [window->ns.object isOpaque];
  692. }
  693. - (BOOL)canBecomeKeyView
  694. {
  695. return YES;
  696. }
  697. - (BOOL)acceptsFirstResponder
  698. {
  699. return YES;
  700. }
  701. - (void) viewWillStartLiveResize
  702. {
  703. if (!window) return;
  704. _glfwInputLiveResize(window, true);
  705. }
  706. - (void)viewDidEndLiveResize
  707. {
  708. if (!window) return;
  709. _glfwInputLiveResize(window, false);
  710. }
  711. - (BOOL)wantsUpdateLayer
  712. {
  713. return YES;
  714. }
  715. - (void)updateLayer
  716. {
  717. if (!window) return;
  718. if (window->context.client != GLFW_NO_API) {
  719. @try {
  720. [window->context.nsgl.object update];
  721. } @catch (NSException *e) {
  722. _glfwInputError(GLFW_PLATFORM_ERROR,
  723. "Failed to update NSGL Context object with error: %s (%s)",
  724. [[e name] UTF8String], [[e reason] UTF8String]);
  725. }
  726. }
  727. _glfwInputWindowDamage(window);
  728. }
  729. - (void)cursorUpdate:(NSEvent *)event
  730. {
  731. (void)event;
  732. if (window) updateCursorImage(window);
  733. }
  734. - (BOOL)acceptsFirstMouse:(NSEvent *)event
  735. {
  736. (void)event;
  737. return NO; // changed by Kovid, to follow cocoa platform conventions
  738. }
  739. - (void)mouseDown:(NSEvent *)event
  740. {
  741. if (!window) return;
  742. _glfwInputMouseClick(window,
  743. GLFW_MOUSE_BUTTON_LEFT,
  744. GLFW_PRESS,
  745. translateFlags([event modifierFlags]));
  746. }
  747. - (void)mouseDragged:(NSEvent *)event
  748. {
  749. [self mouseMoved:event];
  750. }
  751. - (void)mouseUp:(NSEvent *)event
  752. {
  753. if (!window) return;
  754. _glfwInputMouseClick(window,
  755. GLFW_MOUSE_BUTTON_LEFT,
  756. GLFW_RELEASE,
  757. translateFlags([event modifierFlags]));
  758. }
  759. - (void)mouseMoved:(NSEvent *)event
  760. {
  761. if (!window) return;
  762. if (window->cursorMode == GLFW_CURSOR_DISABLED)
  763. {
  764. const double dx = [event deltaX] - window->ns.cursorWarpDeltaX;
  765. const double dy = [event deltaY] - window->ns.cursorWarpDeltaY;
  766. _glfwInputCursorPos(window,
  767. window->virtualCursorPosX + dx,
  768. window->virtualCursorPosY + dy);
  769. }
  770. else
  771. {
  772. const NSRect contentRect = [window->ns.view frame];
  773. // NOTE: The returned location uses base 0,1 not 0,0
  774. const NSPoint pos = [event locationInWindow];
  775. _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y);
  776. }
  777. window->ns.cursorWarpDeltaX = 0;
  778. window->ns.cursorWarpDeltaY = 0;
  779. if (window->ns.delayed_cursor_update_requested) {
  780. window->ns.delayed_cursor_update_requested = false;
  781. if (cursorInContentArea(window)) updateCursorImage(window);
  782. }
  783. }
  784. - (void)rightMouseDown:(NSEvent *)event
  785. {
  786. if (!window) return;
  787. _glfwInputMouseClick(window,
  788. GLFW_MOUSE_BUTTON_RIGHT,
  789. GLFW_PRESS,
  790. translateFlags([event modifierFlags]));
  791. }
  792. - (void)rightMouseDragged:(NSEvent *)event
  793. {
  794. [self mouseMoved:event];
  795. }
  796. - (void)rightMouseUp:(NSEvent *)event
  797. {
  798. if (!window) return;
  799. _glfwInputMouseClick(window,
  800. GLFW_MOUSE_BUTTON_RIGHT,
  801. GLFW_RELEASE,
  802. translateFlags([event modifierFlags]));
  803. }
  804. - (void)otherMouseDown:(NSEvent *)event
  805. {
  806. if (!window) return;
  807. _glfwInputMouseClick(window,
  808. (int) [event buttonNumber],
  809. GLFW_PRESS,
  810. translateFlags([event modifierFlags]));
  811. }
  812. - (void)otherMouseDragged:(NSEvent *)event
  813. {
  814. [self mouseMoved:event];
  815. }
  816. - (void)otherMouseUp:(NSEvent *)event
  817. {
  818. if (!window) return;
  819. _glfwInputMouseClick(window,
  820. (int) [event buttonNumber],
  821. GLFW_RELEASE,
  822. translateFlags([event modifierFlags]));
  823. }
  824. - (void)mouseExited:(NSEvent *)event
  825. {
  826. (void)event;
  827. if (!window) return;
  828. _glfwInputCursorEnter(window, false);
  829. [[NSCursor arrowCursor] set];
  830. }
  831. - (void)mouseEntered:(NSEvent *)event
  832. {
  833. (void)event;
  834. if (!window) return;
  835. _glfwInputCursorEnter(window, true);
  836. updateCursorImage(window);
  837. }
  838. - (void)viewDidChangeEffectiveAppearance
  839. {
  840. static GLFWColorScheme appearance = GLFW_COLOR_SCHEME_NO_PREFERENCE;
  841. GLFWColorScheme new_appearance = glfwGetCurrentSystemColorTheme(true);
  842. if (new_appearance != appearance) {
  843. appearance = new_appearance;
  844. _glfwInputColorScheme(appearance, false);
  845. }
  846. }
  847. - (void)viewDidChangeBackingProperties
  848. {
  849. if (!window) return;
  850. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  851. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  852. if (fbRect.size.width != window->ns.fbWidth ||
  853. fbRect.size.height != window->ns.fbHeight)
  854. {
  855. window->ns.fbWidth = (int)fbRect.size.width;
  856. window->ns.fbHeight = (int)fbRect.size.height;
  857. _glfwInputFramebufferSize(window, (int)fbRect.size.width, (int)fbRect.size.height);
  858. }
  859. const float xscale = fbRect.size.width / contentRect.size.width;
  860. const float yscale = fbRect.size.height / contentRect.size.height;
  861. if (xscale != window->ns.xscale || yscale != window->ns.yscale)
  862. {
  863. window->ns.xscale = xscale;
  864. window->ns.yscale = yscale;
  865. _glfwInputWindowContentScale(window, xscale, yscale);
  866. if (window->ns.retina && window->ns.layer)
  867. [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]];
  868. }
  869. }
  870. - (void)drawRect:(NSRect)rect
  871. {
  872. (void)rect;
  873. if (!window) return;
  874. _glfwInputWindowDamage(window);
  875. }
  876. - (void)updateTrackingAreas
  877. {
  878. if (window && [window->ns.object areCursorRectsEnabled])
  879. [window->ns.object disableCursorRects];
  880. if (trackingArea != nil)
  881. {
  882. [self removeTrackingArea:trackingArea];
  883. [trackingArea release];
  884. }
  885. const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
  886. NSTrackingActiveAlways |
  887. NSTrackingEnabledDuringMouseDrag |
  888. NSTrackingCursorUpdate |
  889. NSTrackingInVisibleRect |
  890. NSTrackingAssumeInside;
  891. trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
  892. options:options
  893. owner:self
  894. userInfo:nil];
  895. [self addTrackingArea:trackingArea];
  896. [super updateTrackingAreas];
  897. }
  898. - (NSTextInputContext *)inputContext
  899. {
  900. return input_context;
  901. }
  902. static UInt32
  903. convert_cocoa_to_carbon_modifiers(NSUInteger flags) {
  904. UInt32 mods = 0;
  905. if (flags & NSEventModifierFlagShift)
  906. mods |= shiftKey;
  907. if (flags & NSEventModifierFlagControl)
  908. mods |= controlKey;
  909. if (flags & NSEventModifierFlagOption)
  910. mods |= optionKey;
  911. if (flags & NSEventModifierFlagCommand)
  912. mods |= cmdKey;
  913. if (flags & NSEventModifierFlagCapsLock)
  914. mods |= alphaLock;
  915. return (mods >> 8) & 0xFF;
  916. }
  917. static void
  918. convert_utf16_to_utf8(UniChar *src, UniCharCount src_length, char *dest, size_t dest_sz) {
  919. CFStringRef string = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
  920. src,
  921. src_length,
  922. kCFAllocatorNull);
  923. CFStringGetCString(string,
  924. dest,
  925. dest_sz,
  926. kCFStringEncodingUTF8);
  927. CFRelease(string);
  928. }
  929. static bool
  930. alternate_key_is_ok(uint32_t key, uint32_t akey) {
  931. return akey > 31 && akey != key && !is_pua_char(akey);
  932. }
  933. static void
  934. add_alternate_keys(GLFWkeyevent *ev, NSEvent *event) {
  935. ev->alternate_key = translateKey(ev->native_key, false);
  936. if (!alternate_key_is_ok(ev->key, ev->alternate_key)) ev->alternate_key = 0;
  937. if (ev->mods & GLFW_MOD_SHIFT) {
  938. NSString *ci = [event charactersIgnoringModifiers];
  939. if (ci) {
  940. unsigned sz = [ci length];
  941. if (sz > 0) {
  942. UniChar buf[2] = {0};
  943. buf[0] = [ci characterAtIndex:0];
  944. if (sz > 1) buf[1] = [ci characterAtIndex:1];
  945. ev->shifted_key = get_first_codepoint(buf, sz);
  946. }
  947. }
  948. if (!alternate_key_is_ok(ev->key, ev->shifted_key)) ev->shifted_key = 0;
  949. }
  950. }
  951. static bool
  952. is_ascii_control_char(char x) {
  953. return x == 0 || (1 <= x && x <= 31) || x == 127;
  954. }
  955. - (void)keyDown:(NSEvent *)event
  956. {
  957. #define CLEAR_PRE_EDIT_TEXT glfw_keyevent.text = NULL; glfw_keyevent.ime_state = GLFW_IME_PREEDIT_CHANGED; _glfwInputKeyboard(window, &glfw_keyevent);
  958. #define UPDATE_PRE_EDIT_TEXT glfw_keyevent.text = [[markedText string] UTF8String]; glfw_keyevent.ime_state = GLFW_IME_PREEDIT_CHANGED; _glfwInputKeyboard(window, &glfw_keyevent);
  959. const bool previous_has_marked_text = [self hasMarkedText];
  960. if (input_context && (!input_source_at_last_key_event || ![input_source_at_last_key_event isEqualToString:input_context.selectedKeyboardInputSource])) {
  961. if (input_source_at_last_key_event) {
  962. debug_key("Input source changed, clearing pre-edit text and resetting deadkey state\n");
  963. GLFWkeyevent dummy = {.action = GLFW_RELEASE, .ime_state = GLFW_IME_PREEDIT_CHANGED};
  964. window->ns.deadKeyState = 0;
  965. _glfwInputKeyboard(window, &dummy); // clear pre-edit text
  966. [input_source_at_last_key_event release];
  967. input_source_at_last_key_event = nil;
  968. }
  969. input_source_at_last_key_event = [input_context.selectedKeyboardInputSource retain];
  970. [self unmarkText];
  971. }
  972. const unsigned int keycode = [event keyCode];
  973. const NSUInteger flags = [event modifierFlags];
  974. const int mods = translateFlags(flags);
  975. const uint32_t key = translateKey(keycode, true);
  976. const bool process_text = !_glfw.ignoreOSKeyboardProcessing && (!window->ns.textInputFilterCallback || window->ns.textInputFilterCallback(key, mods, keycode, flags) != 1);
  977. _glfw.ns.text[0] = 0;
  978. if (keycode == 0x33 /* backspace */ || keycode == 0x35 /* escape */) [self unmarkText];
  979. GLFWkeyevent glfw_keyevent = {.key = key, .native_key = keycode, .native_key_id = keycode, .action = GLFW_PRESS, .mods = mods};
  980. if (!_glfw.ns.unicodeData) {
  981. // Using the cocoa API for key handling is disabled, as there is no
  982. // reliable way to handle dead keys using it. Only use it if the
  983. // keyboard unicode data is not available.
  984. if (process_text) {
  985. // this will call insertText with the text for this event, if any
  986. [self interpretKeyEvents:@[event]];
  987. }
  988. } else {
  989. static UniChar text[256];
  990. UniCharCount char_count = 0;
  991. const bool in_compose_sequence = window->ns.deadKeyState != 0;
  992. if (UCKeyTranslate(
  993. [(NSData*) _glfw.ns.unicodeData bytes],
  994. keycode,
  995. kUCKeyActionDown,
  996. convert_cocoa_to_carbon_modifiers(flags),
  997. LMGetKbdType(),
  998. (process_text ? 0 : kUCKeyTranslateNoDeadKeysMask),
  999. &(window->ns.deadKeyState),
  1000. sizeof(text)/sizeof(text[0]),
  1001. &char_count,
  1002. text
  1003. ) != noErr) {
  1004. debug_key("UCKeyTranslate failed for keycode: 0x%x (%s) %s\n",
  1005. keycode, safe_name_for_keycode(keycode), format_mods(mods));
  1006. window->ns.deadKeyState = 0;
  1007. return;
  1008. }
  1009. debug_key("\x1b[31mPress:\x1b[m native_key: 0x%x (%s) glfw_key: 0x%x %schar_count: %lu deadKeyState: %u repeat: %d ",
  1010. keycode, safe_name_for_keycode(keycode), key, format_mods(mods), char_count, window->ns.deadKeyState, event.ARepeat);
  1011. marked_text_cleared_by_insert = false;
  1012. if (process_text) {
  1013. in_key_handler = 1;
  1014. // this will call insertText which will fill up _glfw.ns.text
  1015. [self interpretKeyEvents:@[event]];
  1016. in_key_handler = 0;
  1017. } else {
  1018. window->ns.deadKeyState = 0;
  1019. }
  1020. if (window->ns.deadKeyState && (char_count == 0 || keycode == 0x75)) {
  1021. // 0x75 is the delete key which needs to be ignored during a compose sequence
  1022. debug_key("Sending pre-edit text for dead key (text: %s markedText: %s).\n", format_text(_glfw.ns.text), glfw_keyevent.text);
  1023. UPDATE_PRE_EDIT_TEXT;
  1024. return;
  1025. }
  1026. if (in_compose_sequence) {
  1027. debug_key("Clearing pre-edit text at end of compose sequence\n");
  1028. CLEAR_PRE_EDIT_TEXT;
  1029. }
  1030. }
  1031. if (is_ascii_control_char(_glfw.ns.text[0])) _glfw.ns.text[0] = 0; // don't send text for ascii control codes
  1032. debug_key("text: %s glfw_key: %s marked_text: (%s)\n",
  1033. format_text(_glfw.ns.text), _glfwGetKeyName(key), [[markedText string] UTF8String]);
  1034. bool bracketed_ime = false;
  1035. if (!window->ns.deadKeyState) {
  1036. if ([self hasMarkedText]) {
  1037. if (!marked_text_cleared_by_insert) {
  1038. UPDATE_PRE_EDIT_TEXT;
  1039. } else bracketed_ime = true;
  1040. } else if (previous_has_marked_text) {
  1041. CLEAR_PRE_EDIT_TEXT;
  1042. }
  1043. if (([self hasMarkedText] || previous_has_marked_text) && !_glfw.ns.text[0]) {
  1044. // do not pass keys like BACKSPACE while there's pre-edit text, let IME handle it
  1045. debug_key("Ignoring key press as IME is active and it generated no text\n");
  1046. return;
  1047. }
  1048. }
  1049. if (bracketed_ime) {
  1050. // insertText followed by setMarkedText
  1051. CLEAR_PRE_EDIT_TEXT;
  1052. }
  1053. glfw_keyevent.text = _glfw.ns.text;
  1054. glfw_keyevent.ime_state = GLFW_IME_NONE;
  1055. add_alternate_keys(&glfw_keyevent, event);
  1056. _glfwInputKeyboard(window, &glfw_keyevent);
  1057. if (bracketed_ime) {
  1058. // insertText followed by setMarkedText
  1059. UPDATE_PRE_EDIT_TEXT;
  1060. }
  1061. }
  1062. static bool
  1063. is_modifier_pressed(NSUInteger flags, NSUInteger target_mask, NSUInteger other_mask, NSUInteger either_mask) {
  1064. bool target_pressed = (flags & target_mask) != 0;
  1065. bool other_pressed = (flags & other_mask) != 0;
  1066. bool either_pressed = (flags & either_mask) != 0;
  1067. if (either_pressed != (target_pressed || other_pressed)) return either_pressed;
  1068. return target_pressed;
  1069. }
  1070. - (void)flagsChanged:(NSEvent *)event
  1071. {
  1072. int action = GLFW_RELEASE;
  1073. const char old_first_char = _glfw.ns.text[0];
  1074. _glfw.ns.text[0] = 0;
  1075. const NSUInteger modifierFlags = [event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
  1076. const uint32_t key = vk_code_to_functional_key_code([event keyCode]);
  1077. const unsigned int keycode = [event keyCode];
  1078. const int mods = translateFlags(modifierFlags);
  1079. const bool process_text = !_glfw.ignoreOSKeyboardProcessing && (!window->ns.textInputFilterCallback || window->ns.textInputFilterCallback(key, mods, keycode, modifierFlags) != 1);
  1080. const char *mod_name = "unknown";
  1081. // Code for handling modifier key events copied form SDL_cocoakeyboard.m, with thanks. See IsModifierKeyPressedFunction()
  1082. #define action_for(modname, target_mask, other_mask, either_mask) action = is_modifier_pressed([event modifierFlags], target_mask, other_mask, either_mask) ? GLFW_PRESS : GLFW_RELEASE; mod_name = #modname; break;
  1083. switch(key) {
  1084. case GLFW_FKEY_CAPS_LOCK:
  1085. mod_name = "capslock";
  1086. action = modifierFlags & NSEventModifierFlagCapsLock ? GLFW_PRESS : GLFW_RELEASE; break;
  1087. case GLFW_FKEY_LEFT_SUPER: action_for(super, NX_DEVICELCMDKEYMASK, NX_DEVICERCMDKEYMASK, NX_COMMANDMASK);
  1088. case GLFW_FKEY_RIGHT_SUPER: action_for(super, NX_DEVICERCMDKEYMASK, NX_DEVICELCMDKEYMASK, NX_COMMANDMASK);
  1089. case GLFW_FKEY_LEFT_CONTROL: action_for(ctrl, NX_DEVICELCTLKEYMASK, NX_DEVICERCTLKEYMASK, NX_CONTROLMASK);
  1090. case GLFW_FKEY_RIGHT_CONTROL: action_for(ctrl, NX_DEVICERCTLKEYMASK, NX_DEVICELCTLKEYMASK, NX_CONTROLMASK);
  1091. case GLFW_FKEY_LEFT_ALT: action_for(alt, NX_DEVICELALTKEYMASK, NX_DEVICERALTKEYMASK, NX_ALTERNATEMASK);
  1092. case GLFW_FKEY_RIGHT_ALT: action_for(alt, NX_DEVICERALTKEYMASK, NX_DEVICELALTKEYMASK, NX_ALTERNATEMASK);
  1093. case GLFW_FKEY_LEFT_SHIFT: action_for(shift, NX_DEVICELSHIFTKEYMASK, NX_DEVICERSHIFTKEYMASK, NX_SHIFTMASK);
  1094. case GLFW_FKEY_RIGHT_SHIFT: action_for(shift, NX_DEVICERSHIFTKEYMASK, NX_DEVICELSHIFTKEYMASK, NX_SHIFTMASK);
  1095. default:
  1096. return;
  1097. }
  1098. #undef action_for
  1099. GLFWkeyevent glfw_keyevent = {.key = key, .native_key = keycode, .native_key_id = keycode, .action = action, .mods = mods};
  1100. debug_key("\x1b[33mflagsChanged:\x1b[m modifier: %s native_key: 0x%x (%s) glfw_key: 0x%x %s\n",
  1101. mod_name, keycode, safe_name_for_keycode(keycode), key, format_mods(mods));
  1102. marked_text_cleared_by_insert = false;
  1103. if (process_text && input_context) {
  1104. // this will call insertText which will fill up _glfw.ns.text
  1105. in_key_handler = 2;
  1106. [input_context handleEvent:event];
  1107. in_key_handler = 0;
  1108. if (marked_text_cleared_by_insert) {
  1109. debug_key("Clearing pre-edit text because insertText called from flagsChanged\n");
  1110. CLEAR_PRE_EDIT_TEXT;
  1111. if (_glfw.ns.text[0]) glfw_keyevent.text = _glfw.ns.text;
  1112. else _glfw.ns.text[0] = old_first_char;
  1113. }
  1114. }
  1115. glfw_keyevent.ime_state = GLFW_IME_NONE;
  1116. _glfwInputKeyboard(window, &glfw_keyevent);
  1117. }
  1118. - (void)keyUp:(NSEvent *)event
  1119. {
  1120. const uint32_t keycode = [event keyCode];
  1121. const uint32_t key = translateKey(keycode, true);
  1122. const int mods = translateFlags([event modifierFlags]);
  1123. GLFWkeyevent glfw_keyevent = {.key = key, .native_key = keycode, .native_key_id = keycode, .action = GLFW_RELEASE, .mods = mods};
  1124. add_alternate_keys(&glfw_keyevent, event);
  1125. debug_key("\x1b[32mRelease:\x1b[m native_key: 0x%x (%s) glfw_key: 0x%x %s\n",
  1126. keycode, safe_name_for_keycode(keycode), key, format_mods(mods));
  1127. _glfwInputKeyboard(window, &glfw_keyevent);
  1128. }
  1129. #undef CLEAR_PRE_EDIT_TEXT
  1130. #undef UPDATE_PRE_EDIT_TEXT
  1131. - (void)scrollWheel:(NSEvent *)event
  1132. {
  1133. double deltaX = [event scrollingDeltaX];
  1134. double deltaY = [event scrollingDeltaY];
  1135. int flags = [event hasPreciseScrollingDeltas] ? 1 : 0;
  1136. if (flags) {
  1137. float xscale = 1, yscale = 1;
  1138. _glfwPlatformGetWindowContentScale(window, &xscale, &yscale);
  1139. if (xscale > 0) deltaX *= xscale;
  1140. if (yscale > 0) deltaY *= yscale;
  1141. }
  1142. switch([event momentumPhase]) {
  1143. case NSEventPhaseBegan:
  1144. flags |= (1 << 1); break;
  1145. case NSEventPhaseStationary:
  1146. flags |= (2 << 1); break;
  1147. case NSEventPhaseChanged:
  1148. flags |= (3 << 1); break;
  1149. case NSEventPhaseEnded:
  1150. flags |= (4 << 1); break;
  1151. case NSEventPhaseCancelled:
  1152. flags |= (5 << 1); break;
  1153. case NSEventPhaseMayBegin:
  1154. flags |= (6 << 1); break;
  1155. case NSEventPhaseNone:
  1156. default:
  1157. break;
  1158. }
  1159. _glfwInputScroll(window, deltaX, deltaY, flags, translateFlags([event modifierFlags]));
  1160. }
  1161. - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
  1162. {
  1163. (void)sender;
  1164. // HACK: We don't know what to say here because we don't know what the
  1165. // application wants to do with the paths
  1166. return NSDragOperationGeneric;
  1167. }
  1168. - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
  1169. {
  1170. const NSRect contentRect = [window->ns.view frame];
  1171. // NOTE: The returned location uses base 0,1 not 0,0
  1172. const NSPoint pos = [sender draggingLocation];
  1173. _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y);
  1174. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1175. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  1176. NSArray* objs = [pasteboard readObjectsForClasses:@[[NSURL class], [NSString class]]
  1177. options:options];
  1178. if (!objs) return NO;
  1179. const NSUInteger count = [objs count];
  1180. NSMutableString *uri_list = [NSMutableString stringWithCapacity:4096]; // auto-released
  1181. if (count)
  1182. {
  1183. for (NSUInteger i = 0; i < count; i++)
  1184. {
  1185. id obj = objs[i];
  1186. if ([obj isKindOfClass:[NSURL class]]) {
  1187. NSURL *url = (NSURL*)obj;
  1188. if ([uri_list length] > 0) [uri_list appendString:@("\n")];
  1189. if (url.fileURL) [uri_list appendString:url.filePathURL.absoluteString];
  1190. else [uri_list appendString:url.absoluteString];
  1191. } else if ([obj isKindOfClass:[NSString class]]) {
  1192. const char *text = [obj UTF8String];
  1193. _glfwInputDrop(window, "text/plain;charset=utf-8", text, strlen(text));
  1194. } else {
  1195. _glfwInputError(GLFW_PLATFORM_ERROR,
  1196. "Cocoa: Object is neither a URL nor a string");
  1197. }
  1198. }
  1199. }
  1200. if ([uri_list length] > 0) _glfwInputDrop(window, "text/uri-list", uri_list.UTF8String, strlen(uri_list.UTF8String));
  1201. return YES;
  1202. }
  1203. - (BOOL)hasMarkedText
  1204. {
  1205. return [markedText length] > 0;
  1206. }
  1207. - (NSRange)markedRange
  1208. {
  1209. if ([markedText length] > 0)
  1210. return NSMakeRange(0, [markedText length] - 1);
  1211. else
  1212. return kEmptyRange;
  1213. }
  1214. - (NSRange)selectedRange
  1215. {
  1216. return kEmptyRange;
  1217. }
  1218. - (void)setMarkedText:(id)string
  1219. selectedRange:(NSRange)selectedRange
  1220. replacementRange:(NSRange)replacementRange
  1221. {
  1222. const char *s = polymorphic_string_as_utf8(string);
  1223. debug_key("\n\tsetMarkedText: %s selectedRange: (%lu, %lu) replacementRange: (%lu, %lu)\n", s, selectedRange.location, selectedRange.length, replacementRange.location, replacementRange.length);
  1224. if (string == nil || !s[0]) {
  1225. bool had_marked_text = [self hasMarkedText];
  1226. [self unmarkText];
  1227. if (had_marked_text && (!in_key_handler || in_key_handler == 2)) {
  1228. debug_key("Clearing pre-edit because setMarkedText called from %s\n", in_key_handler ? "flagsChanged" : "event loop");
  1229. GLFWkeyevent glfw_keyevent = {.ime_state = GLFW_IME_PREEDIT_CHANGED};
  1230. _glfwInputKeyboard(window, &glfw_keyevent);
  1231. _glfw.ns.text[0] = 0;
  1232. }
  1233. return;
  1234. }
  1235. if ([string isKindOfClass:[NSAttributedString class]]) {
  1236. if (((NSMutableAttributedString*)string).length == 0) { [self unmarkText]; return; }
  1237. [markedText release];
  1238. markedText = [[NSMutableAttributedString alloc] initWithAttributedString:string];
  1239. } else {
  1240. if (((NSString*)string).length == 0) { [self unmarkText]; return; }
  1241. [markedText release];
  1242. markedText = [[NSMutableAttributedString alloc] initWithString:string];
  1243. }
  1244. if (!in_key_handler || in_key_handler == 2) {
  1245. debug_key("Updating IME text in kitty from setMarkedText called from %s: %s\n", in_key_handler ? "flagsChanged" : "event loop", _glfw.ns.text);
  1246. GLFWkeyevent glfw_keyevent = {.text=[[markedText string] UTF8String], .ime_state = GLFW_IME_PREEDIT_CHANGED};
  1247. _glfwInputKeyboard(window, &glfw_keyevent);
  1248. _glfw.ns.text[0] = 0;
  1249. }
  1250. }
  1251. - (void)unmarkText
  1252. {
  1253. [[markedText mutableString] setString:@""];
  1254. }
  1255. void _glfwPlatformUpdateIMEState(_GLFWwindow *w, const GLFWIMEUpdateEvent *ev) {
  1256. [w->ns.view updateIMEStateFor: ev->type focused:(bool)ev->focused];
  1257. }
  1258. - (void)updateIMEStateFor:(GLFWIMEUpdateType)which
  1259. focused:(bool)focused
  1260. {
  1261. if (which == GLFW_IME_UPDATE_FOCUS && !focused && [self hasMarkedText] && window) {
  1262. [input_context discardMarkedText];
  1263. [self unmarkText];
  1264. GLFWkeyevent glfw_keyevent = {.ime_state = GLFW_IME_PREEDIT_CHANGED};
  1265. _glfwInputKeyboard(window, &glfw_keyevent);
  1266. _glfw.ns.text[0] = 0;
  1267. }
  1268. if (which != GLFW_IME_UPDATE_CURSOR_POSITION) return;
  1269. if (_glfwPlatformWindowFocused(window)) [[window->ns.view inputContext] invalidateCharacterCoordinates];
  1270. }
  1271. - (NSArray*)validAttributesForMarkedText
  1272. {
  1273. return [NSArray array];
  1274. }
  1275. - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
  1276. actualRange:(NSRangePointer)actualRange
  1277. {
  1278. (void)range; (void)actualRange;
  1279. return nil;
  1280. }
  1281. - (NSUInteger)characterIndexForPoint:(NSPoint)point
  1282. {
  1283. (void)point;
  1284. return 0;
  1285. }
  1286. - (NSRect)firstRectForCharacterRange:(NSRange)range
  1287. actualRange:(NSRangePointer)actualRange
  1288. {
  1289. (void)range; (void)actualRange;
  1290. if (_glfw.callbacks.get_ime_cursor_position) {
  1291. GLFWIMEUpdateEvent ev = { .type = GLFW_IME_UPDATE_CURSOR_POSITION };
  1292. if (window && _glfw.callbacks.get_ime_cursor_position((GLFWwindow*)window, &ev)) {
  1293. const CGFloat left = (CGFloat)ev.cursor.left / window->ns.xscale;
  1294. const CGFloat top = (CGFloat)ev.cursor.top / window->ns.yscale;
  1295. const CGFloat cellWidth = (CGFloat)ev.cursor.width / window->ns.xscale;
  1296. const CGFloat cellHeight = (CGFloat)ev.cursor.height / window->ns.yscale;
  1297. debug_key("updateIMEPosition: left=%f, top=%f, width=%f, height=%f\n", left, top, cellWidth, cellHeight);
  1298. const NSRect frame = [window->ns.view frame];
  1299. const NSRect rectInView = NSMakeRect(left,
  1300. frame.size.height - top - cellHeight,
  1301. cellWidth, cellHeight);
  1302. markedRect = [window->ns.object convertRectToScreen: rectInView];
  1303. }
  1304. }
  1305. return markedRect;
  1306. }
  1307. - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
  1308. {
  1309. const char *utf8 = polymorphic_string_as_utf8(string);
  1310. debug_key("\n\tinsertText: %s replacementRange: (%lu, %lu)\n", utf8, replacementRange.location, replacementRange.length);
  1311. if ([self hasMarkedText] && !is_ascii_control_char(utf8[0])) {
  1312. [self unmarkText];
  1313. marked_text_cleared_by_insert = true;
  1314. if (!in_key_handler) {
  1315. debug_key("Clearing pre-edit because insertText called from event loop\n");
  1316. GLFWkeyevent glfw_keyevent = {.ime_state = GLFW_IME_PREEDIT_CHANGED};
  1317. _glfwInputKeyboard(window, &glfw_keyevent);
  1318. _glfw.ns.text[0] = 0;
  1319. }
  1320. }
  1321. // insertText can be called multiple times for a single key event
  1322. size_t existing_length = strnlen(_glfw.ns.text, sizeof(_glfw.ns.text));
  1323. size_t required_length = strlen(utf8) + 1;
  1324. size_t available_length = sizeof(_glfw.ns.text) - existing_length;
  1325. if (available_length >= required_length) {
  1326. memcpy(_glfw.ns.text + existing_length, utf8, required_length); // copies the null terminator from utf8 as well
  1327. _glfw.ns.text[sizeof(_glfw.ns.text) - 1] = 0;
  1328. if ((!in_key_handler || in_key_handler == 2) && _glfw.ns.text[0]) {
  1329. if (!is_ascii_control_char(_glfw.ns.text[0])) {
  1330. debug_key("Sending text to kitty from insertText called from %s: %s\n", in_key_handler ? "flagsChanged" : "event loop", _glfw.ns.text);
  1331. GLFWkeyevent glfw_keyevent = {.text=_glfw.ns.text, .ime_state=GLFW_IME_COMMIT_TEXT};
  1332. _glfwInputKeyboard(window, &glfw_keyevent);
  1333. }
  1334. _glfw.ns.text[0] = 0;
  1335. }
  1336. }
  1337. }
  1338. - (void)doCommandBySelector:(SEL)selector
  1339. {
  1340. debug_key("\n\tdoCommandBySelector: (%s)\n", [NSStringFromSelector(selector) UTF8String]);
  1341. }
  1342. - (BOOL)isAccessibilityElement
  1343. {
  1344. return YES;
  1345. }
  1346. - (BOOL)isAccessibilitySelectorAllowed:(SEL)selector
  1347. {
  1348. if (selector == @selector(accessibilityRole) || selector == @selector(accessibilitySelectedText)) return YES;
  1349. return NO;
  1350. }
  1351. #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400)
  1352. - (NSAccessibilityRole)accessibilityRole
  1353. {
  1354. return NSAccessibilityTextAreaRole;
  1355. }
  1356. #endif
  1357. - (NSString *)accessibilitySelectedText
  1358. {
  1359. NSString *text = nil;
  1360. if (_glfw.callbacks.get_current_selection) {
  1361. char *s = _glfw.callbacks.get_current_selection();
  1362. if (s) {
  1363. text = [NSString stringWithUTF8String:s];
  1364. free(s);
  1365. }
  1366. }
  1367. return text;
  1368. }
  1369. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SysServices/Articles/using.html>
  1370. // Support services receiving "public.utf8-plain-text" and "NSStringPboardType"
  1371. - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
  1372. {
  1373. if (
  1374. (!sendType || [sendType isEqual:NSPasteboardTypeString] || [sendType isEqual:@"NSStringPboardType"]) &&
  1375. (!returnType || [returnType isEqual:NSPasteboardTypeString] || [returnType isEqual:@"NSStringPboardType"])
  1376. ) {
  1377. if (_glfw.callbacks.has_current_selection && _glfw.callbacks.has_current_selection()) return self;
  1378. }
  1379. return [super validRequestorForSendType:sendType returnType:returnType];
  1380. }
  1381. // Selected text as input to be sent to Services
  1382. // For example, after selecting an absolute path, open the global menu bar kitty->Services and click `Show in Finder`.
  1383. - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types
  1384. {
  1385. if (!_glfw.callbacks.get_current_selection) return NO;
  1386. char *text = _glfw.callbacks.get_current_selection();
  1387. if (!text) return NO;
  1388. BOOL ans = NO;
  1389. if (text[0]) {
  1390. if ([types containsObject:NSPasteboardTypeString] == YES) {
  1391. [pboard declareTypes:@[NSPasteboardTypeString] owner:self];
  1392. ans = [pboard setString:@(text) forType:NSPasteboardTypeString];
  1393. } else if ([types containsObject:@"NSStringPboardType"] == YES) {
  1394. [pboard declareTypes:@[@"NSStringPboardType"] owner:self];
  1395. ans = [pboard setString:@(text) forType:@"NSStringPboardType"];
  1396. }
  1397. free(text);
  1398. }
  1399. return ans;
  1400. }
  1401. // Service output to be handled
  1402. // For example, open System Settings->Keyboard->Keyboard Shortcuts->Services->Text, enable `Convert Text to Full Width`, select some text and execute the service.
  1403. - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
  1404. {
  1405. NSString* text = nil;
  1406. NSArray *types = [pboard types];
  1407. if ([types containsObject:NSPasteboardTypeString] == YES) {
  1408. text = [pboard stringForType:NSPasteboardTypeString]; // public.utf8-plain-text
  1409. } else if ([types containsObject:@"NSStringPboardType"] == YES) {
  1410. text = [pboard stringForType:@"NSStringPboardType"]; // for older services (need re-encode?)
  1411. } else {
  1412. return NO;
  1413. }
  1414. if (text && [text length] > 0) {
  1415. // The service wants us to replace the selection, but we can't replace anything but insert text.
  1416. const char *utf8 = polymorphic_string_as_utf8(text);
  1417. debug_key("Sending text received in readSelectionFromPasteboard as key event\n");
  1418. GLFWkeyevent glfw_keyevent = {.text=utf8, .ime_state=GLFW_IME_COMMIT_TEXT};
  1419. _glfwInputKeyboard(window, &glfw_keyevent);
  1420. // Restore pre-edit text after inserting the received text
  1421. if ([self hasMarkedText]) {
  1422. glfw_keyevent.text = [[markedText string] UTF8String];
  1423. glfw_keyevent.ime_state = GLFW_IME_PREEDIT_CHANGED;
  1424. _glfwInputKeyboard(window, &glfw_keyevent);
  1425. }
  1426. return YES;
  1427. }
  1428. return NO;
  1429. }
  1430. @end
  1431. // }}}
  1432. // GLFW window class {{{
  1433. @interface GLFWWindow : NSWindow {
  1434. _GLFWwindow* glfw_window;
  1435. }
  1436. - (instancetype)initWithGlfwWindow:(NSRect)contentRect
  1437. styleMask:(NSWindowStyleMask)style
  1438. backing:(NSBackingStoreType)backingStoreType
  1439. initWindow:(_GLFWwindow *)initWindow;
  1440. - (void) removeGLFWWindow;
  1441. @end
  1442. @implementation GLFWWindow
  1443. - (instancetype)initWithGlfwWindow:(NSRect)contentRect
  1444. styleMask:(NSWindowStyleMask)style
  1445. backing:(NSBackingStoreType)backingStoreType
  1446. initWindow:(_GLFWwindow *)initWindow
  1447. {
  1448. self = [super initWithContentRect:contentRect styleMask:style backing:backingStoreType defer:NO];
  1449. if (self != nil) {
  1450. glfw_window = initWindow;
  1451. self.tabbingMode = NSWindowTabbingModeDisallowed;
  1452. }
  1453. return self;
  1454. }
  1455. - (void) removeGLFWWindow
  1456. {
  1457. glfw_window = NULL;
  1458. }
  1459. - (BOOL)validateMenuItem:(NSMenuItem *)item {
  1460. if (item.action == @selector(performMiniaturize:)) return YES;
  1461. return [super validateMenuItem:item];
  1462. }
  1463. - (void)performMiniaturize:(id)sender
  1464. {
  1465. if (glfw_window && (!glfw_window->decorated || glfw_window->ns.titlebar_hidden)) [self miniaturize:self];
  1466. else [super performMiniaturize:sender];
  1467. }
  1468. - (BOOL)canBecomeKeyWindow
  1469. {
  1470. // Required for NSWindowStyleMaskBorderless windows
  1471. return YES;
  1472. }
  1473. - (BOOL)canBecomeMainWindow
  1474. {
  1475. return YES;
  1476. }
  1477. static void
  1478. update_titlebar_button_visibility_after_fullscreen_transition(_GLFWwindow* w, bool traditional, bool made_fullscreen) {
  1479. // Update window button visibility
  1480. if (w->ns.titlebar_hidden) {
  1481. NSWindow *window = w->ns.object;
  1482. // The hidden buttons might be automatically reset to be visible after going full screen
  1483. // to show up in the auto-hide title bar, so they need to be set back to hidden.
  1484. BOOL button_hidden = YES;
  1485. // When title bar is configured to be hidden, it should be shown with buttons (auto-hide) after going to full screen.
  1486. if (!traditional) {
  1487. button_hidden = (BOOL) !made_fullscreen;
  1488. }
  1489. [[window standardWindowButton: NSWindowCloseButton] setHidden:button_hidden];
  1490. [[window standardWindowButton: NSWindowMiniaturizeButton] setHidden:button_hidden];
  1491. [[window standardWindowButton: NSWindowZoomButton] setHidden:button_hidden];
  1492. }
  1493. }
  1494. - (void)toggleFullScreen:(nullable id)sender
  1495. {
  1496. if (glfw_window) {
  1497. if (glfw_window->ns.in_fullscreen_transition) return;
  1498. if (glfw_window->ns.toggleFullscreenCallback && glfw_window->ns.toggleFullscreenCallback((GLFWwindow*)glfw_window) == 1) return;
  1499. glfw_window->ns.in_fullscreen_transition = true;
  1500. }
  1501. NSWindowStyleMask sm = [self styleMask];
  1502. bool is_fullscreen_already = (sm & NSWindowStyleMaskFullScreen) != 0;
  1503. // When resizeIncrements is set, Cocoa cannot restore the original window size after returning from fullscreen.
  1504. const NSSize original = [self resizeIncrements];
  1505. [self setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1506. [super toggleFullScreen:sender];
  1507. [self setResizeIncrements:original];
  1508. // When the window decoration is hidden, toggling fullscreen causes the style mask to be changed,
  1509. // and causes the first responder to be cleared.
  1510. if (glfw_window && !glfw_window->decorated && glfw_window->ns.view) [self makeFirstResponder:glfw_window->ns.view];
  1511. update_titlebar_button_visibility_after_fullscreen_transition(glfw_window, false, !is_fullscreen_already);
  1512. }
  1513. - (void)zoom:(id)sender
  1514. {
  1515. if (![self isZoomed]) {
  1516. const NSSize original = [self resizeIncrements];
  1517. [self setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1518. [super zoom:sender];
  1519. [self setResizeIncrements:original];
  1520. } else {
  1521. [super zoom:sender];
  1522. }
  1523. }
  1524. @end
  1525. // }}}
  1526. // Create the Cocoa window
  1527. //
  1528. static bool createNativeWindow(_GLFWwindow* window,
  1529. const _GLFWwndconfig* wndconfig,
  1530. const _GLFWfbconfig* fbconfig)
  1531. {
  1532. window->ns.delegate = [[GLFWWindowDelegate alloc] initWithGlfwWindow:window];
  1533. if (window->ns.delegate == nil)
  1534. {
  1535. _glfwInputError(GLFW_PLATFORM_ERROR,
  1536. "Cocoa: Failed to create window delegate");
  1537. return false;
  1538. }
  1539. NSRect contentRect;
  1540. if (window->monitor)
  1541. {
  1542. GLFWvidmode mode;
  1543. int xpos, ypos;
  1544. _glfwPlatformGetVideoMode(window->monitor, &mode);
  1545. _glfwPlatformGetMonitorPos(window->monitor, &xpos, &ypos);
  1546. contentRect = NSMakeRect(xpos, ypos, mode.width, mode.height);
  1547. }
  1548. else
  1549. contentRect = NSMakeRect(0, 0, wndconfig->width, wndconfig->height);
  1550. window->ns.object = [[GLFWWindow alloc]
  1551. initWithGlfwWindow:contentRect
  1552. styleMask:getStyleMask(window)
  1553. backing:NSBackingStoreBuffered
  1554. initWindow:window
  1555. ];
  1556. if (window->ns.object == nil)
  1557. {
  1558. _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to create window");
  1559. return false;
  1560. }
  1561. if (window->monitor)
  1562. [window->ns.object setLevel:NSMainMenuWindowLevel + 1];
  1563. else
  1564. {
  1565. [(NSWindow*) window->ns.object center];
  1566. CGRect screen_frame = [[(NSWindow*) window->ns.object screen] frame];
  1567. if (CGRectContainsPoint(screen_frame, _glfw.ns.cascadePoint)
  1568. || CGPointEqualToPoint(CGPointZero, _glfw.ns.cascadePoint)) {
  1569. _glfw.ns.cascadePoint =
  1570. NSPointToCGPoint([window->ns.object cascadeTopLeftFromPoint:
  1571. NSPointFromCGPoint(_glfw.ns.cascadePoint)]);
  1572. } else {
  1573. _glfw.ns.cascadePoint = CGPointZero;
  1574. }
  1575. if (wndconfig->resizable)
  1576. {
  1577. const NSWindowCollectionBehavior behavior =
  1578. NSWindowCollectionBehaviorFullScreenPrimary |
  1579. NSWindowCollectionBehaviorManaged;
  1580. [window->ns.object setCollectionBehavior:behavior];
  1581. }
  1582. if (wndconfig->floating)
  1583. [window->ns.object setLevel:NSFloatingWindowLevel];
  1584. if (wndconfig->maximized)
  1585. [window->ns.object zoom:nil];
  1586. }
  1587. if (strlen(wndconfig->ns.frameName))
  1588. [window->ns.object setFrameAutosaveName:@(wndconfig->ns.frameName)];
  1589. window->ns.view = [[GLFWContentView alloc] initWithGlfwWindow:window];
  1590. window->ns.retina = wndconfig->ns.retina;
  1591. if (fbconfig->transparent)
  1592. {
  1593. [window->ns.object setOpaque:NO];
  1594. [window->ns.object setHasShadow:NO];
  1595. [window->ns.object setBackgroundColor:[NSColor clearColor]];
  1596. }
  1597. [window->ns.object setContentView:window->ns.view];
  1598. [window->ns.object makeFirstResponder:window->ns.view];
  1599. [window->ns.object setTitle:@(wndconfig->title)];
  1600. [window->ns.object setDelegate:window->ns.delegate];
  1601. [window->ns.object setAcceptsMouseMovedEvents:YES];
  1602. [window->ns.object setRestorable:NO];
  1603. _glfwPlatformGetWindowSize(window, &window->ns.width, &window->ns.height);
  1604. _glfwPlatformGetFramebufferSize(window, &window->ns.fbWidth, &window->ns.fbHeight);
  1605. if (wndconfig->blur_radius > 0) _glfwPlatformSetWindowBlur(window, wndconfig->blur_radius);
  1606. return true;
  1607. }
  1608. //////////////////////////////////////////////////////////////////////////
  1609. ////// GLFW platform API //////
  1610. //////////////////////////////////////////////////////////////////////////
  1611. int _glfwPlatformCreateWindow(_GLFWwindow* window,
  1612. const _GLFWwndconfig* wndconfig,
  1613. const _GLFWctxconfig* ctxconfig,
  1614. const _GLFWfbconfig* fbconfig)
  1615. {
  1616. window->ns.deadKeyState = 0;
  1617. if (!_glfw.ns.finishedLaunching)
  1618. {
  1619. [NSApp run];
  1620. _glfw.ns.finishedLaunching = true;
  1621. }
  1622. if (!createNativeWindow(window, wndconfig, fbconfig))
  1623. return false;
  1624. switch((GlfwCocoaColorSpaces)wndconfig->ns.color_space) {
  1625. case SRGB_COLORSPACE: [window->ns.object setColorSpace:[NSColorSpace sRGBColorSpace]]; break;
  1626. case DISPLAY_P3_COLORSPACE: [window->ns.object setColorSpace:[NSColorSpace displayP3ColorSpace]]; break;
  1627. case DEFAULT_COLORSPACE: break;
  1628. }
  1629. if (ctxconfig->client != GLFW_NO_API)
  1630. {
  1631. if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API)
  1632. {
  1633. if (!_glfwInitNSGL())
  1634. return false;
  1635. if (!_glfwCreateContextNSGL(window, ctxconfig, fbconfig))
  1636. return false;
  1637. }
  1638. else if (ctxconfig->source == GLFW_EGL_CONTEXT_API)
  1639. {
  1640. // EGL implementation on macOS use CALayer* EGLNativeWindowType so we
  1641. // need to get the layer for EGL window surface creation.
  1642. [window->ns.view setWantsLayer:YES];
  1643. window->ns.layer = [window->ns.view layer];
  1644. if (!_glfwInitEGL())
  1645. return false;
  1646. if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig))
  1647. return false;
  1648. }
  1649. else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API)
  1650. {
  1651. if (!_glfwInitOSMesa())
  1652. return false;
  1653. if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig))
  1654. return false;
  1655. }
  1656. }
  1657. if (window->monitor)
  1658. {
  1659. // Do not show the window here until after setting the window size, maximized state, and full screen
  1660. // _glfwPlatformShowWindow(window);
  1661. // _glfwPlatformFocusWindow(window);
  1662. acquireMonitor(window);
  1663. }
  1664. return true;
  1665. }
  1666. void _glfwPlatformDestroyWindow(_GLFWwindow* window)
  1667. {
  1668. if (_glfw.ns.disabledCursorWindow == window)
  1669. _glfw.ns.disabledCursorWindow = NULL;
  1670. [window->ns.object orderOut:nil];
  1671. if (window->monitor)
  1672. releaseMonitor(window);
  1673. if (window->context.destroy)
  1674. window->context.destroy(window);
  1675. [window->ns.object setDelegate:nil];
  1676. [window->ns.delegate release];
  1677. window->ns.delegate = nil;
  1678. [window->ns.view removeGLFWWindow];
  1679. [window->ns.view release];
  1680. window->ns.view = nil;
  1681. [window->ns.object removeGLFWWindow];
  1682. [window->ns.object close];
  1683. window->ns.object = nil;
  1684. }
  1685. void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
  1686. {
  1687. if (!title) return;
  1688. NSString* string = @(title);
  1689. if (!string) return; // the runtime failed to convert title to an NSString
  1690. [window->ns.object setTitle:string];
  1691. // HACK: Set the miniwindow title explicitly as setTitle: doesn't update it
  1692. // if the window lacks NSWindowStyleMaskTitled
  1693. [window->ns.object setMiniwindowTitle:string];
  1694. }
  1695. void _glfwPlatformSetWindowIcon(_GLFWwindow* window UNUSED,
  1696. int count UNUSED, const GLFWimage* images UNUSED)
  1697. {
  1698. _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
  1699. "Cocoa: Regular windows do not have icons on macOS");
  1700. }
  1701. void _glfwPlatformGetWindowPos(_GLFWwindow* window, int* xpos, int* ypos)
  1702. {
  1703. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1704. if (xpos)
  1705. *xpos = (int)contentRect.origin.x;
  1706. if (ypos)
  1707. *ypos = (int)_glfwTransformYNS(contentRect.origin.y + contentRect.size.height - 1);
  1708. }
  1709. void _glfwPlatformSetWindowPos(_GLFWwindow* window, int x, int y)
  1710. {
  1711. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1712. const NSRect dummyRect = NSMakeRect(x, _glfwTransformYNS(y + contentRect.size.height - 1), 0, 0);
  1713. const NSRect frameRect = [window->ns.object frameRectForContentRect:dummyRect];
  1714. [window->ns.object setFrameOrigin:frameRect.origin];
  1715. }
  1716. void _glfwPlatformGetWindowSize(_GLFWwindow* window, int* width, int* height)
  1717. {
  1718. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1719. if (width)
  1720. *width = (int)contentRect.size.width;
  1721. if (height)
  1722. *height = (int)contentRect.size.height;
  1723. }
  1724. void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
  1725. {
  1726. if (window->monitor)
  1727. {
  1728. if (window->monitor->window == window)
  1729. acquireMonitor(window);
  1730. }
  1731. else
  1732. {
  1733. // Disable window resizing in fullscreen.
  1734. if ([window->ns.object styleMask] & NSWindowStyleMaskFullScreen || window->ns.in_traditional_fullscreen) return;
  1735. NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1736. contentRect.origin.y += contentRect.size.height - height;
  1737. contentRect.size = NSMakeSize(width, height);
  1738. [window->ns.object setFrame:[window->ns.object frameRectForContentRect:contentRect]
  1739. display:YES];
  1740. }
  1741. }
  1742. void _glfwPlatformSetWindowSizeLimits(_GLFWwindow* window,
  1743. int minwidth, int minheight,
  1744. int maxwidth, int maxheight)
  1745. {
  1746. if (minwidth == GLFW_DONT_CARE || minheight == GLFW_DONT_CARE)
  1747. [window->ns.object setContentMinSize:NSMakeSize(0, 0)];
  1748. else
  1749. [window->ns.object setContentMinSize:NSMakeSize(minwidth, minheight)];
  1750. if (maxwidth == GLFW_DONT_CARE || maxheight == GLFW_DONT_CARE)
  1751. [window->ns.object setContentMaxSize:NSMakeSize(DBL_MAX, DBL_MAX)];
  1752. else
  1753. [window->ns.object setContentMaxSize:NSMakeSize(maxwidth, maxheight)];
  1754. }
  1755. void _glfwPlatformSetWindowAspectRatio(_GLFWwindow* window, int numer, int denom)
  1756. {
  1757. if (numer == GLFW_DONT_CARE || denom == GLFW_DONT_CARE)
  1758. [window->ns.object setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1759. else
  1760. [window->ns.object setContentAspectRatio:NSMakeSize(numer, denom)];
  1761. }
  1762. void _glfwPlatformSetWindowSizeIncrements(_GLFWwindow* window, int widthincr, int heightincr)
  1763. {
  1764. if (widthincr != GLFW_DONT_CARE && heightincr != GLFW_DONT_CARE) {
  1765. float xscale = 1, yscale = 1;
  1766. _glfwPlatformGetWindowContentScale(window, &xscale, &yscale);
  1767. [window->ns.object setResizeIncrements:NSMakeSize(widthincr / xscale, heightincr / yscale)];
  1768. } else {
  1769. [window->ns.object setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1770. }
  1771. }
  1772. void _glfwPlatformGetFramebufferSize(_GLFWwindow* window, int* width, int* height)
  1773. {
  1774. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1775. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  1776. if (width)
  1777. *width = (int) fbRect.size.width;
  1778. if (height)
  1779. *height = (int) fbRect.size.height;
  1780. }
  1781. void _glfwPlatformGetWindowFrameSize(_GLFWwindow* window,
  1782. int* left, int* top,
  1783. int* right, int* bottom)
  1784. {
  1785. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1786. const NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect];
  1787. if (left)
  1788. *left = (int)(contentRect.origin.x - frameRect.origin.x);
  1789. if (top)
  1790. *top = (int)(frameRect.origin.y + frameRect.size.height -
  1791. contentRect.origin.y - contentRect.size.height);
  1792. if (right)
  1793. *right = (int)(frameRect.origin.x + frameRect.size.width -
  1794. contentRect.origin.x - contentRect.size.width);
  1795. if (bottom)
  1796. *bottom = (int)(contentRect.origin.y - frameRect.origin.y);
  1797. }
  1798. void _glfwPlatformGetWindowContentScale(_GLFWwindow* window,
  1799. float* xscale, float* yscale)
  1800. {
  1801. const NSRect points = get_window_size_without_border_in_logical_pixels(window);
  1802. const NSRect pixels = [window->ns.view convertRectToBacking:points];
  1803. if (xscale)
  1804. *xscale = (float) (pixels.size.width / points.size.width);
  1805. if (yscale)
  1806. *yscale = (float) (pixels.size.height / points.size.height);
  1807. }
  1808. monotonic_t _glfwPlatformGetDoubleClickInterval(_GLFWwindow* window UNUSED)
  1809. {
  1810. return s_double_to_monotonic_t([NSEvent doubleClickInterval]);
  1811. }
  1812. void _glfwPlatformIconifyWindow(_GLFWwindow* window)
  1813. {
  1814. [window->ns.object miniaturize:nil];
  1815. }
  1816. void _glfwPlatformRestoreWindow(_GLFWwindow* window)
  1817. {
  1818. if ([window->ns.object isMiniaturized])
  1819. [window->ns.object deminiaturize:nil];
  1820. else if ([window->ns.object isZoomed])
  1821. [window->ns.object zoom:nil];
  1822. }
  1823. void _glfwPlatformMaximizeWindow(_GLFWwindow* window)
  1824. {
  1825. if (![window->ns.object isZoomed]) {
  1826. [window->ns.object zoom:nil];
  1827. }
  1828. }
  1829. void _glfwPlatformShowWindow(_GLFWwindow* window)
  1830. {
  1831. [window->ns.object orderFront:nil];
  1832. }
  1833. void _glfwPlatformHideWindow(_GLFWwindow* window)
  1834. {
  1835. [window->ns.object orderOut:nil];
  1836. }
  1837. void _glfwPlatformRequestWindowAttention(_GLFWwindow* window UNUSED)
  1838. {
  1839. [NSApp requestUserAttention:NSInformationalRequest];
  1840. }
  1841. int _glfwPlatformWindowBell(_GLFWwindow* window UNUSED)
  1842. {
  1843. NSBeep();
  1844. return true;
  1845. }
  1846. void _glfwPlatformFocusWindow(_GLFWwindow* window)
  1847. {
  1848. // Make us the active application
  1849. // HACK: This is here to prevent applications using only hidden windows from
  1850. // being activated, but should probably not be done every time any
  1851. // window is shown
  1852. [NSApp activateIgnoringOtherApps:YES];
  1853. [window->ns.object makeKeyAndOrderFront:nil];
  1854. }
  1855. void _glfwPlatformSetWindowMonitor(_GLFWwindow* window,
  1856. _GLFWmonitor* monitor,
  1857. int xpos, int ypos,
  1858. int width, int height,
  1859. int refreshRate UNUSED)
  1860. {
  1861. if (window->monitor == monitor)
  1862. {
  1863. if (monitor)
  1864. {
  1865. if (monitor->window == window)
  1866. acquireMonitor(window);
  1867. }
  1868. else
  1869. {
  1870. const NSRect contentRect =
  1871. NSMakeRect(xpos, _glfwTransformYNS(ypos + height - 1), width, height);
  1872. const NSRect frameRect =
  1873. [window->ns.object frameRectForContentRect:contentRect
  1874. styleMask:getStyleMask(window)];
  1875. [window->ns.object setFrame:frameRect display:YES];
  1876. }
  1877. return;
  1878. }
  1879. if (window->monitor)
  1880. releaseMonitor(window);
  1881. _glfwInputWindowMonitor(window, monitor);
  1882. const NSUInteger styleMask = getStyleMask(window);
  1883. [window->ns.object setStyleMask:styleMask];
  1884. // HACK: Changing the style mask can cause the first responder to be cleared
  1885. [window->ns.object makeFirstResponder:window->ns.view];
  1886. if (window->monitor)
  1887. {
  1888. [window->ns.object setLevel:NSMainMenuWindowLevel + 1];
  1889. [window->ns.object setHasShadow:NO];
  1890. acquireMonitor(window);
  1891. }
  1892. else
  1893. {
  1894. NSRect contentRect = NSMakeRect(xpos, _glfwTransformYNS(ypos + height - 1),
  1895. width, height);
  1896. NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect
  1897. styleMask:styleMask];
  1898. [window->ns.object setFrame:frameRect display:YES];
  1899. if (window->numer != GLFW_DONT_CARE &&
  1900. window->denom != GLFW_DONT_CARE)
  1901. {
  1902. [window->ns.object setContentAspectRatio:NSMakeSize(window->numer,
  1903. window->denom)];
  1904. }
  1905. if (window->minwidth != GLFW_DONT_CARE &&
  1906. window->minheight != GLFW_DONT_CARE)
  1907. {
  1908. [window->ns.object setContentMinSize:NSMakeSize(window->minwidth,
  1909. window->minheight)];
  1910. }
  1911. if (window->maxwidth != GLFW_DONT_CARE &&
  1912. window->maxheight != GLFW_DONT_CARE)
  1913. {
  1914. [window->ns.object setContentMaxSize:NSMakeSize(window->maxwidth,
  1915. window->maxheight)];
  1916. }
  1917. if (window->floating)
  1918. [window->ns.object setLevel:NSFloatingWindowLevel];
  1919. else
  1920. [window->ns.object setLevel:NSNormalWindowLevel];
  1921. [window->ns.object setHasShadow:YES];
  1922. // HACK: Clearing NSWindowStyleMaskTitled resets and disables the window
  1923. // title property but the miniwindow title property is unaffected
  1924. [window->ns.object setTitle:[window->ns.object miniwindowTitle]];
  1925. }
  1926. }
  1927. int _glfwPlatformWindowFocused(_GLFWwindow* window)
  1928. {
  1929. return [window->ns.object isKeyWindow];
  1930. }
  1931. int _glfwPlatformWindowOccluded(_GLFWwindow* window)
  1932. {
  1933. return !([window->ns.object occlusionState] & NSWindowOcclusionStateVisible);
  1934. }
  1935. int _glfwPlatformWindowIconified(_GLFWwindow* window)
  1936. {
  1937. return [window->ns.object isMiniaturized];
  1938. }
  1939. int _glfwPlatformWindowVisible(_GLFWwindow* window)
  1940. {
  1941. return [window->ns.object isVisible];
  1942. }
  1943. int _glfwPlatformWindowMaximized(_GLFWwindow* window)
  1944. {
  1945. return [window->ns.object isZoomed];
  1946. }
  1947. int _glfwPlatformWindowHovered(_GLFWwindow* window)
  1948. {
  1949. const NSPoint point = [NSEvent mouseLocation];
  1950. if ([NSWindow windowNumberAtPoint:point belowWindowWithWindowNumber:0] !=
  1951. [window->ns.object windowNumber])
  1952. {
  1953. return false;
  1954. }
  1955. return NSMouseInRect(point,
  1956. [window->ns.object convertRectToScreen:[window->ns.view frame]], NO);
  1957. }
  1958. int _glfwPlatformFramebufferTransparent(_GLFWwindow* window)
  1959. {
  1960. return ![window->ns.object isOpaque] && ![window->ns.view isOpaque];
  1961. }
  1962. void _glfwPlatformSetWindowResizable(_GLFWwindow* window, bool enabled UNUSED)
  1963. {
  1964. [window->ns.object setStyleMask:getStyleMask(window)];
  1965. [window->ns.object makeFirstResponder:window->ns.view];
  1966. }
  1967. void _glfwPlatformSetWindowDecorated(_GLFWwindow* window, bool enabled UNUSED)
  1968. {
  1969. [window->ns.object setStyleMask:getStyleMask(window)];
  1970. [window->ns.object makeFirstResponder:window->ns.view];
  1971. }
  1972. void _glfwPlatformSetWindowFloating(_GLFWwindow* window, bool enabled)
  1973. {
  1974. if (enabled)
  1975. [window->ns.object setLevel:NSFloatingWindowLevel];
  1976. else
  1977. [window->ns.object setLevel:NSNormalWindowLevel];
  1978. }
  1979. void _glfwPlatformSetWindowMousePassthrough(_GLFWwindow* window, bool enabled)
  1980. {
  1981. [window->ns.object setIgnoresMouseEvents:enabled];
  1982. }
  1983. float _glfwPlatformGetWindowOpacity(_GLFWwindow* window)
  1984. {
  1985. return (float) [window->ns.object alphaValue];
  1986. }
  1987. void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity)
  1988. {
  1989. [window->ns.object setAlphaValue:opacity];
  1990. }
  1991. void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window UNUSED, bool enabled UNUSED)
  1992. {
  1993. _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
  1994. "Cocoa: Raw mouse motion not yet implemented");
  1995. }
  1996. bool _glfwPlatformRawMouseMotionSupported(void)
  1997. {
  1998. return false;
  1999. }
  2000. void _glfwPlatformGetCursorPos(_GLFWwindow* window, double* xpos, double* ypos)
  2001. {
  2002. const NSRect contentRect = [window->ns.view frame];
  2003. // NOTE: The returned location uses base 0,1 not 0,0
  2004. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  2005. if (xpos)
  2006. *xpos = pos.x;
  2007. if (ypos)
  2008. *ypos = contentRect.size.height - pos.y;
  2009. }
  2010. void _glfwPlatformSetCursorPos(_GLFWwindow* window, double x, double y)
  2011. {
  2012. updateCursorImage(window);
  2013. const NSRect contentRect = [window->ns.view frame];
  2014. // NOTE: The returned location uses base 0,1 not 0,0
  2015. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  2016. window->ns.cursorWarpDeltaX += x - pos.x;
  2017. window->ns.cursorWarpDeltaY += y - contentRect.size.height + pos.y;
  2018. if (window->monitor)
  2019. {
  2020. CGDisplayMoveCursorToPoint(window->monitor->ns.displayID,
  2021. CGPointMake(x, y));
  2022. }
  2023. else
  2024. {
  2025. const NSRect localRect = NSMakeRect(x, contentRect.size.height - y - 1, 0, 0);
  2026. const NSRect globalRect = [window->ns.object convertRectToScreen:localRect];
  2027. const NSPoint globalPoint = globalRect.origin;
  2028. CGWarpMouseCursorPosition(CGPointMake(globalPoint.x,
  2029. _glfwTransformYNS(globalPoint.y)));
  2030. }
  2031. }
  2032. void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode UNUSED)
  2033. {
  2034. if (_glfwPlatformWindowFocused(window))
  2035. updateCursorMode(window);
  2036. }
  2037. const char* _glfwPlatformGetNativeKeyName(int keycode)
  2038. {
  2039. UInt32 deadKeyState = 0;
  2040. UniChar characters[8];
  2041. UniCharCount characterCount = 0;
  2042. if (UCKeyTranslate([(NSData*) _glfw.ns.unicodeData bytes],
  2043. keycode,
  2044. kUCKeyActionDisplay,
  2045. 0,
  2046. LMGetKbdType(),
  2047. kUCKeyTranslateNoDeadKeysBit,
  2048. &deadKeyState,
  2049. sizeof(characters) / sizeof(characters[0]),
  2050. &characterCount,
  2051. characters) != noErr)
  2052. {
  2053. return NULL;
  2054. }
  2055. if (!characterCount)
  2056. return NULL;
  2057. convert_utf16_to_utf8(characters, characterCount, _glfw.ns.keyName, sizeof(_glfw.ns.keyName));
  2058. return _glfw.ns.keyName;
  2059. }
  2060. int _glfwPlatformGetNativeKeyForKey(uint32_t glfw_key)
  2061. {
  2062. if (GLFW_FKEY_FIRST <= glfw_key && glfw_key <= GLFW_FKEY_LAST) { // {{{
  2063. switch(glfw_key) {
  2064. /* start functional to macu (auto generated by gen-key-constants.py do not edit) */
  2065. case GLFW_FKEY_ENTER: return NSCarriageReturnCharacter;
  2066. case GLFW_FKEY_TAB: return NSTabCharacter;
  2067. case GLFW_FKEY_BACKSPACE: return NSBackspaceCharacter;
  2068. case GLFW_FKEY_INSERT: return NSInsertFunctionKey;
  2069. case GLFW_FKEY_DELETE: return NSDeleteFunctionKey;
  2070. case GLFW_FKEY_LEFT: return NSLeftArrowFunctionKey;
  2071. case GLFW_FKEY_RIGHT: return NSRightArrowFunctionKey;
  2072. case GLFW_FKEY_UP: return NSUpArrowFunctionKey;
  2073. case GLFW_FKEY_DOWN: return NSDownArrowFunctionKey;
  2074. case GLFW_FKEY_PAGE_UP: return NSPageUpFunctionKey;
  2075. case GLFW_FKEY_PAGE_DOWN: return NSPageDownFunctionKey;
  2076. case GLFW_FKEY_HOME: return NSHomeFunctionKey;
  2077. case GLFW_FKEY_END: return NSEndFunctionKey;
  2078. case GLFW_FKEY_SCROLL_LOCK: return NSScrollLockFunctionKey;
  2079. case GLFW_FKEY_NUM_LOCK: return NSClearLineFunctionKey;
  2080. case GLFW_FKEY_PRINT_SCREEN: return NSPrintScreenFunctionKey;
  2081. case GLFW_FKEY_PAUSE: return NSPauseFunctionKey;
  2082. case GLFW_FKEY_MENU: return NSMenuFunctionKey;
  2083. case GLFW_FKEY_F1: return NSF1FunctionKey;
  2084. case GLFW_FKEY_F2: return NSF2FunctionKey;
  2085. case GLFW_FKEY_F3: return NSF3FunctionKey;
  2086. case GLFW_FKEY_F4: return NSF4FunctionKey;
  2087. case GLFW_FKEY_F5: return NSF5FunctionKey;
  2088. case GLFW_FKEY_F6: return NSF6FunctionKey;
  2089. case GLFW_FKEY_F7: return NSF7FunctionKey;
  2090. case GLFW_FKEY_F8: return NSF8FunctionKey;
  2091. case GLFW_FKEY_F9: return NSF9FunctionKey;
  2092. case GLFW_FKEY_F10: return NSF10FunctionKey;
  2093. case GLFW_FKEY_F11: return NSF11FunctionKey;
  2094. case GLFW_FKEY_F12: return NSF12FunctionKey;
  2095. case GLFW_FKEY_F13: return NSF13FunctionKey;
  2096. case GLFW_FKEY_F14: return NSF14FunctionKey;
  2097. case GLFW_FKEY_F15: return NSF15FunctionKey;
  2098. case GLFW_FKEY_F16: return NSF16FunctionKey;
  2099. case GLFW_FKEY_F17: return NSF17FunctionKey;
  2100. case GLFW_FKEY_F18: return NSF18FunctionKey;
  2101. case GLFW_FKEY_F19: return NSF19FunctionKey;
  2102. case GLFW_FKEY_F20: return NSF20FunctionKey;
  2103. case GLFW_FKEY_F21: return NSF21FunctionKey;
  2104. case GLFW_FKEY_F22: return NSF22FunctionKey;
  2105. case GLFW_FKEY_F23: return NSF23FunctionKey;
  2106. case GLFW_FKEY_F24: return NSF24FunctionKey;
  2107. case GLFW_FKEY_F25: return NSF25FunctionKey;
  2108. case GLFW_FKEY_F26: return NSF26FunctionKey;
  2109. case GLFW_FKEY_F27: return NSF27FunctionKey;
  2110. case GLFW_FKEY_F28: return NSF28FunctionKey;
  2111. case GLFW_FKEY_F29: return NSF29FunctionKey;
  2112. case GLFW_FKEY_F30: return NSF30FunctionKey;
  2113. case GLFW_FKEY_F31: return NSF31FunctionKey;
  2114. case GLFW_FKEY_F32: return NSF32FunctionKey;
  2115. case GLFW_FKEY_F33: return NSF33FunctionKey;
  2116. case GLFW_FKEY_F34: return NSF34FunctionKey;
  2117. case GLFW_FKEY_F35: return NSF35FunctionKey;
  2118. case GLFW_FKEY_KP_ENTER: return NSEnterCharacter;
  2119. /* end functional to macu */
  2120. default:
  2121. return 0;
  2122. }
  2123. } // }}}
  2124. if (!is_pua_char(glfw_key)) return glfw_key;
  2125. return 0;
  2126. }
  2127. int _glfwPlatformCreateCursor(_GLFWcursor* cursor,
  2128. const GLFWimage* image,
  2129. int xhot, int yhot, int count)
  2130. {
  2131. NSImage* native;
  2132. NSBitmapImageRep* rep;
  2133. native = [[NSImage alloc] initWithSize:NSMakeSize(image->width, image->height)];
  2134. if (native == nil)
  2135. return false;
  2136. for (int i = 0; i < count; i++) {
  2137. const GLFWimage *src = image + i;
  2138. rep = [[NSBitmapImageRep alloc]
  2139. initWithBitmapDataPlanes:NULL
  2140. pixelsWide:src->width
  2141. pixelsHigh:src->height
  2142. bitsPerSample:8
  2143. samplesPerPixel:4
  2144. hasAlpha:YES
  2145. isPlanar:NO
  2146. colorSpaceName:NSCalibratedRGBColorSpace
  2147. bitmapFormat:NSBitmapFormatAlphaNonpremultiplied
  2148. bytesPerRow:src->width * 4
  2149. bitsPerPixel:32];
  2150. if (rep == nil) {
  2151. [native release];
  2152. return false;
  2153. }
  2154. memcpy([rep bitmapData], src->pixels, src->width * src->height * 4);
  2155. [native addRepresentation:rep];
  2156. [rep release];
  2157. }
  2158. cursor->ns.object = [[NSCursor alloc] initWithImage:native
  2159. hotSpot:NSMakePoint(xhot, yhot)];
  2160. [native release];
  2161. if (cursor->ns.object == nil)
  2162. return false;
  2163. return true;
  2164. }
  2165. static NSCursor*
  2166. load_hidden_system_cursor(NSString *name, SEL fallback) {
  2167. // this implementation comes from SDL_cocoamouse.m
  2168. NSString *cursorPath = [@"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors" stringByAppendingPathComponent:name];
  2169. NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:[cursorPath stringByAppendingPathComponent:@"info.plist"]];
  2170. /* we can't do animation atm. :/ */
  2171. const int frames = (int)[[info valueForKey:@"frames"] integerValue];
  2172. NSCursor *cursor;
  2173. NSImage *image = [[NSImage alloc] initWithContentsOfFile:[cursorPath stringByAppendingPathComponent:@"cursor.pdf"]];
  2174. if ((image == nil) || (image.isValid == NO)) {
  2175. return [NSCursor performSelector:fallback];
  2176. }
  2177. if (frames > 1) {
  2178. const NSCompositingOperation operation = NSCompositingOperationCopy;
  2179. const NSSize cropped_size = NSMakeSize(image.size.width, (int)(image.size.height / frames));
  2180. NSImage *cropped = [[NSImage alloc] initWithSize:cropped_size];
  2181. if (cropped == nil) {
  2182. return [NSCursor performSelector:fallback];
  2183. }
  2184. [cropped lockFocus];
  2185. {
  2186. const NSRect cropped_rect = NSMakeRect(0, 0, cropped_size.width, cropped_size.height);
  2187. [image drawInRect:cropped_rect fromRect:cropped_rect operation:operation fraction:1];
  2188. }
  2189. [cropped unlockFocus];
  2190. image = cropped;
  2191. }
  2192. cursor = [[NSCursor alloc] initWithImage:image hotSpot:NSMakePoint([[info valueForKey:@"hotx"] doubleValue], [[info valueForKey:@"hoty"] doubleValue])];
  2193. return cursor;
  2194. }
  2195. int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, GLFWCursorShape shape) {
  2196. #define C(name, val) case name: cursor->ns.object = [NSCursor val]; break;
  2197. #define U(name, val) case name: cursor->ns.object = [NSCursor performSelector:@selector(val)]; break;
  2198. #define S(name, val, fallback) case name: cursor->ns.object = load_hidden_system_cursor(@#val, @selector(val)); break;
  2199. switch(shape) {
  2200. /* start glfw to cocoa (auto generated by gen-key-constants.py do not edit) */
  2201. C(GLFW_DEFAULT_CURSOR, arrowCursor);
  2202. C(GLFW_TEXT_CURSOR, IBeamCursor);
  2203. C(GLFW_POINTER_CURSOR, pointingHandCursor);
  2204. S(GLFW_HELP_CURSOR, help, arrowCursor);
  2205. S(GLFW_WAIT_CURSOR, busybutclickable, arrowCursor);
  2206. S(GLFW_PROGRESS_CURSOR, busybutclickable, arrowCursor);
  2207. C(GLFW_CROSSHAIR_CURSOR, crosshairCursor);
  2208. S(GLFW_CELL_CURSOR, cell, crosshairCursor);
  2209. C(GLFW_VERTICAL_TEXT_CURSOR, IBeamCursorForVerticalLayout);
  2210. S(GLFW_MOVE_CURSOR, move, openHandCursor);
  2211. C(GLFW_E_RESIZE_CURSOR, resizeRightCursor);
  2212. S(GLFW_NE_RESIZE_CURSOR, resizenortheast, _windowResizeNorthEastSouthWestCursor);
  2213. S(GLFW_NW_RESIZE_CURSOR, resizenorthwest, _windowResizeNorthWestSouthEastCursor);
  2214. C(GLFW_N_RESIZE_CURSOR, resizeUpCursor);
  2215. S(GLFW_SE_RESIZE_CURSOR, resizesoutheast, _windowResizeNorthWestSouthEastCursor);
  2216. S(GLFW_SW_RESIZE_CURSOR, resizesouthwest, _windowResizeNorthEastSouthWestCursor);
  2217. C(GLFW_S_RESIZE_CURSOR, resizeDownCursor);
  2218. C(GLFW_W_RESIZE_CURSOR, resizeLeftCursor);
  2219. C(GLFW_EW_RESIZE_CURSOR, resizeLeftRightCursor);
  2220. C(GLFW_NS_RESIZE_CURSOR, resizeUpDownCursor);
  2221. U(GLFW_NESW_RESIZE_CURSOR, _windowResizeNorthEastSouthWestCursor);
  2222. U(GLFW_NWSE_RESIZE_CURSOR, _windowResizeNorthWestSouthEastCursor);
  2223. S(GLFW_ZOOM_IN_CURSOR, zoomin, arrowCursor);
  2224. S(GLFW_ZOOM_OUT_CURSOR, zoomout, arrowCursor);
  2225. C(GLFW_ALIAS_CURSOR, dragLinkCursor);
  2226. C(GLFW_COPY_CURSOR, dragCopyCursor);
  2227. C(GLFW_NOT_ALLOWED_CURSOR, operationNotAllowedCursor);
  2228. C(GLFW_NO_DROP_CURSOR, operationNotAllowedCursor);
  2229. C(GLFW_GRAB_CURSOR, openHandCursor);
  2230. C(GLFW_GRABBING_CURSOR, closedHandCursor);
  2231. /* end glfw to cocoa */
  2232. case GLFW_INVALID_CURSOR:
  2233. return false;
  2234. }
  2235. #undef C
  2236. #undef U
  2237. #undef S
  2238. if (!cursor->ns.object)
  2239. {
  2240. _glfwInputError(GLFW_PLATFORM_ERROR,
  2241. "Cocoa: Failed to retrieve standard cursor");
  2242. return false;
  2243. }
  2244. [cursor->ns.object retain];
  2245. return true;
  2246. }
  2247. void _glfwPlatformDestroyCursor(_GLFWcursor* cursor)
  2248. {
  2249. if (cursor->ns.object)
  2250. [(NSCursor*) cursor->ns.object release];
  2251. }
  2252. void _glfwPlatformSetCursor(_GLFWwindow* window, _GLFWcursor* cursor UNUSED)
  2253. {
  2254. if (cursorInContentArea(window))
  2255. updateCursorImage(window);
  2256. }
  2257. bool _glfwPlatformIsFullscreen(_GLFWwindow* w, unsigned int flags) {
  2258. NSWindow *window = w->ns.object;
  2259. bool traditional = !(flags & 1);
  2260. if (traditional) { if(@available(macOS 10.15.7, *)) return w->ns.in_traditional_fullscreen; }
  2261. NSWindowStyleMask sm = [window styleMask];
  2262. return sm & NSWindowStyleMaskFullScreen;
  2263. }
  2264. static void
  2265. make_window_fullscreen_after_show(unsigned long long timer_id, void* data) {
  2266. (void)timer_id;
  2267. unsigned long long window_id = (uintptr_t)data;
  2268. for (_GLFWwindow *w = _glfw.windowListHead; w; w = w->next) {
  2269. if (w->id == window_id) {
  2270. NSWindow *window = w->ns.object;
  2271. [window toggleFullScreen: nil];
  2272. update_titlebar_button_visibility_after_fullscreen_transition(w, false, true);
  2273. break;
  2274. }
  2275. }
  2276. }
  2277. bool _glfwPlatformToggleFullscreen(_GLFWwindow* w, unsigned int flags) {
  2278. NSWindow *window = w->ns.object;
  2279. bool made_fullscreen = true;
  2280. bool traditional = !(flags & 1);
  2281. NSWindowStyleMask sm = [window styleMask];
  2282. if (traditional) {
  2283. if (@available(macOS 10.15.7, *)) {
  2284. // As of Big Turd NSWindowStyleMaskFullScreen is no longer usable
  2285. // Also no longer compatible after a minor release of macOS 10.15.7
  2286. if (!w->ns.in_traditional_fullscreen) {
  2287. w->ns.pre_full_screen_style_mask = sm;
  2288. [window setStyleMask: NSWindowStyleMaskBorderless];
  2289. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];
  2290. [window setFrame:[window.screen frame] display:YES];
  2291. w->ns.in_traditional_fullscreen = true;
  2292. } else {
  2293. made_fullscreen = false;
  2294. [window setStyleMask: w->ns.pre_full_screen_style_mask];
  2295. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationDefault];
  2296. w->ns.in_traditional_fullscreen = false;
  2297. }
  2298. } else {
  2299. bool in_fullscreen = sm & NSWindowStyleMaskFullScreen;
  2300. if (!(in_fullscreen)) {
  2301. sm |= NSWindowStyleMaskBorderless | NSWindowStyleMaskFullScreen;
  2302. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];
  2303. } else {
  2304. made_fullscreen = false;
  2305. sm &= ~(NSWindowStyleMaskBorderless | NSWindowStyleMaskFullScreen);
  2306. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationDefault];
  2307. }
  2308. [window setStyleMask: sm];
  2309. }
  2310. // Changing the style mask causes the first responder to be cleared
  2311. [window makeFirstResponder:w->ns.view];
  2312. // If the dock and menubar are hidden going from maximized to fullscreen doesn't change the window size
  2313. // and macOS forgets to trigger windowDidResize, so call it ourselves
  2314. NSNotification *notification = [NSNotification notificationWithName:NSWindowDidResizeNotification object:window];
  2315. [w->ns.delegate performSelector:@selector(windowDidResize:) withObject:notification afterDelay:0];
  2316. } else {
  2317. bool in_fullscreen = sm & NSWindowStyleMaskFullScreen;
  2318. if (!in_fullscreen && !_glfwPlatformWindowVisible(w)) {
  2319. // Bug in Apple's fullscreen implementation causes fullscreen to
  2320. // not work before window is shown (at creation) if another window
  2321. // is already fullscreen. Le sigh. https://github.com/kovidgoyal/kitty/issues/7448
  2322. _glfwPlatformAddTimer(0, false, make_window_fullscreen_after_show, (void*)(uintptr_t)(w->id), NULL);
  2323. return made_fullscreen;
  2324. }
  2325. if (in_fullscreen) made_fullscreen = false;
  2326. [window toggleFullScreen: nil];
  2327. }
  2328. update_titlebar_button_visibility_after_fullscreen_transition(w, traditional, made_fullscreen);
  2329. return made_fullscreen;
  2330. }
  2331. // Clipboard {{{
  2332. #define UTI_ROUNDTRIP_PREFIX @"uti-is-typical-apple-nih."
  2333. static NSString*
  2334. mime_to_uti(const char *mime) {
  2335. if (strcmp(mime, "text/plain") == 0) return NSPasteboardTypeString;
  2336. if (@available(macOS 11.0, *)) {
  2337. UTType *t = [UTType typeWithMIMEType:@(mime)]; // auto-released
  2338. if (t != nil && !t.dynamic) return t.identifier;
  2339. }
  2340. return [NSString stringWithFormat:@"%@%s", UTI_ROUNDTRIP_PREFIX, mime]; // auto-released
  2341. }
  2342. static const char*
  2343. uti_to_mime(NSString *uti) {
  2344. if ([uti isEqualToString:NSPasteboardTypeString]) return "text/plain";
  2345. if ([uti hasPrefix:UTI_ROUNDTRIP_PREFIX]) return [[uti substringFromIndex:[UTI_ROUNDTRIP_PREFIX length]] UTF8String];
  2346. if (@available(macOS 11.0, *)) {
  2347. UTType *t = [UTType typeWithIdentifier:uti]; // auto-released
  2348. if (t.preferredMIMEType != nil) return [t.preferredMIMEType UTF8String];
  2349. }
  2350. return "";
  2351. }
  2352. static void
  2353. list_clipboard_mimetypes(GLFWclipboardwritedatafun write_data, void *object) {
  2354. #define w(x) { if (ok) ok = write_data(object, x, strlen(x)); }
  2355. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2356. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  2357. BOOL has_file_urls = [pasteboard canReadObjectForClasses:@[[NSURL class]] options:options];
  2358. BOOL has_strings = [pasteboard canReadObjectForClasses:@[[NSString class]] options:nil];
  2359. /* NSLog(@"has_file_urls: %d has_strings: %d", has_file_urls, has_strings); */
  2360. bool ok = true;
  2361. if (has_strings) w("text/plain");
  2362. if (has_file_urls) w("text/local-path-list");
  2363. for (NSPasteboardItem * item in pasteboard.pasteboardItems) {
  2364. for (NSPasteboardType type in item.types) {
  2365. /* NSLog(@"%@", type); */
  2366. const char *mime = uti_to_mime(type);
  2367. if (mime && mime[0] && ![@(mime) hasPrefix:@"text/plain"]) {
  2368. /* NSLog(@"ut: %@ mt: %@ tags: %@", ut, ut.preferredMIMEType, ut.tags); */
  2369. w(mime);
  2370. }
  2371. }
  2372. }
  2373. #undef w
  2374. }
  2375. static void
  2376. get_text_plain(GLFWclipboardwritedatafun write_data, void *object) {
  2377. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2378. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  2379. NSArray* objs = [pasteboard readObjectsForClasses:@[[NSURL class], [NSString class]] options:options];
  2380. bool found = false;
  2381. if (objs) {
  2382. const NSUInteger count = [objs count];
  2383. if (count) {
  2384. NSMutableData *path_list = [NSMutableData dataWithCapacity:4096]; // auto-released
  2385. NSMutableData *text_list = [NSMutableData dataWithCapacity:4096]; // auto-released
  2386. for (NSUInteger i = 0; i < count; i++) {
  2387. id obj = objs[i];
  2388. if ([obj isKindOfClass:[NSURL class]]) {
  2389. NSURL *url = (NSURL*)obj;
  2390. if (url.fileURL && url.fileSystemRepresentation) {
  2391. if ([path_list length] > 0) [path_list appendBytes:"\n" length:1];
  2392. [path_list appendBytes:url.fileSystemRepresentation length:strlen(url.fileSystemRepresentation)];
  2393. }
  2394. } else if ([obj isKindOfClass:[NSString class]]) {
  2395. if ([text_list length] > 0) [text_list appendBytes:"\n" length:1];
  2396. [text_list appendData:[obj dataUsingEncoding:NSUTF8StringEncoding]];
  2397. }
  2398. }
  2399. const NSMutableData *text = nil;
  2400. if (path_list.length > 0) text = path_list;
  2401. else if (text_list.length > 0) text = text_list;
  2402. if (text) {
  2403. found = true;
  2404. write_data(object, text.mutableBytes, text.length);
  2405. }
  2406. }
  2407. }
  2408. if (!found) _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to retrieve text/plain from pasteboard");
  2409. }
  2410. void
  2411. _glfwPlatformGetClipboard(GLFWClipboardType clipboard_type, const char* mime_type, GLFWclipboardwritedatafun write_data, void *object) {
  2412. if (clipboard_type != GLFW_CLIPBOARD) return;
  2413. if (mime_type == NULL) {
  2414. list_clipboard_mimetypes(write_data, object);
  2415. return;
  2416. }
  2417. if (strcmp(mime_type, "text/plain") == 0) {
  2418. get_text_plain(write_data, object);
  2419. return;
  2420. }
  2421. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2422. /* NSLog(@"mime: %s uti: %@", mime_type, mime_to_uti(mime_type)); */
  2423. NSPasteboardType t = [pasteboard availableTypeFromArray:@[mime_to_uti(mime_type)]];
  2424. /* NSLog(@"available type: %@", t); */
  2425. if (t != nil) {
  2426. NSData *data = [pasteboard dataForType:t]; // auto-released
  2427. /* NSLog(@"data: %@", data); */
  2428. if (data != nil && data.length > 0) {
  2429. write_data(object, data.bytes, data.length);
  2430. }
  2431. }
  2432. }
  2433. static NSMutableData*
  2434. get_clipboard_data(const _GLFWClipboardData *cd, const char *mime) {
  2435. NSMutableData *ans = [NSMutableData dataWithCapacity:8192];
  2436. if (ans == nil) return nil;
  2437. GLFWDataChunk chunk = cd->get_data(mime, NULL, cd->ctype);
  2438. void *iter = chunk.iter;
  2439. if (!iter) return ans;
  2440. while (true) {
  2441. chunk = cd->get_data(mime, iter, cd->ctype);
  2442. if (!chunk.sz) break;
  2443. [ans appendBytes:chunk.data length:chunk.sz];
  2444. if (chunk.free) chunk.free((void*)chunk.free_data);
  2445. }
  2446. cd->get_data(NULL, iter, cd->ctype);
  2447. return ans;
  2448. }
  2449. void
  2450. _glfwPlatformSetClipboard(GLFWClipboardType t) {
  2451. if (t != GLFW_CLIPBOARD) return;
  2452. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2453. NSMutableArray<NSPasteboardType> *ptypes = [NSMutableArray arrayWithCapacity:_glfw.clipboard.num_mime_types]; // auto-released
  2454. for (size_t i = 0; i < _glfw.clipboard.num_mime_types; i++) {
  2455. [ptypes addObject:mime_to_uti(_glfw.clipboard.mime_types[i])];
  2456. }
  2457. [pasteboard declareTypes:ptypes owner:nil];
  2458. for (size_t i = 0; i < _glfw.clipboard.num_mime_types; i++) {
  2459. NSMutableData *data = get_clipboard_data(&_glfw.clipboard, _glfw.clipboard.mime_types[i]); // auto-released
  2460. /* NSLog(@"putting data: %@ for: %s with UTI: %@", data, _glfw.clipboard.mime_types[i], ptypes[i]); */
  2461. if (data != nil) [pasteboard setData:data forType:ptypes[i]];
  2462. }
  2463. }
  2464. // }}}
  2465. EGLenum _glfwPlatformGetEGLPlatform(EGLint** attribs)
  2466. {
  2467. if (_glfw.egl.ANGLE_platform_angle)
  2468. {
  2469. int type = 0;
  2470. if (_glfw.egl.ANGLE_platform_angle_opengl)
  2471. {
  2472. if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_OPENGL)
  2473. type = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE;
  2474. }
  2475. if (_glfw.egl.ANGLE_platform_angle_metal)
  2476. {
  2477. if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_METAL)
  2478. type = EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE;
  2479. }
  2480. if (type)
  2481. {
  2482. *attribs = calloc(3, sizeof(EGLint));
  2483. (*attribs)[0] = EGL_PLATFORM_ANGLE_TYPE_ANGLE;
  2484. (*attribs)[1] = type;
  2485. (*attribs)[2] = EGL_NONE;
  2486. return EGL_PLATFORM_ANGLE_ANGLE;
  2487. }
  2488. }
  2489. return 0;
  2490. }
  2491. EGLNativeDisplayType _glfwPlatformGetEGLNativeDisplay(void)
  2492. {
  2493. return EGL_DEFAULT_DISPLAY;
  2494. }
  2495. EGLNativeWindowType _glfwPlatformGetEGLNativeWindow(_GLFWwindow* window)
  2496. {
  2497. return window->ns.layer;
  2498. }
  2499. void _glfwPlatformGetRequiredInstanceExtensions(char** extensions)
  2500. {
  2501. if (_glfw.vk.KHR_surface && _glfw.vk.EXT_metal_surface)
  2502. {
  2503. extensions[0] = "VK_KHR_surface";
  2504. extensions[1] = "VK_EXT_metal_surface";
  2505. }
  2506. else if (_glfw.vk.KHR_surface && _glfw.vk.MVK_macos_surface)
  2507. {
  2508. extensions[0] = "VK_KHR_surface";
  2509. extensions[1] = "VK_MVK_macos_surface";
  2510. }
  2511. }
  2512. int _glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance UNUSED,
  2513. VkPhysicalDevice device UNUSED,
  2514. uint32_t queuefamily UNUSED)
  2515. {
  2516. return true;
  2517. }
  2518. VkResult _glfwPlatformCreateWindowSurface(VkInstance instance,
  2519. _GLFWwindow* window,
  2520. const VkAllocationCallbacks* allocator,
  2521. VkSurfaceKHR* surface)
  2522. {
  2523. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101100
  2524. // HACK: Dynamically load Core Animation to avoid adding an extra
  2525. // dependency for the majority who don't use MoltenVK
  2526. NSBundle* bundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/QuartzCore.framework"];
  2527. if (!bundle)
  2528. {
  2529. _glfwInputError(GLFW_PLATFORM_ERROR,
  2530. "Cocoa: Failed to find QuartzCore.framework");
  2531. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2532. }
  2533. // NOTE: Create the layer here as makeBackingLayer should not return nil
  2534. window->ns.layer = [[bundle classNamed:@"CAMetalLayer"] layer];
  2535. if (!window->ns.layer)
  2536. {
  2537. _glfwInputError(GLFW_PLATFORM_ERROR,
  2538. "Cocoa: Failed to create layer for view");
  2539. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2540. }
  2541. if (window->ns.retina)
  2542. [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]];
  2543. [window->ns.view setLayer:window->ns.layer];
  2544. [window->ns.view setWantsLayer:YES];
  2545. VkResult err;
  2546. if (_glfw.vk.EXT_metal_surface)
  2547. {
  2548. VkMetalSurfaceCreateInfoEXT sci;
  2549. PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT;
  2550. vkCreateMetalSurfaceEXT = (PFN_vkCreateMetalSurfaceEXT)
  2551. vkGetInstanceProcAddr(instance, "vkCreateMetalSurfaceEXT");
  2552. if (!vkCreateMetalSurfaceEXT)
  2553. {
  2554. _glfwInputError(GLFW_API_UNAVAILABLE,
  2555. "Cocoa: Vulkan instance missing VK_EXT_metal_surface extension");
  2556. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2557. }
  2558. memset(&sci, 0, sizeof(sci));
  2559. sci.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
  2560. sci.pLayer = window->ns.layer;
  2561. err = vkCreateMetalSurfaceEXT(instance, &sci, allocator, surface);
  2562. }
  2563. else
  2564. {
  2565. VkMacOSSurfaceCreateInfoMVK sci;
  2566. PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK;
  2567. vkCreateMacOSSurfaceMVK = (PFN_vkCreateMacOSSurfaceMVK)
  2568. vkGetInstanceProcAddr(instance, "vkCreateMacOSSurfaceMVK");
  2569. if (!vkCreateMacOSSurfaceMVK)
  2570. {
  2571. _glfwInputError(GLFW_API_UNAVAILABLE,
  2572. "Cocoa: Vulkan instance missing VK_MVK_macos_surface extension");
  2573. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2574. }
  2575. memset(&sci, 0, sizeof(sci));
  2576. sci.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
  2577. sci.pView = window->ns.view;
  2578. err = vkCreateMacOSSurfaceMVK(instance, &sci, allocator, surface);
  2579. }
  2580. if (err)
  2581. {
  2582. _glfwInputError(GLFW_PLATFORM_ERROR,
  2583. "Cocoa: Failed to create Vulkan surface: %s",
  2584. _glfwGetVulkanResultString(err));
  2585. }
  2586. return err;
  2587. #else
  2588. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2589. #endif
  2590. }
  2591. int
  2592. _glfwPlatformSetWindowBlur(_GLFWwindow *window, int radius) {
  2593. int orig = window->ns.blur_radius;
  2594. if (radius > -1 && radius != window->ns.blur_radius) {
  2595. extern OSStatus CGSSetWindowBackgroundBlurRadius(void* connection, NSInteger windowNumber, int radius);
  2596. extern void* CGSDefaultConnectionForThread(void);
  2597. CGSSetWindowBackgroundBlurRadius(CGSDefaultConnectionForThread(), [window->ns.object windowNumber], radius);
  2598. window->ns.blur_radius = radius;
  2599. }
  2600. return orig;
  2601. }
  2602. //////////////////////////////////////////////////////////////////////////
  2603. ////// GLFW native API //////
  2604. //////////////////////////////////////////////////////////////////////////
  2605. GLFWAPI id glfwGetCocoaWindow(GLFWwindow* handle)
  2606. {
  2607. _GLFWwindow* window = (_GLFWwindow*) handle;
  2608. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2609. return window->ns.object;
  2610. }
  2611. GLFWAPI GLFWcocoatextinputfilterfun glfwSetCocoaTextInputFilter(GLFWwindow *handle, GLFWcocoatextinputfilterfun callback) {
  2612. _GLFWwindow* window = (_GLFWwindow*) handle;
  2613. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2614. GLFWcocoatextinputfilterfun previous = window->ns.textInputFilterCallback;
  2615. window->ns.textInputFilterCallback = callback;
  2616. return previous;
  2617. }
  2618. GLFWAPI GLFWhandleurlopen glfwSetCocoaURLOpenCallback(GLFWhandleurlopen callback) {
  2619. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2620. GLFWhandleurlopen prev = _glfw.ns.url_open_callback;
  2621. _glfw.ns.url_open_callback = callback;
  2622. return prev;
  2623. }
  2624. GLFWAPI GLFWcocoatogglefullscreenfun glfwSetCocoaToggleFullscreenIntercept(GLFWwindow *handle, GLFWcocoatogglefullscreenfun callback) {
  2625. _GLFWwindow* window = (_GLFWwindow*) handle;
  2626. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2627. GLFWcocoatogglefullscreenfun previous = window->ns.toggleFullscreenCallback;
  2628. window->ns.toggleFullscreenCallback = callback;
  2629. return previous;
  2630. }
  2631. GLFWAPI void glfwCocoaRequestRenderFrame(GLFWwindow *w, GLFWcocoarenderframefun callback) {
  2632. requestRenderFrame((_GLFWwindow*)w, callback);
  2633. }
  2634. GLFWAPI GLFWcocoarenderframefun glfwCocoaSetWindowResizeCallback(GLFWwindow *w, GLFWcocoarenderframefun cb) {
  2635. _GLFWwindow* window = (_GLFWwindow*)w;
  2636. GLFWcocoarenderframefun current = window->ns.resizeCallback;
  2637. window->ns.resizeCallback = cb;
  2638. return current;
  2639. }
  2640. GLFWAPI void glfwCocoaSetWindowChrome(GLFWwindow *w, unsigned int color, bool use_system_color, unsigned int system_color, int background_blur, unsigned int hide_window_decorations, bool show_text_in_titlebar, int color_space, float background_opacity, bool resizable) { @autoreleasepool {
  2641. _GLFWwindow* window = (_GLFWwindow*)w;
  2642. const bool is_transparent = ![window->ns.object isOpaque];
  2643. if (!is_transparent) { background_opacity = 1.0; background_blur = 0; }
  2644. NSColor *background = nil;
  2645. NSAppearance *appearance = nil;
  2646. bool titlebar_transparent = false;
  2647. const NSWindowStyleMask current_style_mask = [window->ns.object styleMask];
  2648. const bool in_fullscreen = ((current_style_mask & NSWindowStyleMaskFullScreen) != 0) || window->ns.in_traditional_fullscreen;
  2649. NSAppearance *light_appearance = is_transparent ? [NSAppearance appearanceNamed:NSAppearanceNameVibrantLight] : [NSAppearance appearanceNamed:NSAppearanceNameAqua];
  2650. NSAppearance *dark_appearance = is_transparent ? [NSAppearance appearanceNamed:NSAppearanceNameVibrantDark] : [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
  2651. if (use_system_color || background_opacity < 1.0) {
  2652. if (is_transparent) {
  2653. // prevent blurring of shadows at window corners with desktop background by setting a low alpha background
  2654. background = background_blur > 0 ? [NSColor colorWithWhite: 0 alpha: 0.001f] : [NSColor clearColor];
  2655. } else background = [NSColor windowBackgroundColor];
  2656. switch (system_color) {
  2657. case 1:
  2658. appearance = light_appearance; break;
  2659. case 2:
  2660. appearance = dark_appearance; break;
  2661. }
  2662. } else {
  2663. // set a background color and make the title bar transparent so the background color is visible
  2664. double red = ((color >> 16) & 0xFF) / 255.0;
  2665. double green = ((color >> 8) & 0xFF) / 255.0;
  2666. double blue = (color & 0xFF) / 255.0;
  2667. double luma = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
  2668. background = [NSColor colorWithSRGBRed:red green:green blue:blue alpha:1.f];
  2669. appearance = luma < 0.5 ? dark_appearance : light_appearance;
  2670. titlebar_transparent = true;
  2671. }
  2672. [window->ns.object setBackgroundColor:background];
  2673. [window->ns.object setAppearance:appearance];
  2674. _glfwPlatformSetWindowBlur(window, background_blur);
  2675. bool has_shadow = false;
  2676. const char *decorations_desc = "full";
  2677. window->ns.titlebar_hidden = false;
  2678. switch (hide_window_decorations) {
  2679. case 1:
  2680. decorations_desc = "none";
  2681. window->decorated = false;
  2682. break;
  2683. case 2:
  2684. decorations_desc = "no-titlebar";
  2685. window->decorated = true;
  2686. has_shadow = true;
  2687. titlebar_transparent = true;
  2688. window->ns.titlebar_hidden = true;
  2689. show_text_in_titlebar = false;
  2690. break;
  2691. case 4:
  2692. decorations_desc = "no-titlebar-and-no-corners";
  2693. window->decorated = false;
  2694. has_shadow = true;
  2695. break;
  2696. default:
  2697. window->decorated = true;
  2698. has_shadow = true;
  2699. break;
  2700. }
  2701. // shadow causes burn-in/ghosting because cocoa doesnt invalidate it on OS window resize/minimize/restore.
  2702. // https://github.com/kovidgoyal/kitty/issues/6439
  2703. if (is_transparent) has_shadow = false;
  2704. bool hide_titlebar_buttons = !in_fullscreen && window->ns.titlebar_hidden;
  2705. [window->ns.object setTitlebarAppearsTransparent:titlebar_transparent];
  2706. [window->ns.object setHasShadow:has_shadow];
  2707. [window->ns.object setTitleVisibility:(show_text_in_titlebar) ? NSWindowTitleVisible : NSWindowTitleHidden];
  2708. NSColorSpace *cs = nil;
  2709. switch (color_space) {
  2710. case SRGB_COLORSPACE: cs = [NSColorSpace sRGBColorSpace]; break;
  2711. case DISPLAY_P3_COLORSPACE: cs = [NSColorSpace displayP3ColorSpace]; break;
  2712. case DEFAULT_COLORSPACE: cs = nil; break; // using deviceRGBColorSpace causes a hang when transitioning to fullscreen
  2713. }
  2714. window->resizable = resizable;
  2715. debug(
  2716. "Window Chrome state:\n\tbackground: %s\n\tappearance: %s color_space: %s\n\t"
  2717. "blur: %d has_shadow: %d resizable: %d decorations: %s (%d)\n\t"
  2718. "titlebar: transparent: %d title_visibility: %d hidden: %d buttons_hidden: %d"
  2719. "\n",
  2720. background ? [background.description UTF8String] : "<nil>",
  2721. appearance ? [appearance.name UTF8String] : "<nil>",
  2722. cs ? (cs.localizedName ? [cs.localizedName UTF8String] : [cs.description UTF8String]) : "<nil>",
  2723. background_blur, has_shadow, resizable, decorations_desc, window->decorated, titlebar_transparent,
  2724. show_text_in_titlebar, window->ns.titlebar_hidden, hide_titlebar_buttons
  2725. );
  2726. [window->ns.object setColorSpace:cs];
  2727. [[window->ns.object standardWindowButton: NSWindowCloseButton] setHidden:hide_titlebar_buttons];
  2728. [[window->ns.object standardWindowButton: NSWindowMiniaturizeButton] setHidden:hide_titlebar_buttons];
  2729. [[window->ns.object standardWindowButton: NSWindowZoomButton] setHidden:hide_titlebar_buttons];
  2730. // Apple throws a hissy fit if one attempts to clear the value of NSWindowStyleMaskFullScreen outside of a full screen transition
  2731. // event. See https://github.com/kovidgoyal/kitty/issues/7106
  2732. NSWindowStyleMask fsmask = current_style_mask & NSWindowStyleMaskFullScreen;
  2733. window->ns.pre_full_screen_style_mask = getStyleMask(window);
  2734. if (in_fullscreen && window->ns.in_traditional_fullscreen) {
  2735. [window->ns.object setStyleMask:NSWindowStyleMaskBorderless];
  2736. } else {
  2737. [window->ns.object setStyleMask:window->ns.pre_full_screen_style_mask | fsmask];
  2738. }
  2739. // HACK: Changing the style mask can cause the first responder to be cleared
  2740. [window->ns.object makeFirstResponder:window->ns.view];
  2741. }}
  2742. GLFWAPI GLFWColorScheme glfwGetCurrentSystemColorTheme(bool query_if_unintialized) {
  2743. (void)query_if_unintialized;
  2744. int theme_type = 0;
  2745. NSAppearance *changedAppearance = NSApp.effectiveAppearance;
  2746. NSAppearanceName newAppearance = [changedAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
  2747. if([newAppearance isEqualToString:NSAppearanceNameDarkAqua]){
  2748. theme_type = 1;
  2749. } else {
  2750. theme_type = 2;
  2751. }
  2752. return theme_type;
  2753. }
  2754. GLFWAPI uint32_t
  2755. glfwGetCocoaKeyEquivalent(uint32_t glfw_key, int glfw_mods, int *cocoa_mods) {
  2756. *cocoa_mods = 0;
  2757. if (glfw_mods & GLFW_MOD_SHIFT)
  2758. *cocoa_mods |= NSEventModifierFlagShift;
  2759. if (glfw_mods & GLFW_MOD_CONTROL)
  2760. *cocoa_mods |= NSEventModifierFlagControl;
  2761. if (glfw_mods & GLFW_MOD_ALT)
  2762. *cocoa_mods |= NSEventModifierFlagOption;
  2763. if (glfw_mods & GLFW_MOD_SUPER)
  2764. *cocoa_mods |= NSEventModifierFlagCommand;
  2765. if (glfw_mods & GLFW_MOD_CAPS_LOCK)
  2766. *cocoa_mods |= NSEventModifierFlagCapsLock;
  2767. return _glfwPlatformGetNativeKeyForKey(glfw_key);
  2768. }
  2769. //////////////////////////////////////////////////////////////////////////
  2770. ////// GLFW internal API //////
  2771. //////////////////////////////////////////////////////////////////////////
  2772. // Transforms a y-coordinate between the CG display and NS screen spaces
  2773. //
  2774. float _glfwTransformYNS(float y)
  2775. {
  2776. return CGDisplayBounds(CGMainDisplayID()).size.height - y - 1;
  2777. }
  2778. void _glfwCocoaPostEmptyEvent(void) {
  2779. NSEvent* event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
  2780. location:NSMakePoint(0, 0)
  2781. modifierFlags:0
  2782. timestamp:0
  2783. windowNumber:0
  2784. context:nil
  2785. subtype:0
  2786. data1:0
  2787. data2:0];
  2788. [NSApp postEvent:event atStart:YES];
  2789. }