Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_mac_NSViewComponentPeer.mm 108KB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. @interface NSEvent (DeviceDelta)
  19. - (float)deviceDeltaX;
  20. - (float)deviceDeltaY;
  21. @end
  22. //==============================================================================
  23. namespace juce
  24. {
  25. using AppFocusChangeCallback = void (*)();
  26. extern AppFocusChangeCallback appFocusChangeCallback;
  27. using CheckEventBlockedByModalComps = bool (*) (NSEvent*);
  28. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  29. //==============================================================================
  30. static void resetTrackingArea (NSView* view)
  31. {
  32. const auto trackingAreas = [view trackingAreas];
  33. jassert ([trackingAreas count] <= 1);
  34. for (NSTrackingArea* area in trackingAreas)
  35. [view removeTrackingArea: area];
  36. const auto options = NSTrackingMouseEnteredAndExited
  37. | NSTrackingMouseMoved
  38. | NSTrackingEnabledDuringMouseDrag
  39. | NSTrackingActiveAlways
  40. | NSTrackingInVisibleRect;
  41. const NSUniquePtr<NSTrackingArea> trackingArea { [[NSTrackingArea alloc] initWithRect: [view bounds]
  42. options: options
  43. owner: view
  44. userInfo: nil] };
  45. [view addTrackingArea: trackingArea.get()];
  46. }
  47. static constexpr int translateVirtualToAsciiKeyCode (int keyCode) noexcept
  48. {
  49. switch (keyCode)
  50. {
  51. // The virtual keycodes are from HIToolbox/Events.h
  52. case 0x00: return 'A';
  53. case 0x01: return 'S';
  54. case 0x02: return 'D';
  55. case 0x03: return 'F';
  56. case 0x04: return 'H';
  57. case 0x05: return 'G';
  58. case 0x06: return 'Z';
  59. case 0x07: return 'X';
  60. case 0x08: return 'C';
  61. case 0x09: return 'V';
  62. case 0x0B: return 'B';
  63. case 0x0C: return 'Q';
  64. case 0x0D: return 'W';
  65. case 0x0E: return 'E';
  66. case 0x0F: return 'R';
  67. case 0x10: return 'Y';
  68. case 0x11: return 'T';
  69. case 0x12: return '1';
  70. case 0x13: return '2';
  71. case 0x14: return '3';
  72. case 0x15: return '4';
  73. case 0x16: return '6';
  74. case 0x17: return '5';
  75. case 0x18: return '='; // kVK_ANSI_Equal
  76. case 0x19: return '9';
  77. case 0x1A: return '7';
  78. case 0x1B: return '-'; // kVK_ANSI_Minus
  79. case 0x1C: return '8';
  80. case 0x1D: return '0';
  81. case 0x1E: return ']'; // kVK_ANSI_RightBracket
  82. case 0x1F: return 'O';
  83. case 0x20: return 'U';
  84. case 0x21: return '['; // kVK_ANSI_LeftBracket
  85. case 0x22: return 'I';
  86. case 0x23: return 'P';
  87. case 0x25: return 'L';
  88. case 0x26: return 'J';
  89. case 0x27: return '"'; // kVK_ANSI_Quote
  90. case 0x28: return 'K';
  91. case 0x29: return ';'; // kVK_ANSI_Semicolon
  92. case 0x2A: return '\\'; // kVK_ANSI_Backslash
  93. case 0x2B: return ','; // kVK_ANSI_Comma
  94. case 0x2C: return '/'; // kVK_ANSI_Slash
  95. case 0x2D: return 'N';
  96. case 0x2E: return 'M';
  97. case 0x2F: return '.'; // kVK_ANSI_Period
  98. case 0x32: return '`'; // kVK_ANSI_Grave
  99. default: return keyCode;
  100. }
  101. }
  102. constexpr int extendedKeyModifier = 0x30000;
  103. //==============================================================================
  104. class NSViewComponentPeer : public ComponentPeer
  105. {
  106. public:
  107. NSViewComponentPeer (Component& comp, const int windowStyleFlags, NSView* viewToAttachTo)
  108. : ComponentPeer (comp, windowStyleFlags),
  109. safeComponent (&comp),
  110. isSharedWindow (viewToAttachTo != nil),
  111. lastRepaintTime (Time::getMillisecondCounter())
  112. {
  113. appFocusChangeCallback = appFocusChanged;
  114. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  115. auto r = makeNSRect (component.getLocalBounds());
  116. view = [createViewInstance() initWithFrame: r];
  117. setOwner (view, this);
  118. [view registerForDraggedTypes: getSupportedDragTypes()];
  119. resetTrackingArea (view);
  120. notificationCenter = [NSNotificationCenter defaultCenter];
  121. [notificationCenter addObserver: view
  122. selector: frameChangedSelector
  123. name: NSViewFrameDidChangeNotification
  124. object: view];
  125. [view setPostsFrameChangedNotifications: YES];
  126. #if USE_COREGRAPHICS_RENDERING
  127. #if JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  128. if (@available (macOS 10.14, *))
  129. metalRenderer = std::make_unique<CoreGraphicsMetalLayerRenderer<NSView>> (view, getComponent());
  130. #endif
  131. if ((windowStyleFlags & ComponentPeer::windowRequiresSynchronousCoreGraphicsRendering) == 0)
  132. {
  133. if (@available (macOS 10.8, *))
  134. {
  135. [view setWantsLayer: YES];
  136. [[view layer] setDrawsAsynchronously: YES];
  137. }
  138. }
  139. #endif
  140. createCVDisplayLink();
  141. if (isSharedWindow)
  142. {
  143. window = [viewToAttachTo window];
  144. [viewToAttachTo addSubview: view];
  145. }
  146. else
  147. {
  148. r.origin.x = (CGFloat) component.getX();
  149. r.origin.y = (CGFloat) component.getY();
  150. r = flippedScreenRect (r);
  151. window = [createWindowInstance() initWithContentRect: r
  152. styleMask: getNSWindowStyleMask (windowStyleFlags)
  153. backing: NSBackingStoreBuffered
  154. defer: YES];
  155. setOwner (window, this);
  156. if (@available (macOS 10.10, *))
  157. [window setAccessibilityElement: YES];
  158. [window orderOut: nil];
  159. [window setDelegate: (id<NSWindowDelegate>) window];
  160. [window setOpaque: component.isOpaque()];
  161. if (! [window isOpaque])
  162. [window setBackgroundColor: [NSColor clearColor]];
  163. if (@available (macOS 10.9, *))
  164. [view setAppearance: [NSAppearance appearanceNamed: NSAppearanceNameAqua]];
  165. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  166. if (component.isAlwaysOnTop())
  167. setAlwaysOnTop (true);
  168. [window setContentView: view];
  169. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  170. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  171. [window setReleasedWhenClosed: YES];
  172. [window retain];
  173. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  174. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  175. setCollectionBehaviour (false);
  176. [window setRestorable: NO];
  177. #if defined (MAC_OS_X_VERSION_10_12) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12)
  178. if (@available (macOS 10.12, *))
  179. [window setTabbingMode: NSWindowTabbingModeDisallowed];
  180. #endif
  181. [notificationCenter addObserver: view
  182. selector: frameChangedSelector
  183. name: NSWindowDidMoveNotification
  184. object: window];
  185. [notificationCenter addObserver: view
  186. selector: frameChangedSelector
  187. name: NSWindowDidMiniaturizeNotification
  188. object: window];
  189. [notificationCenter addObserver: view
  190. selector: @selector (windowWillMiniaturize:)
  191. name: NSWindowWillMiniaturizeNotification
  192. object: window];
  193. [notificationCenter addObserver: view
  194. selector: @selector (windowDidDeminiaturize:)
  195. name: NSWindowDidDeminiaturizeNotification
  196. object: window];
  197. }
  198. auto alpha = component.getAlpha();
  199. if (alpha < 1.0f)
  200. setAlpha (alpha);
  201. setTitle (component.getName());
  202. getNativeRealtimeModifiers = []
  203. {
  204. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  205. NSViewComponentPeer::updateModifiers ([NSEvent modifierFlags]);
  206. return ModifierKeys::currentModifiers;
  207. };
  208. }
  209. ~NSViewComponentPeer() override
  210. {
  211. CVDisplayLinkStop (displayLink);
  212. dispatch_source_cancel (displaySource);
  213. [notificationCenter removeObserver: view];
  214. setOwner (view, nullptr);
  215. if ([view superview] != nil)
  216. {
  217. redirectWillMoveToWindow (nullptr);
  218. [view removeFromSuperview];
  219. }
  220. if (! isSharedWindow)
  221. {
  222. setOwner (window, nullptr);
  223. [window setContentView: nil];
  224. [window close];
  225. [window release];
  226. }
  227. [view release];
  228. }
  229. //==============================================================================
  230. void* getNativeHandle() const override { return view; }
  231. void setVisible (bool shouldBeVisible) override
  232. {
  233. if (isSharedWindow)
  234. {
  235. if (shouldBeVisible)
  236. [view setHidden: false];
  237. else if ([window firstResponder] != view || ([window firstResponder] == view && [window makeFirstResponder: nil]))
  238. [view setHidden: true];
  239. }
  240. else
  241. {
  242. if (shouldBeVisible)
  243. {
  244. ++insideToFrontCall;
  245. [window orderFront: nil];
  246. --insideToFrontCall;
  247. handleBroughtToFront();
  248. }
  249. else
  250. {
  251. [window orderOut: nil];
  252. }
  253. }
  254. }
  255. void setTitle (const String& title) override
  256. {
  257. JUCE_AUTORELEASEPOOL
  258. {
  259. if (! isSharedWindow)
  260. [window setTitle: juceStringToNS (title)];
  261. }
  262. }
  263. bool setDocumentEditedStatus (bool edited) override
  264. {
  265. if (! hasNativeTitleBar())
  266. return false;
  267. [window setDocumentEdited: edited];
  268. return true;
  269. }
  270. void setRepresentedFile (const File& file) override
  271. {
  272. if (! isSharedWindow)
  273. {
  274. [window setRepresentedFilename: juceStringToNS (file != File()
  275. ? file.getFullPathName()
  276. : String())];
  277. windowRepresentsFile = (file != File());
  278. }
  279. }
  280. void setBounds (const Rectangle<int>& newBounds, bool) override
  281. {
  282. auto r = makeNSRect (newBounds);
  283. auto oldViewSize = [view frame].size;
  284. if (isSharedWindow)
  285. {
  286. [view setFrame: r];
  287. }
  288. else
  289. {
  290. // Repaint behaviour of setFrame seemed to change in 10.11, and the drawing became synchronous,
  291. // causing performance issues. But sending an async update causes flickering in older versions,
  292. // hence this version check to use the old behaviour on pre 10.11 machines
  293. static bool isPre10_11 = SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_10;
  294. [window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
  295. display: isPre10_11];
  296. }
  297. if (oldViewSize.width != r.size.width || oldViewSize.height != r.size.height)
  298. {
  299. #if USE_COREGRAPHICS_RENDERING
  300. numFramesToSkipMetalRenderer = 5;
  301. #endif
  302. [view setNeedsDisplay: true];
  303. }
  304. }
  305. Rectangle<int> getBounds (const bool global) const
  306. {
  307. auto r = [view frame];
  308. NSWindow* viewWindow = [view window];
  309. if (global && viewWindow != nil)
  310. {
  311. r = [[view superview] convertRect: r toView: nil];
  312. r = [viewWindow convertRectToScreen: r];
  313. r = flippedScreenRect (r);
  314. }
  315. return convertToRectInt (r);
  316. }
  317. Rectangle<int> getBounds() const override
  318. {
  319. return getBounds (! isSharedWindow);
  320. }
  321. Point<float> localToGlobal (Point<float> relativePosition) override
  322. {
  323. return relativePosition + getBounds (true).getPosition().toFloat();
  324. }
  325. using ComponentPeer::localToGlobal;
  326. Point<float> globalToLocal (Point<float> screenPosition) override
  327. {
  328. return screenPosition - getBounds (true).getPosition().toFloat();
  329. }
  330. using ComponentPeer::globalToLocal;
  331. void setAlpha (float newAlpha) override
  332. {
  333. if (isSharedWindow)
  334. [view setAlphaValue: (CGFloat) newAlpha];
  335. else
  336. [window setAlphaValue: (CGFloat) newAlpha];
  337. }
  338. void setMinimised (bool shouldBeMinimised) override
  339. {
  340. if (! isSharedWindow)
  341. {
  342. if (shouldBeMinimised)
  343. [window miniaturize: nil];
  344. else
  345. [window deminiaturize: nil];
  346. }
  347. }
  348. bool isMinimised() const override
  349. {
  350. return [window isMiniaturized];
  351. }
  352. NSWindowCollectionBehavior getCollectionBehavior (bool forceFullScreen) const
  353. {
  354. if (forceFullScreen)
  355. return NSWindowCollectionBehaviorFullScreenPrimary;
  356. // Some SDK versions don't define NSWindowCollectionBehaviorFullScreenNone
  357. constexpr auto fullScreenNone = (NSUInteger) (1 << 9);
  358. return (getStyleFlags() & (windowHasMaximiseButton | windowIsResizable)) == (windowHasMaximiseButton | windowIsResizable)
  359. ? NSWindowCollectionBehaviorFullScreenPrimary
  360. : fullScreenNone;
  361. }
  362. void setCollectionBehaviour (bool forceFullScreen) const
  363. {
  364. [window setCollectionBehavior: getCollectionBehavior (forceFullScreen)];
  365. }
  366. void setFullScreen (bool shouldBeFullScreen) override
  367. {
  368. if (isSharedWindow)
  369. return;
  370. if (shouldBeFullScreen)
  371. setCollectionBehaviour (true);
  372. if (isMinimised())
  373. setMinimised (false);
  374. if (shouldBeFullScreen != isFullScreen())
  375. [window toggleFullScreen: nil];
  376. }
  377. bool isFullScreen() const override
  378. {
  379. return ([window styleMask] & NSWindowStyleMaskFullScreen) != 0;
  380. }
  381. bool isKioskMode() const override
  382. {
  383. return isFullScreen() && ComponentPeer::isKioskMode();
  384. }
  385. static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
  386. {
  387. if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
  388. return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
  389. return true;
  390. }
  391. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  392. {
  393. NSRect viewFrame = [view frame];
  394. if (! (isPositiveAndBelow (localPos.getX(), viewFrame.size.width)
  395. && isPositiveAndBelow (localPos.getY(), viewFrame.size.height)))
  396. return false;
  397. if (! SystemStats::isRunningInAppExtensionSandbox())
  398. {
  399. if (NSWindow* const viewWindow = [view window])
  400. {
  401. NSRect windowFrame = [viewWindow frame];
  402. NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, localPos.y) toView: nil];
  403. NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
  404. windowFrame.origin.y + windowPoint.y);
  405. if (! isWindowAtPoint (viewWindow, screenPoint))
  406. return false;
  407. }
  408. }
  409. NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
  410. viewFrame.origin.y + localPos.getY())];
  411. return trueIfInAChildWindow ? (v != nil)
  412. : (v == view);
  413. }
  414. OptionalBorderSize getFrameSizeIfPresent() const override
  415. {
  416. if (! isSharedWindow)
  417. {
  418. BorderSize<int> b;
  419. NSRect v = [view convertRect: [view frame] toView: nil];
  420. NSRect w = [window frame];
  421. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  422. b.setBottom ((int) v.origin.y);
  423. b.setLeft ((int) v.origin.x);
  424. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  425. return OptionalBorderSize { b };
  426. }
  427. return {};
  428. }
  429. BorderSize<int> getFrameSize() const override
  430. {
  431. if (const auto frameSize = getFrameSizeIfPresent())
  432. return *frameSize;
  433. return {};
  434. }
  435. bool hasNativeTitleBar() const
  436. {
  437. return (getStyleFlags() & windowHasTitleBar) != 0;
  438. }
  439. bool setAlwaysOnTop (bool alwaysOnTop) override
  440. {
  441. if (! isSharedWindow)
  442. {
  443. [window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
  444. : NSFloatingWindowLevel)
  445. : NSNormalWindowLevel];
  446. isAlwaysOnTop = alwaysOnTop;
  447. }
  448. return true;
  449. }
  450. void toFront (bool makeActiveWindow) override
  451. {
  452. if (isSharedWindow)
  453. {
  454. NSView* superview = [view superview];
  455. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  456. const auto isFrontmost = [[subviews lastObject] isEqual: view];
  457. if (! isFrontmost)
  458. {
  459. [view retain];
  460. [subviews removeObject: view];
  461. [subviews addObject: view];
  462. [superview setSubviews: subviews];
  463. [view release];
  464. }
  465. }
  466. if (window != nil && component.isVisible())
  467. {
  468. ++insideToFrontCall;
  469. if (makeActiveWindow)
  470. [window makeKeyAndOrderFront: nil];
  471. else
  472. [window orderFront: nil];
  473. if (insideToFrontCall <= 1)
  474. {
  475. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  476. handleBroughtToFront();
  477. }
  478. --insideToFrontCall;
  479. }
  480. }
  481. void toBehind (ComponentPeer* other) override
  482. {
  483. if (auto* otherPeer = dynamic_cast<NSViewComponentPeer*> (other))
  484. {
  485. if (isSharedWindow)
  486. {
  487. NSView* superview = [view superview];
  488. NSMutableArray* subviews = [NSMutableArray arrayWithArray: [superview subviews]];
  489. const auto otherViewIndex = [subviews indexOfObject: otherPeer->view];
  490. if (otherViewIndex == NSNotFound)
  491. return;
  492. const auto isBehind = [subviews indexOfObject: view] < otherViewIndex;
  493. if (! isBehind)
  494. {
  495. [view retain];
  496. [subviews removeObject: view];
  497. [subviews insertObject: view
  498. atIndex: otherViewIndex];
  499. [superview setSubviews: subviews];
  500. [view release];
  501. }
  502. }
  503. else if (component.isVisible())
  504. {
  505. [window orderWindow: NSWindowBelow
  506. relativeTo: [otherPeer->window windowNumber]];
  507. }
  508. }
  509. else
  510. {
  511. jassertfalse; // wrong type of window?
  512. }
  513. }
  514. void setIcon (const Image& newIcon) override
  515. {
  516. if (! isSharedWindow)
  517. {
  518. // need to set a dummy represented file here to show the file icon (which we then set to the new icon)
  519. if (! windowRepresentsFile)
  520. [window setRepresentedFilename: juceStringToNS (" ")]; // can't just use an empty string for some reason...
  521. auto img = NSUniquePtr<NSImage> { imageToNSImage (ScaledImage (newIcon)) };
  522. [[window standardWindowButton: NSWindowDocumentIconButton] setImage: img.get()];
  523. }
  524. }
  525. StringArray getAvailableRenderingEngines() override
  526. {
  527. StringArray s ("Software Renderer");
  528. #if USE_COREGRAPHICS_RENDERING
  529. s.add ("CoreGraphics Renderer");
  530. #endif
  531. return s;
  532. }
  533. int getCurrentRenderingEngine() const override
  534. {
  535. return usingCoreGraphics ? 1 : 0;
  536. }
  537. void setCurrentRenderingEngine (int index) override
  538. {
  539. #if USE_COREGRAPHICS_RENDERING
  540. if (usingCoreGraphics != (index > 0))
  541. {
  542. usingCoreGraphics = index > 0;
  543. [view setNeedsDisplay: true];
  544. }
  545. #else
  546. ignoreUnused (index);
  547. #endif
  548. }
  549. void redirectMouseDown (NSEvent* ev)
  550. {
  551. if (! Process::isForegroundProcess())
  552. Process::makeForegroundProcess();
  553. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  554. sendMouseEvent (ev);
  555. }
  556. void redirectMouseUp (NSEvent* ev)
  557. {
  558. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  559. sendMouseEvent (ev);
  560. showArrowCursorIfNeeded();
  561. }
  562. void redirectMouseDrag (NSEvent* ev)
  563. {
  564. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  565. sendMouseEvent (ev);
  566. }
  567. void redirectMouseMove (NSEvent* ev)
  568. {
  569. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  570. NSPoint windowPos = [ev locationInWindow];
  571. NSPoint screenPos = [[ev window] convertRectToScreen: NSMakeRect (windowPos.x, windowPos.y, 1.0f, 1.0f)].origin;
  572. if (isWindowAtPoint ([ev window], screenPos))
  573. sendMouseEvent (ev);
  574. else
  575. // moved into another window which overlaps this one, so trigger an exit
  576. handleMouseEvent (MouseInputSource::InputSourceType::mouse, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  577. getMousePressure (ev), MouseInputSource::defaultOrientation, getMouseTime (ev));
  578. showArrowCursorIfNeeded();
  579. }
  580. void redirectMouseEnter (NSEvent* ev)
  581. {
  582. sendMouseEnterExit (ev);
  583. }
  584. void redirectMouseExit (NSEvent* ev)
  585. {
  586. sendMouseEnterExit (ev);
  587. }
  588. static float checkDeviceDeltaReturnValue (float v) noexcept
  589. {
  590. // (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
  591. v *= 0.5f / 256.0f;
  592. return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
  593. }
  594. void redirectMouseWheel (NSEvent* ev)
  595. {
  596. updateModifiers (ev);
  597. MouseWheelDetails wheel;
  598. wheel.deltaX = 0;
  599. wheel.deltaY = 0;
  600. wheel.isReversed = false;
  601. wheel.isSmooth = false;
  602. wheel.isInertial = false;
  603. @try
  604. {
  605. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  606. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  607. wheel.isInertial = ([ev momentumPhase] != NSEventPhaseNone);
  608. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  609. {
  610. if ([ev hasPreciseScrollingDeltas])
  611. {
  612. const float scale = 0.5f / 256.0f;
  613. wheel.deltaX = scale * (float) [ev scrollingDeltaX];
  614. wheel.deltaY = scale * (float) [ev scrollingDeltaY];
  615. wheel.isSmooth = true;
  616. }
  617. }
  618. else if ([ev respondsToSelector: @selector (deviceDeltaX)])
  619. {
  620. wheel.deltaX = checkDeviceDeltaReturnValue ([ev deviceDeltaX]);
  621. wheel.deltaY = checkDeviceDeltaReturnValue ([ev deviceDeltaY]);
  622. }
  623. }
  624. @catch (...)
  625. {}
  626. if (wheel.deltaX == 0.0f && wheel.deltaY == 0.0f)
  627. {
  628. const float scale = 10.0f / 256.0f;
  629. wheel.deltaX = scale * (float) [ev deltaX];
  630. wheel.deltaY = scale * (float) [ev deltaY];
  631. }
  632. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), wheel);
  633. }
  634. void redirectMagnify (NSEvent* ev)
  635. {
  636. const float invScale = 1.0f - (float) [ev magnification];
  637. if (invScale > 0.0f)
  638. handleMagnifyGesture (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
  639. }
  640. void redirectCopy (NSObject*) { handleKeyPress (KeyPress ('c', ModifierKeys (ModifierKeys::commandModifier), 'c')); }
  641. void redirectPaste (NSObject*) { handleKeyPress (KeyPress ('v', ModifierKeys (ModifierKeys::commandModifier), 'v')); }
  642. void redirectCut (NSObject*) { handleKeyPress (KeyPress ('x', ModifierKeys (ModifierKeys::commandModifier), 'x')); }
  643. void redirectSelectAll (NSObject*) { handleKeyPress (KeyPress ('a', ModifierKeys (ModifierKeys::commandModifier), 'a')); }
  644. void redirectWillMoveToWindow (NSWindow* newWindow)
  645. {
  646. if (auto* currentWindow = [view window])
  647. {
  648. [notificationCenter removeObserver: view
  649. name: NSWindowDidMoveNotification
  650. object: currentWindow];
  651. [notificationCenter removeObserver: view
  652. name: NSWindowWillMiniaturizeNotification
  653. object: currentWindow];
  654. [notificationCenter removeObserver: view
  655. name: NSWindowDidBecomeKeyNotification
  656. object: currentWindow];
  657. [notificationCenter removeObserver: view
  658. name: NSWindowDidChangeScreenNotification
  659. object: currentWindow];
  660. }
  661. if (isSharedWindow && [view window] == window && newWindow == nullptr)
  662. {
  663. if (auto* comp = safeComponent.get())
  664. comp->setVisible (false);
  665. }
  666. }
  667. void sendMouseEvent (NSEvent* ev)
  668. {
  669. updateModifiers (ev);
  670. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), ModifierKeys::currentModifiers,
  671. getMousePressure (ev), MouseInputSource::defaultOrientation, getMouseTime (ev));
  672. }
  673. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  674. {
  675. auto unicode = nsStringToJuce ([ev characters]);
  676. auto keyCode = getKeyCodeFromEvent (ev);
  677. #if JUCE_DEBUG_KEYCODES
  678. DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  679. auto unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  680. DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  681. #endif
  682. if (keyCode != 0 || unicode.isNotEmpty())
  683. {
  684. if (isKeyDown)
  685. {
  686. bool used = false;
  687. for (auto u = unicode.getCharPointer(); ! u.isEmpty();)
  688. {
  689. auto textCharacter = u.getAndAdvance();
  690. switch (keyCode)
  691. {
  692. case NSLeftArrowFunctionKey:
  693. case NSRightArrowFunctionKey:
  694. case NSUpArrowFunctionKey:
  695. case NSDownArrowFunctionKey:
  696. case NSPageUpFunctionKey:
  697. case NSPageDownFunctionKey:
  698. case NSEndFunctionKey:
  699. case NSHomeFunctionKey:
  700. case NSDeleteFunctionKey:
  701. textCharacter = 0;
  702. break; // (these all seem to generate unwanted garbage unicode strings)
  703. default:
  704. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0
  705. || (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
  706. textCharacter = 0;
  707. break;
  708. }
  709. used = handleKeyUpOrDown (true) || used;
  710. used = handleKeyPress (keyCode, textCharacter) || used;
  711. }
  712. return used;
  713. }
  714. if (handleKeyUpOrDown (false))
  715. return true;
  716. }
  717. return false;
  718. }
  719. bool redirectKeyDown (NSEvent* ev)
  720. {
  721. // (need to retain this in case a modal loop runs in handleKeyEvent and
  722. // our event object gets lost)
  723. const NSUniquePtr<NSEvent> r ([ev retain]);
  724. updateKeysDown (ev, true);
  725. bool used = handleKeyEvent (ev, true);
  726. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0)
  727. {
  728. // for command keys, the key-up event is thrown away, so simulate one..
  729. updateKeysDown (ev, false);
  730. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  731. }
  732. // (If we're running modally, don't allow unused keystrokes to be passed
  733. // along to other blocked views..)
  734. if (Component::getCurrentlyModalComponent() != nullptr)
  735. used = true;
  736. return used;
  737. }
  738. bool redirectKeyUp (NSEvent* ev)
  739. {
  740. updateKeysDown (ev, false);
  741. return handleKeyEvent (ev, false)
  742. || Component::getCurrentlyModalComponent() != nullptr;
  743. }
  744. void redirectModKeyChange (NSEvent* ev)
  745. {
  746. // (need to retain this in case a modal loop runs and our event object gets lost)
  747. const NSUniquePtr<NSEvent> r ([ev retain]);
  748. keysCurrentlyDown.clear();
  749. handleKeyUpOrDown (true);
  750. updateModifiers (ev);
  751. handleModifierKeysChange();
  752. }
  753. //==============================================================================
  754. void drawRect (NSRect r)
  755. {
  756. if (r.size.width < 1.0f || r.size.height < 1.0f)
  757. return;
  758. auto cg = []
  759. {
  760. if (@available (macOS 10.10, *))
  761. return (CGContextRef) [[NSGraphicsContext currentContext] CGContext];
  762. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  763. return (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  764. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  765. }();
  766. drawRectWithContext (cg, r);
  767. }
  768. void drawRectWithContext (CGContextRef cg, NSRect r)
  769. {
  770. if (! component.isOpaque())
  771. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  772. float displayScale = 1.0f;
  773. NSScreen* screen = [[view window] screen];
  774. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  775. displayScale = (float) screen.backingScaleFactor;
  776. auto invalidateTransparentWindowShadow = [this]
  777. {
  778. // transparent NSWindows with a drop-shadow need to redraw their shadow when the content
  779. // changes to avoid stale shadows being drawn behind the window
  780. if (! isSharedWindow && ! [window isOpaque] && [window hasShadow])
  781. [window invalidateShadow];
  782. };
  783. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  784. // This was a workaround for a CGContext not having a way of finding whether a rectangle
  785. // falls within its clip region. However Apple removed the capability of
  786. // [view getRectsBeingDrawn: ...] sometime around 10.13, so on later versions of macOS
  787. // numRects will always be 1 and you'll need to use a CoreGraphicsMetalLayerRenderer
  788. // to avoid CoreGraphics consolidating disparate rects.
  789. if (usingCoreGraphics && metalRenderer == nullptr)
  790. {
  791. const NSRect* rects = nullptr;
  792. NSInteger numRects = 0;
  793. [view getRectsBeingDrawn: &rects count: &numRects];
  794. if (numRects > 1)
  795. {
  796. for (int i = 0; i < numRects; ++i)
  797. {
  798. NSRect rect = rects[i];
  799. CGContextSaveGState (cg);
  800. CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
  801. renderRect (cg, rect, displayScale);
  802. CGContextRestoreGState (cg);
  803. }
  804. invalidateTransparentWindowShadow();
  805. return;
  806. }
  807. }
  808. #endif
  809. renderRect (cg, r, displayScale);
  810. invalidateTransparentWindowShadow();
  811. }
  812. void renderRect (CGContextRef cg, NSRect r, float displayScale)
  813. {
  814. #if USE_COREGRAPHICS_RENDERING
  815. if (usingCoreGraphics)
  816. {
  817. const auto height = getComponent().getHeight();
  818. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, height));
  819. CoreGraphicsContext context (cg, (float) height);
  820. handlePaint (context);
  821. }
  822. else
  823. #endif
  824. {
  825. const Point<int> offset (-roundToInt (r.origin.x), -roundToInt (r.origin.y));
  826. auto clipW = (int) (r.size.width + 0.5f);
  827. auto clipH = (int) (r.size.height + 0.5f);
  828. RectangleList<int> clip;
  829. getClipRects (clip, offset, clipW, clipH);
  830. if (! clip.isEmpty())
  831. {
  832. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  833. roundToInt (clipW * displayScale),
  834. roundToInt (clipH * displayScale),
  835. ! component.isOpaque());
  836. {
  837. auto intScale = roundToInt (displayScale);
  838. if (intScale != 1)
  839. clip.scaleAll (intScale);
  840. auto context = component.getLookAndFeel()
  841. .createGraphicsContext (temp, offset * intScale, clip);
  842. if (intScale != 1)
  843. context->addTransform (AffineTransform::scale (displayScale));
  844. handlePaint (*context);
  845. }
  846. detail::ColorSpacePtr colourSpace { CGColorSpaceCreateWithName (kCGColorSpaceSRGB) };
  847. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace.get());
  848. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, r.origin.x, r.origin.y + clipH));
  849. CGContextDrawImage (cg, CGRectMake (0.0f, 0.0f, clipW, clipH), image);
  850. CGImageRelease (image);
  851. }
  852. }
  853. }
  854. void repaint (const Rectangle<int>& area) override
  855. {
  856. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  857. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  858. // a few when there's a lot of activity.
  859. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  860. // asynchronously asking the OS to repaint them.
  861. deferredRepaints.add (area.toFloat());
  862. }
  863. static bool shouldThrottleRepaint()
  864. {
  865. return areAnyWindowsInLiveResize();
  866. }
  867. void setNeedsDisplayRectangles()
  868. {
  869. if (deferredRepaints.isEmpty())
  870. return;
  871. auto now = Time::getMillisecondCounter();
  872. auto msSinceLastRepaint = (lastRepaintTime >= now) ? now - lastRepaintTime
  873. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now;
  874. constexpr uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  875. // When windows are being resized, artificially throttling high-frequency repaints helps
  876. // to stop the event queue getting clogged, and keeps everything working smoothly.
  877. // For some reason Logic also needs this throttling to record parameter events correctly.
  878. if (msSinceLastRepaint < minimumRepaintInterval && shouldThrottleRepaint())
  879. return;
  880. #if USE_COREGRAPHICS_RENDERING
  881. if (metalRenderer != nullptr)
  882. {
  883. const auto compBounds = getComponent().getLocalBounds().toFloat();
  884. // If we are resizing we need to fall back to synchronous drawing to avoid artefacts
  885. if ([window inLiveResize] || numFramesToSkipMetalRenderer > 0)
  886. {
  887. if (metalRenderer->isAttachedToView (view))
  888. {
  889. metalRenderer->detach();
  890. deferredRepaints = compBounds;
  891. }
  892. if (numFramesToSkipMetalRenderer > 0)
  893. --numFramesToSkipMetalRenderer;
  894. }
  895. else
  896. {
  897. if (! metalRenderer->isAttachedToView (view))
  898. {
  899. metalRenderer->attach (view, getComponent());
  900. deferredRepaints = compBounds;
  901. }
  902. }
  903. }
  904. #endif
  905. auto dispatchRectangles = [this]
  906. {
  907. #if USE_COREGRAPHICS_RENDERING
  908. if (metalRenderer != nullptr && metalRenderer->isAttachedToView (view))
  909. return metalRenderer->drawRectangleList (view,
  910. (float) [[view window] backingScaleFactor],
  911. view.frame,
  912. getComponent(),
  913. [this] (CGContextRef ctx, CGRect r) { drawRectWithContext (ctx, r); },
  914. deferredRepaints);
  915. #endif
  916. for (auto& i : deferredRepaints)
  917. [view setNeedsDisplayInRect: makeNSRect (i)];
  918. return true;
  919. };
  920. if (dispatchRectangles())
  921. {
  922. lastRepaintTime = Time::getMillisecondCounter();
  923. deferredRepaints.clear();
  924. }
  925. }
  926. void performAnyPendingRepaintsNow() override
  927. {
  928. [view displayIfNeeded];
  929. }
  930. static bool areAnyWindowsInLiveResize() noexcept
  931. {
  932. for (NSWindow* w in [NSApp windows])
  933. if ([w inLiveResize])
  934. return true;
  935. return false;
  936. }
  937. //==============================================================================
  938. bool isBlockedByModalComponent()
  939. {
  940. if (auto* modal = Component::getCurrentlyModalComponent())
  941. {
  942. if (insideToFrontCall == 0
  943. && (! getComponent().isParentOf (modal))
  944. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  945. {
  946. return true;
  947. }
  948. }
  949. return false;
  950. }
  951. enum class KeyWindowChanged { no, yes };
  952. void sendModalInputAttemptIfBlocked (KeyWindowChanged keyChanged)
  953. {
  954. if (! isBlockedByModalComponent())
  955. return;
  956. if (auto* modal = Component::getCurrentlyModalComponent())
  957. {
  958. if (auto* otherPeer = modal->getPeer())
  959. {
  960. const auto modalPeerIsTemporary = (otherPeer->getStyleFlags() & ComponentPeer::windowIsTemporary) != 0;
  961. if (! modalPeerIsTemporary)
  962. return;
  963. // When a peer resigns key status, it might be because we just created a modal
  964. // component that is now key.
  965. // In this case, we should only dismiss the modal component if it isn't key,
  966. // implying that a third window has become key.
  967. const auto modalPeerIsKey = [NSApp keyWindow] == static_cast<NSViewComponentPeer*> (otherPeer)->window;
  968. if (keyChanged == KeyWindowChanged::yes && modalPeerIsKey)
  969. return;
  970. modal->inputAttemptWhenModal();
  971. }
  972. }
  973. }
  974. bool canBecomeKeyWindow()
  975. {
  976. return component.isVisible() && (getStyleFlags() & ComponentPeer::windowIgnoresKeyPresses) == 0;
  977. }
  978. bool canBecomeMainWindow()
  979. {
  980. return component.isVisible() && dynamic_cast<ResizableWindow*> (&component) != nullptr;
  981. }
  982. bool worksWhenModal() const
  983. {
  984. // In plugins, the host could put our plugin window inside a modal window, so this
  985. // allows us to successfully open other popups. Feels like there could be edge-case
  986. // problems caused by this, so let us know if you spot any issues..
  987. return ! JUCEApplication::isStandaloneApp();
  988. }
  989. void becomeKeyWindow()
  990. {
  991. handleBroughtToFront();
  992. grabFocus();
  993. }
  994. void resignKeyWindow()
  995. {
  996. viewFocusLoss();
  997. }
  998. bool windowShouldClose()
  999. {
  1000. if (! isValidPeer (this))
  1001. return YES;
  1002. handleUserClosingWindow();
  1003. return NO;
  1004. }
  1005. void redirectMovedOrResized()
  1006. {
  1007. handleMovedOrResized();
  1008. setNeedsDisplayRectangles();
  1009. }
  1010. void windowDidChangeScreen()
  1011. {
  1012. updateCVDisplayLinkScreen();
  1013. }
  1014. void viewMovedToWindow()
  1015. {
  1016. if (isSharedWindow)
  1017. {
  1018. auto newWindow = [view window];
  1019. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  1020. window = newWindow;
  1021. if (shouldSetVisible)
  1022. getComponent().setVisible (true);
  1023. }
  1024. if (auto* currentWindow = [view window])
  1025. {
  1026. [notificationCenter addObserver: view
  1027. selector: dismissModalsSelector
  1028. name: NSWindowWillMoveNotification
  1029. object: currentWindow];
  1030. [notificationCenter addObserver: view
  1031. selector: dismissModalsSelector
  1032. name: NSWindowWillMiniaturizeNotification
  1033. object: currentWindow];
  1034. [notificationCenter addObserver: view
  1035. selector: becomeKeySelector
  1036. name: NSWindowDidBecomeKeyNotification
  1037. object: currentWindow];
  1038. [notificationCenter addObserver: view
  1039. selector: resignKeySelector
  1040. name: NSWindowDidResignKeyNotification
  1041. object: currentWindow];
  1042. [notificationCenter addObserver: view
  1043. selector: @selector (windowDidChangeScreen:)
  1044. name: NSWindowDidChangeScreenNotification
  1045. object: currentWindow];
  1046. updateCVDisplayLinkScreen();
  1047. }
  1048. }
  1049. void dismissModals()
  1050. {
  1051. if (hasNativeTitleBar() || isSharedWindow)
  1052. sendModalInputAttemptIfBlocked (KeyWindowChanged::no);
  1053. }
  1054. void becomeKey()
  1055. {
  1056. component.repaint();
  1057. }
  1058. void resignKey()
  1059. {
  1060. viewFocusLoss();
  1061. sendModalInputAttemptIfBlocked (KeyWindowChanged::yes);
  1062. }
  1063. void liveResizingStart()
  1064. {
  1065. if (constrainer == nullptr)
  1066. return;
  1067. constrainer->resizeStart();
  1068. isFirstLiveResize = true;
  1069. setFullScreenSizeConstraints (*constrainer);
  1070. }
  1071. void liveResizingEnd()
  1072. {
  1073. if (constrainer != nullptr)
  1074. constrainer->resizeEnd();
  1075. }
  1076. NSRect constrainRect (const NSRect r)
  1077. {
  1078. if (constrainer == nullptr || isKioskMode() || isFullScreen())
  1079. return r;
  1080. const auto scale = getComponent().getDesktopScaleFactor();
  1081. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  1082. const auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  1083. const auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  1084. const bool inLiveResize = [window inLiveResize];
  1085. if (! inLiveResize || isFirstLiveResize)
  1086. {
  1087. isFirstLiveResize = false;
  1088. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  1089. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  1090. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  1091. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  1092. }
  1093. constrainer->checkBounds (pos, original, screenBounds,
  1094. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  1095. return flippedScreenRect (makeNSRect (ScalingHelpers::scaledScreenPosToUnscaled (scale, pos)));
  1096. }
  1097. static void showArrowCursorIfNeeded()
  1098. {
  1099. auto& desktop = Desktop::getInstance();
  1100. auto mouse = desktop.getMainMouseSource();
  1101. if (mouse.getComponentUnderMouse() == nullptr
  1102. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  1103. {
  1104. [[NSCursor arrowCursor] set];
  1105. }
  1106. }
  1107. static void updateModifiers (NSEvent* e)
  1108. {
  1109. updateModifiers ([e modifierFlags]);
  1110. }
  1111. static void updateModifiers (const NSUInteger flags)
  1112. {
  1113. int m = 0;
  1114. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  1115. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  1116. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  1117. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  1118. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  1119. }
  1120. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  1121. {
  1122. updateModifiers (ev);
  1123. if (auto keyCode = getKeyCodeFromEvent (ev))
  1124. {
  1125. if (isKeyDown)
  1126. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  1127. else
  1128. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  1129. }
  1130. }
  1131. static int getKeyCodeFromEvent (NSEvent* ev)
  1132. {
  1133. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  1134. // Using [ev keyCode] is not a solution either as this will,
  1135. // for example, return VK_KEY_Y if the key is pressed which
  1136. // is typically located at the Y key position on a QWERTY
  1137. // keyboard. However, on international keyboards this might not
  1138. // be the key labeled Y (for example, on German keyboards this key
  1139. // has a Z label). Therefore, we need to query the current keyboard
  1140. // layout to figure out what character the key would have produced
  1141. // if the shift key was not pressed
  1142. String unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  1143. auto keyCode = (int) unmodified[0];
  1144. if (keyCode == 0x19) // (backwards-tab)
  1145. keyCode = '\t';
  1146. else if (keyCode == 0x03) // (enter)
  1147. keyCode = '\r';
  1148. else
  1149. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  1150. // The purpose of the keyCode is to provide information about non-printing characters to facilitate
  1151. // keyboard control over the application.
  1152. //
  1153. // So when keyCode is decoded as a printing character outside the ASCII range we need to replace it.
  1154. // This holds when the keyCode is larger than 0xff and not part one of the two MacOS specific
  1155. // non-printing ranges.
  1156. if (keyCode > 0xff
  1157. && ! (keyCode >= NSUpArrowFunctionKey && keyCode <= NSModeSwitchFunctionKey)
  1158. && ! (keyCode >= extendedKeyModifier))
  1159. {
  1160. keyCode = translateVirtualToAsciiKeyCode ([ev keyCode]);
  1161. }
  1162. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  1163. {
  1164. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  1165. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  1166. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  1167. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  1168. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  1169. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  1170. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  1171. '.', KeyPress::numberPadDecimalPoint,
  1172. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  1173. '=', KeyPress::numberPadEquals };
  1174. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  1175. if (keyCode == numPadConversions [i])
  1176. keyCode = numPadConversions [i + 1];
  1177. }
  1178. return keyCode;
  1179. }
  1180. static int64 getMouseTime (NSEvent* e) noexcept
  1181. {
  1182. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  1183. + (int64) ([e timestamp] * 1000.0);
  1184. }
  1185. static float getMousePressure (NSEvent* e) noexcept
  1186. {
  1187. @try
  1188. {
  1189. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  1190. return (float) e.pressure;
  1191. }
  1192. @catch (NSException* e) {}
  1193. @finally {}
  1194. return 0.0f;
  1195. }
  1196. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1197. {
  1198. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1199. return { (float) p.x, (float) p.y };
  1200. }
  1201. static int getModifierForButtonNumber (const NSInteger num)
  1202. {
  1203. return num == 0 ? ModifierKeys::leftButtonModifier
  1204. : (num == 1 ? ModifierKeys::rightButtonModifier
  1205. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1206. }
  1207. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1208. {
  1209. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1210. : NSWindowStyleMaskBorderless;
  1211. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1212. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1213. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1214. return style;
  1215. }
  1216. static NSArray* getSupportedDragTypes()
  1217. {
  1218. const auto type = []
  1219. {
  1220. #if defined (MAC_OS_X_VERSION_10_13) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13
  1221. if (@available (macOS 10.13, *))
  1222. return NSPasteboardTypeFileURL;
  1223. #endif
  1224. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  1225. return (NSString*) kUTTypeFileURL;
  1226. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1227. }();
  1228. return [NSArray arrayWithObjects: type, (NSString*) kPasteboardTypeFileURLPromise, NSPasteboardTypeString, nil];
  1229. }
  1230. BOOL sendDragCallback (bool (ComponentPeer::* callback) (const DragInfo&), id <NSDraggingInfo> sender)
  1231. {
  1232. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1233. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1234. if (contentType == nil)
  1235. return false;
  1236. const auto p = localToGlobal (convertToPointFloat ([view convertPoint: [sender draggingLocation] fromView: nil]));
  1237. ComponentPeer::DragInfo dragInfo;
  1238. dragInfo.position = ScalingHelpers::screenPosToLocalPos (component, p).roundToInt();
  1239. if (contentType == NSPasteboardTypeString)
  1240. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSPasteboardTypeString]);
  1241. else
  1242. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1243. if (! dragInfo.isEmpty())
  1244. return (this->*callback) (dragInfo);
  1245. return false;
  1246. }
  1247. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1248. {
  1249. StringArray files;
  1250. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1251. if ([contentType isEqualToString: (NSString*) kPasteboardTypeFileURLPromise]
  1252. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1253. {
  1254. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1255. if ([list isKindOfClass: [NSDictionary class]])
  1256. {
  1257. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1258. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1259. NSEnumerator* enumerator = [tracks objectEnumerator];
  1260. NSDictionary* track;
  1261. while ((track = [enumerator nextObject]) != nil)
  1262. {
  1263. if (id value = [track valueForKey: nsStringLiteral ("Location")])
  1264. {
  1265. NSURL* url = [NSURL URLWithString: value];
  1266. if ([url isFileURL])
  1267. files.add (nsStringToJuce ([url path]));
  1268. }
  1269. }
  1270. }
  1271. }
  1272. else
  1273. {
  1274. NSArray* items = [pasteboard readObjectsForClasses:@[[NSURL class]] options: nil];
  1275. for (unsigned int i = 0; i < [items count]; ++i)
  1276. {
  1277. NSURL* url = [items objectAtIndex: i];
  1278. if ([url isFileURL])
  1279. files.add (nsStringToJuce ([url path]));
  1280. }
  1281. }
  1282. return files;
  1283. }
  1284. //==============================================================================
  1285. void viewFocusGain()
  1286. {
  1287. if (currentlyFocusedPeer != this)
  1288. {
  1289. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1290. currentlyFocusedPeer->handleFocusLoss();
  1291. currentlyFocusedPeer = this;
  1292. handleFocusGain();
  1293. }
  1294. }
  1295. void viewFocusLoss()
  1296. {
  1297. if (currentlyFocusedPeer == this)
  1298. {
  1299. currentlyFocusedPeer = nullptr;
  1300. handleFocusLoss();
  1301. }
  1302. }
  1303. bool isFocused() const override
  1304. {
  1305. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1306. ? this == currentlyFocusedPeer
  1307. : [window isKeyWindow];
  1308. }
  1309. void grabFocus() override
  1310. {
  1311. if (window != nil)
  1312. {
  1313. [window makeKeyWindow];
  1314. [window makeFirstResponder: view];
  1315. viewFocusGain();
  1316. }
  1317. }
  1318. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1319. void closeInputMethodContext() override
  1320. {
  1321. stringBeingComposed.clear();
  1322. const auto* inputContext = [NSTextInputContext currentInputContext];
  1323. if (inputContext != nil)
  1324. [inputContext discardMarkedText];
  1325. }
  1326. void resetWindowPresentation()
  1327. {
  1328. if (hasNativeTitleBar())
  1329. {
  1330. [window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (getStyleFlags()))];
  1331. setTitle (getComponent().getName()); // required to force the OS to update the title
  1332. }
  1333. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1334. setCollectionBehaviour (isFullScreen());
  1335. }
  1336. void setHasChangedSinceSaved (bool b) override
  1337. {
  1338. if (! isSharedWindow)
  1339. [window setDocumentEdited: b];
  1340. }
  1341. //==============================================================================
  1342. NSWindow* window = nil;
  1343. NSView* view = nil;
  1344. WeakReference<Component> safeComponent;
  1345. bool isSharedWindow = false;
  1346. #if USE_COREGRAPHICS_RENDERING
  1347. bool usingCoreGraphics = true;
  1348. #else
  1349. bool usingCoreGraphics = false;
  1350. #endif
  1351. bool isZooming = false, isFirstLiveResize = false, textWasInserted = false;
  1352. bool isStretchingTop = false, isStretchingLeft = false, isStretchingBottom = false, isStretchingRight = false;
  1353. bool windowRepresentsFile = false;
  1354. bool isAlwaysOnTop = false, wasAlwaysOnTop = false;
  1355. String stringBeingComposed;
  1356. NSNotificationCenter* notificationCenter = nil;
  1357. Rectangle<float> lastSizeBeforeZoom;
  1358. RectangleList<float> deferredRepaints;
  1359. uint32 lastRepaintTime;
  1360. static ComponentPeer* currentlyFocusedPeer;
  1361. static Array<int> keysCurrentlyDown;
  1362. static int insideToFrontCall;
  1363. static const SEL dismissModalsSelector;
  1364. static const SEL frameChangedSelector;
  1365. static const SEL asyncMouseDownSelector;
  1366. static const SEL asyncMouseUpSelector;
  1367. static const SEL becomeKeySelector;
  1368. static const SEL resignKeySelector;
  1369. private:
  1370. static NSView* createViewInstance();
  1371. static NSWindow* createWindowInstance();
  1372. void sendMouseEnterExit (NSEvent* ev)
  1373. {
  1374. if (auto* area = [ev trackingArea])
  1375. if (! [[view trackingAreas] containsObject: area])
  1376. return;
  1377. sendMouseEvent (ev);
  1378. }
  1379. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1380. {
  1381. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1382. }
  1383. void getClipRects (RectangleList<int>& clip, Point<int> offset, int clipW, int clipH)
  1384. {
  1385. const NSRect* rects = nullptr;
  1386. NSInteger numRects = 0;
  1387. [view getRectsBeingDrawn: &rects count: &numRects];
  1388. const Rectangle<int> clipBounds (clipW, clipH);
  1389. clip.ensureStorageAllocated ((int) numRects);
  1390. for (int i = 0; i < numRects; ++i)
  1391. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1392. roundToInt (rects[i].origin.y) + offset.y,
  1393. roundToInt (rects[i].size.width),
  1394. roundToInt (rects[i].size.height))));
  1395. }
  1396. static void appFocusChanged()
  1397. {
  1398. keysCurrentlyDown.clear();
  1399. if (isValidPeer (currentlyFocusedPeer))
  1400. {
  1401. if (Process::isForegroundProcess())
  1402. {
  1403. currentlyFocusedPeer->handleFocusGain();
  1404. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1405. }
  1406. else
  1407. {
  1408. currentlyFocusedPeer->handleFocusLoss();
  1409. }
  1410. }
  1411. }
  1412. static bool checkEventBlockedByModalComps (NSEvent* e)
  1413. {
  1414. if (Component::getNumCurrentlyModalComponents() == 0)
  1415. return false;
  1416. NSWindow* const w = [e window];
  1417. if (w == nil || [w worksWhenModal])
  1418. return false;
  1419. bool isKey = false, isInputAttempt = false;
  1420. switch ([e type])
  1421. {
  1422. case NSEventTypeKeyDown:
  1423. case NSEventTypeKeyUp:
  1424. isKey = isInputAttempt = true;
  1425. break;
  1426. case NSEventTypeLeftMouseDown:
  1427. case NSEventTypeRightMouseDown:
  1428. case NSEventTypeOtherMouseDown:
  1429. isInputAttempt = true;
  1430. break;
  1431. case NSEventTypeLeftMouseDragged:
  1432. case NSEventTypeRightMouseDragged:
  1433. case NSEventTypeLeftMouseUp:
  1434. case NSEventTypeRightMouseUp:
  1435. case NSEventTypeOtherMouseUp:
  1436. case NSEventTypeOtherMouseDragged:
  1437. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1438. return false;
  1439. break;
  1440. case NSEventTypeMouseMoved:
  1441. case NSEventTypeMouseEntered:
  1442. case NSEventTypeMouseExited:
  1443. case NSEventTypeCursorUpdate:
  1444. case NSEventTypeScrollWheel:
  1445. case NSEventTypeTabletPoint:
  1446. case NSEventTypeTabletProximity:
  1447. break;
  1448. case NSEventTypeFlagsChanged:
  1449. case NSEventTypeAppKitDefined:
  1450. case NSEventTypeSystemDefined:
  1451. case NSEventTypeApplicationDefined:
  1452. case NSEventTypePeriodic:
  1453. case NSEventTypeGesture:
  1454. case NSEventTypeMagnify:
  1455. case NSEventTypeSwipe:
  1456. case NSEventTypeRotate:
  1457. case NSEventTypeBeginGesture:
  1458. case NSEventTypeEndGesture:
  1459. case NSEventTypeQuickLook:
  1460. #if JUCE_64BIT
  1461. case NSEventTypeSmartMagnify:
  1462. case NSEventTypePressure:
  1463. #endif
  1464. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1465. #if JUCE_64BIT
  1466. case NSEventTypeDirectTouch:
  1467. #endif
  1468. #if defined (MAC_OS_X_VERSION_10_15) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
  1469. case NSEventTypeChangeMode:
  1470. #endif
  1471. #endif
  1472. default:
  1473. return false;
  1474. }
  1475. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1476. {
  1477. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1478. {
  1479. if ([peer->view window] == w)
  1480. {
  1481. if (isKey)
  1482. {
  1483. if (peer->view == [w firstResponder])
  1484. return false;
  1485. }
  1486. else
  1487. {
  1488. if (peer->isSharedWindow
  1489. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1490. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1491. return false;
  1492. }
  1493. }
  1494. }
  1495. }
  1496. if (isInputAttempt)
  1497. {
  1498. if (! [NSApp isActive])
  1499. [NSApp activateIgnoringOtherApps: YES];
  1500. if (auto* modal = Component::getCurrentlyModalComponent())
  1501. modal->inputAttemptWhenModal();
  1502. }
  1503. return true;
  1504. }
  1505. void setFullScreenSizeConstraints (const ComponentBoundsConstrainer& c)
  1506. {
  1507. if (@available (macOS 10.11, *))
  1508. {
  1509. const auto minSize = NSMakeSize (static_cast<float> (c.getMinimumWidth()),
  1510. 0.0f);
  1511. [window setMinFullScreenContentSize: minSize];
  1512. [window setMaxFullScreenContentSize: NSMakeSize (100000, 100000)];
  1513. }
  1514. }
  1515. //==============================================================================
  1516. void onDisplaySourceCallback()
  1517. {
  1518. setNeedsDisplayRectangles();
  1519. }
  1520. void onDisplayLinkCallback()
  1521. {
  1522. dispatch_source_merge_data (displaySource, 1);
  1523. }
  1524. static CVReturn displayLinkCallback (CVDisplayLinkRef, const CVTimeStamp*, const CVTimeStamp*,
  1525. CVOptionFlags, CVOptionFlags*, void* context)
  1526. {
  1527. static_cast<NSViewComponentPeer*> (context)->onDisplayLinkCallback();
  1528. return kCVReturnSuccess;
  1529. }
  1530. void updateCVDisplayLinkScreen()
  1531. {
  1532. auto viewDisplayID = (CGDirectDisplayID) [[window.screen.deviceDescription objectForKey: @"NSScreenNumber"] unsignedIntegerValue];
  1533. auto result = CVDisplayLinkSetCurrentCGDisplay (displayLink, viewDisplayID);
  1534. jassertquiet (result == kCVReturnSuccess);
  1535. }
  1536. void createCVDisplayLink()
  1537. {
  1538. displaySource = dispatch_source_create (DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
  1539. dispatch_source_set_event_handler (displaySource, ^(){ onDisplaySourceCallback(); });
  1540. dispatch_resume (displaySource);
  1541. auto cvReturn = CVDisplayLinkCreateWithActiveCGDisplays (&displayLink);
  1542. jassertquiet (cvReturn == kCVReturnSuccess);
  1543. cvReturn = CVDisplayLinkSetOutputCallback (displayLink, &displayLinkCallback, this);
  1544. jassertquiet (cvReturn == kCVReturnSuccess);
  1545. CVDisplayLinkStart (displayLink);
  1546. }
  1547. CVDisplayLinkRef displayLink = nullptr;
  1548. dispatch_source_t displaySource = nullptr;
  1549. #if USE_COREGRAPHICS_RENDERING
  1550. int numFramesToSkipMetalRenderer = 0;
  1551. std::unique_ptr<CoreGraphicsMetalLayerRenderer<NSView>> metalRenderer;
  1552. #endif
  1553. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1554. };
  1555. int NSViewComponentPeer::insideToFrontCall = 0;
  1556. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  1557. const SEL NSViewComponentPeer::dismissModalsSelector = @selector (dismissModals);
  1558. const SEL NSViewComponentPeer::frameChangedSelector = @selector (frameChanged:);
  1559. const SEL NSViewComponentPeer::asyncMouseDownSelector = @selector (asyncMouseDown:);
  1560. const SEL NSViewComponentPeer::asyncMouseUpSelector = @selector (asyncMouseUp:);
  1561. const SEL NSViewComponentPeer::becomeKeySelector = @selector (becomeKey:);
  1562. const SEL NSViewComponentPeer::resignKeySelector = @selector (resignKey:);
  1563. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1564. //==============================================================================
  1565. template <typename Base>
  1566. struct NSViewComponentPeerWrapper : public Base
  1567. {
  1568. explicit NSViewComponentPeerWrapper (const char* baseName)
  1569. : Base (baseName)
  1570. {
  1571. Base::template addIvar<NSViewComponentPeer*> ("owner");
  1572. }
  1573. static NSViewComponentPeer* getOwner (id self)
  1574. {
  1575. return getIvar<NSViewComponentPeer*> (self, "owner");
  1576. }
  1577. static id getAccessibleChild (id self)
  1578. {
  1579. if (auto* owner = getOwner (self))
  1580. if (auto* handler = owner->getComponent().getAccessibilityHandler())
  1581. return (id) handler->getNativeImplementation();
  1582. return nil;
  1583. }
  1584. };
  1585. struct JuceNSViewClass : public NSViewComponentPeerWrapper<ObjCClass<NSView>>
  1586. {
  1587. JuceNSViewClass() : NSViewComponentPeerWrapper ("JUCEView_")
  1588. {
  1589. addMethod (@selector (isOpaque), isOpaque);
  1590. addMethod (@selector (drawRect:), drawRect);
  1591. addMethod (@selector (updateTrackingAreas), updateTrackingAreas);
  1592. addMethod (@selector (mouseDown:), mouseDown);
  1593. addMethod (@selector (mouseUp:), mouseUp);
  1594. addMethod (@selector (mouseDragged:), mouseDragged);
  1595. addMethod (@selector (mouseMoved:), mouseMoved);
  1596. addMethod (@selector (mouseEntered:), mouseEntered);
  1597. addMethod (@selector (mouseExited:), mouseExited);
  1598. addMethod (@selector (rightMouseDown:), mouseDown);
  1599. addMethod (@selector (rightMouseDragged:), mouseDragged);
  1600. addMethod (@selector (rightMouseUp:), mouseUp);
  1601. addMethod (@selector (otherMouseDown:), mouseDown);
  1602. addMethod (@selector (otherMouseDragged:), mouseDragged);
  1603. addMethod (@selector (otherMouseUp:), mouseUp);
  1604. addMethod (@selector (scrollWheel:), scrollWheel);
  1605. addMethod (@selector (magnifyWithEvent:), magnify);
  1606. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse);
  1607. addMethod (@selector (windowWillMiniaturize:), windowWillMiniaturize);
  1608. addMethod (@selector (windowDidDeminiaturize:), windowDidDeminiaturize);
  1609. addMethod (@selector (windowDidChangeScreen:), windowDidChangeScreen);
  1610. addMethod (@selector (wantsDefaultClipping), wantsDefaultClipping);
  1611. addMethod (@selector (worksWhenModal), worksWhenModal);
  1612. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow);
  1613. addMethod (@selector (viewWillDraw), viewWillDraw);
  1614. addMethod (@selector (keyDown:), keyDown);
  1615. addMethod (@selector (keyUp:), keyUp);
  1616. addMethod (@selector (insertText:), insertText);
  1617. addMethod (@selector (doCommandBySelector:), doCommandBySelector);
  1618. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText);
  1619. addMethod (@selector (unmarkText), unmarkText);
  1620. addMethod (@selector (hasMarkedText), hasMarkedText);
  1621. addMethod (@selector (conversationIdentifier), conversationIdentifier);
  1622. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange);
  1623. addMethod (@selector (markedRange), markedRange);
  1624. addMethod (@selector (selectedRange), selectedRange);
  1625. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange);
  1626. addMethod (@selector (characterIndexForPoint:), characterIndexForPoint);
  1627. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText);
  1628. addMethod (@selector (flagsChanged:), flagsChanged);
  1629. addMethod (@selector (becomeFirstResponder), becomeFirstResponder);
  1630. addMethod (@selector (resignFirstResponder), resignFirstResponder);
  1631. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder);
  1632. addMethod (@selector (draggingEntered:), draggingEntered);
  1633. addMethod (@selector (draggingUpdated:), draggingUpdated);
  1634. addMethod (@selector (draggingEnded:), draggingEnded);
  1635. addMethod (@selector (draggingExited:), draggingExited);
  1636. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation);
  1637. addMethod (@selector (performDragOperation:), performDragOperation);
  1638. addMethod (@selector (concludeDragOperation:), concludeDragOperation);
  1639. addMethod (@selector (paste:), paste);
  1640. addMethod (@selector (copy:), copy);
  1641. addMethod (@selector (cut:), cut);
  1642. addMethod (@selector (selectAll:), selectAll);
  1643. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow);
  1644. addMethod (@selector (isAccessibilityElement), getIsAccessibilityElement);
  1645. addMethod (@selector (accessibilityChildren), getAccessibilityChildren);
  1646. addMethod (@selector (accessibilityHitTest:), accessibilityHitTest);
  1647. addMethod (@selector (accessibilityFocusedUIElement), getAccessibilityFocusedUIElement);
  1648. // deprecated methods required for backwards compatibility
  1649. addMethod (@selector (accessibilityIsIgnored), getAccessibilityIsIgnored);
  1650. addMethod (@selector (accessibilityAttributeValue:), getAccessibilityAttributeValue);
  1651. addMethod (@selector (isFlipped), isFlipped);
  1652. addMethod (NSViewComponentPeer::dismissModalsSelector, dismissModals);
  1653. addMethod (NSViewComponentPeer::asyncMouseDownSelector, asyncMouseDown);
  1654. addMethod (NSViewComponentPeer::asyncMouseUpSelector, asyncMouseUp);
  1655. addMethod (NSViewComponentPeer::frameChangedSelector, frameChanged);
  1656. addMethod (NSViewComponentPeer::becomeKeySelector, becomeKey);
  1657. addMethod (NSViewComponentPeer::resignKeySelector, resignKey);
  1658. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent);
  1659. addProtocol (@protocol (NSTextInput));
  1660. registerClass();
  1661. }
  1662. private:
  1663. static void updateTrackingAreas (id self, SEL)
  1664. {
  1665. sendSuperclassMessage<void> (self, @selector (updateTrackingAreas));
  1666. resetTrackingArea (static_cast<NSView*> (self));
  1667. }
  1668. static void mouseDown (id self, SEL s, NSEvent* ev)
  1669. {
  1670. if (JUCEApplicationBase::isStandaloneApp())
  1671. {
  1672. asyncMouseDown (self, s, ev);
  1673. }
  1674. else
  1675. {
  1676. // In some host situations, the host will stop modal loops from working
  1677. // correctly if they're called from a mouse event, so we'll trigger
  1678. // the event asynchronously..
  1679. [self performSelectorOnMainThread: NSViewComponentPeer::asyncMouseDownSelector
  1680. withObject: ev
  1681. waitUntilDone: NO];
  1682. }
  1683. }
  1684. static void mouseUp (id self, SEL s, NSEvent* ev)
  1685. {
  1686. if (JUCEApplicationBase::isStandaloneApp())
  1687. {
  1688. asyncMouseUp (self, s, ev);
  1689. }
  1690. else
  1691. {
  1692. // In some host situations, the host will stop modal loops from working
  1693. // correctly if they're called from a mouse event, so we'll trigger
  1694. // the event asynchronously..
  1695. [self performSelectorOnMainThread: NSViewComponentPeer::asyncMouseUpSelector
  1696. withObject: ev
  1697. waitUntilDone: NO];
  1698. }
  1699. }
  1700. static void asyncMouseDown (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseDown, ev); }
  1701. static void asyncMouseUp (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseUp, ev); }
  1702. static void mouseDragged (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseDrag, ev); }
  1703. static void mouseMoved (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseMove, ev); }
  1704. static void mouseEntered (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseEnter, ev); }
  1705. static void mouseExited (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseExit, ev); }
  1706. static void scrollWheel (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMouseWheel, ev); }
  1707. static void magnify (id self, SEL, NSEvent* ev) { callOnOwner (self, &NSViewComponentPeer::redirectMagnify, ev); }
  1708. static void copy (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectCopy, s); }
  1709. static void paste (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectPaste, s); }
  1710. static void cut (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectCut, s); }
  1711. static void selectAll (id self, SEL, NSObject* s) { callOnOwner (self, &NSViewComponentPeer::redirectSelectAll, s); }
  1712. static void willMoveToWindow (id self, SEL, NSWindow* w) { callOnOwner (self, &NSViewComponentPeer::redirectWillMoveToWindow, w); }
  1713. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1714. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1715. static BOOL worksWhenModal (id self, SEL) { if (auto* p = getOwner (self)) return p->worksWhenModal(); return NO; }
  1716. static void drawRect (id self, SEL, NSRect r) { callOnOwner (self, &NSViewComponentPeer::drawRect, r); }
  1717. static void frameChanged (id self, SEL, NSNotification*) { callOnOwner (self, &NSViewComponentPeer::redirectMovedOrResized); }
  1718. static void viewDidMoveToWindow (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::viewMovedToWindow); }
  1719. static void dismissModals (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::dismissModals); }
  1720. static void becomeKey (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::becomeKey); }
  1721. static void resignKey (id self, SEL) { callOnOwner (self, &NSViewComponentPeer::resignKey); }
  1722. static BOOL isFlipped (id, SEL) { return true; }
  1723. static void viewWillDraw (id self, SEL)
  1724. {
  1725. // Without setting contentsFormat macOS Big Sur will always set the invalid area
  1726. // to be the entire frame.
  1727. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1728. if (@available (macOS 10.12, *))
  1729. {
  1730. CALayer* layer = ((NSView*) self).layer;
  1731. layer.contentsFormat = kCAContentsFormatRGBA8Uint;
  1732. }
  1733. #endif
  1734. sendSuperclassMessage<void> (self, @selector (viewWillDraw));
  1735. }
  1736. static void windowWillMiniaturize (id self, SEL, NSNotification*)
  1737. {
  1738. if (auto* p = getOwner (self))
  1739. {
  1740. if (p->isAlwaysOnTop)
  1741. {
  1742. // there is a bug when restoring minimised always on top windows so we need
  1743. // to remove this behaviour before minimising and restore it afterwards
  1744. p->setAlwaysOnTop (false);
  1745. p->wasAlwaysOnTop = true;
  1746. }
  1747. }
  1748. }
  1749. static void windowDidDeminiaturize (id self, SEL, NSNotification*)
  1750. {
  1751. if (auto* p = getOwner (self))
  1752. {
  1753. if (p->wasAlwaysOnTop)
  1754. p->setAlwaysOnTop (true);
  1755. p->redirectMovedOrResized();
  1756. }
  1757. }
  1758. static void windowDidChangeScreen (id self, SEL, NSNotification*)
  1759. {
  1760. if (auto* p = getOwner (self))
  1761. p->windowDidChangeScreen();
  1762. }
  1763. static BOOL isOpaque (id self, SEL)
  1764. {
  1765. auto* owner = getOwner (self);
  1766. return owner == nullptr || owner->getComponent().isOpaque();
  1767. }
  1768. //==============================================================================
  1769. static void keyDown (id self, SEL, NSEvent* ev)
  1770. {
  1771. if (auto* owner = getOwner (self))
  1772. {
  1773. auto* target = owner->findCurrentTextInputTarget();
  1774. owner->textWasInserted = false;
  1775. if (target != nullptr)
  1776. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1777. else
  1778. owner->stringBeingComposed.clear();
  1779. if (! (owner->textWasInserted || owner->redirectKeyDown (ev)))
  1780. sendSuperclassMessage<void> (self, @selector (keyDown:), ev);
  1781. }
  1782. }
  1783. static void keyUp (id self, SEL, NSEvent* ev)
  1784. {
  1785. auto* owner = getOwner (self);
  1786. if (! owner->redirectKeyUp (ev))
  1787. sendSuperclassMessage<void> (self, @selector (keyUp:), ev);
  1788. }
  1789. //==============================================================================
  1790. static void insertText (id self, SEL, id aString)
  1791. {
  1792. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1793. if (auto* owner = getOwner (self))
  1794. {
  1795. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1796. if ([newText length] > 0)
  1797. {
  1798. if (auto* target = owner->findCurrentTextInputTarget())
  1799. {
  1800. target->insertTextAtCaret (nsStringToJuce (newText));
  1801. owner->textWasInserted = true;
  1802. }
  1803. }
  1804. owner->stringBeingComposed.clear();
  1805. }
  1806. }
  1807. static void doCommandBySelector (id, SEL, SEL) {}
  1808. static void setMarkedText (id self, SEL, id aString, NSRange)
  1809. {
  1810. if (auto* owner = getOwner (self))
  1811. {
  1812. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1813. ? [aString string] : aString);
  1814. if (auto* target = owner->findCurrentTextInputTarget())
  1815. {
  1816. auto currentHighlight = target->getHighlightedRegion();
  1817. target->insertTextAtCaret (owner->stringBeingComposed);
  1818. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1819. owner->textWasInserted = true;
  1820. }
  1821. }
  1822. }
  1823. static void unmarkText (id self, SEL)
  1824. {
  1825. if (auto* owner = getOwner (self))
  1826. {
  1827. if (owner->stringBeingComposed.isNotEmpty())
  1828. {
  1829. if (auto* target = owner->findCurrentTextInputTarget())
  1830. {
  1831. target->insertTextAtCaret (owner->stringBeingComposed);
  1832. owner->textWasInserted = true;
  1833. }
  1834. owner->stringBeingComposed.clear();
  1835. }
  1836. }
  1837. }
  1838. static BOOL hasMarkedText (id self, SEL)
  1839. {
  1840. auto* owner = getOwner (self);
  1841. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1842. }
  1843. static long conversationIdentifier (id self, SEL)
  1844. {
  1845. return (long) (pointer_sized_int) self;
  1846. }
  1847. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1848. {
  1849. if (auto* owner = getOwner (self))
  1850. {
  1851. if (auto* target = owner->findCurrentTextInputTarget())
  1852. {
  1853. Range<int> r ((int) theRange.location,
  1854. (int) (theRange.location + theRange.length));
  1855. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1856. }
  1857. }
  1858. return nil;
  1859. }
  1860. static NSRange markedRange (id self, SEL)
  1861. {
  1862. if (auto* owner = getOwner (self))
  1863. if (owner->stringBeingComposed.isNotEmpty())
  1864. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1865. return NSMakeRange (NSNotFound, 0);
  1866. }
  1867. static NSRange selectedRange (id self, SEL)
  1868. {
  1869. if (auto* owner = getOwner (self))
  1870. {
  1871. if (auto* target = owner->findCurrentTextInputTarget())
  1872. {
  1873. auto highlight = target->getHighlightedRegion();
  1874. if (! highlight.isEmpty())
  1875. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1876. (NSUInteger) highlight.getLength());
  1877. }
  1878. }
  1879. return NSMakeRange (NSNotFound, 0);
  1880. }
  1881. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1882. {
  1883. if (auto* owner = getOwner (self))
  1884. if (auto* comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1885. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1886. return NSZeroRect;
  1887. }
  1888. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1889. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1890. //==============================================================================
  1891. static void flagsChanged (id self, SEL, NSEvent* ev)
  1892. {
  1893. callOnOwner (self, &NSViewComponentPeer::redirectModKeyChange, ev);
  1894. }
  1895. static BOOL becomeFirstResponder (id self, SEL)
  1896. {
  1897. callOnOwner (self, &NSViewComponentPeer::viewFocusGain);
  1898. return YES;
  1899. }
  1900. static BOOL resignFirstResponder (id self, SEL)
  1901. {
  1902. callOnOwner (self, &NSViewComponentPeer::viewFocusLoss);
  1903. return YES;
  1904. }
  1905. static BOOL acceptsFirstResponder (id self, SEL)
  1906. {
  1907. auto* owner = getOwner (self);
  1908. return owner != nullptr && owner->canBecomeKeyWindow();
  1909. }
  1910. //==============================================================================
  1911. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1912. {
  1913. return draggingUpdated (self, s, sender);
  1914. }
  1915. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1916. {
  1917. if (auto* owner = getOwner (self))
  1918. if (owner->sendDragCallback (&NSViewComponentPeer::handleDragMove, sender))
  1919. return NSDragOperationGeneric;
  1920. return NSDragOperationNone;
  1921. }
  1922. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1923. {
  1924. draggingExited (self, s, sender);
  1925. }
  1926. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1927. {
  1928. callOnOwner (self, &NSViewComponentPeer::sendDragCallback, &NSViewComponentPeer::handleDragExit, sender);
  1929. }
  1930. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1931. {
  1932. return YES;
  1933. }
  1934. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1935. {
  1936. auto* owner = getOwner (self);
  1937. return owner != nullptr && owner->sendDragCallback (&NSViewComponentPeer::handleDragDrop, sender);
  1938. }
  1939. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1940. //==============================================================================
  1941. static BOOL getIsAccessibilityElement (id, SEL)
  1942. {
  1943. return NO;
  1944. }
  1945. static NSArray* getAccessibilityChildren (id self, SEL)
  1946. {
  1947. return NSAccessibilityUnignoredChildrenForOnlyChild (getAccessibleChild (self));
  1948. }
  1949. static id accessibilityHitTest (id self, SEL, NSPoint point)
  1950. {
  1951. return [getAccessibleChild (self) accessibilityHitTest: point];
  1952. }
  1953. static id getAccessibilityFocusedUIElement (id self, SEL)
  1954. {
  1955. return [getAccessibleChild (self) accessibilityFocusedUIElement];
  1956. }
  1957. static BOOL getAccessibilityIsIgnored (id, SEL)
  1958. {
  1959. return YES;
  1960. }
  1961. static id getAccessibilityAttributeValue (id self, SEL, NSString* attribute)
  1962. {
  1963. if ([attribute isEqualToString: NSAccessibilityChildrenAttribute])
  1964. return getAccessibilityChildren (self, {});
  1965. return sendSuperclassMessage<id> (self, @selector (accessibilityAttributeValue:), attribute);
  1966. }
  1967. static bool tryPassingKeyEventToPeer (NSEvent* e)
  1968. {
  1969. if ([e type] != NSEventTypeKeyDown && [e type] != NSEventTypeKeyUp)
  1970. return false;
  1971. if (auto* focused = Component::getCurrentlyFocusedComponent())
  1972. {
  1973. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (focused->getPeer()))
  1974. {
  1975. return [e type] == NSEventTypeKeyDown ? peer->redirectKeyDown (e)
  1976. : peer->redirectKeyUp (e);
  1977. }
  1978. }
  1979. return false;
  1980. }
  1981. static BOOL performKeyEquivalent (id self, SEL s, NSEvent* event)
  1982. {
  1983. // We try passing shortcut keys to the currently focused component first.
  1984. // If the component doesn't want the event, we'll fall back to the superclass
  1985. // implementation, which will pass the event to the main menu.
  1986. if (tryPassingKeyEventToPeer (event))
  1987. return YES;
  1988. return sendSuperclassMessage<BOOL> (self, s, event);
  1989. }
  1990. template <typename Func, typename... Args>
  1991. static void callOnOwner (id self, Func&& func, Args&&... args)
  1992. {
  1993. if (auto* owner = getOwner (self))
  1994. (owner->*func) (std::forward<Args> (args)...);
  1995. }
  1996. };
  1997. //==============================================================================
  1998. struct JuceNSWindowClass : public NSViewComponentPeerWrapper<ObjCClass<NSWindow>>
  1999. {
  2000. JuceNSWindowClass() : NSViewComponentPeerWrapper ("JUCEWindow_")
  2001. {
  2002. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow);
  2003. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow);
  2004. addMethod (@selector (becomeKeyWindow), becomeKeyWindow);
  2005. addMethod (@selector (resignKeyWindow), resignKeyWindow);
  2006. addMethod (@selector (windowShouldClose:), windowShouldClose);
  2007. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect);
  2008. addMethod (@selector (windowWillResize:toSize:), windowWillResize);
  2009. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen);
  2010. addMethod (@selector (windowWillEnterFullScreen:), windowWillEnterFullScreen);
  2011. addMethod (@selector (windowWillExitFullScreen:), windowWillExitFullScreen);
  2012. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize);
  2013. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize);
  2014. addMethod (@selector (window:shouldPopUpDocumentPathMenu:), shouldPopUpPathMenu);
  2015. addMethod (@selector (isFlipped), isFlipped);
  2016. addMethod (@selector (windowWillUseStandardFrame:defaultFrame:), windowWillUseStandardFrame);
  2017. addMethod (@selector (windowShouldZoom:toFrame:), windowShouldZoomToFrame);
  2018. addMethod (@selector (accessibilityTitle), getAccessibilityTitle);
  2019. addMethod (@selector (accessibilityLabel), getAccessibilityLabel);
  2020. addMethod (@selector (accessibilityTopLevelUIElement), getAccessibilityWindow);
  2021. addMethod (@selector (accessibilityWindow), getAccessibilityWindow);
  2022. addMethod (@selector (accessibilityRole), getAccessibilityRole);
  2023. addMethod (@selector (accessibilitySubrole), getAccessibilitySubrole);
  2024. addMethod (@selector (keyDown:), keyDown);
  2025. addMethod (@selector (window:shouldDragDocumentWithEvent:from:withPasteboard:), shouldAllowIconDrag);
  2026. addMethod (@selector (toggleFullScreen:), toggleFullScreen);
  2027. addProtocol (@protocol (NSWindowDelegate));
  2028. registerClass();
  2029. }
  2030. private:
  2031. //==============================================================================
  2032. static BOOL isFlipped (id, SEL) { return true; }
  2033. // Key events will be processed by the peer's component.
  2034. // If the component is unable to use the event, it will be re-sent
  2035. // to performKeyEquivalent.
  2036. // performKeyEquivalent will send the event to the view's superclass,
  2037. // which will try passing the event to the main menu.
  2038. // If the event still hasn't been processed, it will be passed to the
  2039. // next responder in the chain, which will be the NSWindow for a peer
  2040. // that is on the desktop.
  2041. // If the NSWindow still doesn't handle the event, the Apple docs imply
  2042. // that the event should be sent to the NSApp for processing, but this
  2043. // doesn't seem to happen for keyDown events.
  2044. // Instead, the NSWindow attempts to process the event, fails, and
  2045. // triggers an annoying NSBeep.
  2046. // Overriding keyDown to "handle" the event seems to suppress the beep.
  2047. static void keyDown (id, SEL, NSEvent* ev)
  2048. {
  2049. ignoreUnused (ev);
  2050. #if JUCE_DEBUG_UNHANDLED_KEYPRESSES
  2051. DBG ("unhandled key down event with keycode: " << [ev keyCode]);
  2052. #endif
  2053. }
  2054. static NSRect windowWillUseStandardFrame (id self, SEL, NSWindow* window, NSRect r)
  2055. {
  2056. if (auto* owner = getOwner (self))
  2057. {
  2058. if (auto* constrainer = owner->getConstrainer())
  2059. {
  2060. if (auto* screen = [window screen])
  2061. {
  2062. const auto safeScreenBounds = convertToRectFloat (flippedScreenRect (owner->hasNativeTitleBar() ? r : [screen visibleFrame]));
  2063. const auto originalBounds = owner->getFrameSize().addedTo (owner->getComponent().getScreenBounds()).toFloat();
  2064. const auto expanded = originalBounds.withWidth ((float) constrainer->getMaximumWidth())
  2065. .withHeight ((float) constrainer->getMaximumHeight());
  2066. const auto constrained = expanded.constrainedWithin (safeScreenBounds);
  2067. return flippedScreenRect (makeNSRect ([&]
  2068. {
  2069. if (constrained == owner->getBounds().toFloat())
  2070. return owner->lastSizeBeforeZoom.toFloat();
  2071. owner->lastSizeBeforeZoom = owner->getBounds().toFloat();
  2072. return constrained;
  2073. }()));
  2074. }
  2075. }
  2076. }
  2077. return r;
  2078. }
  2079. static BOOL windowShouldZoomToFrame (id self, SEL, NSWindow*, NSRect)
  2080. {
  2081. if (auto* owner = getOwner (self))
  2082. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  2083. return NO;
  2084. return YES;
  2085. }
  2086. static BOOL canBecomeKeyWindow (id self, SEL)
  2087. {
  2088. auto* owner = getOwner (self);
  2089. return owner != nullptr
  2090. && owner->canBecomeKeyWindow()
  2091. && ! owner->isBlockedByModalComponent();
  2092. }
  2093. static BOOL canBecomeMainWindow (id self, SEL)
  2094. {
  2095. auto* owner = getOwner (self);
  2096. return owner != nullptr
  2097. && owner->canBecomeMainWindow()
  2098. && ! owner->isBlockedByModalComponent();
  2099. }
  2100. static void becomeKeyWindow (id self, SEL)
  2101. {
  2102. sendSuperclassMessage<void> (self, @selector (becomeKeyWindow));
  2103. if (auto* owner = getOwner (self))
  2104. {
  2105. if (owner->canBecomeKeyWindow())
  2106. {
  2107. owner->becomeKeyWindow();
  2108. return;
  2109. }
  2110. // this fixes a bug causing hidden windows to sometimes become visible when the app regains focus
  2111. if (! owner->getComponent().isVisible())
  2112. [(NSWindow*) self orderOut: nil];
  2113. }
  2114. }
  2115. static void resignKeyWindow (id self, SEL)
  2116. {
  2117. sendSuperclassMessage<void> (self, @selector (resignKeyWindow));
  2118. if (auto* owner = getOwner (self))
  2119. owner->resignKeyWindow();
  2120. }
  2121. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  2122. {
  2123. auto* owner = getOwner (self);
  2124. return owner == nullptr || owner->windowShouldClose();
  2125. }
  2126. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen* screen)
  2127. {
  2128. if (auto* owner = getOwner (self))
  2129. {
  2130. frameRect = sendSuperclassMessage<NSRect, NSRect, NSScreen*> (self, @selector (constrainFrameRect:toScreen:),
  2131. frameRect, screen);
  2132. frameRect = owner->constrainRect (frameRect);
  2133. }
  2134. return frameRect;
  2135. }
  2136. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  2137. {
  2138. auto* owner = getOwner (self);
  2139. if (owner == nullptr || owner->isZooming)
  2140. return proposedFrameSize;
  2141. NSRect frameRect = flippedScreenRect ([(NSWindow*) self frame]);
  2142. frameRect.size = proposedFrameSize;
  2143. frameRect = owner->constrainRect (flippedScreenRect (frameRect));
  2144. owner->dismissModals();
  2145. return frameRect.size;
  2146. }
  2147. static void toggleFullScreen (id self, SEL name, id sender)
  2148. {
  2149. if (auto* owner = getOwner (self))
  2150. {
  2151. const auto isFullScreen = owner->isFullScreen();
  2152. if (! isFullScreen)
  2153. owner->lastSizeBeforeZoom = owner->getBounds().toFloat();
  2154. sendSuperclassMessage<void> (self, name, sender);
  2155. if (isFullScreen)
  2156. {
  2157. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  2158. owner->setBounds (owner->lastSizeBeforeZoom.toNearestInt(), false);
  2159. }
  2160. }
  2161. }
  2162. static void windowDidExitFullScreen (id self, SEL, NSNotification*)
  2163. {
  2164. if (auto* owner = getOwner (self))
  2165. owner->resetWindowPresentation();
  2166. }
  2167. static void windowWillExitFullScreen (id self, SEL, NSNotification*)
  2168. {
  2169. // The exit-fullscreen animation looks bad on Monterey if the window isn't resizable...
  2170. if (auto* owner = getOwner (self))
  2171. if (auto* window = owner->window)
  2172. [window setStyleMask: [window styleMask] | NSWindowStyleMaskResizable];
  2173. }
  2174. static void windowWillEnterFullScreen (id self, SEL, NSNotification*)
  2175. {
  2176. if (SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_9)
  2177. return;
  2178. if (auto* owner = getOwner (self))
  2179. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  2180. [owner->window setStyleMask: NSWindowStyleMaskBorderless];
  2181. }
  2182. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  2183. {
  2184. if (auto* owner = getOwner (self))
  2185. owner->liveResizingStart();
  2186. }
  2187. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  2188. {
  2189. if (auto* owner = getOwner (self))
  2190. owner->liveResizingEnd();
  2191. }
  2192. static bool shouldPopUpPathMenu (id self, SEL, id /*window*/, NSMenu*)
  2193. {
  2194. if (auto* owner = getOwner (self))
  2195. return owner->windowRepresentsFile;
  2196. return false;
  2197. }
  2198. static bool shouldAllowIconDrag (id self, SEL, id /*window*/, NSEvent*, NSPoint, NSPasteboard*)
  2199. {
  2200. if (auto* owner = getOwner (self))
  2201. return owner->windowRepresentsFile;
  2202. return false;
  2203. }
  2204. static NSString* getAccessibilityTitle (id self, SEL)
  2205. {
  2206. return [self title];
  2207. }
  2208. static NSString* getAccessibilityLabel (id self, SEL)
  2209. {
  2210. return [getAccessibleChild (self) accessibilityLabel];
  2211. }
  2212. static id getAccessibilityWindow (id self, SEL)
  2213. {
  2214. return self;
  2215. }
  2216. static NSAccessibilityRole getAccessibilityRole (id, SEL)
  2217. {
  2218. return NSAccessibilityWindowRole;
  2219. }
  2220. static NSAccessibilityRole getAccessibilitySubrole (id self, SEL)
  2221. {
  2222. if (@available (macOS 10.10, *))
  2223. return [getAccessibleChild (self) accessibilitySubrole];
  2224. return nil;
  2225. }
  2226. };
  2227. NSView* NSViewComponentPeer::createViewInstance()
  2228. {
  2229. static JuceNSViewClass cls;
  2230. return cls.createInstance();
  2231. }
  2232. NSWindow* NSViewComponentPeer::createWindowInstance()
  2233. {
  2234. static JuceNSWindowClass cls;
  2235. return cls.createInstance();
  2236. }
  2237. //==============================================================================
  2238. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  2239. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  2240. //==============================================================================
  2241. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  2242. {
  2243. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  2244. return true;
  2245. if (keyCode >= 'A' && keyCode <= 'Z'
  2246. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  2247. return true;
  2248. if (keyCode >= 'a' && keyCode <= 'z'
  2249. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  2250. return true;
  2251. return false;
  2252. }
  2253. //==============================================================================
  2254. bool MouseInputSource::SourceList::addSource()
  2255. {
  2256. if (sources.size() == 0)
  2257. {
  2258. addSource (0, MouseInputSource::InputSourceType::mouse);
  2259. return true;
  2260. }
  2261. return false;
  2262. }
  2263. bool MouseInputSource::SourceList::canUseTouch()
  2264. {
  2265. return false;
  2266. }
  2267. //==============================================================================
  2268. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  2269. {
  2270. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  2271. jassert (peer != nullptr); // (this should have been checked by the caller)
  2272. if (peer->hasNativeTitleBar())
  2273. {
  2274. if (shouldBeEnabled && ! allowMenusAndBars)
  2275. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  2276. else if (! shouldBeEnabled)
  2277. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  2278. peer->setFullScreen (true);
  2279. }
  2280. else
  2281. {
  2282. if (shouldBeEnabled)
  2283. {
  2284. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  2285. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  2286. kioskComp->setBounds (getDisplays().getDisplayForRect (kioskComp->getScreenBounds())->totalArea);
  2287. peer->becomeKeyWindow();
  2288. }
  2289. else
  2290. {
  2291. peer->resetWindowPresentation();
  2292. }
  2293. }
  2294. }
  2295. void Desktop::allowedOrientationsChanged() {}
  2296. //==============================================================================
  2297. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  2298. {
  2299. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  2300. }
  2301. //==============================================================================
  2302. const int KeyPress::spaceKey = ' ';
  2303. const int KeyPress::returnKey = 0x0d;
  2304. const int KeyPress::escapeKey = 0x1b;
  2305. const int KeyPress::backspaceKey = 0x7f;
  2306. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  2307. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  2308. const int KeyPress::upKey = NSUpArrowFunctionKey;
  2309. const int KeyPress::downKey = NSDownArrowFunctionKey;
  2310. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  2311. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  2312. const int KeyPress::endKey = NSEndFunctionKey;
  2313. const int KeyPress::homeKey = NSHomeFunctionKey;
  2314. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  2315. const int KeyPress::insertKey = -1;
  2316. const int KeyPress::tabKey = 9;
  2317. const int KeyPress::F1Key = NSF1FunctionKey;
  2318. const int KeyPress::F2Key = NSF2FunctionKey;
  2319. const int KeyPress::F3Key = NSF3FunctionKey;
  2320. const int KeyPress::F4Key = NSF4FunctionKey;
  2321. const int KeyPress::F5Key = NSF5FunctionKey;
  2322. const int KeyPress::F6Key = NSF6FunctionKey;
  2323. const int KeyPress::F7Key = NSF7FunctionKey;
  2324. const int KeyPress::F8Key = NSF8FunctionKey;
  2325. const int KeyPress::F9Key = NSF9FunctionKey;
  2326. const int KeyPress::F10Key = NSF10FunctionKey;
  2327. const int KeyPress::F11Key = NSF11FunctionKey;
  2328. const int KeyPress::F12Key = NSF12FunctionKey;
  2329. const int KeyPress::F13Key = NSF13FunctionKey;
  2330. const int KeyPress::F14Key = NSF14FunctionKey;
  2331. const int KeyPress::F15Key = NSF15FunctionKey;
  2332. const int KeyPress::F16Key = NSF16FunctionKey;
  2333. const int KeyPress::F17Key = NSF17FunctionKey;
  2334. const int KeyPress::F18Key = NSF18FunctionKey;
  2335. const int KeyPress::F19Key = NSF19FunctionKey;
  2336. const int KeyPress::F20Key = NSF20FunctionKey;
  2337. const int KeyPress::F21Key = NSF21FunctionKey;
  2338. const int KeyPress::F22Key = NSF22FunctionKey;
  2339. const int KeyPress::F23Key = NSF23FunctionKey;
  2340. const int KeyPress::F24Key = NSF24FunctionKey;
  2341. const int KeyPress::F25Key = NSF25FunctionKey;
  2342. const int KeyPress::F26Key = NSF26FunctionKey;
  2343. const int KeyPress::F27Key = NSF27FunctionKey;
  2344. const int KeyPress::F28Key = NSF28FunctionKey;
  2345. const int KeyPress::F29Key = NSF29FunctionKey;
  2346. const int KeyPress::F30Key = NSF30FunctionKey;
  2347. const int KeyPress::F31Key = NSF31FunctionKey;
  2348. const int KeyPress::F32Key = NSF32FunctionKey;
  2349. const int KeyPress::F33Key = NSF33FunctionKey;
  2350. const int KeyPress::F34Key = NSF34FunctionKey;
  2351. const int KeyPress::F35Key = NSF35FunctionKey;
  2352. const int KeyPress::numberPad0 = extendedKeyModifier + 0x20;
  2353. const int KeyPress::numberPad1 = extendedKeyModifier + 0x21;
  2354. const int KeyPress::numberPad2 = extendedKeyModifier + 0x22;
  2355. const int KeyPress::numberPad3 = extendedKeyModifier + 0x23;
  2356. const int KeyPress::numberPad4 = extendedKeyModifier + 0x24;
  2357. const int KeyPress::numberPad5 = extendedKeyModifier + 0x25;
  2358. const int KeyPress::numberPad6 = extendedKeyModifier + 0x26;
  2359. const int KeyPress::numberPad7 = extendedKeyModifier + 0x27;
  2360. const int KeyPress::numberPad8 = extendedKeyModifier + 0x28;
  2361. const int KeyPress::numberPad9 = extendedKeyModifier + 0x29;
  2362. const int KeyPress::numberPadAdd = extendedKeyModifier + 0x2a;
  2363. const int KeyPress::numberPadSubtract = extendedKeyModifier + 0x2b;
  2364. const int KeyPress::numberPadMultiply = extendedKeyModifier + 0x2c;
  2365. const int KeyPress::numberPadDivide = extendedKeyModifier + 0x2d;
  2366. const int KeyPress::numberPadSeparator = extendedKeyModifier + 0x2e;
  2367. const int KeyPress::numberPadDecimalPoint = extendedKeyModifier + 0x2f;
  2368. const int KeyPress::numberPadEquals = extendedKeyModifier + 0x30;
  2369. const int KeyPress::numberPadDelete = extendedKeyModifier + 0x31;
  2370. const int KeyPress::playKey = extendedKeyModifier + 0x00;
  2371. const int KeyPress::stopKey = extendedKeyModifier + 0x01;
  2372. const int KeyPress::fastForwardKey = extendedKeyModifier + 0x02;
  2373. const int KeyPress::rewindKey = extendedKeyModifier + 0x03;
  2374. } // namespace juce