cocoa_window.m 118 KB

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