cocoa_window.m 124 KB

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