cocoa_window.m 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148
  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. }
  830. - (void)mouseEntered:(NSEvent *)event
  831. {
  832. (void)event;
  833. if (!window) return;
  834. _glfwInputCursorEnter(window, true);
  835. }
  836. - (void)viewDidChangeEffectiveAppearance
  837. {
  838. static GLFWColorScheme appearance = GLFW_COLOR_SCHEME_NO_PREFERENCE;
  839. GLFWColorScheme new_appearance = glfwGetCurrentSystemColorTheme(true);
  840. if (new_appearance != appearance) {
  841. appearance = new_appearance;
  842. _glfwInputColorScheme(appearance, false);
  843. }
  844. }
  845. - (void)viewDidChangeBackingProperties
  846. {
  847. if (!window) return;
  848. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  849. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  850. if (fbRect.size.width != window->ns.fbWidth ||
  851. fbRect.size.height != window->ns.fbHeight)
  852. {
  853. window->ns.fbWidth = (int)fbRect.size.width;
  854. window->ns.fbHeight = (int)fbRect.size.height;
  855. _glfwInputFramebufferSize(window, (int)fbRect.size.width, (int)fbRect.size.height);
  856. }
  857. const float xscale = fbRect.size.width / contentRect.size.width;
  858. const float yscale = fbRect.size.height / contentRect.size.height;
  859. if (xscale != window->ns.xscale || yscale != window->ns.yscale)
  860. {
  861. window->ns.xscale = xscale;
  862. window->ns.yscale = yscale;
  863. _glfwInputWindowContentScale(window, xscale, yscale);
  864. if (window->ns.retina && window->ns.layer)
  865. [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]];
  866. }
  867. }
  868. - (void)drawRect:(NSRect)rect
  869. {
  870. (void)rect;
  871. if (!window) return;
  872. _glfwInputWindowDamage(window);
  873. }
  874. - (void)updateTrackingAreas
  875. {
  876. if (window && [window->ns.object areCursorRectsEnabled])
  877. [window->ns.object disableCursorRects];
  878. if (trackingArea != nil)
  879. {
  880. [self removeTrackingArea:trackingArea];
  881. [trackingArea release];
  882. }
  883. const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
  884. NSTrackingActiveAlways |
  885. NSTrackingEnabledDuringMouseDrag |
  886. NSTrackingCursorUpdate |
  887. NSTrackingInVisibleRect |
  888. NSTrackingAssumeInside;
  889. trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
  890. options:options
  891. owner:self
  892. userInfo:nil];
  893. [self addTrackingArea:trackingArea];
  894. [super updateTrackingAreas];
  895. }
  896. - (NSTextInputContext *)inputContext
  897. {
  898. return input_context;
  899. }
  900. static UInt32
  901. convert_cocoa_to_carbon_modifiers(NSUInteger flags) {
  902. UInt32 mods = 0;
  903. if (flags & NSEventModifierFlagShift)
  904. mods |= shiftKey;
  905. if (flags & NSEventModifierFlagControl)
  906. mods |= controlKey;
  907. if (flags & NSEventModifierFlagOption)
  908. mods |= optionKey;
  909. if (flags & NSEventModifierFlagCommand)
  910. mods |= cmdKey;
  911. if (flags & NSEventModifierFlagCapsLock)
  912. mods |= alphaLock;
  913. return (mods >> 8) & 0xFF;
  914. }
  915. static void
  916. convert_utf16_to_utf8(UniChar *src, UniCharCount src_length, char *dest, size_t dest_sz) {
  917. CFStringRef string = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
  918. src,
  919. src_length,
  920. kCFAllocatorNull);
  921. CFStringGetCString(string,
  922. dest,
  923. dest_sz,
  924. kCFStringEncodingUTF8);
  925. CFRelease(string);
  926. }
  927. static bool
  928. alternate_key_is_ok(uint32_t key, uint32_t akey) {
  929. return akey > 31 && akey != key && !is_pua_char(akey);
  930. }
  931. static void
  932. add_alternate_keys(GLFWkeyevent *ev, NSEvent *event) {
  933. ev->alternate_key = translateKey(ev->native_key, false);
  934. if (!alternate_key_is_ok(ev->key, ev->alternate_key)) ev->alternate_key = 0;
  935. if (ev->mods & GLFW_MOD_SHIFT) {
  936. NSString *ci = [event charactersIgnoringModifiers];
  937. if (ci) {
  938. unsigned sz = [ci length];
  939. if (sz > 0) {
  940. UniChar buf[2] = {0};
  941. buf[0] = [ci characterAtIndex:0];
  942. if (sz > 1) buf[1] = [ci characterAtIndex:1];
  943. ev->shifted_key = get_first_codepoint(buf, sz);
  944. }
  945. }
  946. if (!alternate_key_is_ok(ev->key, ev->shifted_key)) ev->shifted_key = 0;
  947. }
  948. }
  949. static bool
  950. is_ascii_control_char(char x) {
  951. return x == 0 || (1 <= x && x <= 31) || x == 127;
  952. }
  953. - (void)keyDown:(NSEvent *)event
  954. {
  955. #define CLEAR_PRE_EDIT_TEXT glfw_keyevent.text = NULL; glfw_keyevent.ime_state = GLFW_IME_PREEDIT_CHANGED; _glfwInputKeyboard(window, &glfw_keyevent);
  956. #define UPDATE_PRE_EDIT_TEXT glfw_keyevent.text = [[markedText string] UTF8String]; glfw_keyevent.ime_state = GLFW_IME_PREEDIT_CHANGED; _glfwInputKeyboard(window, &glfw_keyevent);
  957. const bool previous_has_marked_text = [self hasMarkedText];
  958. if (input_context && (!input_source_at_last_key_event || ![input_source_at_last_key_event isEqualToString:input_context.selectedKeyboardInputSource])) {
  959. if (input_source_at_last_key_event) {
  960. debug_key("Input source changed, clearing pre-edit text and resetting deadkey state\n");
  961. GLFWkeyevent dummy = {.action = GLFW_RELEASE, .ime_state = GLFW_IME_PREEDIT_CHANGED};
  962. window->ns.deadKeyState = 0;
  963. _glfwInputKeyboard(window, &dummy); // clear pre-edit text
  964. [input_source_at_last_key_event release];
  965. input_source_at_last_key_event = nil;
  966. }
  967. input_source_at_last_key_event = [input_context.selectedKeyboardInputSource retain];
  968. [self unmarkText];
  969. }
  970. const unsigned int keycode = [event keyCode];
  971. const NSUInteger flags = [event modifierFlags];
  972. const int mods = translateFlags(flags);
  973. const uint32_t key = translateKey(keycode, true);
  974. const bool process_text = !_glfw.ignoreOSKeyboardProcessing && (!window->ns.textInputFilterCallback || window->ns.textInputFilterCallback(key, mods, keycode, flags) != 1);
  975. _glfw.ns.text[0] = 0;
  976. if (keycode == 0x33 /* backspace */ || keycode == 0x35 /* escape */) [self unmarkText];
  977. GLFWkeyevent glfw_keyevent = {.key = key, .native_key = keycode, .native_key_id = keycode, .action = GLFW_PRESS, .mods = mods};
  978. if (!_glfw.ns.unicodeData) {
  979. // Using the cocoa API for key handling is disabled, as there is no
  980. // reliable way to handle dead keys using it. Only use it if the
  981. // keyboard unicode data is not available.
  982. if (process_text) {
  983. // this will call insertText with the text for this event, if any
  984. [self interpretKeyEvents:@[event]];
  985. }
  986. } else {
  987. static UniChar text[256];
  988. UniCharCount char_count = 0;
  989. const bool in_compose_sequence = window->ns.deadKeyState != 0;
  990. if (UCKeyTranslate(
  991. [(NSData*) _glfw.ns.unicodeData bytes],
  992. keycode,
  993. kUCKeyActionDown,
  994. convert_cocoa_to_carbon_modifiers(flags),
  995. LMGetKbdType(),
  996. (process_text ? 0 : kUCKeyTranslateNoDeadKeysMask),
  997. &(window->ns.deadKeyState),
  998. sizeof(text)/sizeof(text[0]),
  999. &char_count,
  1000. text
  1001. ) != noErr) {
  1002. debug_key("UCKeyTranslate failed for keycode: 0x%x (%s) %s\n",
  1003. keycode, safe_name_for_keycode(keycode), format_mods(mods));
  1004. window->ns.deadKeyState = 0;
  1005. return;
  1006. }
  1007. debug_key("\x1b[31mPress:\x1b[m native_key: 0x%x (%s) glfw_key: 0x%x %schar_count: %lu deadKeyState: %u repeat: %d ",
  1008. keycode, safe_name_for_keycode(keycode), key, format_mods(mods), char_count, window->ns.deadKeyState, event.ARepeat);
  1009. marked_text_cleared_by_insert = false;
  1010. if (process_text) {
  1011. in_key_handler = 1;
  1012. // this will call insertText which will fill up _glfw.ns.text
  1013. [self interpretKeyEvents:@[event]];
  1014. in_key_handler = 0;
  1015. } else {
  1016. window->ns.deadKeyState = 0;
  1017. }
  1018. if (window->ns.deadKeyState && (char_count == 0 || keycode == 0x75)) {
  1019. // 0x75 is the delete key which needs to be ignored during a compose sequence
  1020. debug_key("Sending pre-edit text for dead key (text: %s markedText: %s).\n", format_text(_glfw.ns.text), glfw_keyevent.text);
  1021. UPDATE_PRE_EDIT_TEXT;
  1022. return;
  1023. }
  1024. if (in_compose_sequence) {
  1025. debug_key("Clearing pre-edit text at end of compose sequence\n");
  1026. CLEAR_PRE_EDIT_TEXT;
  1027. }
  1028. }
  1029. if (is_ascii_control_char(_glfw.ns.text[0])) _glfw.ns.text[0] = 0; // don't send text for ascii control codes
  1030. debug_key("text: %s glfw_key: %s marked_text: (%s)\n",
  1031. format_text(_glfw.ns.text), _glfwGetKeyName(key), [[markedText string] UTF8String]);
  1032. bool bracketed_ime = false;
  1033. if (!window->ns.deadKeyState) {
  1034. if ([self hasMarkedText]) {
  1035. if (!marked_text_cleared_by_insert) {
  1036. UPDATE_PRE_EDIT_TEXT;
  1037. } else bracketed_ime = true;
  1038. } else if (previous_has_marked_text) {
  1039. CLEAR_PRE_EDIT_TEXT;
  1040. }
  1041. if (([self hasMarkedText] || previous_has_marked_text) && !_glfw.ns.text[0]) {
  1042. // do not pass keys like BACKSPACE while there's pre-edit text, let IME handle it
  1043. debug_key("Ignoring key press as IME is active and it generated no text\n");
  1044. return;
  1045. }
  1046. }
  1047. if (bracketed_ime) {
  1048. // insertText followed by setMarkedText
  1049. CLEAR_PRE_EDIT_TEXT;
  1050. }
  1051. glfw_keyevent.text = _glfw.ns.text;
  1052. glfw_keyevent.ime_state = GLFW_IME_NONE;
  1053. add_alternate_keys(&glfw_keyevent, event);
  1054. _glfwInputKeyboard(window, &glfw_keyevent);
  1055. if (bracketed_ime) {
  1056. // insertText followed by setMarkedText
  1057. UPDATE_PRE_EDIT_TEXT;
  1058. }
  1059. }
  1060. static bool
  1061. is_modifier_pressed(NSUInteger flags, NSUInteger target_mask, NSUInteger other_mask, NSUInteger either_mask) {
  1062. bool target_pressed = (flags & target_mask) != 0;
  1063. bool other_pressed = (flags & other_mask) != 0;
  1064. bool either_pressed = (flags & either_mask) != 0;
  1065. if (either_pressed != (target_pressed || other_pressed)) return either_pressed;
  1066. return target_pressed;
  1067. }
  1068. - (void)flagsChanged:(NSEvent *)event
  1069. {
  1070. int action = GLFW_RELEASE;
  1071. const char old_first_char = _glfw.ns.text[0];
  1072. _glfw.ns.text[0] = 0;
  1073. const NSUInteger modifierFlags = [event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
  1074. const uint32_t key = vk_code_to_functional_key_code([event keyCode]);
  1075. const unsigned int keycode = [event keyCode];
  1076. const int mods = translateFlags(modifierFlags);
  1077. const bool process_text = !_glfw.ignoreOSKeyboardProcessing && (!window->ns.textInputFilterCallback || window->ns.textInputFilterCallback(key, mods, keycode, modifierFlags) != 1);
  1078. const char *mod_name = "unknown";
  1079. // Code for handling modifier key events copied form SDL_cocoakeyboard.m, with thanks. See IsModifierKeyPressedFunction()
  1080. #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;
  1081. switch(key) {
  1082. case GLFW_FKEY_CAPS_LOCK:
  1083. mod_name = "capslock";
  1084. action = modifierFlags & NSEventModifierFlagCapsLock ? GLFW_PRESS : GLFW_RELEASE; break;
  1085. case GLFW_FKEY_LEFT_SUPER: action_for(super, NX_DEVICELCMDKEYMASK, NX_DEVICERCMDKEYMASK, NX_COMMANDMASK);
  1086. case GLFW_FKEY_RIGHT_SUPER: action_for(super, NX_DEVICERCMDKEYMASK, NX_DEVICELCMDKEYMASK, NX_COMMANDMASK);
  1087. case GLFW_FKEY_LEFT_CONTROL: action_for(ctrl, NX_DEVICELCTLKEYMASK, NX_DEVICERCTLKEYMASK, NX_CONTROLMASK);
  1088. case GLFW_FKEY_RIGHT_CONTROL: action_for(ctrl, NX_DEVICERCTLKEYMASK, NX_DEVICELCTLKEYMASK, NX_CONTROLMASK);
  1089. case GLFW_FKEY_LEFT_ALT: action_for(alt, NX_DEVICELALTKEYMASK, NX_DEVICERALTKEYMASK, NX_ALTERNATEMASK);
  1090. case GLFW_FKEY_RIGHT_ALT: action_for(alt, NX_DEVICERALTKEYMASK, NX_DEVICELALTKEYMASK, NX_ALTERNATEMASK);
  1091. case GLFW_FKEY_LEFT_SHIFT: action_for(shift, NX_DEVICELSHIFTKEYMASK, NX_DEVICERSHIFTKEYMASK, NX_SHIFTMASK);
  1092. case GLFW_FKEY_RIGHT_SHIFT: action_for(shift, NX_DEVICERSHIFTKEYMASK, NX_DEVICELSHIFTKEYMASK, NX_SHIFTMASK);
  1093. default:
  1094. return;
  1095. }
  1096. #undef action_for
  1097. GLFWkeyevent glfw_keyevent = {.key = key, .native_key = keycode, .native_key_id = keycode, .action = action, .mods = mods};
  1098. debug_key("\x1b[33mflagsChanged:\x1b[m modifier: %s native_key: 0x%x (%s) glfw_key: 0x%x %s\n",
  1099. mod_name, keycode, safe_name_for_keycode(keycode), key, format_mods(mods));
  1100. marked_text_cleared_by_insert = false;
  1101. if (process_text && input_context) {
  1102. // this will call insertText which will fill up _glfw.ns.text
  1103. in_key_handler = 2;
  1104. [input_context handleEvent:event];
  1105. in_key_handler = 0;
  1106. if (marked_text_cleared_by_insert) {
  1107. debug_key("Clearing pre-edit text because insertText called from flagsChanged\n");
  1108. CLEAR_PRE_EDIT_TEXT;
  1109. if (_glfw.ns.text[0]) glfw_keyevent.text = _glfw.ns.text;
  1110. else _glfw.ns.text[0] = old_first_char;
  1111. }
  1112. }
  1113. glfw_keyevent.ime_state = GLFW_IME_NONE;
  1114. _glfwInputKeyboard(window, &glfw_keyevent);
  1115. }
  1116. - (void)keyUp:(NSEvent *)event
  1117. {
  1118. const uint32_t keycode = [event keyCode];
  1119. const uint32_t key = translateKey(keycode, true);
  1120. const int mods = translateFlags([event modifierFlags]);
  1121. GLFWkeyevent glfw_keyevent = {.key = key, .native_key = keycode, .native_key_id = keycode, .action = GLFW_RELEASE, .mods = mods};
  1122. add_alternate_keys(&glfw_keyevent, event);
  1123. debug_key("\x1b[32mRelease:\x1b[m native_key: 0x%x (%s) glfw_key: 0x%x %s\n",
  1124. keycode, safe_name_for_keycode(keycode), key, format_mods(mods));
  1125. _glfwInputKeyboard(window, &glfw_keyevent);
  1126. }
  1127. #undef CLEAR_PRE_EDIT_TEXT
  1128. #undef UPDATE_PRE_EDIT_TEXT
  1129. - (void)scrollWheel:(NSEvent *)event
  1130. {
  1131. double deltaX = [event scrollingDeltaX];
  1132. double deltaY = [event scrollingDeltaY];
  1133. int flags = [event hasPreciseScrollingDeltas] ? 1 : 0;
  1134. if (flags) {
  1135. float xscale = 1, yscale = 1;
  1136. _glfwPlatformGetWindowContentScale(window, &xscale, &yscale);
  1137. if (xscale > 0) deltaX *= xscale;
  1138. if (yscale > 0) deltaY *= yscale;
  1139. }
  1140. switch([event momentumPhase]) {
  1141. case NSEventPhaseBegan:
  1142. flags |= (1 << 1); break;
  1143. case NSEventPhaseStationary:
  1144. flags |= (2 << 1); break;
  1145. case NSEventPhaseChanged:
  1146. flags |= (3 << 1); break;
  1147. case NSEventPhaseEnded:
  1148. flags |= (4 << 1); break;
  1149. case NSEventPhaseCancelled:
  1150. flags |= (5 << 1); break;
  1151. case NSEventPhaseMayBegin:
  1152. flags |= (6 << 1); break;
  1153. case NSEventPhaseNone:
  1154. default:
  1155. break;
  1156. }
  1157. _glfwInputScroll(window, deltaX, deltaY, flags, translateFlags([event modifierFlags]));
  1158. }
  1159. - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
  1160. {
  1161. (void)sender;
  1162. // HACK: We don't know what to say here because we don't know what the
  1163. // application wants to do with the paths
  1164. return NSDragOperationGeneric;
  1165. }
  1166. - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
  1167. {
  1168. const NSRect contentRect = [window->ns.view frame];
  1169. // NOTE: The returned location uses base 0,1 not 0,0
  1170. const NSPoint pos = [sender draggingLocation];
  1171. _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y);
  1172. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1173. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  1174. NSArray* objs = [pasteboard readObjectsForClasses:@[[NSURL class], [NSString class]]
  1175. options:options];
  1176. if (!objs) return NO;
  1177. const NSUInteger count = [objs count];
  1178. NSMutableString *uri_list = [NSMutableString stringWithCapacity:4096]; // auto-released
  1179. if (count)
  1180. {
  1181. for (NSUInteger i = 0; i < count; i++)
  1182. {
  1183. id obj = objs[i];
  1184. if ([obj isKindOfClass:[NSURL class]]) {
  1185. NSURL *url = (NSURL*)obj;
  1186. if ([uri_list length] > 0) [uri_list appendString:@("\n")];
  1187. if (url.fileURL) [uri_list appendString:url.filePathURL.absoluteString];
  1188. else [uri_list appendString:url.absoluteString];
  1189. } else if ([obj isKindOfClass:[NSString class]]) {
  1190. const char *text = [obj UTF8String];
  1191. _glfwInputDrop(window, "text/plain;charset=utf-8", text, strlen(text));
  1192. } else {
  1193. _glfwInputError(GLFW_PLATFORM_ERROR,
  1194. "Cocoa: Object is neither a URL nor a string");
  1195. }
  1196. }
  1197. }
  1198. if ([uri_list length] > 0) _glfwInputDrop(window, "text/uri-list", uri_list.UTF8String, strlen(uri_list.UTF8String));
  1199. return YES;
  1200. }
  1201. - (BOOL)hasMarkedText
  1202. {
  1203. return [markedText length] > 0;
  1204. }
  1205. - (NSRange)markedRange
  1206. {
  1207. if ([markedText length] > 0)
  1208. return NSMakeRange(0, [markedText length] - 1);
  1209. else
  1210. return kEmptyRange;
  1211. }
  1212. - (NSRange)selectedRange
  1213. {
  1214. return kEmptyRange;
  1215. }
  1216. - (void)setMarkedText:(id)string
  1217. selectedRange:(NSRange)selectedRange
  1218. replacementRange:(NSRange)replacementRange
  1219. {
  1220. const char *s = polymorphic_string_as_utf8(string);
  1221. debug_key("\n\tsetMarkedText: %s selectedRange: (%lu, %lu) replacementRange: (%lu, %lu)\n", s, selectedRange.location, selectedRange.length, replacementRange.location, replacementRange.length);
  1222. if (string == nil || !s[0]) {
  1223. bool had_marked_text = [self hasMarkedText];
  1224. [self unmarkText];
  1225. if (had_marked_text && (!in_key_handler || in_key_handler == 2)) {
  1226. debug_key("Clearing pre-edit because setMarkedText called from %s\n", in_key_handler ? "flagsChanged" : "event loop");
  1227. GLFWkeyevent glfw_keyevent = {.ime_state = GLFW_IME_PREEDIT_CHANGED};
  1228. _glfwInputKeyboard(window, &glfw_keyevent);
  1229. _glfw.ns.text[0] = 0;
  1230. }
  1231. return;
  1232. }
  1233. if ([string isKindOfClass:[NSAttributedString class]]) {
  1234. if (((NSMutableAttributedString*)string).length == 0) { [self unmarkText]; return; }
  1235. [markedText release];
  1236. markedText = [[NSMutableAttributedString alloc] initWithAttributedString:string];
  1237. } else {
  1238. if (((NSString*)string).length == 0) { [self unmarkText]; return; }
  1239. [markedText release];
  1240. markedText = [[NSMutableAttributedString alloc] initWithString:string];
  1241. }
  1242. if (!in_key_handler || in_key_handler == 2) {
  1243. debug_key("Updating IME text in kitty from setMarkedText called from %s: %s\n", in_key_handler ? "flagsChanged" : "event loop", _glfw.ns.text);
  1244. GLFWkeyevent glfw_keyevent = {.text=[[markedText string] UTF8String], .ime_state = GLFW_IME_PREEDIT_CHANGED};
  1245. _glfwInputKeyboard(window, &glfw_keyevent);
  1246. _glfw.ns.text[0] = 0;
  1247. }
  1248. }
  1249. - (void)unmarkText
  1250. {
  1251. [[markedText mutableString] setString:@""];
  1252. }
  1253. void _glfwPlatformUpdateIMEState(_GLFWwindow *w, const GLFWIMEUpdateEvent *ev) {
  1254. [w->ns.view updateIMEStateFor: ev->type focused:(bool)ev->focused];
  1255. }
  1256. - (void)updateIMEStateFor:(GLFWIMEUpdateType)which
  1257. focused:(bool)focused
  1258. {
  1259. if (which == GLFW_IME_UPDATE_FOCUS && !focused && [self hasMarkedText] && window) {
  1260. [input_context discardMarkedText];
  1261. [self unmarkText];
  1262. GLFWkeyevent glfw_keyevent = {.ime_state = GLFW_IME_PREEDIT_CHANGED};
  1263. _glfwInputKeyboard(window, &glfw_keyevent);
  1264. _glfw.ns.text[0] = 0;
  1265. }
  1266. if (which != GLFW_IME_UPDATE_CURSOR_POSITION) return;
  1267. if (_glfwPlatformWindowFocused(window)) [[window->ns.view inputContext] invalidateCharacterCoordinates];
  1268. }
  1269. - (NSArray*)validAttributesForMarkedText
  1270. {
  1271. return [NSArray array];
  1272. }
  1273. - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
  1274. actualRange:(NSRangePointer)actualRange
  1275. {
  1276. (void)range; (void)actualRange;
  1277. return nil;
  1278. }
  1279. - (NSUInteger)characterIndexForPoint:(NSPoint)point
  1280. {
  1281. (void)point;
  1282. return 0;
  1283. }
  1284. - (NSRect)firstRectForCharacterRange:(NSRange)range
  1285. actualRange:(NSRangePointer)actualRange
  1286. {
  1287. (void)range; (void)actualRange;
  1288. if (_glfw.callbacks.get_ime_cursor_position) {
  1289. GLFWIMEUpdateEvent ev = { .type = GLFW_IME_UPDATE_CURSOR_POSITION };
  1290. if (window && _glfw.callbacks.get_ime_cursor_position((GLFWwindow*)window, &ev)) {
  1291. const CGFloat left = (CGFloat)ev.cursor.left / window->ns.xscale;
  1292. const CGFloat top = (CGFloat)ev.cursor.top / window->ns.yscale;
  1293. const CGFloat cellWidth = (CGFloat)ev.cursor.width / window->ns.xscale;
  1294. const CGFloat cellHeight = (CGFloat)ev.cursor.height / window->ns.yscale;
  1295. debug_key("updateIMEPosition: left=%f, top=%f, width=%f, height=%f\n", left, top, cellWidth, cellHeight);
  1296. const NSRect frame = [window->ns.view frame];
  1297. const NSRect rectInView = NSMakeRect(left,
  1298. frame.size.height - top - cellHeight,
  1299. cellWidth, cellHeight);
  1300. markedRect = [window->ns.object convertRectToScreen: rectInView];
  1301. }
  1302. }
  1303. return markedRect;
  1304. }
  1305. - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
  1306. {
  1307. const char *utf8 = polymorphic_string_as_utf8(string);
  1308. debug_key("\n\tinsertText: %s replacementRange: (%lu, %lu)\n", utf8, replacementRange.location, replacementRange.length);
  1309. if ([self hasMarkedText] && !is_ascii_control_char(utf8[0])) {
  1310. [self unmarkText];
  1311. marked_text_cleared_by_insert = true;
  1312. if (!in_key_handler) {
  1313. debug_key("Clearing pre-edit because insertText called from event loop\n");
  1314. GLFWkeyevent glfw_keyevent = {.ime_state = GLFW_IME_PREEDIT_CHANGED};
  1315. _glfwInputKeyboard(window, &glfw_keyevent);
  1316. _glfw.ns.text[0] = 0;
  1317. }
  1318. }
  1319. // insertText can be called multiple times for a single key event
  1320. size_t existing_length = strnlen(_glfw.ns.text, sizeof(_glfw.ns.text));
  1321. size_t required_length = strlen(utf8) + 1;
  1322. size_t available_length = sizeof(_glfw.ns.text) - existing_length;
  1323. if (available_length >= required_length) {
  1324. memcpy(_glfw.ns.text + existing_length, utf8, required_length); // copies the null terminator from utf8 as well
  1325. _glfw.ns.text[sizeof(_glfw.ns.text) - 1] = 0;
  1326. if ((!in_key_handler || in_key_handler == 2) && _glfw.ns.text[0]) {
  1327. if (!is_ascii_control_char(_glfw.ns.text[0])) {
  1328. debug_key("Sending text to kitty from insertText called from %s: %s\n", in_key_handler ? "flagsChanged" : "event loop", _glfw.ns.text);
  1329. GLFWkeyevent glfw_keyevent = {.text=_glfw.ns.text, .ime_state=GLFW_IME_COMMIT_TEXT};
  1330. _glfwInputKeyboard(window, &glfw_keyevent);
  1331. }
  1332. _glfw.ns.text[0] = 0;
  1333. }
  1334. }
  1335. }
  1336. - (void)doCommandBySelector:(SEL)selector
  1337. {
  1338. debug_key("\n\tdoCommandBySelector: (%s)\n", [NSStringFromSelector(selector) UTF8String]);
  1339. }
  1340. - (BOOL)isAccessibilityElement
  1341. {
  1342. return YES;
  1343. }
  1344. - (BOOL)isAccessibilitySelectorAllowed:(SEL)selector
  1345. {
  1346. if (selector == @selector(accessibilityRole) || selector == @selector(accessibilitySelectedText)) return YES;
  1347. return NO;
  1348. }
  1349. #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400)
  1350. - (NSAccessibilityRole)accessibilityRole
  1351. {
  1352. return NSAccessibilityTextAreaRole;
  1353. }
  1354. #endif
  1355. - (NSString *)accessibilitySelectedText
  1356. {
  1357. NSString *text = nil;
  1358. if (_glfw.callbacks.get_current_selection) {
  1359. char *s = _glfw.callbacks.get_current_selection();
  1360. if (s) {
  1361. text = [NSString stringWithUTF8String:s];
  1362. free(s);
  1363. }
  1364. }
  1365. return text;
  1366. }
  1367. // <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/SysServices/Articles/using.html>
  1368. // Support services receiving "public.utf8-plain-text" and "NSStringPboardType"
  1369. - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
  1370. {
  1371. if (
  1372. (!sendType || [sendType isEqual:NSPasteboardTypeString] || [sendType isEqual:@"NSStringPboardType"]) &&
  1373. (!returnType || [returnType isEqual:NSPasteboardTypeString] || [returnType isEqual:@"NSStringPboardType"])
  1374. ) {
  1375. if (_glfw.callbacks.has_current_selection && _glfw.callbacks.has_current_selection()) return self;
  1376. }
  1377. return [super validRequestorForSendType:sendType returnType:returnType];
  1378. }
  1379. // Selected text as input to be sent to Services
  1380. // For example, after selecting an absolute path, open the global menu bar kitty->Services and click `Show in Finder`.
  1381. - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pboard types:(NSArray *)types
  1382. {
  1383. if (!_glfw.callbacks.get_current_selection) return NO;
  1384. char *text = _glfw.callbacks.get_current_selection();
  1385. if (!text) return NO;
  1386. BOOL ans = NO;
  1387. if (text[0]) {
  1388. if ([types containsObject:NSPasteboardTypeString] == YES) {
  1389. [pboard declareTypes:@[NSPasteboardTypeString] owner:self];
  1390. ans = [pboard setString:@(text) forType:NSPasteboardTypeString];
  1391. } else if ([types containsObject:@"NSStringPboardType"] == YES) {
  1392. [pboard declareTypes:@[@"NSStringPboardType"] owner:self];
  1393. ans = [pboard setString:@(text) forType:@"NSStringPboardType"];
  1394. }
  1395. free(text);
  1396. }
  1397. return ans;
  1398. }
  1399. // Service output to be handled
  1400. // For example, open System Settings->Keyboard->Keyboard Shortcuts->Services->Text, enable `Convert Text to Full Width`, select some text and execute the service.
  1401. - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
  1402. {
  1403. NSString* text = nil;
  1404. NSArray *types = [pboard types];
  1405. if ([types containsObject:NSPasteboardTypeString] == YES) {
  1406. text = [pboard stringForType:NSPasteboardTypeString]; // public.utf8-plain-text
  1407. } else if ([types containsObject:@"NSStringPboardType"] == YES) {
  1408. text = [pboard stringForType:@"NSStringPboardType"]; // for older services (need re-encode?)
  1409. } else {
  1410. return NO;
  1411. }
  1412. if (text && [text length] > 0) {
  1413. // The service wants us to replace the selection, but we can't replace anything but insert text.
  1414. const char *utf8 = polymorphic_string_as_utf8(text);
  1415. debug_key("Sending text received in readSelectionFromPasteboard as key event\n");
  1416. GLFWkeyevent glfw_keyevent = {.text=utf8, .ime_state=GLFW_IME_COMMIT_TEXT};
  1417. _glfwInputKeyboard(window, &glfw_keyevent);
  1418. // Restore pre-edit text after inserting the received text
  1419. if ([self hasMarkedText]) {
  1420. glfw_keyevent.text = [[markedText string] UTF8String];
  1421. glfw_keyevent.ime_state = GLFW_IME_PREEDIT_CHANGED;
  1422. _glfwInputKeyboard(window, &glfw_keyevent);
  1423. }
  1424. return YES;
  1425. }
  1426. return NO;
  1427. }
  1428. @end
  1429. // }}}
  1430. // GLFW window class {{{
  1431. @interface GLFWWindow : NSWindow {
  1432. _GLFWwindow* glfw_window;
  1433. }
  1434. - (instancetype)initWithGlfwWindow:(NSRect)contentRect
  1435. styleMask:(NSWindowStyleMask)style
  1436. backing:(NSBackingStoreType)backingStoreType
  1437. initWindow:(_GLFWwindow *)initWindow;
  1438. - (void) removeGLFWWindow;
  1439. @end
  1440. @implementation GLFWWindow
  1441. - (instancetype)initWithGlfwWindow:(NSRect)contentRect
  1442. styleMask:(NSWindowStyleMask)style
  1443. backing:(NSBackingStoreType)backingStoreType
  1444. initWindow:(_GLFWwindow *)initWindow
  1445. {
  1446. self = [super initWithContentRect:contentRect styleMask:style backing:backingStoreType defer:NO];
  1447. if (self != nil) {
  1448. glfw_window = initWindow;
  1449. self.tabbingMode = NSWindowTabbingModeDisallowed;
  1450. }
  1451. return self;
  1452. }
  1453. - (void) removeGLFWWindow
  1454. {
  1455. glfw_window = NULL;
  1456. }
  1457. - (BOOL)validateMenuItem:(NSMenuItem *)item {
  1458. if (item.action == @selector(performMiniaturize:)) return YES;
  1459. return [super validateMenuItem:item];
  1460. }
  1461. - (void)performMiniaturize:(id)sender
  1462. {
  1463. if (glfw_window && (!glfw_window->decorated || glfw_window->ns.titlebar_hidden)) [self miniaturize:self];
  1464. else [super performMiniaturize:sender];
  1465. }
  1466. - (BOOL)canBecomeKeyWindow
  1467. {
  1468. // Required for NSWindowStyleMaskBorderless windows
  1469. return YES;
  1470. }
  1471. - (BOOL)canBecomeMainWindow
  1472. {
  1473. return YES;
  1474. }
  1475. static void
  1476. update_titlebar_button_visibility_after_fullscreen_transition(_GLFWwindow* w, bool traditional, bool made_fullscreen) {
  1477. // Update window button visibility
  1478. if (w->ns.titlebar_hidden) {
  1479. NSWindow *window = w->ns.object;
  1480. // The hidden buttons might be automatically reset to be visible after going full screen
  1481. // to show up in the auto-hide title bar, so they need to be set back to hidden.
  1482. BOOL button_hidden = YES;
  1483. // When title bar is configured to be hidden, it should be shown with buttons (auto-hide) after going to full screen.
  1484. if (!traditional) {
  1485. button_hidden = (BOOL) !made_fullscreen;
  1486. }
  1487. [[window standardWindowButton: NSWindowCloseButton] setHidden:button_hidden];
  1488. [[window standardWindowButton: NSWindowMiniaturizeButton] setHidden:button_hidden];
  1489. [[window standardWindowButton: NSWindowZoomButton] setHidden:button_hidden];
  1490. }
  1491. }
  1492. - (void)toggleFullScreen:(nullable id)sender
  1493. {
  1494. if (glfw_window) {
  1495. if (glfw_window->ns.in_fullscreen_transition) return;
  1496. if (glfw_window->ns.toggleFullscreenCallback && glfw_window->ns.toggleFullscreenCallback((GLFWwindow*)glfw_window) == 1) return;
  1497. glfw_window->ns.in_fullscreen_transition = true;
  1498. }
  1499. NSWindowStyleMask sm = [self styleMask];
  1500. bool is_fullscreen_already = (sm & NSWindowStyleMaskFullScreen) != 0;
  1501. // When resizeIncrements is set, Cocoa cannot restore the original window size after returning from fullscreen.
  1502. const NSSize original = [self resizeIncrements];
  1503. [self setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1504. [super toggleFullScreen:sender];
  1505. [self setResizeIncrements:original];
  1506. // When the window decoration is hidden, toggling fullscreen causes the style mask to be changed,
  1507. // and causes the first responder to be cleared.
  1508. if (glfw_window && !glfw_window->decorated && glfw_window->ns.view) [self makeFirstResponder:glfw_window->ns.view];
  1509. update_titlebar_button_visibility_after_fullscreen_transition(glfw_window, false, !is_fullscreen_already);
  1510. }
  1511. - (void)zoom:(id)sender
  1512. {
  1513. if (![self isZoomed]) {
  1514. const NSSize original = [self resizeIncrements];
  1515. [self setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1516. [super zoom:sender];
  1517. [self setResizeIncrements:original];
  1518. } else {
  1519. [super zoom:sender];
  1520. }
  1521. }
  1522. @end
  1523. // }}}
  1524. // Create the Cocoa window
  1525. //
  1526. static bool createNativeWindow(_GLFWwindow* window,
  1527. const _GLFWwndconfig* wndconfig,
  1528. const _GLFWfbconfig* fbconfig)
  1529. {
  1530. window->ns.delegate = [[GLFWWindowDelegate alloc] initWithGlfwWindow:window];
  1531. if (window->ns.delegate == nil)
  1532. {
  1533. _glfwInputError(GLFW_PLATFORM_ERROR,
  1534. "Cocoa: Failed to create window delegate");
  1535. return false;
  1536. }
  1537. NSRect contentRect;
  1538. if (window->monitor)
  1539. {
  1540. GLFWvidmode mode;
  1541. int xpos, ypos;
  1542. _glfwPlatformGetVideoMode(window->monitor, &mode);
  1543. _glfwPlatformGetMonitorPos(window->monitor, &xpos, &ypos);
  1544. contentRect = NSMakeRect(xpos, ypos, mode.width, mode.height);
  1545. }
  1546. else
  1547. contentRect = NSMakeRect(0, 0, wndconfig->width, wndconfig->height);
  1548. window->ns.object = [[GLFWWindow alloc]
  1549. initWithGlfwWindow:contentRect
  1550. styleMask:getStyleMask(window)
  1551. backing:NSBackingStoreBuffered
  1552. initWindow:window
  1553. ];
  1554. if (window->ns.object == nil)
  1555. {
  1556. _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to create window");
  1557. return false;
  1558. }
  1559. if (window->monitor)
  1560. [window->ns.object setLevel:NSMainMenuWindowLevel + 1];
  1561. else
  1562. {
  1563. [(NSWindow*) window->ns.object center];
  1564. CGRect screen_frame = [[(NSWindow*) window->ns.object screen] frame];
  1565. if (CGRectContainsPoint(screen_frame, _glfw.ns.cascadePoint)
  1566. || CGPointEqualToPoint(CGPointZero, _glfw.ns.cascadePoint)) {
  1567. _glfw.ns.cascadePoint =
  1568. NSPointToCGPoint([window->ns.object cascadeTopLeftFromPoint:
  1569. NSPointFromCGPoint(_glfw.ns.cascadePoint)]);
  1570. } else {
  1571. _glfw.ns.cascadePoint = CGPointZero;
  1572. }
  1573. if (wndconfig->resizable)
  1574. {
  1575. const NSWindowCollectionBehavior behavior =
  1576. NSWindowCollectionBehaviorFullScreenPrimary |
  1577. NSWindowCollectionBehaviorManaged;
  1578. [window->ns.object setCollectionBehavior:behavior];
  1579. }
  1580. if (wndconfig->floating)
  1581. [window->ns.object setLevel:NSFloatingWindowLevel];
  1582. if (wndconfig->maximized)
  1583. [window->ns.object zoom:nil];
  1584. }
  1585. if (strlen(wndconfig->ns.frameName))
  1586. [window->ns.object setFrameAutosaveName:@(wndconfig->ns.frameName)];
  1587. window->ns.view = [[GLFWContentView alloc] initWithGlfwWindow:window];
  1588. window->ns.retina = wndconfig->ns.retina;
  1589. if (fbconfig->transparent)
  1590. {
  1591. [window->ns.object setOpaque:NO];
  1592. [window->ns.object setHasShadow:NO];
  1593. [window->ns.object setBackgroundColor:[NSColor clearColor]];
  1594. }
  1595. [window->ns.object setContentView:window->ns.view];
  1596. [window->ns.object makeFirstResponder:window->ns.view];
  1597. [window->ns.object setTitle:@(wndconfig->title)];
  1598. [window->ns.object setDelegate:window->ns.delegate];
  1599. [window->ns.object setAcceptsMouseMovedEvents:YES];
  1600. [window->ns.object setRestorable:NO];
  1601. _glfwPlatformGetWindowSize(window, &window->ns.width, &window->ns.height);
  1602. _glfwPlatformGetFramebufferSize(window, &window->ns.fbWidth, &window->ns.fbHeight);
  1603. if (wndconfig->blur_radius > 0) _glfwPlatformSetWindowBlur(window, wndconfig->blur_radius);
  1604. return true;
  1605. }
  1606. //////////////////////////////////////////////////////////////////////////
  1607. ////// GLFW platform API //////
  1608. //////////////////////////////////////////////////////////////////////////
  1609. int _glfwPlatformCreateWindow(_GLFWwindow* window,
  1610. const _GLFWwndconfig* wndconfig,
  1611. const _GLFWctxconfig* ctxconfig,
  1612. const _GLFWfbconfig* fbconfig)
  1613. {
  1614. window->ns.deadKeyState = 0;
  1615. if (!_glfw.ns.finishedLaunching)
  1616. {
  1617. [NSApp run];
  1618. _glfw.ns.finishedLaunching = true;
  1619. }
  1620. if (!createNativeWindow(window, wndconfig, fbconfig))
  1621. return false;
  1622. switch((GlfwCocoaColorSpaces)wndconfig->ns.color_space) {
  1623. case SRGB_COLORSPACE: [window->ns.object setColorSpace:[NSColorSpace sRGBColorSpace]]; break;
  1624. case DISPLAY_P3_COLORSPACE: [window->ns.object setColorSpace:[NSColorSpace displayP3ColorSpace]]; break;
  1625. case DEFAULT_COLORSPACE: break;
  1626. }
  1627. if (ctxconfig->client != GLFW_NO_API)
  1628. {
  1629. if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API)
  1630. {
  1631. if (!_glfwInitNSGL())
  1632. return false;
  1633. if (!_glfwCreateContextNSGL(window, ctxconfig, fbconfig))
  1634. return false;
  1635. }
  1636. else if (ctxconfig->source == GLFW_EGL_CONTEXT_API)
  1637. {
  1638. // EGL implementation on macOS use CALayer* EGLNativeWindowType so we
  1639. // need to get the layer for EGL window surface creation.
  1640. [window->ns.view setWantsLayer:YES];
  1641. window->ns.layer = [window->ns.view layer];
  1642. if (!_glfwInitEGL())
  1643. return false;
  1644. if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig))
  1645. return false;
  1646. }
  1647. else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API)
  1648. {
  1649. if (!_glfwInitOSMesa())
  1650. return false;
  1651. if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig))
  1652. return false;
  1653. }
  1654. }
  1655. if (window->monitor)
  1656. {
  1657. // Do not show the window here until after setting the window size, maximized state, and full screen
  1658. // _glfwPlatformShowWindow(window);
  1659. // _glfwPlatformFocusWindow(window);
  1660. acquireMonitor(window);
  1661. }
  1662. return true;
  1663. }
  1664. void _glfwPlatformDestroyWindow(_GLFWwindow* window)
  1665. {
  1666. if (_glfw.ns.disabledCursorWindow == window)
  1667. _glfw.ns.disabledCursorWindow = NULL;
  1668. [window->ns.object orderOut:nil];
  1669. if (window->monitor)
  1670. releaseMonitor(window);
  1671. if (window->context.destroy)
  1672. window->context.destroy(window);
  1673. [window->ns.object setDelegate:nil];
  1674. [window->ns.delegate release];
  1675. window->ns.delegate = nil;
  1676. [window->ns.view removeGLFWWindow];
  1677. [window->ns.view release];
  1678. window->ns.view = nil;
  1679. [window->ns.object removeGLFWWindow];
  1680. [window->ns.object close];
  1681. window->ns.object = nil;
  1682. }
  1683. void _glfwPlatformSetWindowTitle(_GLFWwindow* window, const char* title)
  1684. {
  1685. if (!title) return;
  1686. NSString* string = @(title);
  1687. if (!string) return; // the runtime failed to convert title to an NSString
  1688. [window->ns.object setTitle:string];
  1689. // HACK: Set the miniwindow title explicitly as setTitle: doesn't update it
  1690. // if the window lacks NSWindowStyleMaskTitled
  1691. [window->ns.object setMiniwindowTitle:string];
  1692. }
  1693. void _glfwPlatformSetWindowIcon(_GLFWwindow* window UNUSED,
  1694. int count UNUSED, const GLFWimage* images UNUSED)
  1695. {
  1696. _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
  1697. "Cocoa: Regular windows do not have icons on macOS");
  1698. }
  1699. void _glfwPlatformGetWindowPos(_GLFWwindow* window, int* xpos, int* ypos)
  1700. {
  1701. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1702. if (xpos)
  1703. *xpos = (int)contentRect.origin.x;
  1704. if (ypos)
  1705. *ypos = (int)_glfwTransformYNS(contentRect.origin.y + contentRect.size.height - 1);
  1706. }
  1707. void _glfwPlatformSetWindowPos(_GLFWwindow* window, int x, int y)
  1708. {
  1709. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1710. const NSRect dummyRect = NSMakeRect(x, _glfwTransformYNS(y + contentRect.size.height - 1), 0, 0);
  1711. const NSRect frameRect = [window->ns.object frameRectForContentRect:dummyRect];
  1712. [window->ns.object setFrameOrigin:frameRect.origin];
  1713. }
  1714. void _glfwPlatformGetWindowSize(_GLFWwindow* window, int* width, int* height)
  1715. {
  1716. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1717. if (width)
  1718. *width = (int)contentRect.size.width;
  1719. if (height)
  1720. *height = (int)contentRect.size.height;
  1721. }
  1722. void _glfwPlatformSetWindowSize(_GLFWwindow* window, int width, int height)
  1723. {
  1724. if (window->monitor)
  1725. {
  1726. if (window->monitor->window == window)
  1727. acquireMonitor(window);
  1728. }
  1729. else
  1730. {
  1731. // Disable window resizing in fullscreen.
  1732. if ([window->ns.object styleMask] & NSWindowStyleMaskFullScreen || window->ns.in_traditional_fullscreen) return;
  1733. NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1734. contentRect.origin.y += contentRect.size.height - height;
  1735. contentRect.size = NSMakeSize(width, height);
  1736. [window->ns.object setFrame:[window->ns.object frameRectForContentRect:contentRect]
  1737. display:YES];
  1738. }
  1739. }
  1740. void _glfwPlatformSetWindowSizeLimits(_GLFWwindow* window,
  1741. int minwidth, int minheight,
  1742. int maxwidth, int maxheight)
  1743. {
  1744. if (minwidth == GLFW_DONT_CARE || minheight == GLFW_DONT_CARE)
  1745. [window->ns.object setContentMinSize:NSMakeSize(0, 0)];
  1746. else
  1747. [window->ns.object setContentMinSize:NSMakeSize(minwidth, minheight)];
  1748. if (maxwidth == GLFW_DONT_CARE || maxheight == GLFW_DONT_CARE)
  1749. [window->ns.object setContentMaxSize:NSMakeSize(DBL_MAX, DBL_MAX)];
  1750. else
  1751. [window->ns.object setContentMaxSize:NSMakeSize(maxwidth, maxheight)];
  1752. }
  1753. void _glfwPlatformSetWindowAspectRatio(_GLFWwindow* window, int numer, int denom)
  1754. {
  1755. if (numer == GLFW_DONT_CARE || denom == GLFW_DONT_CARE)
  1756. [window->ns.object setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1757. else
  1758. [window->ns.object setContentAspectRatio:NSMakeSize(numer, denom)];
  1759. }
  1760. void _glfwPlatformSetWindowSizeIncrements(_GLFWwindow* window, int widthincr, int heightincr)
  1761. {
  1762. if (widthincr != GLFW_DONT_CARE && heightincr != GLFW_DONT_CARE) {
  1763. float xscale = 1, yscale = 1;
  1764. _glfwPlatformGetWindowContentScale(window, &xscale, &yscale);
  1765. [window->ns.object setResizeIncrements:NSMakeSize(widthincr / xscale, heightincr / yscale)];
  1766. } else {
  1767. [window->ns.object setResizeIncrements:NSMakeSize(1.0, 1.0)];
  1768. }
  1769. }
  1770. void _glfwPlatformGetFramebufferSize(_GLFWwindow* window, int* width, int* height)
  1771. {
  1772. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1773. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  1774. if (width)
  1775. *width = (int) fbRect.size.width;
  1776. if (height)
  1777. *height = (int) fbRect.size.height;
  1778. }
  1779. void _glfwPlatformGetWindowFrameSize(_GLFWwindow* window,
  1780. int* left, int* top,
  1781. int* right, int* bottom)
  1782. {
  1783. const NSRect contentRect = get_window_size_without_border_in_logical_pixels(window);
  1784. const NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect];
  1785. if (left)
  1786. *left = (int)(contentRect.origin.x - frameRect.origin.x);
  1787. if (top)
  1788. *top = (int)(frameRect.origin.y + frameRect.size.height -
  1789. contentRect.origin.y - contentRect.size.height);
  1790. if (right)
  1791. *right = (int)(frameRect.origin.x + frameRect.size.width -
  1792. contentRect.origin.x - contentRect.size.width);
  1793. if (bottom)
  1794. *bottom = (int)(contentRect.origin.y - frameRect.origin.y);
  1795. }
  1796. void _glfwPlatformGetWindowContentScale(_GLFWwindow* window,
  1797. float* xscale, float* yscale)
  1798. {
  1799. const NSRect points = get_window_size_without_border_in_logical_pixels(window);
  1800. const NSRect pixels = [window->ns.view convertRectToBacking:points];
  1801. if (xscale)
  1802. *xscale = (float) (pixels.size.width / points.size.width);
  1803. if (yscale)
  1804. *yscale = (float) (pixels.size.height / points.size.height);
  1805. }
  1806. monotonic_t _glfwPlatformGetDoubleClickInterval(_GLFWwindow* window UNUSED)
  1807. {
  1808. return s_double_to_monotonic_t([NSEvent doubleClickInterval]);
  1809. }
  1810. void _glfwPlatformIconifyWindow(_GLFWwindow* window)
  1811. {
  1812. [window->ns.object miniaturize:nil];
  1813. }
  1814. void _glfwPlatformRestoreWindow(_GLFWwindow* window)
  1815. {
  1816. if ([window->ns.object isMiniaturized])
  1817. [window->ns.object deminiaturize:nil];
  1818. else if ([window->ns.object isZoomed])
  1819. [window->ns.object zoom:nil];
  1820. }
  1821. void _glfwPlatformMaximizeWindow(_GLFWwindow* window)
  1822. {
  1823. if (![window->ns.object isZoomed]) {
  1824. [window->ns.object zoom:nil];
  1825. }
  1826. }
  1827. void _glfwPlatformShowWindow(_GLFWwindow* window)
  1828. {
  1829. [window->ns.object orderFront:nil];
  1830. }
  1831. void _glfwPlatformHideWindow(_GLFWwindow* window)
  1832. {
  1833. [window->ns.object orderOut:nil];
  1834. }
  1835. void _glfwPlatformRequestWindowAttention(_GLFWwindow* window UNUSED)
  1836. {
  1837. [NSApp requestUserAttention:NSInformationalRequest];
  1838. }
  1839. int _glfwPlatformWindowBell(_GLFWwindow* window UNUSED)
  1840. {
  1841. NSBeep();
  1842. return true;
  1843. }
  1844. void _glfwPlatformFocusWindow(_GLFWwindow* window)
  1845. {
  1846. // Make us the active application
  1847. // HACK: This is here to prevent applications using only hidden windows from
  1848. // being activated, but should probably not be done every time any
  1849. // window is shown
  1850. [NSApp activateIgnoringOtherApps:YES];
  1851. [window->ns.object makeKeyAndOrderFront:nil];
  1852. }
  1853. void _glfwPlatformSetWindowMonitor(_GLFWwindow* window,
  1854. _GLFWmonitor* monitor,
  1855. int xpos, int ypos,
  1856. int width, int height,
  1857. int refreshRate UNUSED)
  1858. {
  1859. if (window->monitor == monitor)
  1860. {
  1861. if (monitor)
  1862. {
  1863. if (monitor->window == window)
  1864. acquireMonitor(window);
  1865. }
  1866. else
  1867. {
  1868. const NSRect contentRect =
  1869. NSMakeRect(xpos, _glfwTransformYNS(ypos + height - 1), width, height);
  1870. const NSRect frameRect =
  1871. [window->ns.object frameRectForContentRect:contentRect
  1872. styleMask:getStyleMask(window)];
  1873. [window->ns.object setFrame:frameRect display:YES];
  1874. }
  1875. return;
  1876. }
  1877. if (window->monitor)
  1878. releaseMonitor(window);
  1879. _glfwInputWindowMonitor(window, monitor);
  1880. const NSUInteger styleMask = getStyleMask(window);
  1881. [window->ns.object setStyleMask:styleMask];
  1882. // HACK: Changing the style mask can cause the first responder to be cleared
  1883. [window->ns.object makeFirstResponder:window->ns.view];
  1884. if (window->monitor)
  1885. {
  1886. [window->ns.object setLevel:NSMainMenuWindowLevel + 1];
  1887. [window->ns.object setHasShadow:NO];
  1888. acquireMonitor(window);
  1889. }
  1890. else
  1891. {
  1892. NSRect contentRect = NSMakeRect(xpos, _glfwTransformYNS(ypos + height - 1),
  1893. width, height);
  1894. NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect
  1895. styleMask:styleMask];
  1896. [window->ns.object setFrame:frameRect display:YES];
  1897. if (window->numer != GLFW_DONT_CARE &&
  1898. window->denom != GLFW_DONT_CARE)
  1899. {
  1900. [window->ns.object setContentAspectRatio:NSMakeSize(window->numer,
  1901. window->denom)];
  1902. }
  1903. if (window->minwidth != GLFW_DONT_CARE &&
  1904. window->minheight != GLFW_DONT_CARE)
  1905. {
  1906. [window->ns.object setContentMinSize:NSMakeSize(window->minwidth,
  1907. window->minheight)];
  1908. }
  1909. if (window->maxwidth != GLFW_DONT_CARE &&
  1910. window->maxheight != GLFW_DONT_CARE)
  1911. {
  1912. [window->ns.object setContentMaxSize:NSMakeSize(window->maxwidth,
  1913. window->maxheight)];
  1914. }
  1915. if (window->floating)
  1916. [window->ns.object setLevel:NSFloatingWindowLevel];
  1917. else
  1918. [window->ns.object setLevel:NSNormalWindowLevel];
  1919. [window->ns.object setHasShadow:YES];
  1920. // HACK: Clearing NSWindowStyleMaskTitled resets and disables the window
  1921. // title property but the miniwindow title property is unaffected
  1922. [window->ns.object setTitle:[window->ns.object miniwindowTitle]];
  1923. }
  1924. }
  1925. int _glfwPlatformWindowFocused(_GLFWwindow* window)
  1926. {
  1927. return [window->ns.object isKeyWindow];
  1928. }
  1929. int _glfwPlatformWindowOccluded(_GLFWwindow* window)
  1930. {
  1931. return !([window->ns.object occlusionState] & NSWindowOcclusionStateVisible);
  1932. }
  1933. int _glfwPlatformWindowIconified(_GLFWwindow* window)
  1934. {
  1935. return [window->ns.object isMiniaturized];
  1936. }
  1937. int _glfwPlatformWindowVisible(_GLFWwindow* window)
  1938. {
  1939. return [window->ns.object isVisible];
  1940. }
  1941. int _glfwPlatformWindowMaximized(_GLFWwindow* window)
  1942. {
  1943. return [window->ns.object isZoomed];
  1944. }
  1945. int _glfwPlatformWindowHovered(_GLFWwindow* window)
  1946. {
  1947. const NSPoint point = [NSEvent mouseLocation];
  1948. if ([NSWindow windowNumberAtPoint:point belowWindowWithWindowNumber:0] !=
  1949. [window->ns.object windowNumber])
  1950. {
  1951. return false;
  1952. }
  1953. return NSMouseInRect(point,
  1954. [window->ns.object convertRectToScreen:[window->ns.view frame]], NO);
  1955. }
  1956. int _glfwPlatformFramebufferTransparent(_GLFWwindow* window)
  1957. {
  1958. return ![window->ns.object isOpaque] && ![window->ns.view isOpaque];
  1959. }
  1960. void _glfwPlatformSetWindowResizable(_GLFWwindow* window, bool enabled UNUSED)
  1961. {
  1962. [window->ns.object setStyleMask:getStyleMask(window)];
  1963. [window->ns.object makeFirstResponder:window->ns.view];
  1964. }
  1965. void _glfwPlatformSetWindowDecorated(_GLFWwindow* window, bool enabled UNUSED)
  1966. {
  1967. [window->ns.object setStyleMask:getStyleMask(window)];
  1968. [window->ns.object makeFirstResponder:window->ns.view];
  1969. }
  1970. void _glfwPlatformSetWindowFloating(_GLFWwindow* window, bool enabled)
  1971. {
  1972. if (enabled)
  1973. [window->ns.object setLevel:NSFloatingWindowLevel];
  1974. else
  1975. [window->ns.object setLevel:NSNormalWindowLevel];
  1976. }
  1977. void _glfwPlatformSetWindowMousePassthrough(_GLFWwindow* window, bool enabled)
  1978. {
  1979. [window->ns.object setIgnoresMouseEvents:enabled];
  1980. }
  1981. float _glfwPlatformGetWindowOpacity(_GLFWwindow* window)
  1982. {
  1983. return (float) [window->ns.object alphaValue];
  1984. }
  1985. void _glfwPlatformSetWindowOpacity(_GLFWwindow* window, float opacity)
  1986. {
  1987. [window->ns.object setAlphaValue:opacity];
  1988. }
  1989. void _glfwPlatformSetRawMouseMotion(_GLFWwindow *window UNUSED, bool enabled UNUSED)
  1990. {
  1991. _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
  1992. "Cocoa: Raw mouse motion not yet implemented");
  1993. }
  1994. bool _glfwPlatformRawMouseMotionSupported(void)
  1995. {
  1996. return false;
  1997. }
  1998. void _glfwPlatformGetCursorPos(_GLFWwindow* window, double* xpos, double* ypos)
  1999. {
  2000. const NSRect contentRect = [window->ns.view frame];
  2001. // NOTE: The returned location uses base 0,1 not 0,0
  2002. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  2003. if (xpos)
  2004. *xpos = pos.x;
  2005. if (ypos)
  2006. *ypos = contentRect.size.height - pos.y;
  2007. }
  2008. void _glfwPlatformSetCursorPos(_GLFWwindow* window, double x, double y)
  2009. {
  2010. updateCursorImage(window);
  2011. const NSRect contentRect = [window->ns.view frame];
  2012. // NOTE: The returned location uses base 0,1 not 0,0
  2013. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  2014. window->ns.cursorWarpDeltaX += x - pos.x;
  2015. window->ns.cursorWarpDeltaY += y - contentRect.size.height + pos.y;
  2016. if (window->monitor)
  2017. {
  2018. CGDisplayMoveCursorToPoint(window->monitor->ns.displayID,
  2019. CGPointMake(x, y));
  2020. }
  2021. else
  2022. {
  2023. const NSRect localRect = NSMakeRect(x, contentRect.size.height - y - 1, 0, 0);
  2024. const NSRect globalRect = [window->ns.object convertRectToScreen:localRect];
  2025. const NSPoint globalPoint = globalRect.origin;
  2026. CGWarpMouseCursorPosition(CGPointMake(globalPoint.x,
  2027. _glfwTransformYNS(globalPoint.y)));
  2028. }
  2029. }
  2030. void _glfwPlatformSetCursorMode(_GLFWwindow* window, int mode UNUSED)
  2031. {
  2032. if (_glfwPlatformWindowFocused(window))
  2033. updateCursorMode(window);
  2034. }
  2035. const char* _glfwPlatformGetNativeKeyName(int keycode)
  2036. {
  2037. UInt32 deadKeyState = 0;
  2038. UniChar characters[8];
  2039. UniCharCount characterCount = 0;
  2040. if (UCKeyTranslate([(NSData*) _glfw.ns.unicodeData bytes],
  2041. keycode,
  2042. kUCKeyActionDisplay,
  2043. 0,
  2044. LMGetKbdType(),
  2045. kUCKeyTranslateNoDeadKeysBit,
  2046. &deadKeyState,
  2047. sizeof(characters) / sizeof(characters[0]),
  2048. &characterCount,
  2049. characters) != noErr)
  2050. {
  2051. return NULL;
  2052. }
  2053. if (!characterCount)
  2054. return NULL;
  2055. convert_utf16_to_utf8(characters, characterCount, _glfw.ns.keyName, sizeof(_glfw.ns.keyName));
  2056. return _glfw.ns.keyName;
  2057. }
  2058. int _glfwPlatformGetNativeKeyForKey(uint32_t glfw_key)
  2059. {
  2060. if (GLFW_FKEY_FIRST <= glfw_key && glfw_key <= GLFW_FKEY_LAST) { // {{{
  2061. switch(glfw_key) {
  2062. /* start functional to macu (auto generated by gen-key-constants.py do not edit) */
  2063. case GLFW_FKEY_ENTER: return NSCarriageReturnCharacter;
  2064. case GLFW_FKEY_TAB: return NSTabCharacter;
  2065. case GLFW_FKEY_BACKSPACE: return NSBackspaceCharacter;
  2066. case GLFW_FKEY_INSERT: return NSInsertFunctionKey;
  2067. case GLFW_FKEY_DELETE: return NSDeleteFunctionKey;
  2068. case GLFW_FKEY_LEFT: return NSLeftArrowFunctionKey;
  2069. case GLFW_FKEY_RIGHT: return NSRightArrowFunctionKey;
  2070. case GLFW_FKEY_UP: return NSUpArrowFunctionKey;
  2071. case GLFW_FKEY_DOWN: return NSDownArrowFunctionKey;
  2072. case GLFW_FKEY_PAGE_UP: return NSPageUpFunctionKey;
  2073. case GLFW_FKEY_PAGE_DOWN: return NSPageDownFunctionKey;
  2074. case GLFW_FKEY_HOME: return NSHomeFunctionKey;
  2075. case GLFW_FKEY_END: return NSEndFunctionKey;
  2076. case GLFW_FKEY_SCROLL_LOCK: return NSScrollLockFunctionKey;
  2077. case GLFW_FKEY_NUM_LOCK: return NSClearLineFunctionKey;
  2078. case GLFW_FKEY_PRINT_SCREEN: return NSPrintScreenFunctionKey;
  2079. case GLFW_FKEY_PAUSE: return NSPauseFunctionKey;
  2080. case GLFW_FKEY_MENU: return NSMenuFunctionKey;
  2081. case GLFW_FKEY_F1: return NSF1FunctionKey;
  2082. case GLFW_FKEY_F2: return NSF2FunctionKey;
  2083. case GLFW_FKEY_F3: return NSF3FunctionKey;
  2084. case GLFW_FKEY_F4: return NSF4FunctionKey;
  2085. case GLFW_FKEY_F5: return NSF5FunctionKey;
  2086. case GLFW_FKEY_F6: return NSF6FunctionKey;
  2087. case GLFW_FKEY_F7: return NSF7FunctionKey;
  2088. case GLFW_FKEY_F8: return NSF8FunctionKey;
  2089. case GLFW_FKEY_F9: return NSF9FunctionKey;
  2090. case GLFW_FKEY_F10: return NSF10FunctionKey;
  2091. case GLFW_FKEY_F11: return NSF11FunctionKey;
  2092. case GLFW_FKEY_F12: return NSF12FunctionKey;
  2093. case GLFW_FKEY_F13: return NSF13FunctionKey;
  2094. case GLFW_FKEY_F14: return NSF14FunctionKey;
  2095. case GLFW_FKEY_F15: return NSF15FunctionKey;
  2096. case GLFW_FKEY_F16: return NSF16FunctionKey;
  2097. case GLFW_FKEY_F17: return NSF17FunctionKey;
  2098. case GLFW_FKEY_F18: return NSF18FunctionKey;
  2099. case GLFW_FKEY_F19: return NSF19FunctionKey;
  2100. case GLFW_FKEY_F20: return NSF20FunctionKey;
  2101. case GLFW_FKEY_F21: return NSF21FunctionKey;
  2102. case GLFW_FKEY_F22: return NSF22FunctionKey;
  2103. case GLFW_FKEY_F23: return NSF23FunctionKey;
  2104. case GLFW_FKEY_F24: return NSF24FunctionKey;
  2105. case GLFW_FKEY_F25: return NSF25FunctionKey;
  2106. case GLFW_FKEY_F26: return NSF26FunctionKey;
  2107. case GLFW_FKEY_F27: return NSF27FunctionKey;
  2108. case GLFW_FKEY_F28: return NSF28FunctionKey;
  2109. case GLFW_FKEY_F29: return NSF29FunctionKey;
  2110. case GLFW_FKEY_F30: return NSF30FunctionKey;
  2111. case GLFW_FKEY_F31: return NSF31FunctionKey;
  2112. case GLFW_FKEY_F32: return NSF32FunctionKey;
  2113. case GLFW_FKEY_F33: return NSF33FunctionKey;
  2114. case GLFW_FKEY_F34: return NSF34FunctionKey;
  2115. case GLFW_FKEY_F35: return NSF35FunctionKey;
  2116. case GLFW_FKEY_KP_ENTER: return NSEnterCharacter;
  2117. /* end functional to macu */
  2118. default:
  2119. return 0;
  2120. }
  2121. } // }}}
  2122. if (!is_pua_char(glfw_key)) return glfw_key;
  2123. return 0;
  2124. }
  2125. int _glfwPlatformCreateCursor(_GLFWcursor* cursor,
  2126. const GLFWimage* image,
  2127. int xhot, int yhot, int count)
  2128. {
  2129. NSImage* native;
  2130. NSBitmapImageRep* rep;
  2131. native = [[NSImage alloc] initWithSize:NSMakeSize(image->width, image->height)];
  2132. if (native == nil)
  2133. return false;
  2134. for (int i = 0; i < count; i++) {
  2135. const GLFWimage *src = image + i;
  2136. rep = [[NSBitmapImageRep alloc]
  2137. initWithBitmapDataPlanes:NULL
  2138. pixelsWide:src->width
  2139. pixelsHigh:src->height
  2140. bitsPerSample:8
  2141. samplesPerPixel:4
  2142. hasAlpha:YES
  2143. isPlanar:NO
  2144. colorSpaceName:NSCalibratedRGBColorSpace
  2145. bitmapFormat:NSBitmapFormatAlphaNonpremultiplied
  2146. bytesPerRow:src->width * 4
  2147. bitsPerPixel:32];
  2148. if (rep == nil) {
  2149. [native release];
  2150. return false;
  2151. }
  2152. memcpy([rep bitmapData], src->pixels, src->width * src->height * 4);
  2153. [native addRepresentation:rep];
  2154. [rep release];
  2155. }
  2156. cursor->ns.object = [[NSCursor alloc] initWithImage:native
  2157. hotSpot:NSMakePoint(xhot, yhot)];
  2158. [native release];
  2159. if (cursor->ns.object == nil)
  2160. return false;
  2161. return true;
  2162. }
  2163. static NSCursor*
  2164. load_hidden_system_cursor(NSString *name, SEL fallback) {
  2165. // this implementation comes from SDL_cocoamouse.m
  2166. NSString *cursorPath = [@"/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors" stringByAppendingPathComponent:name];
  2167. NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:[cursorPath stringByAppendingPathComponent:@"info.plist"]];
  2168. /* we can't do animation atm. :/ */
  2169. const int frames = (int)[[info valueForKey:@"frames"] integerValue];
  2170. NSCursor *cursor;
  2171. NSImage *image = [[NSImage alloc] initWithContentsOfFile:[cursorPath stringByAppendingPathComponent:@"cursor.pdf"]];
  2172. if ((image == nil) || (image.isValid == NO)) {
  2173. return [NSCursor performSelector:fallback];
  2174. }
  2175. if (frames > 1) {
  2176. const NSCompositingOperation operation = NSCompositingOperationCopy;
  2177. const NSSize cropped_size = NSMakeSize(image.size.width, (int)(image.size.height / frames));
  2178. NSImage *cropped = [[NSImage alloc] initWithSize:cropped_size];
  2179. if (cropped == nil) {
  2180. return [NSCursor performSelector:fallback];
  2181. }
  2182. [cropped lockFocus];
  2183. {
  2184. const NSRect cropped_rect = NSMakeRect(0, 0, cropped_size.width, cropped_size.height);
  2185. [image drawInRect:cropped_rect fromRect:cropped_rect operation:operation fraction:1];
  2186. }
  2187. [cropped unlockFocus];
  2188. image = cropped;
  2189. }
  2190. cursor = [[NSCursor alloc] initWithImage:image hotSpot:NSMakePoint([[info valueForKey:@"hotx"] doubleValue], [[info valueForKey:@"hoty"] doubleValue])];
  2191. return cursor;
  2192. }
  2193. int _glfwPlatformCreateStandardCursor(_GLFWcursor* cursor, GLFWCursorShape shape) {
  2194. #define C(name, val) case name: cursor->ns.object = [NSCursor val]; break;
  2195. #define U(name, val) case name: cursor->ns.object = [NSCursor performSelector:@selector(val)]; break;
  2196. #define S(name, val, fallback) case name: cursor->ns.object = load_hidden_system_cursor(@#val, @selector(val)); break;
  2197. switch(shape) {
  2198. /* start glfw to cocoa (auto generated by gen-key-constants.py do not edit) */
  2199. C(GLFW_DEFAULT_CURSOR, arrowCursor);
  2200. C(GLFW_TEXT_CURSOR, IBeamCursor);
  2201. C(GLFW_POINTER_CURSOR, pointingHandCursor);
  2202. S(GLFW_HELP_CURSOR, help, arrowCursor);
  2203. S(GLFW_WAIT_CURSOR, busybutclickable, arrowCursor);
  2204. S(GLFW_PROGRESS_CURSOR, busybutclickable, arrowCursor);
  2205. C(GLFW_CROSSHAIR_CURSOR, crosshairCursor);
  2206. S(GLFW_CELL_CURSOR, cell, crosshairCursor);
  2207. C(GLFW_VERTICAL_TEXT_CURSOR, IBeamCursorForVerticalLayout);
  2208. S(GLFW_MOVE_CURSOR, move, openHandCursor);
  2209. C(GLFW_E_RESIZE_CURSOR, resizeRightCursor);
  2210. S(GLFW_NE_RESIZE_CURSOR, resizenortheast, _windowResizeNorthEastSouthWestCursor);
  2211. S(GLFW_NW_RESIZE_CURSOR, resizenorthwest, _windowResizeNorthWestSouthEastCursor);
  2212. C(GLFW_N_RESIZE_CURSOR, resizeUpCursor);
  2213. S(GLFW_SE_RESIZE_CURSOR, resizesoutheast, _windowResizeNorthWestSouthEastCursor);
  2214. S(GLFW_SW_RESIZE_CURSOR, resizesouthwest, _windowResizeNorthEastSouthWestCursor);
  2215. C(GLFW_S_RESIZE_CURSOR, resizeDownCursor);
  2216. C(GLFW_W_RESIZE_CURSOR, resizeLeftCursor);
  2217. C(GLFW_EW_RESIZE_CURSOR, resizeLeftRightCursor);
  2218. C(GLFW_NS_RESIZE_CURSOR, resizeUpDownCursor);
  2219. U(GLFW_NESW_RESIZE_CURSOR, _windowResizeNorthEastSouthWestCursor);
  2220. U(GLFW_NWSE_RESIZE_CURSOR, _windowResizeNorthWestSouthEastCursor);
  2221. S(GLFW_ZOOM_IN_CURSOR, zoomin, arrowCursor);
  2222. S(GLFW_ZOOM_OUT_CURSOR, zoomout, arrowCursor);
  2223. C(GLFW_ALIAS_CURSOR, dragLinkCursor);
  2224. C(GLFW_COPY_CURSOR, dragCopyCursor);
  2225. C(GLFW_NOT_ALLOWED_CURSOR, operationNotAllowedCursor);
  2226. C(GLFW_NO_DROP_CURSOR, operationNotAllowedCursor);
  2227. C(GLFW_GRAB_CURSOR, openHandCursor);
  2228. C(GLFW_GRABBING_CURSOR, closedHandCursor);
  2229. /* end glfw to cocoa */
  2230. case GLFW_INVALID_CURSOR:
  2231. return false;
  2232. }
  2233. #undef C
  2234. #undef U
  2235. #undef S
  2236. if (!cursor->ns.object)
  2237. {
  2238. _glfwInputError(GLFW_PLATFORM_ERROR,
  2239. "Cocoa: Failed to retrieve standard cursor");
  2240. return false;
  2241. }
  2242. [cursor->ns.object retain];
  2243. return true;
  2244. }
  2245. void _glfwPlatformDestroyCursor(_GLFWcursor* cursor)
  2246. {
  2247. if (cursor->ns.object)
  2248. [(NSCursor*) cursor->ns.object release];
  2249. }
  2250. void _glfwPlatformSetCursor(_GLFWwindow* window, _GLFWcursor* cursor UNUSED)
  2251. {
  2252. if (cursorInContentArea(window))
  2253. updateCursorImage(window);
  2254. }
  2255. bool _glfwPlatformIsFullscreen(_GLFWwindow* w, unsigned int flags) {
  2256. NSWindow *window = w->ns.object;
  2257. bool traditional = !(flags & 1);
  2258. if (traditional) { if(@available(macOS 10.15.7, *)) return w->ns.in_traditional_fullscreen; }
  2259. NSWindowStyleMask sm = [window styleMask];
  2260. return sm & NSWindowStyleMaskFullScreen;
  2261. }
  2262. static void
  2263. make_window_fullscreen_after_show(unsigned long long timer_id, void* data) {
  2264. (void)timer_id;
  2265. unsigned long long window_id = (uintptr_t)data;
  2266. for (_GLFWwindow *w = _glfw.windowListHead; w; w = w->next) {
  2267. if (w->id == window_id) {
  2268. NSWindow *window = w->ns.object;
  2269. [window toggleFullScreen: nil];
  2270. update_titlebar_button_visibility_after_fullscreen_transition(w, false, true);
  2271. break;
  2272. }
  2273. }
  2274. }
  2275. bool _glfwPlatformToggleFullscreen(_GLFWwindow* w, unsigned int flags) {
  2276. NSWindow *window = w->ns.object;
  2277. bool made_fullscreen = true;
  2278. bool traditional = !(flags & 1);
  2279. NSWindowStyleMask sm = [window styleMask];
  2280. if (traditional) {
  2281. if (@available(macOS 10.15.7, *)) {
  2282. // As of Big Turd NSWindowStyleMaskFullScreen is no longer usable
  2283. // Also no longer compatible after a minor release of macOS 10.15.7
  2284. if (!w->ns.in_traditional_fullscreen) {
  2285. w->ns.pre_full_screen_style_mask = sm;
  2286. [window setStyleMask: NSWindowStyleMaskBorderless];
  2287. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];
  2288. [window setFrame:[window.screen frame] display:YES];
  2289. w->ns.in_traditional_fullscreen = true;
  2290. } else {
  2291. made_fullscreen = false;
  2292. [window setStyleMask: w->ns.pre_full_screen_style_mask];
  2293. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationDefault];
  2294. w->ns.in_traditional_fullscreen = false;
  2295. }
  2296. } else {
  2297. bool in_fullscreen = sm & NSWindowStyleMaskFullScreen;
  2298. if (!(in_fullscreen)) {
  2299. sm |= NSWindowStyleMaskBorderless | NSWindowStyleMaskFullScreen;
  2300. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationAutoHideMenuBar | NSApplicationPresentationAutoHideDock];
  2301. } else {
  2302. made_fullscreen = false;
  2303. sm &= ~(NSWindowStyleMaskBorderless | NSWindowStyleMaskFullScreen);
  2304. [[NSApplication sharedApplication] setPresentationOptions: NSApplicationPresentationDefault];
  2305. }
  2306. [window setStyleMask: sm];
  2307. }
  2308. // Changing the style mask causes the first responder to be cleared
  2309. [window makeFirstResponder:w->ns.view];
  2310. // If the dock and menubar are hidden going from maximized to fullscreen doesn't change the window size
  2311. // and macOS forgets to trigger windowDidResize, so call it ourselves
  2312. NSNotification *notification = [NSNotification notificationWithName:NSWindowDidResizeNotification object:window];
  2313. [w->ns.delegate performSelector:@selector(windowDidResize:) withObject:notification afterDelay:0];
  2314. } else {
  2315. bool in_fullscreen = sm & NSWindowStyleMaskFullScreen;
  2316. if (!in_fullscreen && !_glfwPlatformWindowVisible(w)) {
  2317. // Bug in Apple's fullscreen implementation causes fullscreen to
  2318. // not work before window is shown (at creation) if another window
  2319. // is already fullscreen. Le sigh. https://github.com/kovidgoyal/kitty/issues/7448
  2320. _glfwPlatformAddTimer(0, false, make_window_fullscreen_after_show, (void*)(uintptr_t)(w->id), NULL);
  2321. return made_fullscreen;
  2322. }
  2323. if (in_fullscreen) made_fullscreen = false;
  2324. [window toggleFullScreen: nil];
  2325. }
  2326. update_titlebar_button_visibility_after_fullscreen_transition(w, traditional, made_fullscreen);
  2327. return made_fullscreen;
  2328. }
  2329. // Clipboard {{{
  2330. #define UTI_ROUNDTRIP_PREFIX @"uti-is-typical-apple-nih."
  2331. static NSString*
  2332. mime_to_uti(const char *mime) {
  2333. if (strcmp(mime, "text/plain") == 0) return NSPasteboardTypeString;
  2334. if (@available(macOS 11.0, *)) {
  2335. UTType *t = [UTType typeWithMIMEType:@(mime)]; // auto-released
  2336. if (t != nil && !t.dynamic) return t.identifier;
  2337. }
  2338. return [NSString stringWithFormat:@"%@%s", UTI_ROUNDTRIP_PREFIX, mime]; // auto-released
  2339. }
  2340. static const char*
  2341. uti_to_mime(NSString *uti) {
  2342. if ([uti isEqualToString:NSPasteboardTypeString]) return "text/plain";
  2343. if ([uti hasPrefix:UTI_ROUNDTRIP_PREFIX]) return [[uti substringFromIndex:[UTI_ROUNDTRIP_PREFIX length]] UTF8String];
  2344. if (@available(macOS 11.0, *)) {
  2345. UTType *t = [UTType typeWithIdentifier:uti]; // auto-released
  2346. if (t.preferredMIMEType != nil) return [t.preferredMIMEType UTF8String];
  2347. }
  2348. return "";
  2349. }
  2350. static void
  2351. list_clipboard_mimetypes(GLFWclipboardwritedatafun write_data, void *object) {
  2352. #define w(x) { if (ok) ok = write_data(object, x, strlen(x)); }
  2353. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2354. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  2355. BOOL has_file_urls = [pasteboard canReadObjectForClasses:@[[NSURL class]] options:options];
  2356. BOOL has_strings = [pasteboard canReadObjectForClasses:@[[NSString class]] options:nil];
  2357. /* NSLog(@"has_file_urls: %d has_strings: %d", has_file_urls, has_strings); */
  2358. bool ok = true;
  2359. if (has_strings) w("text/plain");
  2360. if (has_file_urls) w("text/local-path-list");
  2361. for (NSPasteboardItem * item in pasteboard.pasteboardItems) {
  2362. for (NSPasteboardType type in item.types) {
  2363. /* NSLog(@"%@", type); */
  2364. const char *mime = uti_to_mime(type);
  2365. if (mime && mime[0] && ![@(mime) hasPrefix:@"text/plain"]) {
  2366. /* NSLog(@"ut: %@ mt: %@ tags: %@", ut, ut.preferredMIMEType, ut.tags); */
  2367. w(mime);
  2368. }
  2369. }
  2370. }
  2371. #undef w
  2372. }
  2373. static void
  2374. get_text_plain(GLFWclipboardwritedatafun write_data, void *object) {
  2375. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2376. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  2377. NSArray* objs = [pasteboard readObjectsForClasses:@[[NSURL class], [NSString class]] options:options];
  2378. bool found = false;
  2379. if (objs) {
  2380. const NSUInteger count = [objs count];
  2381. if (count) {
  2382. NSMutableData *path_list = [NSMutableData dataWithCapacity:4096]; // auto-released
  2383. NSMutableData *text_list = [NSMutableData dataWithCapacity:4096]; // auto-released
  2384. for (NSUInteger i = 0; i < count; i++) {
  2385. id obj = objs[i];
  2386. if ([obj isKindOfClass:[NSURL class]]) {
  2387. NSURL *url = (NSURL*)obj;
  2388. if (url.fileURL && url.fileSystemRepresentation) {
  2389. if ([path_list length] > 0) [path_list appendBytes:"\n" length:1];
  2390. [path_list appendBytes:url.fileSystemRepresentation length:strlen(url.fileSystemRepresentation)];
  2391. }
  2392. } else if ([obj isKindOfClass:[NSString class]]) {
  2393. if ([text_list length] > 0) [text_list appendBytes:"\n" length:1];
  2394. [text_list appendData:[obj dataUsingEncoding:NSUTF8StringEncoding]];
  2395. }
  2396. }
  2397. const NSMutableData *text = nil;
  2398. if (path_list.length > 0) text = path_list;
  2399. else if (text_list.length > 0) text = text_list;
  2400. if (text) {
  2401. found = true;
  2402. write_data(object, text.mutableBytes, text.length);
  2403. }
  2404. }
  2405. }
  2406. if (!found) _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to retrieve text/plain from pasteboard");
  2407. }
  2408. void
  2409. _glfwPlatformGetClipboard(GLFWClipboardType clipboard_type, const char* mime_type, GLFWclipboardwritedatafun write_data, void *object) {
  2410. if (clipboard_type != GLFW_CLIPBOARD) return;
  2411. if (mime_type == NULL) {
  2412. list_clipboard_mimetypes(write_data, object);
  2413. return;
  2414. }
  2415. if (strcmp(mime_type, "text/plain") == 0) {
  2416. get_text_plain(write_data, object);
  2417. return;
  2418. }
  2419. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2420. /* NSLog(@"mime: %s uti: %@", mime_type, mime_to_uti(mime_type)); */
  2421. NSPasteboardType t = [pasteboard availableTypeFromArray:@[mime_to_uti(mime_type)]];
  2422. /* NSLog(@"available type: %@", t); */
  2423. if (t != nil) {
  2424. NSData *data = [pasteboard dataForType:t]; // auto-released
  2425. /* NSLog(@"data: %@", data); */
  2426. if (data != nil && data.length > 0) {
  2427. write_data(object, data.bytes, data.length);
  2428. }
  2429. }
  2430. }
  2431. static NSMutableData*
  2432. get_clipboard_data(const _GLFWClipboardData *cd, const char *mime) {
  2433. NSMutableData *ans = [NSMutableData dataWithCapacity:8192];
  2434. if (ans == nil) return nil;
  2435. GLFWDataChunk chunk = cd->get_data(mime, NULL, cd->ctype);
  2436. void *iter = chunk.iter;
  2437. if (!iter) return ans;
  2438. while (true) {
  2439. chunk = cd->get_data(mime, iter, cd->ctype);
  2440. if (!chunk.sz) break;
  2441. [ans appendBytes:chunk.data length:chunk.sz];
  2442. if (chunk.free) chunk.free((void*)chunk.free_data);
  2443. }
  2444. cd->get_data(NULL, iter, cd->ctype);
  2445. return ans;
  2446. }
  2447. void
  2448. _glfwPlatformSetClipboard(GLFWClipboardType t) {
  2449. if (t != GLFW_CLIPBOARD) return;
  2450. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  2451. NSMutableArray<NSPasteboardType> *ptypes = [NSMutableArray arrayWithCapacity:_glfw.clipboard.num_mime_types]; // auto-released
  2452. for (size_t i = 0; i < _glfw.clipboard.num_mime_types; i++) {
  2453. [ptypes addObject:mime_to_uti(_glfw.clipboard.mime_types[i])];
  2454. }
  2455. [pasteboard declareTypes:ptypes owner:nil];
  2456. for (size_t i = 0; i < _glfw.clipboard.num_mime_types; i++) {
  2457. NSMutableData *data = get_clipboard_data(&_glfw.clipboard, _glfw.clipboard.mime_types[i]); // auto-released
  2458. /* NSLog(@"putting data: %@ for: %s with UTI: %@", data, _glfw.clipboard.mime_types[i], ptypes[i]); */
  2459. if (data != nil) [pasteboard setData:data forType:ptypes[i]];
  2460. }
  2461. }
  2462. // }}}
  2463. EGLenum _glfwPlatformGetEGLPlatform(EGLint** attribs)
  2464. {
  2465. if (_glfw.egl.ANGLE_platform_angle)
  2466. {
  2467. int type = 0;
  2468. if (_glfw.egl.ANGLE_platform_angle_opengl)
  2469. {
  2470. if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_OPENGL)
  2471. type = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE;
  2472. }
  2473. if (_glfw.egl.ANGLE_platform_angle_metal)
  2474. {
  2475. if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_METAL)
  2476. type = EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE;
  2477. }
  2478. if (type)
  2479. {
  2480. *attribs = calloc(3, sizeof(EGLint));
  2481. (*attribs)[0] = EGL_PLATFORM_ANGLE_TYPE_ANGLE;
  2482. (*attribs)[1] = type;
  2483. (*attribs)[2] = EGL_NONE;
  2484. return EGL_PLATFORM_ANGLE_ANGLE;
  2485. }
  2486. }
  2487. return 0;
  2488. }
  2489. EGLNativeDisplayType _glfwPlatformGetEGLNativeDisplay(void)
  2490. {
  2491. return EGL_DEFAULT_DISPLAY;
  2492. }
  2493. EGLNativeWindowType _glfwPlatformGetEGLNativeWindow(_GLFWwindow* window)
  2494. {
  2495. return window->ns.layer;
  2496. }
  2497. void _glfwPlatformGetRequiredInstanceExtensions(char** extensions)
  2498. {
  2499. if (_glfw.vk.KHR_surface && _glfw.vk.EXT_metal_surface)
  2500. {
  2501. extensions[0] = "VK_KHR_surface";
  2502. extensions[1] = "VK_EXT_metal_surface";
  2503. }
  2504. else if (_glfw.vk.KHR_surface && _glfw.vk.MVK_macos_surface)
  2505. {
  2506. extensions[0] = "VK_KHR_surface";
  2507. extensions[1] = "VK_MVK_macos_surface";
  2508. }
  2509. }
  2510. int _glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance UNUSED,
  2511. VkPhysicalDevice device UNUSED,
  2512. uint32_t queuefamily UNUSED)
  2513. {
  2514. return true;
  2515. }
  2516. VkResult _glfwPlatformCreateWindowSurface(VkInstance instance,
  2517. _GLFWwindow* window,
  2518. const VkAllocationCallbacks* allocator,
  2519. VkSurfaceKHR* surface)
  2520. {
  2521. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101100
  2522. // HACK: Dynamically load Core Animation to avoid adding an extra
  2523. // dependency for the majority who don't use MoltenVK
  2524. NSBundle* bundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/QuartzCore.framework"];
  2525. if (!bundle)
  2526. {
  2527. _glfwInputError(GLFW_PLATFORM_ERROR,
  2528. "Cocoa: Failed to find QuartzCore.framework");
  2529. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2530. }
  2531. // NOTE: Create the layer here as makeBackingLayer should not return nil
  2532. window->ns.layer = [[bundle classNamed:@"CAMetalLayer"] layer];
  2533. if (!window->ns.layer)
  2534. {
  2535. _glfwInputError(GLFW_PLATFORM_ERROR,
  2536. "Cocoa: Failed to create layer for view");
  2537. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2538. }
  2539. if (window->ns.retina)
  2540. [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]];
  2541. [window->ns.view setLayer:window->ns.layer];
  2542. [window->ns.view setWantsLayer:YES];
  2543. VkResult err;
  2544. if (_glfw.vk.EXT_metal_surface)
  2545. {
  2546. VkMetalSurfaceCreateInfoEXT sci;
  2547. PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT;
  2548. vkCreateMetalSurfaceEXT = (PFN_vkCreateMetalSurfaceEXT)
  2549. vkGetInstanceProcAddr(instance, "vkCreateMetalSurfaceEXT");
  2550. if (!vkCreateMetalSurfaceEXT)
  2551. {
  2552. _glfwInputError(GLFW_API_UNAVAILABLE,
  2553. "Cocoa: Vulkan instance missing VK_EXT_metal_surface extension");
  2554. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2555. }
  2556. memset(&sci, 0, sizeof(sci));
  2557. sci.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
  2558. sci.pLayer = window->ns.layer;
  2559. err = vkCreateMetalSurfaceEXT(instance, &sci, allocator, surface);
  2560. }
  2561. else
  2562. {
  2563. VkMacOSSurfaceCreateInfoMVK sci;
  2564. PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK;
  2565. vkCreateMacOSSurfaceMVK = (PFN_vkCreateMacOSSurfaceMVK)
  2566. vkGetInstanceProcAddr(instance, "vkCreateMacOSSurfaceMVK");
  2567. if (!vkCreateMacOSSurfaceMVK)
  2568. {
  2569. _glfwInputError(GLFW_API_UNAVAILABLE,
  2570. "Cocoa: Vulkan instance missing VK_MVK_macos_surface extension");
  2571. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2572. }
  2573. memset(&sci, 0, sizeof(sci));
  2574. sci.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
  2575. sci.pView = window->ns.view;
  2576. err = vkCreateMacOSSurfaceMVK(instance, &sci, allocator, surface);
  2577. }
  2578. if (err)
  2579. {
  2580. _glfwInputError(GLFW_PLATFORM_ERROR,
  2581. "Cocoa: Failed to create Vulkan surface: %s",
  2582. _glfwGetVulkanResultString(err));
  2583. }
  2584. return err;
  2585. #else
  2586. return VK_ERROR_EXTENSION_NOT_PRESENT;
  2587. #endif
  2588. }
  2589. int
  2590. _glfwPlatformSetWindowBlur(_GLFWwindow *window, int radius) {
  2591. int orig = window->ns.blur_radius;
  2592. if (radius > -1 && radius != window->ns.blur_radius) {
  2593. extern OSStatus CGSSetWindowBackgroundBlurRadius(void* connection, NSInteger windowNumber, int radius);
  2594. extern void* CGSDefaultConnectionForThread(void);
  2595. CGSSetWindowBackgroundBlurRadius(CGSDefaultConnectionForThread(), [window->ns.object windowNumber], radius);
  2596. window->ns.blur_radius = radius;
  2597. }
  2598. return orig;
  2599. }
  2600. //////////////////////////////////////////////////////////////////////////
  2601. ////// GLFW native API //////
  2602. //////////////////////////////////////////////////////////////////////////
  2603. GLFWAPI id glfwGetCocoaWindow(GLFWwindow* handle)
  2604. {
  2605. _GLFWwindow* window = (_GLFWwindow*) handle;
  2606. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2607. return window->ns.object;
  2608. }
  2609. GLFWAPI GLFWcocoatextinputfilterfun glfwSetCocoaTextInputFilter(GLFWwindow *handle, GLFWcocoatextinputfilterfun callback) {
  2610. _GLFWwindow* window = (_GLFWwindow*) handle;
  2611. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2612. GLFWcocoatextinputfilterfun previous = window->ns.textInputFilterCallback;
  2613. window->ns.textInputFilterCallback = callback;
  2614. return previous;
  2615. }
  2616. GLFWAPI GLFWhandleurlopen glfwSetCocoaURLOpenCallback(GLFWhandleurlopen callback) {
  2617. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2618. GLFWhandleurlopen prev = _glfw.ns.url_open_callback;
  2619. _glfw.ns.url_open_callback = callback;
  2620. return prev;
  2621. }
  2622. GLFWAPI GLFWcocoatogglefullscreenfun glfwSetCocoaToggleFullscreenIntercept(GLFWwindow *handle, GLFWcocoatogglefullscreenfun callback) {
  2623. _GLFWwindow* window = (_GLFWwindow*) handle;
  2624. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  2625. GLFWcocoatogglefullscreenfun previous = window->ns.toggleFullscreenCallback;
  2626. window->ns.toggleFullscreenCallback = callback;
  2627. return previous;
  2628. }
  2629. GLFWAPI void glfwCocoaRequestRenderFrame(GLFWwindow *w, GLFWcocoarenderframefun callback) {
  2630. requestRenderFrame((_GLFWwindow*)w, callback);
  2631. }
  2632. GLFWAPI GLFWcocoarenderframefun glfwCocoaSetWindowResizeCallback(GLFWwindow *w, GLFWcocoarenderframefun cb) {
  2633. _GLFWwindow* window = (_GLFWwindow*)w;
  2634. GLFWcocoarenderframefun current = window->ns.resizeCallback;
  2635. window->ns.resizeCallback = cb;
  2636. return current;
  2637. }
  2638. 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 {
  2639. _GLFWwindow* window = (_GLFWwindow*)w;
  2640. const bool is_transparent = ![window->ns.object isOpaque];
  2641. if (!is_transparent) { background_opacity = 1.0; background_blur = 0; }
  2642. NSColor *background = nil;
  2643. NSAppearance *appearance = nil;
  2644. bool titlebar_transparent = false;
  2645. const NSWindowStyleMask current_style_mask = [window->ns.object styleMask];
  2646. const bool in_fullscreen = ((current_style_mask & NSWindowStyleMaskFullScreen) != 0) || window->ns.in_traditional_fullscreen;
  2647. NSAppearance *light_appearance = is_transparent ? [NSAppearance appearanceNamed:NSAppearanceNameVibrantLight] : [NSAppearance appearanceNamed:NSAppearanceNameAqua];
  2648. NSAppearance *dark_appearance = is_transparent ? [NSAppearance appearanceNamed:NSAppearanceNameVibrantDark] : [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
  2649. if (use_system_color || background_opacity < 1.0) {
  2650. if (is_transparent) {
  2651. // prevent blurring of shadows at window corners with desktop background by setting a low alpha background
  2652. background = background_blur > 0 ? [NSColor colorWithWhite: 0 alpha: 0.001f] : [NSColor clearColor];
  2653. } else background = [NSColor windowBackgroundColor];
  2654. switch (system_color) {
  2655. case 1:
  2656. appearance = light_appearance; break;
  2657. case 2:
  2658. appearance = dark_appearance; break;
  2659. }
  2660. } else {
  2661. // set a background color and make the title bar transparent so the background color is visible
  2662. double red = ((color >> 16) & 0xFF) / 255.0;
  2663. double green = ((color >> 8) & 0xFF) / 255.0;
  2664. double blue = (color & 0xFF) / 255.0;
  2665. double luma = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
  2666. background = [NSColor colorWithSRGBRed:red green:green blue:blue alpha:1.f];
  2667. appearance = luma < 0.5 ? dark_appearance : light_appearance;
  2668. titlebar_transparent = true;
  2669. }
  2670. [window->ns.object setBackgroundColor:background];
  2671. [window->ns.object setAppearance:appearance];
  2672. _glfwPlatformSetWindowBlur(window, background_blur);
  2673. bool has_shadow = false;
  2674. const char *decorations_desc = "full";
  2675. window->ns.titlebar_hidden = false;
  2676. switch (hide_window_decorations) {
  2677. case 1:
  2678. decorations_desc = "none";
  2679. window->decorated = false;
  2680. break;
  2681. case 2:
  2682. decorations_desc = "no-titlebar";
  2683. window->decorated = true;
  2684. has_shadow = true;
  2685. titlebar_transparent = true;
  2686. window->ns.titlebar_hidden = true;
  2687. show_text_in_titlebar = false;
  2688. break;
  2689. case 4:
  2690. decorations_desc = "no-titlebar-and-no-corners";
  2691. window->decorated = false;
  2692. has_shadow = true;
  2693. break;
  2694. default:
  2695. window->decorated = true;
  2696. has_shadow = true;
  2697. break;
  2698. }
  2699. // shadow causes burn-in/ghosting because cocoa doesnt invalidate it on OS window resize/minimize/restore.
  2700. // https://github.com/kovidgoyal/kitty/issues/6439
  2701. if (is_transparent) has_shadow = false;
  2702. bool hide_titlebar_buttons = !in_fullscreen && window->ns.titlebar_hidden;
  2703. [window->ns.object setTitlebarAppearsTransparent:titlebar_transparent];
  2704. [window->ns.object setHasShadow:has_shadow];
  2705. [window->ns.object setTitleVisibility:(show_text_in_titlebar) ? NSWindowTitleVisible : NSWindowTitleHidden];
  2706. NSColorSpace *cs = nil;
  2707. switch (color_space) {
  2708. case SRGB_COLORSPACE: cs = [NSColorSpace sRGBColorSpace]; break;
  2709. case DISPLAY_P3_COLORSPACE: cs = [NSColorSpace displayP3ColorSpace]; break;
  2710. case DEFAULT_COLORSPACE: cs = nil; break; // using deviceRGBColorSpace causes a hang when transitioning to fullscreen
  2711. }
  2712. window->resizable = resizable;
  2713. debug(
  2714. "Window Chrome state:\n\tbackground: %s\n\tappearance: %s color_space: %s\n\t"
  2715. "blur: %d has_shadow: %d resizable: %d decorations: %s (%d)\n\t"
  2716. "titlebar: transparent: %d title_visibility: %d hidden: %d buttons_hidden: %d"
  2717. "\n",
  2718. background ? [background.description UTF8String] : "<nil>",
  2719. appearance ? [appearance.name UTF8String] : "<nil>",
  2720. cs ? (cs.localizedName ? [cs.localizedName UTF8String] : [cs.description UTF8String]) : "<nil>",
  2721. background_blur, has_shadow, resizable, decorations_desc, window->decorated, titlebar_transparent,
  2722. show_text_in_titlebar, window->ns.titlebar_hidden, hide_titlebar_buttons
  2723. );
  2724. [window->ns.object setColorSpace:cs];
  2725. [[window->ns.object standardWindowButton: NSWindowCloseButton] setHidden:hide_titlebar_buttons];
  2726. [[window->ns.object standardWindowButton: NSWindowMiniaturizeButton] setHidden:hide_titlebar_buttons];
  2727. [[window->ns.object standardWindowButton: NSWindowZoomButton] setHidden:hide_titlebar_buttons];
  2728. // Apple throws a hissy fit if one attempts to clear the value of NSWindowStyleMaskFullScreen outside of a full screen transition
  2729. // event. See https://github.com/kovidgoyal/kitty/issues/7106
  2730. NSWindowStyleMask fsmask = current_style_mask & NSWindowStyleMaskFullScreen;
  2731. window->ns.pre_full_screen_style_mask = getStyleMask(window);
  2732. if (in_fullscreen && window->ns.in_traditional_fullscreen) {
  2733. [window->ns.object setStyleMask:NSWindowStyleMaskBorderless];
  2734. } else {
  2735. [window->ns.object setStyleMask:window->ns.pre_full_screen_style_mask | fsmask];
  2736. }
  2737. // HACK: Changing the style mask can cause the first responder to be cleared
  2738. [window->ns.object makeFirstResponder:window->ns.view];
  2739. }}
  2740. GLFWAPI GLFWColorScheme glfwGetCurrentSystemColorTheme(bool query_if_unintialized) {
  2741. (void)query_if_unintialized;
  2742. int theme_type = 0;
  2743. NSAppearance *changedAppearance = NSApp.effectiveAppearance;
  2744. NSAppearanceName newAppearance = [changedAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
  2745. if([newAppearance isEqualToString:NSAppearanceNameDarkAqua]){
  2746. theme_type = 1;
  2747. } else {
  2748. theme_type = 2;
  2749. }
  2750. return theme_type;
  2751. }
  2752. GLFWAPI uint32_t
  2753. glfwGetCocoaKeyEquivalent(uint32_t glfw_key, int glfw_mods, int *cocoa_mods) {
  2754. *cocoa_mods = 0;
  2755. if (glfw_mods & GLFW_MOD_SHIFT)
  2756. *cocoa_mods |= NSEventModifierFlagShift;
  2757. if (glfw_mods & GLFW_MOD_CONTROL)
  2758. *cocoa_mods |= NSEventModifierFlagControl;
  2759. if (glfw_mods & GLFW_MOD_ALT)
  2760. *cocoa_mods |= NSEventModifierFlagOption;
  2761. if (glfw_mods & GLFW_MOD_SUPER)
  2762. *cocoa_mods |= NSEventModifierFlagCommand;
  2763. if (glfw_mods & GLFW_MOD_CAPS_LOCK)
  2764. *cocoa_mods |= NSEventModifierFlagCapsLock;
  2765. return _glfwPlatformGetNativeKeyForKey(glfw_key);
  2766. }
  2767. //////////////////////////////////////////////////////////////////////////
  2768. ////// GLFW internal API //////
  2769. //////////////////////////////////////////////////////////////////////////
  2770. // Transforms a y-coordinate between the CG display and NS screen spaces
  2771. //
  2772. float _glfwTransformYNS(float y)
  2773. {
  2774. return CGDisplayBounds(CGMainDisplayID()).size.height - y - 1;
  2775. }
  2776. void _glfwCocoaPostEmptyEvent(void) {
  2777. NSEvent* event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
  2778. location:NSMakePoint(0, 0)
  2779. modifierFlags:0
  2780. timestamp:0
  2781. windowNumber:0
  2782. context:nil
  2783. subtype:0
  2784. data1:0
  2785. data2:0];
  2786. [NSApp postEvent:event atStart:YES];
  2787. }