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 87KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - 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 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-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. #if defined (MAC_OS_X_VERSION_10_8) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_8) \
  24. && USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_DRAW_ASYNC
  25. static const juce::Identifier disableAsyncLayerBackedViewIdentifier { "disableAsyncLayerBackedView" };
  26. void setComponentAsyncLayerBackedViewDisabled (juce::Component& comp, bool shouldDisableAsyncLayerBackedView)
  27. {
  28. comp.getProperties().set (disableAsyncLayerBackedViewIdentifier, shouldDisableAsyncLayerBackedView);
  29. }
  30. bool getComponentAsyncLayerBackedViewDisabled (juce::Component& comp)
  31. {
  32. return comp.getProperties()[disableAsyncLayerBackedViewIdentifier];
  33. }
  34. #endif
  35. //==============================================================================
  36. namespace juce
  37. {
  38. typedef void (*AppFocusChangeCallback)();
  39. extern AppFocusChangeCallback appFocusChangeCallback;
  40. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  41. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  42. }
  43. namespace juce
  44. {
  45. //==============================================================================
  46. static CGFloat getMainScreenHeight() noexcept
  47. {
  48. if ([[NSScreen screens] count] == 0)
  49. return 0.0f;
  50. return [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  51. }
  52. static void flipScreenRect (NSRect& r) noexcept
  53. {
  54. r.origin.y = getMainScreenHeight() - (r.origin.y + r.size.height);
  55. }
  56. static NSRect flippedScreenRect (NSRect r) noexcept
  57. {
  58. flipScreenRect (r);
  59. return r;
  60. }
  61. //==============================================================================
  62. class NSViewComponentPeer : public ComponentPeer,
  63. private Timer
  64. {
  65. public:
  66. NSViewComponentPeer (Component& comp, const int windowStyleFlags, NSView* viewToAttachTo)
  67. : ComponentPeer (comp, windowStyleFlags),
  68. safeComponent (&comp),
  69. isSharedWindow (viewToAttachTo != nil),
  70. lastRepaintTime (Time::getMillisecondCounter())
  71. {
  72. appFocusChangeCallback = appFocusChanged;
  73. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  74. auto r = makeNSRect (component.getLocalBounds());
  75. view = [createViewInstance() initWithFrame: r];
  76. setOwner (view, this);
  77. [view registerForDraggedTypes: getSupportedDragTypes()];
  78. notificationCenter = [NSNotificationCenter defaultCenter];
  79. [notificationCenter addObserver: view
  80. selector: @selector (frameChanged:)
  81. name: NSViewFrameDidChangeNotification
  82. object: view];
  83. [view setPostsFrameChangedNotifications: YES];
  84. #if defined (MAC_OS_X_VERSION_10_8) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_8) \
  85. && USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_DRAW_ASYNC
  86. if (! getComponentAsyncLayerBackedViewDisabled (component))
  87. {
  88. [view setWantsLayer: YES];
  89. [[view layer] setDrawsAsynchronously: YES];
  90. }
  91. #endif
  92. if (isSharedWindow)
  93. {
  94. window = [viewToAttachTo window];
  95. [viewToAttachTo addSubview: view];
  96. }
  97. else
  98. {
  99. r.origin.x = (CGFloat) component.getX();
  100. r.origin.y = (CGFloat) component.getY();
  101. flipScreenRect (r);
  102. window = [createWindowInstance() initWithContentRect: r
  103. styleMask: getNSWindowStyleMask (windowStyleFlags)
  104. backing: NSBackingStoreBuffered
  105. defer: YES];
  106. setOwner (window, this);
  107. [window orderOut: nil];
  108. [window setDelegate: (id<NSWindowDelegate>) window];
  109. [window setOpaque: component.isOpaque()];
  110. if (! [window isOpaque])
  111. [window setBackgroundColor: [NSColor clearColor]];
  112. #if defined (MAC_OS_X_VERSION_10_9) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9)
  113. [view setAppearance: [NSAppearance appearanceNamed: NSAppearanceNameAqua]];
  114. #endif
  115. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  116. if (component.isAlwaysOnTop())
  117. setAlwaysOnTop (true);
  118. [window setContentView: view];
  119. [window setAcceptsMouseMovedEvents: YES];
  120. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  121. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  122. [window setReleasedWhenClosed: YES];
  123. [window retain];
  124. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  125. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  126. if ((windowStyleFlags & (windowHasMaximiseButton | windowHasTitleBar)) == (windowHasMaximiseButton | windowHasTitleBar))
  127. [window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
  128. if ([window respondsToSelector: @selector (setRestorable:)])
  129. [window setRestorable: NO];
  130. #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
  131. if ([window respondsToSelector: @selector (setTabbingMode:)])
  132. [window setTabbingMode: NSWindowTabbingModeDisallowed];
  133. #endif
  134. [notificationCenter addObserver: view
  135. selector: @selector (frameChanged:)
  136. name: NSWindowDidMoveNotification
  137. object: window];
  138. [notificationCenter addObserver: view
  139. selector: @selector (frameChanged:)
  140. name: NSWindowDidMiniaturizeNotification
  141. object: window];
  142. [notificationCenter addObserver: view
  143. selector: @selector (windowWillMiniaturize:)
  144. name: NSWindowWillMiniaturizeNotification
  145. object: window];
  146. [notificationCenter addObserver: view
  147. selector: @selector (windowDidDeminiaturize:)
  148. name: NSWindowDidDeminiaturizeNotification
  149. object: window];
  150. }
  151. auto alpha = component.getAlpha();
  152. if (alpha < 1.0f)
  153. setAlpha (alpha);
  154. setTitle (component.getName());
  155. getNativeRealtimeModifiers = []
  156. {
  157. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  158. NSViewComponentPeer::updateModifiers ([NSEvent modifierFlags]);
  159. return ModifierKeys::currentModifiers;
  160. };
  161. }
  162. ~NSViewComponentPeer() override
  163. {
  164. [notificationCenter removeObserver: view];
  165. setOwner (view, nullptr);
  166. if ([view superview] != nil)
  167. {
  168. redirectWillMoveToWindow (nullptr);
  169. [view removeFromSuperview];
  170. }
  171. if (! isSharedWindow)
  172. {
  173. setOwner (window, nullptr);
  174. [window setContentView: nil];
  175. [window close];
  176. [window release];
  177. }
  178. [view release];
  179. }
  180. //==============================================================================
  181. void* getNativeHandle() const override { return view; }
  182. void setVisible (bool shouldBeVisible) override
  183. {
  184. if (isSharedWindow)
  185. {
  186. if (shouldBeVisible)
  187. [view setHidden: false];
  188. else if ([window firstResponder] != view || ([window firstResponder] == view && [window makeFirstResponder: nil]))
  189. [view setHidden: true];
  190. }
  191. else
  192. {
  193. if (shouldBeVisible)
  194. {
  195. ++insideToFrontCall;
  196. [window orderFront: nil];
  197. --insideToFrontCall;
  198. handleBroughtToFront();
  199. }
  200. else
  201. {
  202. [window orderOut: nil];
  203. }
  204. }
  205. }
  206. void setTitle (const String& title) override
  207. {
  208. JUCE_AUTORELEASEPOOL
  209. {
  210. if (! isSharedWindow)
  211. [window setTitle: juceStringToNS (title)];
  212. }
  213. }
  214. bool setDocumentEditedStatus (bool edited) override
  215. {
  216. if (! hasNativeTitleBar())
  217. return false;
  218. [window setDocumentEdited: edited];
  219. return true;
  220. }
  221. void setRepresentedFile (const File& file) override
  222. {
  223. if (! isSharedWindow)
  224. {
  225. [window setRepresentedFilename: juceStringToNS (file != File()
  226. ? file.getFullPathName()
  227. : String())];
  228. windowRepresentsFile = (file != File());
  229. }
  230. }
  231. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  232. {
  233. fullScreen = isNowFullScreen;
  234. auto r = makeNSRect (newBounds);
  235. auto oldViewSize = [view frame].size;
  236. if (isSharedWindow)
  237. {
  238. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  239. [view setFrame: r];
  240. }
  241. else
  242. {
  243. // Repaint behaviour of setFrame seemed to change in 10.11, and the drawing became synchronous,
  244. // causing performance issues. But sending an async update causes flickering in older versions,
  245. // hence this version check to use the old behaviour on pre 10.11 machines
  246. static bool isPre10_11 = SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_10;
  247. [window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
  248. display: isPre10_11];
  249. }
  250. if (oldViewSize.width != r.size.width || oldViewSize.height != r.size.height)
  251. [view setNeedsDisplay: true];
  252. }
  253. Rectangle<int> getBounds (const bool global) const
  254. {
  255. auto r = [view frame];
  256. NSWindow* viewWindow = [view window];
  257. if (global && viewWindow != nil)
  258. {
  259. r = [[view superview] convertRect: r toView: nil];
  260. r = [viewWindow convertRectToScreen: r];
  261. flipScreenRect (r);
  262. }
  263. else
  264. {
  265. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  266. }
  267. return convertToRectInt (r);
  268. }
  269. Rectangle<int> getBounds() const override
  270. {
  271. return getBounds (! isSharedWindow);
  272. }
  273. Point<float> localToGlobal (Point<float> relativePosition) override
  274. {
  275. return relativePosition + getBounds (true).getPosition().toFloat();
  276. }
  277. using ComponentPeer::localToGlobal;
  278. Point<float> globalToLocal (Point<float> screenPosition) override
  279. {
  280. return screenPosition - getBounds (true).getPosition().toFloat();
  281. }
  282. using ComponentPeer::globalToLocal;
  283. void setAlpha (float newAlpha) override
  284. {
  285. if (isSharedWindow)
  286. [view setAlphaValue: (CGFloat) newAlpha];
  287. else
  288. [window setAlphaValue: (CGFloat) newAlpha];
  289. }
  290. void setMinimised (bool shouldBeMinimised) override
  291. {
  292. if (! isSharedWindow)
  293. {
  294. if (shouldBeMinimised)
  295. [window miniaturize: nil];
  296. else
  297. [window deminiaturize: nil];
  298. }
  299. }
  300. bool isMinimised() const override
  301. {
  302. return [window isMiniaturized];
  303. }
  304. void setFullScreen (bool shouldBeFullScreen) override
  305. {
  306. if (! isSharedWindow)
  307. {
  308. auto r = lastNonFullscreenBounds;
  309. if (isMinimised())
  310. setMinimised (false);
  311. if (fullScreen != shouldBeFullScreen)
  312. {
  313. if (shouldBeFullScreen && hasNativeTitleBar())
  314. {
  315. fullScreen = true;
  316. [window performZoom: nil];
  317. }
  318. else
  319. {
  320. if (shouldBeFullScreen)
  321. r = component.getParentMonitorArea();
  322. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  323. if (r != component.getBounds() && ! r.isEmpty())
  324. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  325. }
  326. }
  327. }
  328. }
  329. bool isFullScreen() const override
  330. {
  331. return fullScreen;
  332. }
  333. bool isKioskMode() const override
  334. {
  335. return isWindowInKioskMode || ComponentPeer::isKioskMode();
  336. }
  337. static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
  338. {
  339. if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
  340. return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
  341. return true;
  342. }
  343. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  344. {
  345. NSRect viewFrame = [view frame];
  346. if (! (isPositiveAndBelow (localPos.getX(), viewFrame.size.width)
  347. && isPositiveAndBelow (localPos.getY(), viewFrame.size.height)))
  348. return false;
  349. if (! SystemStats::isRunningInAppExtensionSandbox())
  350. {
  351. if (NSWindow* const viewWindow = [view window])
  352. {
  353. NSRect windowFrame = [viewWindow frame];
  354. NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, viewFrame.size.height - localPos.y) toView: nil];
  355. NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
  356. windowFrame.origin.y + windowPoint.y);
  357. if (! isWindowAtPoint (viewWindow, screenPoint))
  358. return false;
  359. }
  360. }
  361. NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
  362. viewFrame.origin.y + viewFrame.size.height - localPos.getY())];
  363. return trueIfInAChildWindow ? (v != nil)
  364. : (v == view);
  365. }
  366. BorderSize<int> getFrameSize() const override
  367. {
  368. BorderSize<int> b;
  369. if (! isSharedWindow)
  370. {
  371. NSRect v = [view convertRect: [view frame] toView: nil];
  372. NSRect w = [window frame];
  373. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  374. b.setBottom ((int) v.origin.y);
  375. b.setLeft ((int) v.origin.x);
  376. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  377. }
  378. return b;
  379. }
  380. void updateFullscreenStatus()
  381. {
  382. if (hasNativeTitleBar())
  383. {
  384. isWindowInKioskMode = (([window styleMask] & NSWindowStyleMaskFullScreen) != 0);
  385. auto screen = getFrameSize().subtractedFrom (component.getParentMonitorArea());
  386. fullScreen = component.getScreenBounds().expanded (2, 2).contains (screen);
  387. }
  388. else
  389. {
  390. isWindowInKioskMode = false;
  391. }
  392. }
  393. bool hasNativeTitleBar() const
  394. {
  395. return (getStyleFlags() & windowHasTitleBar) != 0;
  396. }
  397. bool setAlwaysOnTop (bool alwaysOnTop) override
  398. {
  399. if (! isSharedWindow)
  400. {
  401. [window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
  402. : NSFloatingWindowLevel)
  403. : NSNormalWindowLevel];
  404. isAlwaysOnTop = alwaysOnTop;
  405. }
  406. return true;
  407. }
  408. void toFront (bool makeActiveWindow) override
  409. {
  410. if (isSharedWindow)
  411. [[view superview] addSubview: view
  412. positioned: NSWindowAbove
  413. relativeTo: nil];
  414. if (window != nil && component.isVisible())
  415. {
  416. ++insideToFrontCall;
  417. if (makeActiveWindow)
  418. [window makeKeyAndOrderFront: nil];
  419. else
  420. [window orderFront: nil];
  421. if (insideToFrontCall <= 1)
  422. {
  423. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  424. handleBroughtToFront();
  425. }
  426. --insideToFrontCall;
  427. }
  428. }
  429. void toBehind (ComponentPeer* other) override
  430. {
  431. if (auto* otherPeer = dynamic_cast<NSViewComponentPeer*> (other))
  432. {
  433. if (isSharedWindow)
  434. {
  435. [[view superview] addSubview: view
  436. positioned: NSWindowBelow
  437. relativeTo: otherPeer->view];
  438. }
  439. else if (component.isVisible())
  440. {
  441. [window orderWindow: NSWindowBelow
  442. relativeTo: [otherPeer->window windowNumber]];
  443. }
  444. }
  445. else
  446. {
  447. jassertfalse; // wrong type of window?
  448. }
  449. }
  450. void setIcon (const Image& newIcon) override
  451. {
  452. if (! isSharedWindow)
  453. {
  454. // need to set a dummy represented file here to show the file icon (which we then set to the new icon)
  455. if (! windowRepresentsFile)
  456. [window setRepresentedFilename:juceStringToNS (" ")]; // can't just use an empty string for some reason...
  457. [[window standardWindowButton:NSWindowDocumentIconButton] setImage:imageToNSImage (newIcon)];
  458. }
  459. }
  460. StringArray getAvailableRenderingEngines() override
  461. {
  462. StringArray s ("Software Renderer");
  463. #if USE_COREGRAPHICS_RENDERING
  464. s.add ("CoreGraphics Renderer");
  465. #endif
  466. return s;
  467. }
  468. int getCurrentRenderingEngine() const override
  469. {
  470. return usingCoreGraphics ? 1 : 0;
  471. }
  472. void setCurrentRenderingEngine (int index) override
  473. {
  474. #if USE_COREGRAPHICS_RENDERING
  475. if (usingCoreGraphics != (index > 0))
  476. {
  477. usingCoreGraphics = index > 0;
  478. [view setNeedsDisplay: true];
  479. }
  480. #else
  481. ignoreUnused (index);
  482. #endif
  483. }
  484. void redirectMouseDown (NSEvent* ev)
  485. {
  486. if (! Process::isForegroundProcess())
  487. Process::makeForegroundProcess();
  488. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  489. sendMouseEvent (ev);
  490. }
  491. void redirectMouseUp (NSEvent* ev)
  492. {
  493. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  494. sendMouseEvent (ev);
  495. showArrowCursorIfNeeded();
  496. }
  497. void redirectMouseDrag (NSEvent* ev)
  498. {
  499. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  500. sendMouseEvent (ev);
  501. }
  502. void redirectMouseMove (NSEvent* ev)
  503. {
  504. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  505. NSPoint windowPos = [ev locationInWindow];
  506. NSPoint screenPos = [[ev window] convertRectToScreen: NSMakeRect (windowPos.x, windowPos.y, 1.0f, 1.0f)].origin;
  507. if (isWindowAtPoint ([ev window], screenPos))
  508. sendMouseEvent (ev);
  509. else
  510. // moved into another window which overlaps this one, so trigger an exit
  511. handleMouseEvent (MouseInputSource::InputSourceType::mouse, MouseInputSource::offscreenMousePos, ModifierKeys::currentModifiers,
  512. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  513. showArrowCursorIfNeeded();
  514. }
  515. void redirectMouseEnter (NSEvent* ev)
  516. {
  517. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  518. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  519. sendMouseEvent (ev);
  520. }
  521. void redirectMouseExit (NSEvent* ev)
  522. {
  523. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withoutMouseButtons();
  524. sendMouseEvent (ev);
  525. }
  526. static float checkDeviceDeltaReturnValue (float v) noexcept
  527. {
  528. // (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
  529. v *= 0.5f / 256.0f;
  530. return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
  531. }
  532. void redirectMouseWheel (NSEvent* ev)
  533. {
  534. updateModifiers (ev);
  535. MouseWheelDetails wheel;
  536. wheel.deltaX = 0;
  537. wheel.deltaY = 0;
  538. wheel.isReversed = false;
  539. wheel.isSmooth = false;
  540. wheel.isInertial = false;
  541. @try
  542. {
  543. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  544. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  545. wheel.isInertial = ([ev momentumPhase] != NSEventPhaseNone);
  546. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  547. {
  548. if ([ev hasPreciseScrollingDeltas])
  549. {
  550. const float scale = 0.5f / 256.0f;
  551. wheel.deltaX = scale * (float) [ev scrollingDeltaX];
  552. wheel.deltaY = scale * (float) [ev scrollingDeltaY];
  553. wheel.isSmooth = true;
  554. }
  555. }
  556. else if ([ev respondsToSelector: @selector (deviceDeltaX)])
  557. {
  558. wheel.deltaX = checkDeviceDeltaReturnValue ([ev deviceDeltaX]);
  559. wheel.deltaY = checkDeviceDeltaReturnValue ([ev deviceDeltaY]);
  560. }
  561. }
  562. @catch (...)
  563. {}
  564. if (wheel.deltaX == 0.0f && wheel.deltaY == 0.0f)
  565. {
  566. const float scale = 10.0f / 256.0f;
  567. wheel.deltaX = scale * (float) [ev deltaX];
  568. wheel.deltaY = scale * (float) [ev deltaY];
  569. }
  570. handleMouseWheel (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), wheel);
  571. }
  572. void redirectMagnify (NSEvent* ev)
  573. {
  574. const float invScale = 1.0f - (float) [ev magnification];
  575. if (invScale > 0.0f)
  576. handleMagnifyGesture (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
  577. }
  578. void redirectCopy (NSObject*) { handleKeyPress (KeyPress ('c', ModifierKeys (ModifierKeys::commandModifier), 'c')); }
  579. void redirectPaste (NSObject*) { handleKeyPress (KeyPress ('v', ModifierKeys (ModifierKeys::commandModifier), 'v')); }
  580. void redirectCut (NSObject*) { handleKeyPress (KeyPress ('x', ModifierKeys (ModifierKeys::commandModifier), 'x')); }
  581. void redirectWillMoveToWindow (NSWindow* newWindow)
  582. {
  583. if (isSharedWindow && [view window] == window && newWindow == nullptr)
  584. {
  585. if (auto* comp = safeComponent.get())
  586. comp->setVisible (false);
  587. }
  588. }
  589. void sendMouseEvent (NSEvent* ev)
  590. {
  591. updateModifiers (ev);
  592. handleMouseEvent (MouseInputSource::InputSourceType::mouse, getMousePos (ev, view), ModifierKeys::currentModifiers,
  593. getMousePressure (ev), MouseInputSource::invalidOrientation, getMouseTime (ev));
  594. }
  595. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  596. {
  597. auto unicode = nsStringToJuce ([ev characters]);
  598. auto keyCode = getKeyCodeFromEvent (ev);
  599. #if JUCE_DEBUG_KEYCODES
  600. DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  601. auto unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  602. DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  603. #endif
  604. if (keyCode != 0 || unicode.isNotEmpty())
  605. {
  606. if (isKeyDown)
  607. {
  608. bool used = false;
  609. for (auto u = unicode.getCharPointer(); ! u.isEmpty();)
  610. {
  611. auto textCharacter = u.getAndAdvance();
  612. switch (keyCode)
  613. {
  614. case NSLeftArrowFunctionKey:
  615. case NSRightArrowFunctionKey:
  616. case NSUpArrowFunctionKey:
  617. case NSDownArrowFunctionKey:
  618. case NSPageUpFunctionKey:
  619. case NSPageDownFunctionKey:
  620. case NSEndFunctionKey:
  621. case NSHomeFunctionKey:
  622. case NSDeleteFunctionKey:
  623. textCharacter = 0;
  624. break; // (these all seem to generate unwanted garbage unicode strings)
  625. default:
  626. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0
  627. || (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
  628. textCharacter = 0;
  629. break;
  630. }
  631. used = handleKeyUpOrDown (true) || used;
  632. used = handleKeyPress (keyCode, textCharacter) || used;
  633. }
  634. return used;
  635. }
  636. if (handleKeyUpOrDown (false))
  637. return true;
  638. }
  639. return false;
  640. }
  641. bool redirectKeyDown (NSEvent* ev)
  642. {
  643. // (need to retain this in case a modal loop runs in handleKeyEvent and
  644. // our event object gets lost)
  645. const std::unique_ptr<NSEvent, NSObjectDeleter> r ([ev retain]);
  646. updateKeysDown (ev, true);
  647. bool used = handleKeyEvent (ev, true);
  648. if (([ev modifierFlags] & NSEventModifierFlagCommand) != 0)
  649. {
  650. // for command keys, the key-up event is thrown away, so simulate one..
  651. updateKeysDown (ev, false);
  652. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  653. }
  654. // (If we're running modally, don't allow unused keystrokes to be passed
  655. // along to other blocked views..)
  656. if (Component::getCurrentlyModalComponent() != nullptr)
  657. used = true;
  658. return used;
  659. }
  660. bool redirectKeyUp (NSEvent* ev)
  661. {
  662. updateKeysDown (ev, false);
  663. return handleKeyEvent (ev, false)
  664. || Component::getCurrentlyModalComponent() != nullptr;
  665. }
  666. void redirectModKeyChange (NSEvent* ev)
  667. {
  668. // (need to retain this in case a modal loop runs and our event object gets lost)
  669. const std::unique_ptr<NSEvent, NSObjectDeleter> r ([ev retain]);
  670. keysCurrentlyDown.clear();
  671. handleKeyUpOrDown (true);
  672. updateModifiers (ev);
  673. handleModifierKeysChange();
  674. }
  675. //==============================================================================
  676. void drawRect (NSRect r)
  677. {
  678. if (r.size.width < 1.0f || r.size.height < 1.0f)
  679. return;
  680. auto cg = (CGContextRef) [[NSGraphicsContext currentContext]
  681. #if (defined (MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10)
  682. CGContext];
  683. #else
  684. graphicsPort];
  685. #endif
  686. if (! component.isOpaque())
  687. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  688. float displayScale = 1.0f;
  689. NSScreen* screen = [[view window] screen];
  690. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  691. displayScale = (float) screen.backingScaleFactor;
  692. #if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
  693. // This option invokes a separate paint call for each rectangle of the clip region.
  694. // It's a long story, but this is a basically a workaround for a CGContext not having
  695. // a way of finding whether a rectangle falls within its clip region
  696. if (usingCoreGraphics)
  697. {
  698. const NSRect* rects = nullptr;
  699. NSInteger numRects = 0;
  700. [view getRectsBeingDrawn: &rects count: &numRects];
  701. if (numRects > 1)
  702. {
  703. for (int i = 0; i < numRects; ++i)
  704. {
  705. NSRect rect = rects[i];
  706. CGContextSaveGState (cg);
  707. CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
  708. drawRect (cg, rect, displayScale);
  709. CGContextRestoreGState (cg);
  710. }
  711. return;
  712. }
  713. }
  714. #endif
  715. drawRect (cg, r, displayScale);
  716. }
  717. void drawRect (CGContextRef cg, NSRect r, float displayScale)
  718. {
  719. #if USE_COREGRAPHICS_RENDERING
  720. if (usingCoreGraphics)
  721. {
  722. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  723. invokePaint (context);
  724. }
  725. else
  726. #endif
  727. {
  728. const Point<int> offset (-roundToInt (r.origin.x),
  729. -roundToInt ([view frame].size.height - (r.origin.y + r.size.height)));
  730. auto clipW = (int) (r.size.width + 0.5f);
  731. auto clipH = (int) (r.size.height + 0.5f);
  732. RectangleList<int> clip;
  733. getClipRects (clip, offset, clipW, clipH);
  734. if (! clip.isEmpty())
  735. {
  736. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  737. roundToInt (clipW * displayScale),
  738. roundToInt (clipH * displayScale),
  739. ! component.isOpaque());
  740. {
  741. auto intScale = roundToInt (displayScale);
  742. if (intScale != 1)
  743. clip.scaleAll (intScale);
  744. auto context = component.getLookAndFeel()
  745. .createGraphicsContext (temp, offset * intScale, clip);
  746. if (intScale != 1)
  747. context->addTransform (AffineTransform::scale (displayScale));
  748. invokePaint (*context);
  749. }
  750. CGColorSpaceRef colourSpace = CGColorSpaceCreateWithName (kCGColorSpaceSRGB);
  751. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace, false);
  752. CGColorSpaceRelease (colourSpace);
  753. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
  754. CGImageRelease (image);
  755. }
  756. }
  757. }
  758. void repaint (const Rectangle<int>& area) override
  759. {
  760. // In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
  761. // no longer be trusted to coalesce all the regions, or to even remember them all without losing
  762. // a few when there's a lot of activity.
  763. // As a work around for this, we use a RectangleList to do our own coalescing of regions before
  764. // asynchronously asking the OS to repaint them.
  765. deferredRepaints.add ((float) area.getX(), (float) ([view frame].size.height - area.getBottom()),
  766. (float) area.getWidth(), (float) area.getHeight());
  767. if (isTimerRunning())
  768. return;
  769. auto now = Time::getMillisecondCounter();
  770. auto msSinceLastRepaint = (lastRepaintTime >= now) ? now - lastRepaintTime
  771. : (std::numeric_limits<uint32>::max() - lastRepaintTime) + now;
  772. static uint32 minimumRepaintInterval = 1000 / 30; // 30fps
  773. // When windows are being resized, artificially throttling high-frequency repaints helps
  774. // to stop the event queue getting clogged, and keeps everything working smoothly.
  775. // For some reason Logic also needs this throttling to record parameter events correctly.
  776. if (msSinceLastRepaint < minimumRepaintInterval && shouldThrottleRepaint())
  777. {
  778. startTimer (static_cast<int> (minimumRepaintInterval - msSinceLastRepaint));
  779. return;
  780. }
  781. setNeedsDisplayRectangles();
  782. }
  783. static bool shouldThrottleRepaint()
  784. {
  785. return areAnyWindowsInLiveResize() || ! JUCEApplication::isStandaloneApp();
  786. }
  787. void timerCallback() override
  788. {
  789. setNeedsDisplayRectangles();
  790. stopTimer();
  791. }
  792. void setNeedsDisplayRectangles()
  793. {
  794. for (auto& i : deferredRepaints)
  795. [view setNeedsDisplayInRect: makeNSRect (i)];
  796. lastRepaintTime = Time::getMillisecondCounter();
  797. deferredRepaints.clear();
  798. }
  799. void invokePaint (LowLevelGraphicsContext& context)
  800. {
  801. handlePaint (context);
  802. }
  803. void performAnyPendingRepaintsNow() override
  804. {
  805. [view displayIfNeeded];
  806. }
  807. static bool areAnyWindowsInLiveResize() noexcept
  808. {
  809. for (NSWindow* w in [NSApp windows])
  810. if ([w inLiveResize])
  811. return true;
  812. return false;
  813. }
  814. //==============================================================================
  815. bool isBlockedByModalComponent()
  816. {
  817. if (auto* modal = Component::getCurrentlyModalComponent())
  818. {
  819. if (insideToFrontCall == 0
  820. && (! getComponent().isParentOf (modal))
  821. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  822. {
  823. return true;
  824. }
  825. }
  826. return false;
  827. }
  828. void sendModalInputAttemptIfBlocked()
  829. {
  830. if (isBlockedByModalComponent())
  831. if (auto* modal = Component::getCurrentlyModalComponent())
  832. modal->inputAttemptWhenModal();
  833. }
  834. bool canBecomeKeyWindow()
  835. {
  836. return component.isVisible() && (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  837. }
  838. bool canBecomeMainWindow()
  839. {
  840. return component.isVisible() && dynamic_cast<ResizableWindow*> (&component) != nullptr;
  841. }
  842. bool worksWhenModal() const
  843. {
  844. // In plugins, the host could put our plugin window inside a modal window, so this
  845. // allows us to successfully open other popups. Feels like there could be edge-case
  846. // problems caused by this, so let us know if you spot any issues..
  847. return ! JUCEApplication::isStandaloneApp();
  848. }
  849. void becomeKeyWindow()
  850. {
  851. handleBroughtToFront();
  852. grabFocus();
  853. }
  854. bool windowShouldClose()
  855. {
  856. if (! isValidPeer (this))
  857. return YES;
  858. handleUserClosingWindow();
  859. return NO;
  860. }
  861. void redirectMovedOrResized()
  862. {
  863. updateFullscreenStatus();
  864. handleMovedOrResized();
  865. }
  866. void viewMovedToWindow()
  867. {
  868. if (isSharedWindow)
  869. {
  870. auto newWindow = [view window];
  871. bool shouldSetVisible = (window == nullptr && newWindow != nullptr);
  872. window = newWindow;
  873. if (shouldSetVisible)
  874. getComponent().setVisible (true);
  875. }
  876. }
  877. void liveResizingStart()
  878. {
  879. if (constrainer == nullptr)
  880. return;
  881. constrainer->resizeStart();
  882. isFirstLiveResize = true;
  883. setFullScreenSizeConstraints (*constrainer);
  884. }
  885. void liveResizingEnd()
  886. {
  887. if (constrainer != nullptr)
  888. constrainer->resizeEnd();
  889. }
  890. NSRect constrainRect (const NSRect r)
  891. {
  892. if (constrainer == nullptr || isKioskMode())
  893. return r;
  894. const auto scale = getComponent().getDesktopScaleFactor();
  895. auto pos = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect (r)));
  896. const auto original = ScalingHelpers::unscaledScreenPosToScaled (scale, convertToRectInt (flippedScreenRect ([window frame])));
  897. const auto screenBounds = Desktop::getInstance().getDisplays().getTotalBounds (true);
  898. const bool inLiveResize = [window inLiveResize];
  899. if (! inLiveResize || isFirstLiveResize)
  900. {
  901. isFirstLiveResize = false;
  902. isStretchingTop = (pos.getY() != original.getY() && pos.getBottom() == original.getBottom());
  903. isStretchingLeft = (pos.getX() != original.getX() && pos.getRight() == original.getRight());
  904. isStretchingBottom = (pos.getY() == original.getY() && pos.getBottom() != original.getBottom());
  905. isStretchingRight = (pos.getX() == original.getX() && pos.getRight() != original.getRight());
  906. }
  907. constrainer->checkBounds (pos, original, screenBounds,
  908. isStretchingTop, isStretchingLeft, isStretchingBottom, isStretchingRight);
  909. return flippedScreenRect (makeNSRect (ScalingHelpers::scaledScreenPosToUnscaled (scale, pos)));
  910. }
  911. static void showArrowCursorIfNeeded()
  912. {
  913. auto& desktop = Desktop::getInstance();
  914. auto mouse = desktop.getMainMouseSource();
  915. if (mouse.getComponentUnderMouse() == nullptr
  916. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  917. {
  918. [[NSCursor arrowCursor] set];
  919. }
  920. }
  921. static void updateModifiers (NSEvent* e)
  922. {
  923. updateModifiers ([e modifierFlags]);
  924. }
  925. static void updateModifiers (const NSUInteger flags)
  926. {
  927. int m = 0;
  928. if ((flags & NSEventModifierFlagShift) != 0) m |= ModifierKeys::shiftModifier;
  929. if ((flags & NSEventModifierFlagControl) != 0) m |= ModifierKeys::ctrlModifier;
  930. if ((flags & NSEventModifierFlagOption) != 0) m |= ModifierKeys::altModifier;
  931. if ((flags & NSEventModifierFlagCommand) != 0) m |= ModifierKeys::commandModifier;
  932. ModifierKeys::currentModifiers = ModifierKeys::currentModifiers.withOnlyMouseButtons().withFlags (m);
  933. }
  934. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  935. {
  936. updateModifiers (ev);
  937. if (auto keyCode = getKeyCodeFromEvent (ev))
  938. {
  939. if (isKeyDown)
  940. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  941. else
  942. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  943. }
  944. }
  945. static int getKeyCodeFromEvent (NSEvent* ev)
  946. {
  947. // Unfortunately, charactersIgnoringModifiers does not ignore the shift key.
  948. // Using [ev keyCode] is not a solution either as this will,
  949. // for example, return VK_KEY_Y if the key is pressed which
  950. // is typically located at the Y key position on a QWERTY
  951. // keyboard. However, on international keyboards this might not
  952. // be the key labeled Y (for example, on German keyboards this key
  953. // has a Z label). Therefore, we need to query the current keyboard
  954. // layout to figure out what character the key would have produced
  955. // if the shift key was not pressed
  956. String unmodified;
  957. #if JUCE_SUPPORT_CARBON
  958. if (TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource())
  959. {
  960. if (auto layoutData = (CFDataRef) TISGetInputSourceProperty (currentKeyboard,
  961. kTISPropertyUnicodeKeyLayoutData))
  962. {
  963. if (auto* layoutPtr = (const UCKeyboardLayout*) CFDataGetBytePtr (layoutData))
  964. {
  965. UInt32 keysDown = 0;
  966. UniChar buffer[4];
  967. UniCharCount actual;
  968. if (UCKeyTranslate (layoutPtr, [ev keyCode], kUCKeyActionDown, 0, LMGetKbdType(),
  969. kUCKeyTranslateNoDeadKeysBit, &keysDown, sizeof (buffer) / sizeof (UniChar),
  970. &actual, buffer) == 0)
  971. unmodified = String (CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (buffer)), 4);
  972. }
  973. }
  974. CFRelease (currentKeyboard);
  975. }
  976. // did the above layout conversion fail
  977. if (unmodified.isEmpty())
  978. #endif
  979. {
  980. unmodified = nsStringToJuce ([ev charactersIgnoringModifiers]);
  981. }
  982. auto keyCode = (int) unmodified[0];
  983. if (keyCode == 0x19) // (backwards-tab)
  984. keyCode = '\t';
  985. else if (keyCode == 0x03) // (enter)
  986. keyCode = '\r';
  987. else
  988. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  989. if (([ev modifierFlags] & NSEventModifierFlagNumericPad) != 0)
  990. {
  991. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  992. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  993. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  994. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  995. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  996. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  997. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  998. '.', KeyPress::numberPadDecimalPoint,
  999. ',', KeyPress::numberPadDecimalPoint, // (to deal with non-english kbds)
  1000. '=', KeyPress::numberPadEquals };
  1001. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  1002. if (keyCode == numPadConversions [i])
  1003. keyCode = numPadConversions [i + 1];
  1004. }
  1005. return keyCode;
  1006. }
  1007. static int64 getMouseTime (NSEvent* e) noexcept
  1008. {
  1009. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  1010. + (int64) ([e timestamp] * 1000.0);
  1011. }
  1012. static float getMousePressure (NSEvent* e) noexcept
  1013. {
  1014. @try
  1015. {
  1016. if (e.type != NSEventTypeMouseEntered && e.type != NSEventTypeMouseExited)
  1017. return (float) e.pressure;
  1018. }
  1019. @catch (NSException* e) {}
  1020. @finally {}
  1021. return 0.0f;
  1022. }
  1023. static Point<float> getMousePos (NSEvent* e, NSView* view)
  1024. {
  1025. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  1026. return { (float) p.x, (float) ([view frame].size.height - p.y) };
  1027. }
  1028. static int getModifierForButtonNumber (const NSInteger num)
  1029. {
  1030. return num == 0 ? ModifierKeys::leftButtonModifier
  1031. : (num == 1 ? ModifierKeys::rightButtonModifier
  1032. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  1033. }
  1034. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  1035. {
  1036. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSWindowStyleMaskTitled
  1037. : NSWindowStyleMaskBorderless;
  1038. if ((flags & windowHasMinimiseButton) != 0) style |= NSWindowStyleMaskMiniaturizable;
  1039. if ((flags & windowHasCloseButton) != 0) style |= NSWindowStyleMaskClosable;
  1040. if ((flags & windowIsResizable) != 0) style |= NSWindowStyleMaskResizable;
  1041. return style;
  1042. }
  1043. static NSArray* getSupportedDragTypes()
  1044. {
  1045. return [NSArray arrayWithObjects: (NSString*) kUTTypeFileURL, (NSString*) kPasteboardTypeFileURLPromise, NSPasteboardTypeString, nil];
  1046. }
  1047. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  1048. {
  1049. NSPasteboard* pasteboard = [sender draggingPasteboard];
  1050. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  1051. if (contentType == nil)
  1052. return false;
  1053. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  1054. ComponentPeer::DragInfo dragInfo;
  1055. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  1056. if (contentType == NSPasteboardTypeString)
  1057. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSPasteboardTypeString]);
  1058. else
  1059. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  1060. if (! dragInfo.isEmpty())
  1061. {
  1062. switch (type)
  1063. {
  1064. case 0: return handleDragMove (dragInfo);
  1065. case 1: return handleDragExit (dragInfo);
  1066. case 2: return handleDragDrop (dragInfo);
  1067. default: jassertfalse; break;
  1068. }
  1069. }
  1070. return false;
  1071. }
  1072. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  1073. {
  1074. StringArray files;
  1075. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  1076. if ([contentType isEqualToString: (NSString*) kPasteboardTypeFileURLPromise]
  1077. && [[pasteboard types] containsObject: iTunesPasteboardType])
  1078. {
  1079. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  1080. if ([list isKindOfClass: [NSDictionary class]])
  1081. {
  1082. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  1083. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  1084. NSEnumerator* enumerator = [tracks objectEnumerator];
  1085. NSDictionary* track;
  1086. while ((track = [enumerator nextObject]) != nil)
  1087. {
  1088. if (id value = [track valueForKey: nsStringLiteral ("Location")])
  1089. {
  1090. NSURL* url = [NSURL URLWithString: value];
  1091. if ([url isFileURL])
  1092. files.add (nsStringToJuce ([url path]));
  1093. }
  1094. }
  1095. }
  1096. }
  1097. else
  1098. {
  1099. NSArray* items = [pasteboard readObjectsForClasses:@[[NSURL class]] options: nil];
  1100. for (unsigned int i = 0; i < [items count]; ++i)
  1101. {
  1102. NSURL* url = [items objectAtIndex: i];
  1103. if ([url isFileURL])
  1104. files.add (nsStringToJuce ([url path]));
  1105. }
  1106. }
  1107. return files;
  1108. }
  1109. //==============================================================================
  1110. void viewFocusGain()
  1111. {
  1112. if (currentlyFocusedPeer != this)
  1113. {
  1114. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  1115. currentlyFocusedPeer->handleFocusLoss();
  1116. currentlyFocusedPeer = this;
  1117. handleFocusGain();
  1118. }
  1119. }
  1120. void viewFocusLoss()
  1121. {
  1122. if (currentlyFocusedPeer == this)
  1123. {
  1124. currentlyFocusedPeer = nullptr;
  1125. handleFocusLoss();
  1126. }
  1127. }
  1128. bool isFocused() const override
  1129. {
  1130. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  1131. ? this == currentlyFocusedPeer
  1132. : [window isKeyWindow];
  1133. }
  1134. void grabFocus() override
  1135. {
  1136. if (window != nil)
  1137. {
  1138. [window makeKeyWindow];
  1139. [window makeFirstResponder: view];
  1140. viewFocusGain();
  1141. }
  1142. }
  1143. void textInputRequired (Point<int>, TextInputTarget&) override {}
  1144. void resetWindowPresentation()
  1145. {
  1146. if (hasNativeTitleBar())
  1147. {
  1148. [window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (getStyleFlags()))];
  1149. setTitle (getComponent().getName()); // required to force the OS to update the title
  1150. }
  1151. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1152. }
  1153. //==============================================================================
  1154. NSWindow* window = nil;
  1155. NSView* view = nil;
  1156. WeakReference<Component> safeComponent;
  1157. bool isSharedWindow = false, fullScreen = false;
  1158. bool isWindowInKioskMode = false;
  1159. #if USE_COREGRAPHICS_RENDERING
  1160. bool usingCoreGraphics = true;
  1161. #else
  1162. bool usingCoreGraphics = false;
  1163. #endif
  1164. bool isZooming = false, isFirstLiveResize = false, textWasInserted = false;
  1165. bool isStretchingTop = false, isStretchingLeft = false, isStretchingBottom = false, isStretchingRight = false;
  1166. bool windowRepresentsFile = false;
  1167. bool isAlwaysOnTop = false, wasAlwaysOnTop = false;
  1168. String stringBeingComposed;
  1169. NSNotificationCenter* notificationCenter = nil;
  1170. RectangleList<float> deferredRepaints;
  1171. uint32 lastRepaintTime;
  1172. static ComponentPeer* currentlyFocusedPeer;
  1173. static Array<int> keysCurrentlyDown;
  1174. static int insideToFrontCall;
  1175. private:
  1176. static NSView* createViewInstance();
  1177. static NSWindow* createWindowInstance();
  1178. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1179. {
  1180. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1181. }
  1182. void getClipRects (RectangleList<int>& clip, Point<int> offset, int clipW, int clipH)
  1183. {
  1184. const NSRect* rects = nullptr;
  1185. NSInteger numRects = 0;
  1186. [view getRectsBeingDrawn: &rects count: &numRects];
  1187. const Rectangle<int> clipBounds (clipW, clipH);
  1188. auto viewH = [view frame].size.height;
  1189. clip.ensureStorageAllocated ((int) numRects);
  1190. for (int i = 0; i < numRects; ++i)
  1191. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1192. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + offset.y,
  1193. roundToInt (rects[i].size.width),
  1194. roundToInt (rects[i].size.height))));
  1195. }
  1196. static void appFocusChanged()
  1197. {
  1198. keysCurrentlyDown.clear();
  1199. if (isValidPeer (currentlyFocusedPeer))
  1200. {
  1201. if (Process::isForegroundProcess())
  1202. {
  1203. currentlyFocusedPeer->handleFocusGain();
  1204. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1205. }
  1206. else
  1207. {
  1208. currentlyFocusedPeer->handleFocusLoss();
  1209. }
  1210. }
  1211. }
  1212. static bool checkEventBlockedByModalComps (NSEvent* e)
  1213. {
  1214. if (Component::getNumCurrentlyModalComponents() == 0)
  1215. return false;
  1216. NSWindow* const w = [e window];
  1217. if (w == nil || [w worksWhenModal])
  1218. return false;
  1219. bool isKey = false, isInputAttempt = false;
  1220. switch ([e type])
  1221. {
  1222. case NSEventTypeKeyDown:
  1223. case NSEventTypeKeyUp:
  1224. isKey = isInputAttempt = true;
  1225. break;
  1226. case NSEventTypeLeftMouseDown:
  1227. case NSEventTypeRightMouseDown:
  1228. case NSEventTypeOtherMouseDown:
  1229. isInputAttempt = true;
  1230. break;
  1231. case NSEventTypeLeftMouseDragged:
  1232. case NSEventTypeRightMouseDragged:
  1233. case NSEventTypeLeftMouseUp:
  1234. case NSEventTypeRightMouseUp:
  1235. case NSEventTypeOtherMouseUp:
  1236. case NSEventTypeOtherMouseDragged:
  1237. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1238. return false;
  1239. break;
  1240. case NSEventTypeMouseMoved:
  1241. case NSEventTypeMouseEntered:
  1242. case NSEventTypeMouseExited:
  1243. case NSEventTypeCursorUpdate:
  1244. case NSEventTypeScrollWheel:
  1245. case NSEventTypeTabletPoint:
  1246. case NSEventTypeTabletProximity:
  1247. break;
  1248. case NSEventTypeFlagsChanged:
  1249. case NSEventTypeAppKitDefined:
  1250. case NSEventTypeSystemDefined:
  1251. case NSEventTypeApplicationDefined:
  1252. case NSEventTypePeriodic:
  1253. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_8
  1254. case NSEventTypeGesture:
  1255. #endif
  1256. case NSEventTypeMagnify:
  1257. case NSEventTypeSwipe:
  1258. case NSEventTypeRotate:
  1259. case NSEventTypeBeginGesture:
  1260. case NSEventTypeEndGesture:
  1261. case NSEventTypeQuickLook:
  1262. #if JUCE_64BIT
  1263. case NSEventTypeSmartMagnify:
  1264. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_8
  1265. case NSEventTypePressure:
  1266. #endif
  1267. #endif
  1268. #if defined (MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12
  1269. #if JUCE_64BIT
  1270. case NSEventTypeDirectTouch:
  1271. #endif
  1272. #if defined (MAC_OS_X_VERSION_10_15) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
  1273. case NSEventTypeChangeMode:
  1274. #endif
  1275. #endif
  1276. default:
  1277. return false;
  1278. }
  1279. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1280. {
  1281. if (auto* peer = dynamic_cast<NSViewComponentPeer*> (ComponentPeer::getPeer (i)))
  1282. {
  1283. if ([peer->view window] == w)
  1284. {
  1285. if (isKey)
  1286. {
  1287. if (peer->view == [w firstResponder])
  1288. return false;
  1289. }
  1290. else
  1291. {
  1292. if (peer->isSharedWindow
  1293. ? NSPointInRect ([peer->view convertPoint: [e locationInWindow] fromView: nil], [peer->view bounds])
  1294. : NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height)))
  1295. return false;
  1296. }
  1297. }
  1298. }
  1299. }
  1300. if (isInputAttempt)
  1301. {
  1302. if (! [NSApp isActive])
  1303. [NSApp activateIgnoringOtherApps: YES];
  1304. if (auto* modal = Component::getCurrentlyModalComponent())
  1305. modal->inputAttemptWhenModal();
  1306. }
  1307. return true;
  1308. }
  1309. void setFullScreenSizeConstraints (const ComponentBoundsConstrainer& c)
  1310. {
  1311. const auto minSize = NSMakeSize (static_cast<float> (c.getMinimumWidth()),
  1312. 0.0f);
  1313. [window setMinFullScreenContentSize: minSize];
  1314. }
  1315. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1316. };
  1317. int NSViewComponentPeer::insideToFrontCall = 0;
  1318. //==============================================================================
  1319. struct JuceNSViewClass : public ObjCClass<NSView>
  1320. {
  1321. JuceNSViewClass() : ObjCClass<NSView> ("JUCEView_")
  1322. {
  1323. addIvar<NSViewComponentPeer*> ("owner");
  1324. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1325. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1326. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1327. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1328. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1329. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1330. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1331. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1332. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1333. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1334. addMethod (@selector (rightMouseDown:), mouseDown, "v@:@");
  1335. addMethod (@selector (rightMouseDragged:), mouseDragged, "v@:@");
  1336. addMethod (@selector (rightMouseUp:), mouseUp, "v@:@");
  1337. addMethod (@selector (otherMouseDown:), mouseDown, "v@:@");
  1338. addMethod (@selector (otherMouseDragged:), mouseDragged, "v@:@");
  1339. addMethod (@selector (otherMouseUp:), mouseUp, "v@:@");
  1340. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1341. addMethod (@selector (magnifyWithEvent:), magnify, "v@:@");
  1342. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "c@:@");
  1343. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1344. addMethod (@selector (windowWillMiniaturize:), windowWillMiniaturize, "v@:@");
  1345. addMethod (@selector (windowDidDeminiaturize:), windowDidDeminiaturize, "v@:@");
  1346. addMethod (@selector (wantsDefaultClipping:), wantsDefaultClipping, "c@:");
  1347. addMethod (@selector (worksWhenModal), worksWhenModal, "c@:");
  1348. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1349. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1350. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1351. addMethod (@selector (insertText:), insertText, "v@:@");
  1352. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1353. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1354. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1355. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1356. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1357. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1358. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1359. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1360. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1361. addMethod (@selector (characterIndexForPoint:), characterIndexForPoint, "L@:", @encode (NSPoint));
  1362. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1363. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1364. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1365. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1366. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1367. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1368. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1369. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1370. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1371. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1372. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1373. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1374. addMethod (@selector (paste:), paste, "v@:@");
  1375. addMethod (@selector (copy:), copy, "v@:@");
  1376. addMethod (@selector (cut:), cut, "v@:@");
  1377. addMethod (@selector (viewWillMoveToWindow:), willMoveToWindow, "v@:@");
  1378. addProtocol (@protocol (NSTextInput));
  1379. registerClass();
  1380. }
  1381. private:
  1382. static NSViewComponentPeer* getOwner (id self)
  1383. {
  1384. return getIvar<NSViewComponentPeer*> (self, "owner");
  1385. }
  1386. static void mouseDown (id self, SEL s, NSEvent* ev)
  1387. {
  1388. if (JUCEApplicationBase::isStandaloneApp())
  1389. asyncMouseDown (self, s, ev);
  1390. else
  1391. // In some host situations, the host will stop modal loops from working
  1392. // correctly if they're called from a mouse event, so we'll trigger
  1393. // the event asynchronously..
  1394. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1395. withObject: ev
  1396. waitUntilDone: NO];
  1397. }
  1398. static void mouseUp (id self, SEL s, NSEvent* ev)
  1399. {
  1400. if (JUCEApplicationBase::isStandaloneApp())
  1401. asyncMouseUp (self, s, ev);
  1402. else
  1403. // In some host situations, the host will stop modal loops from working
  1404. // correctly if they're called from a mouse event, so we'll trigger
  1405. // the event asynchronously..
  1406. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1407. withObject: ev
  1408. waitUntilDone: NO];
  1409. }
  1410. static void asyncMouseDown (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseDown (ev); }
  1411. static void asyncMouseUp (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseUp (ev); }
  1412. static void mouseDragged (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseDrag (ev); }
  1413. static void mouseMoved (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseMove (ev); }
  1414. static void mouseEntered (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseEnter (ev); }
  1415. static void mouseExited (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseExit (ev); }
  1416. static void scrollWheel (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMouseWheel (ev); }
  1417. static void magnify (id self, SEL, NSEvent* ev) { if (auto* p = getOwner (self)) p->redirectMagnify (ev); }
  1418. static void copy (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectCopy (s); }
  1419. static void paste (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectPaste (s); }
  1420. static void cut (id self, SEL, NSObject* s) { if (auto* p = getOwner (self)) p->redirectCut (s); }
  1421. static void willMoveToWindow (id self, SEL, NSWindow* w) { if (auto* p = getOwner (self)) p->redirectWillMoveToWindow (w); }
  1422. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1423. static BOOL wantsDefaultClipping (id, SEL) { return YES; } // (this is the default, but may want to customise it in future)
  1424. static BOOL worksWhenModal (id self, SEL) { if (auto* p = getOwner (self)) return p->worksWhenModal(); return NO; }
  1425. static void drawRect (id self, SEL, NSRect r) { if (auto* p = getOwner (self)) p->drawRect (r); }
  1426. static void frameChanged (id self, SEL, NSNotification*) { if (auto* p = getOwner (self)) p->redirectMovedOrResized(); }
  1427. static void viewDidMoveToWindow (id self, SEL) { if (auto* p = getOwner (self)) p->viewMovedToWindow(); }
  1428. static void windowWillMiniaturize (id self, SEL, NSNotification*)
  1429. {
  1430. if (auto* p = getOwner (self))
  1431. {
  1432. if (p->isAlwaysOnTop)
  1433. {
  1434. // there is a bug when restoring minimised always on top windows so we need
  1435. // to remove this behaviour before minimising and restore it afterwards
  1436. p->setAlwaysOnTop (false);
  1437. p->wasAlwaysOnTop = true;
  1438. }
  1439. }
  1440. }
  1441. static void windowDidDeminiaturize (id self, SEL, NSNotification*)
  1442. {
  1443. if (auto* p = getOwner (self))
  1444. {
  1445. if (p->wasAlwaysOnTop)
  1446. p->setAlwaysOnTop (true);
  1447. p->redirectMovedOrResized();
  1448. }
  1449. }
  1450. static BOOL isOpaque (id self, SEL)
  1451. {
  1452. auto* owner = getOwner (self);
  1453. return owner == nullptr || owner->getComponent().isOpaque();
  1454. }
  1455. //==============================================================================
  1456. static void keyDown (id self, SEL, NSEvent* ev)
  1457. {
  1458. if (auto* owner = getOwner (self))
  1459. {
  1460. auto* target = owner->findCurrentTextInputTarget();
  1461. owner->textWasInserted = false;
  1462. if (target != nullptr)
  1463. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1464. else
  1465. owner->stringBeingComposed.clear();
  1466. if (! (owner->textWasInserted || owner->redirectKeyDown (ev)))
  1467. sendSuperclassMessage<void> (self, @selector (keyDown:), ev);
  1468. }
  1469. }
  1470. static void keyUp (id self, SEL, NSEvent* ev)
  1471. {
  1472. auto* owner = getOwner (self);
  1473. if (! owner->redirectKeyUp (ev))
  1474. sendSuperclassMessage<void> (self, @selector (keyUp:), ev);
  1475. }
  1476. //==============================================================================
  1477. static void insertText (id self, SEL, id aString)
  1478. {
  1479. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1480. if (auto* owner = getOwner (self))
  1481. {
  1482. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1483. if ([newText length] > 0)
  1484. {
  1485. if (auto* target = owner->findCurrentTextInputTarget())
  1486. {
  1487. target->insertTextAtCaret (nsStringToJuce (newText));
  1488. owner->textWasInserted = true;
  1489. }
  1490. }
  1491. owner->stringBeingComposed.clear();
  1492. }
  1493. }
  1494. static void doCommandBySelector (id, SEL, SEL) {}
  1495. static void setMarkedText (id self, SEL, id aString, NSRange)
  1496. {
  1497. if (auto* owner = getOwner (self))
  1498. {
  1499. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1500. ? [aString string] : aString);
  1501. if (auto* target = owner->findCurrentTextInputTarget())
  1502. {
  1503. auto currentHighlight = target->getHighlightedRegion();
  1504. target->insertTextAtCaret (owner->stringBeingComposed);
  1505. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1506. owner->textWasInserted = true;
  1507. }
  1508. }
  1509. }
  1510. static void unmarkText (id self, SEL)
  1511. {
  1512. if (auto* owner = getOwner (self))
  1513. {
  1514. if (owner->stringBeingComposed.isNotEmpty())
  1515. {
  1516. if (auto* target = owner->findCurrentTextInputTarget())
  1517. {
  1518. target->insertTextAtCaret (owner->stringBeingComposed);
  1519. owner->textWasInserted = true;
  1520. }
  1521. owner->stringBeingComposed.clear();
  1522. }
  1523. }
  1524. }
  1525. static BOOL hasMarkedText (id self, SEL)
  1526. {
  1527. auto* owner = getOwner (self);
  1528. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1529. }
  1530. static long conversationIdentifier (id self, SEL)
  1531. {
  1532. return (long) (pointer_sized_int) self;
  1533. }
  1534. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1535. {
  1536. if (auto* owner = getOwner (self))
  1537. {
  1538. if (auto* target = owner->findCurrentTextInputTarget())
  1539. {
  1540. Range<int> r ((int) theRange.location,
  1541. (int) (theRange.location + theRange.length));
  1542. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1543. }
  1544. }
  1545. return nil;
  1546. }
  1547. static NSRange markedRange (id self, SEL)
  1548. {
  1549. if (auto* owner = getOwner (self))
  1550. if (owner->stringBeingComposed.isNotEmpty())
  1551. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1552. return NSMakeRange (NSNotFound, 0);
  1553. }
  1554. static NSRange selectedRange (id self, SEL)
  1555. {
  1556. if (auto* owner = getOwner (self))
  1557. {
  1558. if (auto* target = owner->findCurrentTextInputTarget())
  1559. {
  1560. auto highlight = target->getHighlightedRegion();
  1561. if (! highlight.isEmpty())
  1562. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1563. (NSUInteger) highlight.getLength());
  1564. }
  1565. }
  1566. return NSMakeRange (NSNotFound, 0);
  1567. }
  1568. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1569. {
  1570. if (auto* owner = getOwner (self))
  1571. if (auto* comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1572. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1573. return NSZeroRect;
  1574. }
  1575. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1576. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1577. //==============================================================================
  1578. static void flagsChanged (id self, SEL, NSEvent* ev)
  1579. {
  1580. if (auto* owner = getOwner (self))
  1581. owner->redirectModKeyChange (ev);
  1582. }
  1583. static BOOL becomeFirstResponder (id self, SEL)
  1584. {
  1585. if (auto* owner = getOwner (self))
  1586. owner->viewFocusGain();
  1587. return YES;
  1588. }
  1589. static BOOL resignFirstResponder (id self, SEL)
  1590. {
  1591. if (auto* owner = getOwner (self))
  1592. owner->viewFocusLoss();
  1593. return YES;
  1594. }
  1595. static BOOL acceptsFirstResponder (id self, SEL)
  1596. {
  1597. auto* owner = getOwner (self);
  1598. return owner != nullptr && owner->canBecomeKeyWindow();
  1599. }
  1600. //==============================================================================
  1601. static NSDragOperation draggingEntered (id self, SEL s, id<NSDraggingInfo> sender)
  1602. {
  1603. return draggingUpdated (self, s, sender);
  1604. }
  1605. static NSDragOperation draggingUpdated (id self, SEL, id<NSDraggingInfo> sender)
  1606. {
  1607. if (auto* owner = getOwner (self))
  1608. if (owner->sendDragCallback (0, sender))
  1609. return NSDragOperationGeneric;
  1610. return NSDragOperationNone;
  1611. }
  1612. static void draggingEnded (id self, SEL s, id<NSDraggingInfo> sender)
  1613. {
  1614. draggingExited (self, s, sender);
  1615. }
  1616. static void draggingExited (id self, SEL, id<NSDraggingInfo> sender)
  1617. {
  1618. if (auto* owner = getOwner (self))
  1619. owner->sendDragCallback (1, sender);
  1620. }
  1621. static BOOL prepareForDragOperation (id, SEL, id<NSDraggingInfo>)
  1622. {
  1623. return YES;
  1624. }
  1625. static BOOL performDragOperation (id self, SEL, id<NSDraggingInfo> sender)
  1626. {
  1627. auto* owner = getOwner (self);
  1628. return owner != nullptr && owner->sendDragCallback (2, sender);
  1629. }
  1630. static void concludeDragOperation (id, SEL, id<NSDraggingInfo>) {}
  1631. };
  1632. //==============================================================================
  1633. struct JuceNSWindowClass : public ObjCClass<NSWindow>
  1634. {
  1635. JuceNSWindowClass() : ObjCClass<NSWindow> ("JUCEWindow_")
  1636. {
  1637. addIvar<NSViewComponentPeer*> ("owner");
  1638. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1639. addMethod (@selector (canBecomeMainWindow), canBecomeMainWindow, "c@:");
  1640. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1641. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1642. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect), "@");
  1643. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1644. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen, "v@:@");
  1645. addMethod (@selector (windowWillEnterFullScreen:), windowWillEnterFullScreen, "v@:@");
  1646. addMethod (@selector (zoom:), zoom, "v@:@");
  1647. addMethod (@selector (windowWillMove:), windowWillMove, "v@:@");
  1648. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize, "v@:@");
  1649. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize, "v@:@");
  1650. addMethod (@selector (window:shouldPopUpDocumentPathMenu:), shouldPopUpPathMenu, "B@:@", @encode (NSMenu*));
  1651. addMethod (@selector (window:shouldDragDocumentWithEvent:from:withPasteboard:),
  1652. shouldAllowIconDrag, "B@:@", @encode (NSEvent*), @encode (NSPoint), @encode (NSPasteboard*));
  1653. addProtocol (@protocol (NSWindowDelegate));
  1654. registerClass();
  1655. }
  1656. private:
  1657. static NSViewComponentPeer* getOwner (id self)
  1658. {
  1659. return getIvar<NSViewComponentPeer*> (self, "owner");
  1660. }
  1661. //==============================================================================
  1662. static BOOL canBecomeKeyWindow (id self, SEL)
  1663. {
  1664. auto* owner = getOwner (self);
  1665. return owner != nullptr
  1666. && owner->canBecomeKeyWindow()
  1667. && ! owner->isBlockedByModalComponent();
  1668. }
  1669. static BOOL canBecomeMainWindow (id self, SEL)
  1670. {
  1671. auto* owner = getOwner (self);
  1672. return owner != nullptr
  1673. && owner->canBecomeMainWindow()
  1674. && ! owner->isBlockedByModalComponent();
  1675. }
  1676. static void becomeKeyWindow (id self, SEL)
  1677. {
  1678. sendSuperclassMessage<void> (self, @selector (becomeKeyWindow));
  1679. if (auto* owner = getOwner (self))
  1680. {
  1681. if (owner->canBecomeKeyWindow())
  1682. {
  1683. owner->becomeKeyWindow();
  1684. return;
  1685. }
  1686. // this fixes a bug causing hidden windows to sometimes become visible when the app regains focus
  1687. if (! owner->getComponent().isVisible())
  1688. [(NSWindow*) self orderOut: nil];
  1689. }
  1690. }
  1691. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1692. {
  1693. auto* owner = getOwner (self);
  1694. return owner == nullptr || owner->windowShouldClose();
  1695. }
  1696. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen* screen)
  1697. {
  1698. if (auto* owner = getOwner (self))
  1699. {
  1700. frameRect = sendSuperclassMessage<NSRect, NSRect, NSScreen*> (self, @selector (constrainFrameRect:toScreen:),
  1701. frameRect, screen);
  1702. frameRect = owner->constrainRect (frameRect);
  1703. }
  1704. return frameRect;
  1705. }
  1706. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1707. {
  1708. auto* owner = getOwner (self);
  1709. if (owner == nullptr || owner->isZooming)
  1710. return proposedFrameSize;
  1711. NSRect frameRect = [(NSWindow*) self frame];
  1712. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1713. frameRect.size = proposedFrameSize;
  1714. frameRect = owner->constrainRect (frameRect);
  1715. if (owner->hasNativeTitleBar())
  1716. owner->sendModalInputAttemptIfBlocked();
  1717. return frameRect.size;
  1718. }
  1719. static void windowDidExitFullScreen (id self, SEL, NSNotification*)
  1720. {
  1721. if (auto* owner = getOwner (self))
  1722. owner->resetWindowPresentation();
  1723. }
  1724. static void windowWillEnterFullScreen (id self, SEL, NSNotification*)
  1725. {
  1726. if (SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_9)
  1727. return;
  1728. if (auto* owner = getOwner (self))
  1729. if (owner->hasNativeTitleBar() && (owner->getStyleFlags() & ComponentPeer::windowIsResizable) == 0)
  1730. [owner->window setStyleMask: NSWindowStyleMaskBorderless];
  1731. }
  1732. static void zoom (id self, SEL, id sender)
  1733. {
  1734. if (auto* owner = getOwner (self))
  1735. {
  1736. {
  1737. const ScopedValueSetter<bool> svs (owner->isZooming, true);
  1738. sendSuperclassMessage<void> (self, @selector (zoom:), sender);
  1739. }
  1740. owner->redirectMovedOrResized();
  1741. }
  1742. }
  1743. static void windowWillMove (id self, SEL, NSNotification*)
  1744. {
  1745. if (auto* owner = getOwner (self))
  1746. if (owner->hasNativeTitleBar())
  1747. owner->sendModalInputAttemptIfBlocked();
  1748. }
  1749. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  1750. {
  1751. if (auto* owner = getOwner (self))
  1752. owner->liveResizingStart();
  1753. }
  1754. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  1755. {
  1756. if (auto* owner = getOwner (self))
  1757. owner->liveResizingEnd();
  1758. }
  1759. static bool shouldPopUpPathMenu (id self, SEL, id /*window*/, NSMenu*)
  1760. {
  1761. if (auto* owner = getOwner (self))
  1762. return owner->windowRepresentsFile;
  1763. return false;
  1764. }
  1765. static bool shouldAllowIconDrag (id self, SEL, id /*window*/, NSEvent*, NSPoint, NSPasteboard*)
  1766. {
  1767. if (auto* owner = getOwner (self))
  1768. return owner->windowRepresentsFile;
  1769. return false;
  1770. }
  1771. };
  1772. NSView* NSViewComponentPeer::createViewInstance()
  1773. {
  1774. static JuceNSViewClass cls;
  1775. return cls.createInstance();
  1776. }
  1777. NSWindow* NSViewComponentPeer::createWindowInstance()
  1778. {
  1779. static JuceNSWindowClass cls;
  1780. return cls.createInstance();
  1781. }
  1782. //==============================================================================
  1783. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1784. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1785. //==============================================================================
  1786. bool KeyPress::isKeyCurrentlyDown (int keyCode)
  1787. {
  1788. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1789. return true;
  1790. if (keyCode >= 'A' && keyCode <= 'Z'
  1791. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1792. return true;
  1793. if (keyCode >= 'a' && keyCode <= 'z'
  1794. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1795. return true;
  1796. return false;
  1797. }
  1798. //==============================================================================
  1799. bool MouseInputSource::SourceList::addSource()
  1800. {
  1801. if (sources.size() == 0)
  1802. {
  1803. addSource (0, MouseInputSource::InputSourceType::mouse);
  1804. return true;
  1805. }
  1806. return false;
  1807. }
  1808. bool MouseInputSource::SourceList::canUseTouch()
  1809. {
  1810. return false;
  1811. }
  1812. //==============================================================================
  1813. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  1814. {
  1815. auto* peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  1816. jassert (peer != nullptr); // (this should have been checked by the caller)
  1817. if (peer->hasNativeTitleBar()
  1818. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1819. {
  1820. if (shouldBeEnabled && ! allowMenusAndBars)
  1821. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  1822. else if (! shouldBeEnabled)
  1823. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1824. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  1825. }
  1826. else
  1827. {
  1828. if (shouldBeEnabled)
  1829. {
  1830. if (peer->hasNativeTitleBar())
  1831. [peer->window setStyleMask: NSWindowStyleMaskBorderless];
  1832. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1833. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1834. kioskComp->setBounds (getDisplays().findDisplayForRect (kioskComp->getScreenBounds()).totalArea);
  1835. peer->becomeKeyWindow();
  1836. }
  1837. else
  1838. {
  1839. peer->resetWindowPresentation();
  1840. }
  1841. }
  1842. }
  1843. void Desktop::allowedOrientationsChanged() {}
  1844. //==============================================================================
  1845. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1846. {
  1847. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  1848. }
  1849. //==============================================================================
  1850. const int KeyPress::spaceKey = ' ';
  1851. const int KeyPress::returnKey = 0x0d;
  1852. const int KeyPress::escapeKey = 0x1b;
  1853. const int KeyPress::backspaceKey = 0x7f;
  1854. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1855. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1856. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1857. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1858. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1859. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1860. const int KeyPress::endKey = NSEndFunctionKey;
  1861. const int KeyPress::homeKey = NSHomeFunctionKey;
  1862. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1863. const int KeyPress::insertKey = -1;
  1864. const int KeyPress::tabKey = 9;
  1865. const int KeyPress::F1Key = NSF1FunctionKey;
  1866. const int KeyPress::F2Key = NSF2FunctionKey;
  1867. const int KeyPress::F3Key = NSF3FunctionKey;
  1868. const int KeyPress::F4Key = NSF4FunctionKey;
  1869. const int KeyPress::F5Key = NSF5FunctionKey;
  1870. const int KeyPress::F6Key = NSF6FunctionKey;
  1871. const int KeyPress::F7Key = NSF7FunctionKey;
  1872. const int KeyPress::F8Key = NSF8FunctionKey;
  1873. const int KeyPress::F9Key = NSF9FunctionKey;
  1874. const int KeyPress::F10Key = NSF10FunctionKey;
  1875. const int KeyPress::F11Key = NSF11FunctionKey;
  1876. const int KeyPress::F12Key = NSF12FunctionKey;
  1877. const int KeyPress::F13Key = NSF13FunctionKey;
  1878. const int KeyPress::F14Key = NSF14FunctionKey;
  1879. const int KeyPress::F15Key = NSF15FunctionKey;
  1880. const int KeyPress::F16Key = NSF16FunctionKey;
  1881. const int KeyPress::F17Key = NSF17FunctionKey;
  1882. const int KeyPress::F18Key = NSF18FunctionKey;
  1883. const int KeyPress::F19Key = NSF19FunctionKey;
  1884. const int KeyPress::F20Key = NSF20FunctionKey;
  1885. const int KeyPress::F21Key = NSF21FunctionKey;
  1886. const int KeyPress::F22Key = NSF22FunctionKey;
  1887. const int KeyPress::F23Key = NSF23FunctionKey;
  1888. const int KeyPress::F24Key = NSF24FunctionKey;
  1889. const int KeyPress::F25Key = NSF25FunctionKey;
  1890. const int KeyPress::F26Key = NSF26FunctionKey;
  1891. const int KeyPress::F27Key = NSF27FunctionKey;
  1892. const int KeyPress::F28Key = NSF28FunctionKey;
  1893. const int KeyPress::F29Key = NSF29FunctionKey;
  1894. const int KeyPress::F30Key = NSF30FunctionKey;
  1895. const int KeyPress::F31Key = NSF31FunctionKey;
  1896. const int KeyPress::F32Key = NSF32FunctionKey;
  1897. const int KeyPress::F33Key = NSF33FunctionKey;
  1898. const int KeyPress::F34Key = NSF34FunctionKey;
  1899. const int KeyPress::F35Key = NSF35FunctionKey;
  1900. const int KeyPress::numberPad0 = 0x30020;
  1901. const int KeyPress::numberPad1 = 0x30021;
  1902. const int KeyPress::numberPad2 = 0x30022;
  1903. const int KeyPress::numberPad3 = 0x30023;
  1904. const int KeyPress::numberPad4 = 0x30024;
  1905. const int KeyPress::numberPad5 = 0x30025;
  1906. const int KeyPress::numberPad6 = 0x30026;
  1907. const int KeyPress::numberPad7 = 0x30027;
  1908. const int KeyPress::numberPad8 = 0x30028;
  1909. const int KeyPress::numberPad9 = 0x30029;
  1910. const int KeyPress::numberPadAdd = 0x3002a;
  1911. const int KeyPress::numberPadSubtract = 0x3002b;
  1912. const int KeyPress::numberPadMultiply = 0x3002c;
  1913. const int KeyPress::numberPadDivide = 0x3002d;
  1914. const int KeyPress::numberPadSeparator = 0x3002e;
  1915. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1916. const int KeyPress::numberPadEquals = 0x30030;
  1917. const int KeyPress::numberPadDelete = 0x30031;
  1918. const int KeyPress::playKey = 0x30000;
  1919. const int KeyPress::stopKey = 0x30001;
  1920. const int KeyPress::fastForwardKey = 0x30002;
  1921. const int KeyPress::rewindKey = 0x30003;
  1922. } // namespace juce