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

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. typedef void (*AppFocusChangeCallback)();
  18. extern AppFocusChangeCallback appFocusChangeCallback;
  19. typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
  20. extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
  21. //==============================================================================
  22. #if ! (defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
  23. } // (juce namespace)
  24. @interface NSEvent (JuceDeviceDelta)
  25. - (CGFloat) scrollingDeltaX;
  26. - (CGFloat) scrollingDeltaY;
  27. - (BOOL) hasPreciseScrollingDeltas;
  28. - (BOOL) isDirectionInvertedFromDevice;
  29. @end
  30. namespace juce {
  31. #endif
  32. //==============================================================================
  33. static CGFloat getMainScreenHeight() noexcept
  34. {
  35. return [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  36. }
  37. static void flipScreenRect (NSRect& r) noexcept
  38. {
  39. r.origin.y = getMainScreenHeight() - (r.origin.y + r.size.height);
  40. }
  41. static NSRect flippedScreenRect (NSRect r) noexcept
  42. {
  43. flipScreenRect (r);
  44. return r;
  45. }
  46. //==============================================================================
  47. class NSViewComponentPeer : public ComponentPeer
  48. {
  49. public:
  50. NSViewComponentPeer (Component& comp, const int windowStyleFlags, NSView* viewToAttachTo)
  51. : ComponentPeer (comp, windowStyleFlags),
  52. window (nil),
  53. view (nil),
  54. isSharedWindow (viewToAttachTo != nil),
  55. fullScreen (false),
  56. insideDrawRect (false),
  57. #if USE_COREGRAPHICS_RENDERING
  58. usingCoreGraphics (true),
  59. #else
  60. usingCoreGraphics (false),
  61. #endif
  62. isZooming (false),
  63. textWasInserted (false),
  64. notificationCenter (nil)
  65. {
  66. appFocusChangeCallback = appFocusChanged;
  67. isEventBlockedByModalComps = checkEventBlockedByModalComps;
  68. NSRect r = makeNSRect (component.getLocalBounds());
  69. view = [createViewInstance() initWithFrame: r];
  70. setOwner (view, this);
  71. [view registerForDraggedTypes: getSupportedDragTypes()];
  72. notificationCenter = [NSNotificationCenter defaultCenter];
  73. [notificationCenter addObserver: view
  74. selector: @selector (frameChanged:)
  75. name: NSViewFrameDidChangeNotification
  76. object: view];
  77. if (! isSharedWindow)
  78. {
  79. [notificationCenter addObserver: view
  80. selector: @selector (frameChanged:)
  81. name: NSWindowDidMoveNotification
  82. object: window];
  83. [notificationCenter addObserver: view
  84. selector: @selector (frameChanged:)
  85. name: NSWindowDidMiniaturizeNotification
  86. object: window];
  87. [notificationCenter addObserver: view
  88. selector: @selector (frameChanged:)
  89. name: NSWindowDidDeminiaturizeNotification
  90. object: window];
  91. }
  92. [view setPostsFrameChangedNotifications: YES];
  93. if (isSharedWindow)
  94. {
  95. window = [viewToAttachTo window];
  96. [viewToAttachTo addSubview: view];
  97. }
  98. else
  99. {
  100. r.origin.x = (CGFloat) component.getX();
  101. r.origin.y = (CGFloat) component.getY();
  102. flipScreenRect (r);
  103. window = [createWindowInstance() initWithContentRect: r
  104. styleMask: getNSWindowStyleMask (windowStyleFlags)
  105. backing: NSBackingStoreBuffered
  106. defer: YES];
  107. setOwner (window, this);
  108. [window orderOut: nil];
  109. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  110. [window setDelegate: (id<NSWindowDelegate>) window];
  111. #else
  112. [window setDelegate: window];
  113. #endif
  114. [window setOpaque: component.isOpaque()];
  115. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  116. if (component.isAlwaysOnTop())
  117. setAlwaysOnTop (true);
  118. [window setContentView: view];
  119. [window setAutodisplay: YES];
  120. [window setAcceptsMouseMovedEvents: YES];
  121. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  122. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  123. [window setReleasedWhenClosed: YES];
  124. [window retain];
  125. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  126. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  127. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  128. if ((windowStyleFlags & (windowHasMaximiseButton | windowHasTitleBar)) == (windowHasMaximiseButton | windowHasTitleBar))
  129. [window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
  130. if ([window respondsToSelector: @selector (setRestorable:)])
  131. [window setRestorable: NO];
  132. #endif
  133. }
  134. const float alpha = component.getAlpha();
  135. if (alpha < 1.0f)
  136. setAlpha (alpha);
  137. setTitle (component.getName());
  138. }
  139. ~NSViewComponentPeer()
  140. {
  141. [notificationCenter removeObserver: view];
  142. setOwner (view, nullptr);
  143. if ([view superview] != nil)
  144. [view removeFromSuperview];
  145. [view release];
  146. if (! isSharedWindow)
  147. {
  148. setOwner (window, nullptr);
  149. [window close];
  150. [window release];
  151. }
  152. }
  153. //==============================================================================
  154. void* getNativeHandle() const override { return view; }
  155. void setVisible (bool shouldBeVisible) override
  156. {
  157. if (isSharedWindow)
  158. {
  159. [view setHidden: ! shouldBeVisible];
  160. }
  161. else
  162. {
  163. if (shouldBeVisible)
  164. {
  165. ++insideToFrontCall;
  166. [window orderFront: nil];
  167. --insideToFrontCall;
  168. handleBroughtToFront();
  169. }
  170. else
  171. {
  172. [window orderOut: nil];
  173. }
  174. }
  175. }
  176. void setTitle (const String& title) override
  177. {
  178. JUCE_AUTORELEASEPOOL
  179. {
  180. if (! isSharedWindow)
  181. [window setTitle: juceStringToNS (title)];
  182. }
  183. }
  184. bool setDocumentEditedStatus (bool edited) override
  185. {
  186. if (! hasNativeTitleBar())
  187. return false;
  188. [window setDocumentEdited: edited];
  189. return true;
  190. }
  191. void setRepresentedFile (const File& file) override
  192. {
  193. if (! isSharedWindow)
  194. [window setRepresentedFilename: juceStringToNS (file != File::nonexistent
  195. ? file.getFullPathName()
  196. : String::empty)];
  197. }
  198. void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
  199. {
  200. fullScreen = isNowFullScreen;
  201. NSRect r = makeNSRect (newBounds);
  202. if (isSharedWindow)
  203. {
  204. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  205. if ([view frame].size.width != r.size.width
  206. || [view frame].size.height != r.size.height)
  207. {
  208. [view setNeedsDisplay: true];
  209. }
  210. [view setFrame: r];
  211. }
  212. else
  213. {
  214. [window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
  215. display: true];
  216. }
  217. }
  218. Rectangle<int> getBounds (const bool global) const
  219. {
  220. NSRect r = [view frame];
  221. NSWindow* viewWindow = [view window];
  222. if (global && viewWindow != nil)
  223. {
  224. r = [[view superview] convertRect: r toView: nil];
  225. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
  226. r = [viewWindow convertRectToScreen: r];
  227. #else
  228. r.origin = [viewWindow convertBaseToScreen: r.origin];
  229. #endif
  230. flipScreenRect (r);
  231. }
  232. else
  233. {
  234. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  235. }
  236. return convertToRectInt (r);
  237. }
  238. Rectangle<int> getBounds() const override
  239. {
  240. return getBounds (! isSharedWindow);
  241. }
  242. Point<float> localToGlobal (Point<float> relativePosition) override
  243. {
  244. return relativePosition + getBounds (true).getPosition().toFloat();
  245. }
  246. Point<float> globalToLocal (Point<float> screenPosition) override
  247. {
  248. return screenPosition - getBounds (true).getPosition().toFloat();
  249. }
  250. void setAlpha (float newAlpha) override
  251. {
  252. if (! isSharedWindow)
  253. {
  254. [window setAlphaValue: (CGFloat) newAlpha];
  255. }
  256. else
  257. {
  258. #if defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  259. [view setAlphaValue: (CGFloat) newAlpha];
  260. #else
  261. if ([view respondsToSelector: @selector (setAlphaValue:)])
  262. {
  263. // PITA dynamic invocation for 10.4 builds..
  264. NSInvocation* inv = [NSInvocation invocationWithMethodSignature: [view methodSignatureForSelector: @selector (setAlphaValue:)]];
  265. [inv setSelector: @selector (setAlphaValue:)];
  266. [inv setTarget: view];
  267. CGFloat cgNewAlpha = (CGFloat) newAlpha;
  268. [inv setArgument: &cgNewAlpha atIndex: 2];
  269. [inv invoke];
  270. }
  271. #endif
  272. }
  273. }
  274. void setMinimised (bool shouldBeMinimised) override
  275. {
  276. if (! isSharedWindow)
  277. {
  278. if (shouldBeMinimised)
  279. [window miniaturize: nil];
  280. else
  281. [window deminiaturize: nil];
  282. }
  283. }
  284. bool isMinimised() const override
  285. {
  286. return [window isMiniaturized];
  287. }
  288. void setFullScreen (bool shouldBeFullScreen) override
  289. {
  290. if (! isSharedWindow)
  291. {
  292. Rectangle<int> r (lastNonFullscreenBounds);
  293. if (isMinimised())
  294. setMinimised (false);
  295. if (fullScreen != shouldBeFullScreen)
  296. {
  297. if (shouldBeFullScreen && hasNativeTitleBar())
  298. {
  299. fullScreen = true;
  300. [window performZoom: nil];
  301. }
  302. else
  303. {
  304. if (shouldBeFullScreen)
  305. r = component.getParentMonitorArea();
  306. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  307. if (r != component.getBounds() && ! r.isEmpty())
  308. setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
  309. }
  310. }
  311. }
  312. }
  313. bool isFullScreen() const override
  314. {
  315. return fullScreen;
  316. }
  317. bool isKioskMode() const override
  318. {
  319. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  320. if (hasNativeTitleBar() && ([window styleMask] & NSFullScreenWindowMask) != 0)
  321. return true;
  322. #endif
  323. return ComponentPeer::isKioskMode();
  324. }
  325. static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
  326. {
  327. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  328. if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
  329. return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
  330. #endif
  331. return true;
  332. }
  333. bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
  334. {
  335. NSRect viewFrame = [view frame];
  336. if (! (isPositiveAndBelow (localPos.getX(), (int) viewFrame.size.width)
  337. && isPositiveAndBelow (localPos.getY(), (int) viewFrame.size.height)))
  338. return false;
  339. if (NSWindow* const viewWindow = [view window])
  340. {
  341. const NSRect windowFrame = [viewWindow frame];
  342. const NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, localPos.y) toView: nil];
  343. const NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
  344. windowFrame.origin.y + windowFrame.size.height - windowPoint.y);
  345. if (! isWindowAtPoint (viewWindow, screenPoint))
  346. return false;
  347. }
  348. NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
  349. viewFrame.origin.y + viewFrame.size.height - localPos.getY())];
  350. return trueIfInAChildWindow ? (v != nil)
  351. : (v == view);
  352. }
  353. BorderSize<int> getFrameSize() const override
  354. {
  355. BorderSize<int> b;
  356. if (! isSharedWindow)
  357. {
  358. NSRect v = [view convertRect: [view frame] toView: nil];
  359. NSRect w = [window frame];
  360. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  361. b.setBottom ((int) v.origin.y);
  362. b.setLeft ((int) v.origin.x);
  363. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  364. }
  365. return b;
  366. }
  367. void updateFullscreenStatus()
  368. {
  369. if (hasNativeTitleBar())
  370. {
  371. const Rectangle<int> screen (getFrameSize().subtractedFrom (component.getParentMonitorArea()));
  372. fullScreen = component.getScreenBounds().expanded (2, 2).contains (screen);
  373. }
  374. }
  375. bool hasNativeTitleBar() const
  376. {
  377. return (getStyleFlags() & windowHasTitleBar) != 0;
  378. }
  379. bool setAlwaysOnTop (bool alwaysOnTop) override
  380. {
  381. if (! isSharedWindow)
  382. [window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
  383. : NSFloatingWindowLevel)
  384. : NSNormalWindowLevel];
  385. return true;
  386. }
  387. void toFront (bool makeActiveWindow) override
  388. {
  389. if (isSharedWindow)
  390. [[view superview] addSubview: view
  391. positioned: NSWindowAbove
  392. relativeTo: nil];
  393. if (window != nil && component.isVisible())
  394. {
  395. ++insideToFrontCall;
  396. if (makeActiveWindow)
  397. [window makeKeyAndOrderFront: nil];
  398. else
  399. [window orderFront: nil];
  400. if (insideToFrontCall <= 1)
  401. {
  402. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  403. handleBroughtToFront();
  404. }
  405. --insideToFrontCall;
  406. }
  407. }
  408. void toBehind (ComponentPeer* other) override
  409. {
  410. NSViewComponentPeer* const otherPeer = dynamic_cast<NSViewComponentPeer*> (other);
  411. jassert (otherPeer != nullptr); // wrong type of window?
  412. if (otherPeer != nullptr)
  413. {
  414. if (isSharedWindow)
  415. {
  416. [[view superview] addSubview: view
  417. positioned: NSWindowBelow
  418. relativeTo: otherPeer->view];
  419. }
  420. else if (component.isVisible())
  421. {
  422. [window orderWindow: NSWindowBelow
  423. relativeTo: [otherPeer->window windowNumber]];
  424. }
  425. }
  426. }
  427. void setIcon (const Image&) override
  428. {
  429. // to do..
  430. }
  431. StringArray getAvailableRenderingEngines() override
  432. {
  433. StringArray s ("Software Renderer");
  434. #if USE_COREGRAPHICS_RENDERING
  435. s.add ("CoreGraphics Renderer");
  436. #endif
  437. return s;
  438. }
  439. int getCurrentRenderingEngine() const override
  440. {
  441. return usingCoreGraphics ? 1 : 0;
  442. }
  443. void setCurrentRenderingEngine (int index) override
  444. {
  445. #if USE_COREGRAPHICS_RENDERING
  446. if (usingCoreGraphics != (index > 0))
  447. {
  448. usingCoreGraphics = index > 0;
  449. [view setNeedsDisplay: true];
  450. }
  451. #endif
  452. }
  453. void redirectMouseDown (NSEvent* ev)
  454. {
  455. if (! Process::isForegroundProcess())
  456. Process::makeForegroundProcess();
  457. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  458. sendMouseEvent (ev);
  459. }
  460. void redirectMouseUp (NSEvent* ev)
  461. {
  462. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  463. sendMouseEvent (ev);
  464. showArrowCursorIfNeeded();
  465. }
  466. void redirectMouseDrag (NSEvent* ev)
  467. {
  468. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  469. sendMouseEvent (ev);
  470. }
  471. void redirectMouseMove (NSEvent* ev)
  472. {
  473. currentModifiers = currentModifiers.withoutMouseButtons();
  474. if (isWindowAtPoint ([ev window], [[ev window] convertBaseToScreen: [ev locationInWindow]]))
  475. sendMouseEvent (ev);
  476. else
  477. // moved into another window which overlaps this one, so trigger an exit
  478. handleMouseEvent (0, Point<float> (-1.0f, -1.0f), currentModifiers, getMouseTime (ev));
  479. showArrowCursorIfNeeded();
  480. }
  481. void redirectMouseEnter (NSEvent* ev)
  482. {
  483. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  484. currentModifiers = currentModifiers.withoutMouseButtons();
  485. sendMouseEvent (ev);
  486. }
  487. void redirectMouseExit (NSEvent* ev)
  488. {
  489. currentModifiers = currentModifiers.withoutMouseButtons();
  490. sendMouseEvent (ev);
  491. }
  492. static float checkDeviceDeltaReturnValue (float v) noexcept
  493. {
  494. // (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
  495. v *= 0.5f / 256.0f;
  496. return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
  497. }
  498. void redirectMouseWheel (NSEvent* ev)
  499. {
  500. updateModifiers (ev);
  501. MouseWheelDetails wheel;
  502. wheel.deltaX = 0;
  503. wheel.deltaY = 0;
  504. wheel.isReversed = false;
  505. wheel.isSmooth = false;
  506. #if ! JUCE_PPC
  507. @try
  508. {
  509. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  510. if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
  511. wheel.isReversed = [ev isDirectionInvertedFromDevice];
  512. if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
  513. {
  514. if ([ev hasPreciseScrollingDeltas])
  515. {
  516. const float scale = 0.5f / 256.0f;
  517. wheel.deltaX = scale * (float) [ev scrollingDeltaX];
  518. wheel.deltaY = scale * (float) [ev scrollingDeltaY];
  519. wheel.isSmooth = true;
  520. }
  521. }
  522. else
  523. #endif
  524. if ([ev respondsToSelector: @selector (deviceDeltaX)])
  525. {
  526. wheel.deltaX = checkDeviceDeltaReturnValue ((float) objc_msgSend_fpret (ev, @selector (deviceDeltaX)));
  527. wheel.deltaY = checkDeviceDeltaReturnValue ((float) objc_msgSend_fpret (ev, @selector (deviceDeltaY)));
  528. }
  529. }
  530. @catch (...)
  531. {}
  532. #endif
  533. if (wheel.deltaX == 0 && wheel.deltaY == 0)
  534. {
  535. const float scale = 10.0f / 256.0f;
  536. wheel.deltaX = scale * (float) [ev deltaX];
  537. wheel.deltaY = scale * (float) [ev deltaY];
  538. }
  539. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), wheel);
  540. }
  541. void redirectMagnify (NSEvent* ev)
  542. {
  543. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  544. const float invScale = 1.0f - (float) [ev magnification];
  545. if (invScale != 0.0f)
  546. handleMagnifyGesture (0, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
  547. #endif
  548. (void) ev;
  549. }
  550. void sendMouseEvent (NSEvent* ev)
  551. {
  552. updateModifiers (ev);
  553. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  554. }
  555. bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
  556. {
  557. const String unicode (nsStringToJuce ([ev characters]));
  558. const int keyCode = getKeyCodeFromEvent (ev);
  559. #if JUCE_DEBUG_KEYCODES
  560. DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  561. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  562. DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  563. #endif
  564. if (keyCode != 0 || unicode.isNotEmpty())
  565. {
  566. if (isKeyDown)
  567. {
  568. bool used = false;
  569. for (String::CharPointerType u (unicode.getCharPointer()); ! u.isEmpty();)
  570. {
  571. juce_wchar textCharacter = u.getAndAdvance();
  572. switch (keyCode)
  573. {
  574. case NSLeftArrowFunctionKey:
  575. case NSRightArrowFunctionKey:
  576. case NSUpArrowFunctionKey:
  577. case NSDownArrowFunctionKey:
  578. case NSPageUpFunctionKey:
  579. case NSPageDownFunctionKey:
  580. case NSEndFunctionKey:
  581. case NSHomeFunctionKey:
  582. case NSDeleteFunctionKey:
  583. textCharacter = 0;
  584. break; // (these all seem to generate unwanted garbage unicode strings)
  585. default:
  586. if (([ev modifierFlags] & NSCommandKeyMask) != 0
  587. || (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
  588. textCharacter = 0;
  589. break;
  590. }
  591. used = handleKeyUpOrDown (true) || used;
  592. used = handleKeyPress (keyCode, textCharacter) || used;
  593. }
  594. return used;
  595. }
  596. if (handleKeyUpOrDown (false))
  597. return true;
  598. }
  599. return false;
  600. }
  601. bool redirectKeyDown (NSEvent* ev)
  602. {
  603. // (need to retain this in case a modal loop runs in handleKeyEvent and
  604. // our event object gets lost)
  605. const NSObjectRetainer<NSEvent> r (ev);
  606. updateKeysDown (ev, true);
  607. bool used = handleKeyEvent (ev, true);
  608. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  609. {
  610. // for command keys, the key-up event is thrown away, so simulate one..
  611. updateKeysDown (ev, false);
  612. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  613. }
  614. // (If we're running modally, don't allow unused keystrokes to be passed
  615. // along to other blocked views..)
  616. if (Component::getCurrentlyModalComponent() != nullptr)
  617. used = true;
  618. return used;
  619. }
  620. bool redirectKeyUp (NSEvent* ev)
  621. {
  622. updateKeysDown (ev, false);
  623. return handleKeyEvent (ev, false)
  624. || Component::getCurrentlyModalComponent() != nullptr;
  625. }
  626. void redirectModKeyChange (NSEvent* ev)
  627. {
  628. // (need to retain this in case a modal loop runs and our event object gets lost)
  629. const NSObjectRetainer<NSEvent> r (ev);
  630. keysCurrentlyDown.clear();
  631. handleKeyUpOrDown (true);
  632. updateModifiers (ev);
  633. handleModifierKeysChange();
  634. }
  635. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  636. bool redirectPerformKeyEquivalent (NSEvent* ev)
  637. {
  638. if ([ev type] == NSKeyDown) return redirectKeyDown (ev);
  639. if ([ev type] == NSKeyUp) return redirectKeyUp (ev);
  640. return false;
  641. }
  642. #endif
  643. void drawRect (NSRect r)
  644. {
  645. if (r.size.width < 1.0f || r.size.height < 1.0f)
  646. return;
  647. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  648. if (! component.isOpaque())
  649. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  650. float displayScale = 1.0f;
  651. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  652. NSScreen* screen = [[view window] screen];
  653. if ([screen respondsToSelector: @selector (backingScaleFactor)])
  654. displayScale = (float) screen.backingScaleFactor;
  655. #endif
  656. #if USE_COREGRAPHICS_RENDERING
  657. if (usingCoreGraphics)
  658. {
  659. CoreGraphicsContext context (cg, (float) [view frame].size.height, displayScale);
  660. insideDrawRect = true;
  661. handlePaint (context);
  662. insideDrawRect = false;
  663. }
  664. else
  665. #endif
  666. {
  667. const Point<int> offset (-roundToInt (r.origin.x),
  668. -roundToInt ([view frame].size.height - (r.origin.y + r.size.height)));
  669. const int clipW = (int) (r.size.width + 0.5f);
  670. const int clipH = (int) (r.size.height + 0.5f);
  671. RectangleList<int> clip;
  672. getClipRects (clip, offset, clipW, clipH);
  673. if (! clip.isEmpty())
  674. {
  675. Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
  676. roundToInt (clipW * displayScale),
  677. roundToInt (clipH * displayScale),
  678. ! component.isOpaque());
  679. {
  680. const int intScale = roundToInt (displayScale);
  681. if (intScale != 1)
  682. clip.scaleAll (intScale);
  683. ScopedPointer<LowLevelGraphicsContext> context (component.getLookAndFeel()
  684. .createGraphicsContext (temp, offset * intScale, clip));
  685. if (intScale != 1)
  686. context->addTransform (AffineTransform::scale (displayScale));
  687. insideDrawRect = true;
  688. handlePaint (*context);
  689. insideDrawRect = false;
  690. }
  691. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  692. CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace, false);
  693. CGColorSpaceRelease (colourSpace);
  694. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
  695. CGImageRelease (image);
  696. }
  697. }
  698. }
  699. bool sendModalInputAttemptIfBlocked()
  700. {
  701. Component* const modal = Component::getCurrentlyModalComponent();
  702. if (modal != nullptr
  703. && insideToFrontCall == 0
  704. && (! getComponent().isParentOf (modal))
  705. && getComponent().isCurrentlyBlockedByAnotherModalComponent())
  706. {
  707. modal->inputAttemptWhenModal();
  708. return true;
  709. }
  710. return false;
  711. }
  712. bool canBecomeKeyWindow()
  713. {
  714. return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
  715. }
  716. void becomeKeyWindow()
  717. {
  718. handleBroughtToFront();
  719. grabFocus();
  720. }
  721. bool windowShouldClose()
  722. {
  723. if (! isValidPeer (this))
  724. return YES;
  725. handleUserClosingWindow();
  726. return NO;
  727. }
  728. void redirectMovedOrResized()
  729. {
  730. updateFullscreenStatus();
  731. handleMovedOrResized();
  732. }
  733. void viewMovedToWindow()
  734. {
  735. if (isSharedWindow)
  736. window = [view window];
  737. }
  738. void liveResizingStart()
  739. {
  740. if (constrainer != nullptr)
  741. constrainer->resizeStart();
  742. }
  743. void liveResizingEnd()
  744. {
  745. if (constrainer != nullptr)
  746. constrainer->resizeEnd();
  747. }
  748. NSRect constrainRect (NSRect r)
  749. {
  750. if (constrainer != nullptr && ! isKioskMode())
  751. {
  752. Rectangle<int> pos (convertToRectInt (flippedScreenRect (r)));
  753. Rectangle<int> original (convertToRectInt (flippedScreenRect ([window frame])));
  754. const Rectangle<int> screenBounds (Desktop::getInstance().getDisplays().getTotalBounds (true));
  755. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  756. if ([window inLiveResize])
  757. #else
  758. if ([window respondsToSelector: @selector (inLiveResize)]
  759. && [window performSelector: @selector (inLiveResize)])
  760. #endif
  761. {
  762. constrainer->checkBounds (pos, original, screenBounds,
  763. false, false, true, true);
  764. }
  765. else
  766. {
  767. constrainer->checkBounds (pos, original, screenBounds,
  768. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  769. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  770. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  771. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  772. }
  773. r = flippedScreenRect (makeNSRect (pos));
  774. }
  775. return r;
  776. }
  777. static void showArrowCursorIfNeeded()
  778. {
  779. Desktop& desktop = Desktop::getInstance();
  780. MouseInputSource mouse = desktop.getMainMouseSource();
  781. if (mouse.getComponentUnderMouse() == nullptr
  782. && desktop.findComponentAt (mouse.getScreenPosition().roundToInt()) == nullptr)
  783. {
  784. [[NSCursor arrowCursor] set];
  785. }
  786. }
  787. static void updateModifiers (NSEvent* e)
  788. {
  789. updateModifiers ([e modifierFlags]);
  790. }
  791. static void updateModifiers (const NSUInteger flags)
  792. {
  793. int m = 0;
  794. if ((flags & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  795. if ((flags & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  796. if ((flags & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  797. if ((flags & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  798. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  799. }
  800. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  801. {
  802. updateModifiers (ev);
  803. int keyCode = getKeyCodeFromEvent (ev);
  804. if (keyCode != 0)
  805. {
  806. if (isKeyDown)
  807. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  808. else
  809. keysCurrentlyDown.removeFirstMatchingValue (keyCode);
  810. }
  811. }
  812. static int getKeyCodeFromEvent (NSEvent* ev)
  813. {
  814. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  815. int keyCode = unmodified[0];
  816. if (keyCode == 0x19) // (backwards-tab)
  817. keyCode = '\t';
  818. else if (keyCode == 0x03) // (enter)
  819. keyCode = '\r';
  820. else
  821. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  822. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  823. {
  824. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  825. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  826. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  827. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  828. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  829. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  830. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  831. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  832. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  833. if (keyCode == numPadConversions [i])
  834. keyCode = numPadConversions [i + 1];
  835. }
  836. return keyCode;
  837. }
  838. static int64 getMouseTime (NSEvent* e)
  839. {
  840. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  841. + (int64) ([e timestamp] * 1000.0);
  842. }
  843. static Point<float> getMousePos (NSEvent* e, NSView* view)
  844. {
  845. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  846. return Point<float> ((float) p.x, (float) ([view frame].size.height - p.y));
  847. }
  848. static int getModifierForButtonNumber (const NSInteger num)
  849. {
  850. return num == 0 ? ModifierKeys::leftButtonModifier
  851. : (num == 1 ? ModifierKeys::rightButtonModifier
  852. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  853. }
  854. static unsigned int getNSWindowStyleMask (const int flags) noexcept
  855. {
  856. unsigned int style = (flags & windowHasTitleBar) != 0 ? NSTitledWindowMask
  857. : NSBorderlessWindowMask;
  858. if ((flags & windowHasMinimiseButton) != 0) style |= NSMiniaturizableWindowMask;
  859. if ((flags & windowHasCloseButton) != 0) style |= NSClosableWindowMask;
  860. if ((flags & windowIsResizable) != 0) style |= NSResizableWindowMask;
  861. return style;
  862. }
  863. static NSArray* getSupportedDragTypes()
  864. {
  865. return [NSArray arrayWithObjects: NSFilenamesPboardType, NSFilesPromisePboardType, NSStringPboardType, nil];
  866. }
  867. BOOL sendDragCallback (const int type, id <NSDraggingInfo> sender)
  868. {
  869. NSPasteboard* pasteboard = [sender draggingPasteboard];
  870. NSString* contentType = [pasteboard availableTypeFromArray: getSupportedDragTypes()];
  871. if (contentType == nil)
  872. return false;
  873. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  874. ComponentPeer::DragInfo dragInfo;
  875. dragInfo.position.setXY ((int) p.x, (int) ([view frame].size.height - p.y));
  876. if (contentType == NSStringPboardType)
  877. dragInfo.text = nsStringToJuce ([pasteboard stringForType: NSStringPboardType]);
  878. else
  879. dragInfo.files = getDroppedFiles (pasteboard, contentType);
  880. if (! dragInfo.isEmpty())
  881. {
  882. switch (type)
  883. {
  884. case 0: return handleDragMove (dragInfo);
  885. case 1: return handleDragExit (dragInfo);
  886. case 2: return handleDragDrop (dragInfo);
  887. default: jassertfalse; break;
  888. }
  889. }
  890. return false;
  891. }
  892. StringArray getDroppedFiles (NSPasteboard* pasteboard, NSString* contentType)
  893. {
  894. StringArray files;
  895. NSString* iTunesPasteboardType = nsStringLiteral ("CorePasteboardFlavorType 0x6974756E"); // 'itun'
  896. if (contentType == NSFilesPromisePboardType
  897. && [[pasteboard types] containsObject: iTunesPasteboardType])
  898. {
  899. id list = [pasteboard propertyListForType: iTunesPasteboardType];
  900. if ([list isKindOfClass: [NSDictionary class]])
  901. {
  902. NSDictionary* iTunesDictionary = (NSDictionary*) list;
  903. NSArray* tracks = [iTunesDictionary valueForKey: nsStringLiteral ("Tracks")];
  904. NSEnumerator* enumerator = [tracks objectEnumerator];
  905. NSDictionary* track;
  906. while ((track = [enumerator nextObject]) != nil)
  907. {
  908. NSURL* url = [NSURL URLWithString: [track valueForKey: nsStringLiteral ("Location")]];
  909. if ([url isFileURL])
  910. files.add (nsStringToJuce ([url path]));
  911. }
  912. }
  913. }
  914. else
  915. {
  916. id list = [pasteboard propertyListForType: NSFilenamesPboardType];
  917. if ([list isKindOfClass: [NSArray class]])
  918. {
  919. NSArray* items = (NSArray*) [pasteboard propertyListForType: NSFilenamesPboardType];
  920. for (unsigned int i = 0; i < [items count]; ++i)
  921. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  922. }
  923. }
  924. return files;
  925. }
  926. //==============================================================================
  927. void viewFocusGain()
  928. {
  929. if (currentlyFocusedPeer != this)
  930. {
  931. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  932. currentlyFocusedPeer->handleFocusLoss();
  933. currentlyFocusedPeer = this;
  934. handleFocusGain();
  935. }
  936. }
  937. void viewFocusLoss()
  938. {
  939. if (currentlyFocusedPeer == this)
  940. {
  941. currentlyFocusedPeer = nullptr;
  942. handleFocusLoss();
  943. }
  944. }
  945. bool isFocused() const override
  946. {
  947. return (isSharedWindow || ! JUCEApplication::isStandaloneApp())
  948. ? this == currentlyFocusedPeer
  949. : [window isKeyWindow];
  950. }
  951. void grabFocus() override
  952. {
  953. if (window != nil)
  954. {
  955. [window makeKeyWindow];
  956. [window makeFirstResponder: view];
  957. viewFocusGain();
  958. }
  959. }
  960. void textInputRequired (Point<int>, TextInputTarget&) override {}
  961. //==============================================================================
  962. void repaint (const Rectangle<int>& area) override
  963. {
  964. if (insideDrawRect)
  965. {
  966. class AsyncRepaintMessage : public CallbackMessage
  967. {
  968. public:
  969. AsyncRepaintMessage (NSViewComponentPeer* const p, const Rectangle<int>& r)
  970. : peer (p), rect (r)
  971. {}
  972. void messageCallback() override
  973. {
  974. if (ComponentPeer::isValidPeer (peer))
  975. peer->repaint (rect);
  976. }
  977. private:
  978. NSViewComponentPeer* const peer;
  979. const Rectangle<int> rect;
  980. };
  981. (new AsyncRepaintMessage (this, area))->post();
  982. }
  983. else
  984. {
  985. [view setNeedsDisplayInRect: NSMakeRect ((CGFloat) area.getX(), [view frame].size.height - (CGFloat) area.getBottom(),
  986. (CGFloat) area.getWidth(), (CGFloat) area.getHeight())];
  987. }
  988. }
  989. void performAnyPendingRepaintsNow() override
  990. {
  991. [view displayIfNeeded];
  992. }
  993. //==============================================================================
  994. NSWindow* window;
  995. NSView* view;
  996. bool isSharedWindow, fullScreen, insideDrawRect;
  997. bool usingCoreGraphics, isZooming, textWasInserted;
  998. String stringBeingComposed;
  999. NSNotificationCenter* notificationCenter;
  1000. static ModifierKeys currentModifiers;
  1001. static ComponentPeer* currentlyFocusedPeer;
  1002. static Array<int> keysCurrentlyDown;
  1003. static int insideToFrontCall;
  1004. private:
  1005. static NSView* createViewInstance();
  1006. static NSWindow* createWindowInstance();
  1007. static void setOwner (id viewOrWindow, NSViewComponentPeer* newOwner)
  1008. {
  1009. object_setInstanceVariable (viewOrWindow, "owner", newOwner);
  1010. }
  1011. void getClipRects (RectangleList<int>& clip, const Point<int> offset, const int clipW, const int clipH)
  1012. {
  1013. const NSRect* rects = nullptr;
  1014. NSInteger numRects = 0;
  1015. [view getRectsBeingDrawn: &rects count: &numRects];
  1016. const Rectangle<int> clipBounds (clipW, clipH);
  1017. const CGFloat viewH = [view frame].size.height;
  1018. clip.ensureStorageAllocated ((int) numRects);
  1019. for (int i = 0; i < numRects; ++i)
  1020. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + offset.x,
  1021. roundToInt (viewH - (rects[i].origin.y + rects[i].size.height)) + offset.y,
  1022. roundToInt (rects[i].size.width),
  1023. roundToInt (rects[i].size.height))));
  1024. }
  1025. static void appFocusChanged()
  1026. {
  1027. keysCurrentlyDown.clear();
  1028. if (isValidPeer (currentlyFocusedPeer))
  1029. {
  1030. if (Process::isForegroundProcess())
  1031. {
  1032. currentlyFocusedPeer->handleFocusGain();
  1033. ModalComponentManager::getInstance()->bringModalComponentsToFront();
  1034. }
  1035. else
  1036. {
  1037. currentlyFocusedPeer->handleFocusLoss();
  1038. }
  1039. }
  1040. }
  1041. static bool checkEventBlockedByModalComps (NSEvent* e)
  1042. {
  1043. if (Component::getNumCurrentlyModalComponents() == 0)
  1044. return false;
  1045. NSWindow* const w = [e window];
  1046. if (w == nil || [w worksWhenModal])
  1047. return false;
  1048. bool isKey = false, isInputAttempt = false;
  1049. switch ([e type])
  1050. {
  1051. case NSKeyDown:
  1052. case NSKeyUp:
  1053. isKey = isInputAttempt = true;
  1054. break;
  1055. case NSLeftMouseDown:
  1056. case NSRightMouseDown:
  1057. case NSOtherMouseDown:
  1058. isInputAttempt = true;
  1059. break;
  1060. case NSLeftMouseDragged:
  1061. case NSRightMouseDragged:
  1062. case NSLeftMouseUp:
  1063. case NSRightMouseUp:
  1064. case NSOtherMouseUp:
  1065. case NSOtherMouseDragged:
  1066. if (Desktop::getInstance().getDraggingMouseSource(0) != nullptr)
  1067. return false;
  1068. break;
  1069. case NSMouseMoved:
  1070. case NSMouseEntered:
  1071. case NSMouseExited:
  1072. case NSCursorUpdate:
  1073. case NSScrollWheel:
  1074. case NSTabletPoint:
  1075. case NSTabletProximity:
  1076. break;
  1077. default:
  1078. return false;
  1079. }
  1080. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1081. {
  1082. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  1083. NSView* const compView = (NSView*) peer->getNativeHandle();
  1084. if ([compView window] == w)
  1085. {
  1086. if (isKey)
  1087. {
  1088. if (compView == [w firstResponder])
  1089. return false;
  1090. }
  1091. else
  1092. {
  1093. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  1094. if ((nsViewPeer == nullptr || ! nsViewPeer->isSharedWindow)
  1095. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  1096. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  1097. return false;
  1098. }
  1099. }
  1100. }
  1101. if (isInputAttempt)
  1102. {
  1103. if (! [NSApp isActive])
  1104. [NSApp activateIgnoringOtherApps: YES];
  1105. if (Component* const modal = Component::getCurrentlyModalComponent())
  1106. modal->inputAttemptWhenModal();
  1107. }
  1108. return true;
  1109. }
  1110. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NSViewComponentPeer)
  1111. };
  1112. int NSViewComponentPeer::insideToFrontCall = 0;
  1113. //==============================================================================
  1114. struct JuceNSViewClass : public ObjCClass <NSView>
  1115. {
  1116. JuceNSViewClass() : ObjCClass <NSView> ("JUCEView_")
  1117. {
  1118. addIvar<NSViewComponentPeer*> ("owner");
  1119. addMethod (@selector (isOpaque), isOpaque, "c@:");
  1120. addMethod (@selector (drawRect:), drawRect, "v@:", @encode (NSRect));
  1121. addMethod (@selector (mouseDown:), mouseDown, "v@:@");
  1122. addMethod (@selector (asyncMouseDown:), asyncMouseDown, "v@:@");
  1123. addMethod (@selector (mouseUp:), mouseUp, "v@:@");
  1124. addMethod (@selector (asyncMouseUp:), asyncMouseUp, "v@:@");
  1125. addMethod (@selector (mouseDragged:), mouseDragged, "v@:@");
  1126. addMethod (@selector (mouseMoved:), mouseMoved, "v@:@");
  1127. addMethod (@selector (mouseEntered:), mouseEntered, "v@:@");
  1128. addMethod (@selector (mouseExited:), mouseExited, "v@:@");
  1129. addMethod (@selector (rightMouseDown:), mouseDown, "v@:@");
  1130. addMethod (@selector (rightMouseDragged:), mouseDragged, "v@:@");
  1131. addMethod (@selector (rightMouseUp:), mouseUp, "v@:@");
  1132. addMethod (@selector (otherMouseDown:), mouseDown, "v@:@");
  1133. addMethod (@selector (otherMouseDragged:), mouseDragged, "v@:@");
  1134. addMethod (@selector (otherMouseUp:), mouseUp, "v@:@");
  1135. addMethod (@selector (scrollWheel:), scrollWheel, "v@:@");
  1136. addMethod (@selector (magnifyWithEvent:), magnify, "v@:@");
  1137. addMethod (@selector (acceptsFirstMouse:), acceptsFirstMouse, "v@:@");
  1138. addMethod (@selector (frameChanged:), frameChanged, "v@:@");
  1139. addMethod (@selector (viewDidMoveToWindow), viewDidMoveToWindow, "v@:");
  1140. addMethod (@selector (keyDown:), keyDown, "v@:@");
  1141. addMethod (@selector (keyUp:), keyUp, "v@:@");
  1142. addMethod (@selector (insertText:), insertText, "v@:@");
  1143. addMethod (@selector (doCommandBySelector:), doCommandBySelector, "v@::");
  1144. addMethod (@selector (setMarkedText:selectedRange:), setMarkedText, "v@:@", @encode (NSRange));
  1145. addMethod (@selector (unmarkText), unmarkText, "v@:");
  1146. addMethod (@selector (hasMarkedText), hasMarkedText, "c@:");
  1147. addMethod (@selector (conversationIdentifier), conversationIdentifier, "l@:");
  1148. addMethod (@selector (attributedSubstringFromRange:), attributedSubstringFromRange, "@@:", @encode (NSRange));
  1149. addMethod (@selector (markedRange), markedRange, @encode (NSRange), "@:");
  1150. addMethod (@selector (selectedRange), selectedRange, @encode (NSRange), "@:");
  1151. addMethod (@selector (firstRectForCharacterRange:), firstRectForCharacterRange, @encode (NSRect), "@:", @encode (NSRange));
  1152. addMethod (@selector (validAttributesForMarkedText), validAttributesForMarkedText, "@@:");
  1153. addMethod (@selector (flagsChanged:), flagsChanged, "v@:@");
  1154. addMethod (@selector (becomeFirstResponder), becomeFirstResponder, "c@:");
  1155. addMethod (@selector (resignFirstResponder), resignFirstResponder, "c@:");
  1156. addMethod (@selector (acceptsFirstResponder), acceptsFirstResponder, "c@:");
  1157. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1158. addMethod (@selector (performKeyEquivalent:), performKeyEquivalent, "c@:@");
  1159. #endif
  1160. addMethod (@selector (draggingEntered:), draggingEntered, @encode (NSDragOperation), "@:@");
  1161. addMethod (@selector (draggingUpdated:), draggingUpdated, @encode (NSDragOperation), "@:@");
  1162. addMethod (@selector (draggingEnded:), draggingEnded, "v@:@");
  1163. addMethod (@selector (draggingExited:), draggingExited, "v@:@");
  1164. addMethod (@selector (prepareForDragOperation:), prepareForDragOperation, "c@:@");
  1165. addMethod (@selector (performDragOperation:), performDragOperation, "c@:@");
  1166. addMethod (@selector (concludeDragOperation:), concludeDragOperation, "v@:@");
  1167. addProtocol (@protocol (NSTextInput));
  1168. registerClass();
  1169. }
  1170. private:
  1171. static NSViewComponentPeer* getOwner (id self)
  1172. {
  1173. return getIvar<NSViewComponentPeer*> (self, "owner");
  1174. }
  1175. static void mouseDown (id self, SEL s, NSEvent* ev)
  1176. {
  1177. if (JUCEApplicationBase::isStandaloneApp())
  1178. asyncMouseDown (self, s, ev);
  1179. else
  1180. // In some host situations, the host will stop modal loops from working
  1181. // correctly if they're called from a mouse event, so we'll trigger
  1182. // the event asynchronously..
  1183. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  1184. withObject: ev
  1185. waitUntilDone: NO];
  1186. }
  1187. static void mouseUp (id self, SEL s, NSEvent* ev)
  1188. {
  1189. if (JUCEApplicationBase::isStandaloneApp())
  1190. asyncMouseUp (self, s, ev);
  1191. else
  1192. // In some host situations, the host will stop modal loops from working
  1193. // correctly if they're called from a mouse event, so we'll trigger
  1194. // the event asynchronously..
  1195. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  1196. withObject: ev
  1197. waitUntilDone: NO];
  1198. }
  1199. static void asyncMouseDown (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseDown (ev); }
  1200. static void asyncMouseUp (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseUp (ev); }
  1201. static void mouseDragged (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseDrag (ev); }
  1202. static void mouseMoved (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseMove (ev); }
  1203. static void mouseEntered (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseEnter (ev); }
  1204. static void mouseExited (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseExit (ev); }
  1205. static void scrollWheel (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMouseWheel (ev); }
  1206. static void magnify (id self, SEL, NSEvent* ev) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMagnify (ev); }
  1207. static BOOL acceptsFirstMouse (id, SEL, NSEvent*) { return YES; }
  1208. static void drawRect (id self, SEL, NSRect r) { if (NSViewComponentPeer* const p = getOwner (self)) p->drawRect (r); }
  1209. static void frameChanged (id self, SEL, NSNotification*) { if (NSViewComponentPeer* const p = getOwner (self)) p->redirectMovedOrResized(); }
  1210. static void viewDidMoveToWindow (id self, SEL) { if (NSViewComponentPeer* const p = getOwner (self)) p->viewMovedToWindow(); }
  1211. static BOOL isOpaque (id self, SEL)
  1212. {
  1213. NSViewComponentPeer* const owner = getOwner (self);
  1214. return owner == nullptr || owner->getComponent().isOpaque();
  1215. }
  1216. //==============================================================================
  1217. static void keyDown (id self, SEL, NSEvent* ev)
  1218. {
  1219. if (NSViewComponentPeer* const owner = getOwner (self))
  1220. {
  1221. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  1222. owner->textWasInserted = false;
  1223. if (target != nullptr)
  1224. [(NSView*) self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  1225. else
  1226. owner->stringBeingComposed.clear();
  1227. if ((! owner->textWasInserted) && (owner == nullptr || ! owner->redirectKeyDown (ev)))
  1228. {
  1229. objc_super s = { self, [NSView class] };
  1230. objc_msgSendSuper (&s, @selector (keyDown:), ev);
  1231. }
  1232. }
  1233. }
  1234. static void keyUp (id self, SEL, NSEvent* ev)
  1235. {
  1236. NSViewComponentPeer* const owner = getOwner (self);
  1237. if (owner == nullptr || ! owner->redirectKeyUp (ev))
  1238. {
  1239. objc_super s = { self, [NSView class] };
  1240. objc_msgSendSuper (&s, @selector (keyUp:), ev);
  1241. }
  1242. }
  1243. //==============================================================================
  1244. static void insertText (id self, SEL, id aString)
  1245. {
  1246. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  1247. if (NSViewComponentPeer* const owner = getOwner (self))
  1248. {
  1249. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  1250. if ([newText length] > 0)
  1251. {
  1252. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1253. {
  1254. target->insertTextAtCaret (nsStringToJuce (newText));
  1255. owner->textWasInserted = true;
  1256. }
  1257. }
  1258. owner->stringBeingComposed.clear();
  1259. }
  1260. }
  1261. static void doCommandBySelector (id, SEL, SEL) {}
  1262. static void setMarkedText (id self, SEL, id aString, NSRange)
  1263. {
  1264. if (NSViewComponentPeer* const owner = getOwner (self))
  1265. {
  1266. owner->stringBeingComposed = nsStringToJuce ([aString isKindOfClass: [NSAttributedString class]]
  1267. ? [aString string] : aString);
  1268. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1269. {
  1270. const Range<int> currentHighlight (target->getHighlightedRegion());
  1271. target->insertTextAtCaret (owner->stringBeingComposed);
  1272. target->setHighlightedRegion (currentHighlight.withLength (owner->stringBeingComposed.length()));
  1273. owner->textWasInserted = true;
  1274. }
  1275. }
  1276. }
  1277. static void unmarkText (id self, SEL)
  1278. {
  1279. if (NSViewComponentPeer* const owner = getOwner (self))
  1280. {
  1281. if (owner->stringBeingComposed.isNotEmpty())
  1282. {
  1283. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1284. {
  1285. target->insertTextAtCaret (owner->stringBeingComposed);
  1286. owner->textWasInserted = true;
  1287. }
  1288. owner->stringBeingComposed.clear();
  1289. }
  1290. }
  1291. }
  1292. static BOOL hasMarkedText (id self, SEL)
  1293. {
  1294. NSViewComponentPeer* const owner = getOwner (self);
  1295. return owner != nullptr && owner->stringBeingComposed.isNotEmpty();
  1296. }
  1297. static long conversationIdentifier (id self, SEL)
  1298. {
  1299. return (long) (pointer_sized_int) self;
  1300. }
  1301. static NSAttributedString* attributedSubstringFromRange (id self, SEL, NSRange theRange)
  1302. {
  1303. if (NSViewComponentPeer* const owner = getOwner (self))
  1304. {
  1305. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1306. {
  1307. const Range<int> r ((int) theRange.location,
  1308. (int) (theRange.location + theRange.length));
  1309. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  1310. }
  1311. }
  1312. return nil;
  1313. }
  1314. static NSRange markedRange (id self, SEL)
  1315. {
  1316. if (NSViewComponentPeer* const owner = getOwner (self))
  1317. if (owner->stringBeingComposed.isNotEmpty())
  1318. return NSMakeRange (0, (NSUInteger) owner->stringBeingComposed.length());
  1319. return NSMakeRange (NSNotFound, 0);
  1320. }
  1321. static NSRange selectedRange (id self, SEL)
  1322. {
  1323. if (NSViewComponentPeer* const owner = getOwner (self))
  1324. {
  1325. if (TextInputTarget* const target = owner->findCurrentTextInputTarget())
  1326. {
  1327. const Range<int> highlight (target->getHighlightedRegion());
  1328. if (! highlight.isEmpty())
  1329. return NSMakeRange ((NSUInteger) highlight.getStart(),
  1330. (NSUInteger) highlight.getLength());
  1331. }
  1332. }
  1333. return NSMakeRange (NSNotFound, 0);
  1334. }
  1335. static NSRect firstRectForCharacterRange (id self, SEL, NSRange)
  1336. {
  1337. if (NSViewComponentPeer* const owner = getOwner (self))
  1338. if (Component* const comp = dynamic_cast<Component*> (owner->findCurrentTextInputTarget()))
  1339. return flippedScreenRect (makeNSRect (comp->getScreenBounds()));
  1340. return NSZeroRect;
  1341. }
  1342. static NSUInteger characterIndexForPoint (id, SEL, NSPoint) { return NSNotFound; }
  1343. static NSArray* validAttributesForMarkedText (id, SEL) { return [NSArray array]; }
  1344. //==============================================================================
  1345. static void flagsChanged (id self, SEL, NSEvent* ev)
  1346. {
  1347. if (NSViewComponentPeer* const owner = getOwner (self))
  1348. owner->redirectModKeyChange (ev);
  1349. }
  1350. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  1351. static BOOL performKeyEquivalent (id self, SEL, NSEvent* ev)
  1352. {
  1353. if (NSViewComponentPeer* const owner = getOwner (self))
  1354. if (owner->redirectPerformKeyEquivalent (ev))
  1355. return true;
  1356. objc_super s = { self, [NSView class] };
  1357. return objc_msgSendSuper (&s, @selector (performKeyEquivalent:), ev) != nil;
  1358. }
  1359. #endif
  1360. static BOOL becomeFirstResponder (id self, SEL)
  1361. {
  1362. if (NSViewComponentPeer* const owner = getOwner (self))
  1363. owner->viewFocusGain();
  1364. return YES;
  1365. }
  1366. static BOOL resignFirstResponder (id self, SEL)
  1367. {
  1368. if (NSViewComponentPeer* const owner = getOwner (self))
  1369. owner->viewFocusLoss();
  1370. return YES;
  1371. }
  1372. static BOOL acceptsFirstResponder (id self, SEL)
  1373. {
  1374. NSViewComponentPeer* const owner = getOwner (self);
  1375. return owner != nullptr && owner->canBecomeKeyWindow();
  1376. }
  1377. //==============================================================================
  1378. static NSDragOperation draggingEntered (id self, SEL s, id <NSDraggingInfo> sender)
  1379. {
  1380. return draggingUpdated (self, s, sender);
  1381. }
  1382. static NSDragOperation draggingUpdated (id self, SEL, id <NSDraggingInfo> sender)
  1383. {
  1384. if (NSViewComponentPeer* const owner = getOwner (self))
  1385. if (owner->sendDragCallback (0, sender))
  1386. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  1387. return NSDragOperationNone;
  1388. }
  1389. static void draggingEnded (id self, SEL s, id <NSDraggingInfo> sender)
  1390. {
  1391. draggingExited (self, s, sender);
  1392. }
  1393. static void draggingExited (id self, SEL, id <NSDraggingInfo> sender)
  1394. {
  1395. if (NSViewComponentPeer* const owner = getOwner (self))
  1396. owner->sendDragCallback (1, sender);
  1397. }
  1398. static BOOL prepareForDragOperation (id, SEL, id <NSDraggingInfo>)
  1399. {
  1400. return YES;
  1401. }
  1402. static BOOL performDragOperation (id self, SEL, id <NSDraggingInfo> sender)
  1403. {
  1404. NSViewComponentPeer* const owner = getOwner (self);
  1405. return owner != nullptr && owner->sendDragCallback (2, sender);
  1406. }
  1407. static void concludeDragOperation (id, SEL, id <NSDraggingInfo>) {}
  1408. };
  1409. //==============================================================================
  1410. struct JuceNSWindowClass : public ObjCClass<NSWindow>
  1411. {
  1412. JuceNSWindowClass() : ObjCClass<NSWindow> ("JUCEWindow_")
  1413. {
  1414. addIvar<NSViewComponentPeer*> ("owner");
  1415. addMethod (@selector (canBecomeKeyWindow), canBecomeKeyWindow, "c@:");
  1416. addMethod (@selector (becomeKeyWindow), becomeKeyWindow, "v@:");
  1417. addMethod (@selector (windowShouldClose:), windowShouldClose, "c@:@");
  1418. addMethod (@selector (constrainFrameRect:toScreen:), constrainFrameRect, @encode (NSRect), "@:", @encode (NSRect), "@");
  1419. addMethod (@selector (windowWillResize:toSize:), windowWillResize, @encode (NSSize), "@:@", @encode (NSSize));
  1420. addMethod (@selector (windowDidExitFullScreen:), windowDidExitFullScreen, "v@:@");
  1421. addMethod (@selector (zoom:), zoom, "v@:@");
  1422. addMethod (@selector (windowWillMove:), windowWillMove, "v@:@");
  1423. addMethod (@selector (windowWillStartLiveResize:), windowWillStartLiveResize, "v@:@");
  1424. addMethod (@selector (windowDidEndLiveResize:), windowDidEndLiveResize, "v@:@");
  1425. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1426. addProtocol (@protocol (NSWindowDelegate));
  1427. #endif
  1428. registerClass();
  1429. }
  1430. private:
  1431. static NSViewComponentPeer* getOwner (id self)
  1432. {
  1433. return getIvar<NSViewComponentPeer*> (self, "owner");
  1434. }
  1435. //==============================================================================
  1436. static BOOL canBecomeKeyWindow (id self, SEL)
  1437. {
  1438. NSViewComponentPeer* const owner = getOwner (self);
  1439. return owner != nullptr
  1440. && owner->canBecomeKeyWindow()
  1441. && ! owner->sendModalInputAttemptIfBlocked();
  1442. }
  1443. static void becomeKeyWindow (id self, SEL)
  1444. {
  1445. sendSuperclassMessage (self, @selector (becomeKeyWindow));
  1446. if (NSViewComponentPeer* const owner = getOwner (self))
  1447. owner->becomeKeyWindow();
  1448. }
  1449. static BOOL windowShouldClose (id self, SEL, id /*window*/)
  1450. {
  1451. NSViewComponentPeer* const owner = getOwner (self);
  1452. return owner == nullptr || owner->windowShouldClose();
  1453. }
  1454. static NSRect constrainFrameRect (id self, SEL, NSRect frameRect, NSScreen*)
  1455. {
  1456. if (NSViewComponentPeer* const owner = getOwner (self))
  1457. frameRect = owner->constrainRect (frameRect);
  1458. return frameRect;
  1459. }
  1460. static NSSize windowWillResize (id self, SEL, NSWindow*, NSSize proposedFrameSize)
  1461. {
  1462. NSViewComponentPeer* const owner = getOwner (self);
  1463. if (owner == nullptr || owner->isZooming)
  1464. return proposedFrameSize;
  1465. NSRect frameRect = [(NSWindow*) self frame];
  1466. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  1467. frameRect.size = proposedFrameSize;
  1468. frameRect = owner->constrainRect (frameRect);
  1469. if (owner->hasNativeTitleBar())
  1470. owner->sendModalInputAttemptIfBlocked();
  1471. return frameRect.size;
  1472. }
  1473. static void windowDidExitFullScreen (id, SEL, NSNotification*)
  1474. {
  1475. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1476. }
  1477. static void zoom (id self, SEL, id sender)
  1478. {
  1479. if (NSViewComponentPeer* const owner = getOwner (self))
  1480. {
  1481. owner->isZooming = true;
  1482. objc_super s = { self, [NSWindow class] };
  1483. objc_msgSendSuper (&s, @selector (zoom:), sender);
  1484. owner->isZooming = false;
  1485. owner->redirectMovedOrResized();
  1486. }
  1487. }
  1488. static void windowWillMove (id self, SEL, NSNotification*)
  1489. {
  1490. if (NSViewComponentPeer* const owner = getOwner (self))
  1491. if (owner->hasNativeTitleBar())
  1492. owner->sendModalInputAttemptIfBlocked();
  1493. }
  1494. static void windowWillStartLiveResize (id self, SEL, NSNotification*)
  1495. {
  1496. if (NSViewComponentPeer* const owner = getOwner (self))
  1497. owner->liveResizingStart();
  1498. }
  1499. static void windowDidEndLiveResize (id self, SEL, NSNotification*)
  1500. {
  1501. if (NSViewComponentPeer* const owner = getOwner (self))
  1502. owner->liveResizingEnd();
  1503. }
  1504. };
  1505. NSView* NSViewComponentPeer::createViewInstance()
  1506. {
  1507. static JuceNSViewClass cls;
  1508. return cls.createInstance();
  1509. }
  1510. NSWindow* NSViewComponentPeer::createWindowInstance()
  1511. {
  1512. static JuceNSWindowClass cls;
  1513. return cls.createInstance();
  1514. }
  1515. //==============================================================================
  1516. ModifierKeys NSViewComponentPeer::currentModifiers;
  1517. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = nullptr;
  1518. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  1519. //==============================================================================
  1520. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  1521. {
  1522. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  1523. return true;
  1524. if (keyCode >= 'A' && keyCode <= 'Z'
  1525. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  1526. return true;
  1527. if (keyCode >= 'a' && keyCode <= 'z'
  1528. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  1529. return true;
  1530. return false;
  1531. }
  1532. ModifierKeys ModifierKeys::getCurrentModifiersRealtime() noexcept
  1533. {
  1534. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  1535. if ([NSEvent respondsToSelector: @selector (modifierFlags)])
  1536. NSViewComponentPeer::updateModifiers ((NSUInteger) [NSEvent modifierFlags]);
  1537. #endif
  1538. return NSViewComponentPeer::currentModifiers;
  1539. }
  1540. void ModifierKeys::updateCurrentModifiers() noexcept
  1541. {
  1542. currentModifiers = NSViewComponentPeer::currentModifiers;
  1543. }
  1544. //==============================================================================
  1545. bool MouseInputSource::SourceList::addSource()
  1546. {
  1547. if (sources.size() == 0)
  1548. {
  1549. addSource (0, true);
  1550. return true;
  1551. }
  1552. return false;
  1553. }
  1554. //==============================================================================
  1555. void Desktop::setKioskComponent (Component* kioskComp, bool shouldBeEnabled, bool allowMenusAndBars)
  1556. {
  1557. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  1558. NSViewComponentPeer* const peer = dynamic_cast<NSViewComponentPeer*> (kioskComp->getPeer());
  1559. jassert (peer != nullptr); // (this should have been checked by the caller)
  1560. #if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
  1561. if (peer->hasNativeTitleBar()
  1562. && [peer->window respondsToSelector: @selector (toggleFullScreen:)])
  1563. {
  1564. if (shouldBeEnabled && ! allowMenusAndBars)
  1565. [NSApp setPresentationOptions: NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
  1566. [peer->window performSelector: @selector (toggleFullScreen:) withObject: nil];
  1567. }
  1568. else
  1569. #endif
  1570. {
  1571. if (shouldBeEnabled)
  1572. {
  1573. if (peer->hasNativeTitleBar())
  1574. [peer->window setStyleMask: NSBorderlessWindowMask];
  1575. [NSApp setPresentationOptions: (allowMenusAndBars ? (NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)
  1576. : (NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar))];
  1577. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1578. peer->becomeKeyWindow();
  1579. }
  1580. else
  1581. {
  1582. if (peer->hasNativeTitleBar())
  1583. {
  1584. [peer->window setStyleMask: (NSViewComponentPeer::getNSWindowStyleMask (peer->getStyleFlags()))];
  1585. peer->setTitle (peer->getComponent().getName()); // required to force the OS to update the title
  1586. }
  1587. [NSApp setPresentationOptions: NSApplicationPresentationDefault];
  1588. }
  1589. }
  1590. #elif JUCE_SUPPORT_CARBON
  1591. if (shouldBeEnabled)
  1592. {
  1593. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  1594. kioskComp->setBounds (Desktop::getInstance().getDisplays().getMainDisplay().totalArea);
  1595. }
  1596. else
  1597. {
  1598. SetSystemUIMode (kUIModeNormal, 0);
  1599. }
  1600. #else
  1601. (void) kioskComp; (void) shouldBeEnabled; (void) allowMenusAndBars;
  1602. // If you're targeting OSes earlier than 10.6 and want to use this feature,
  1603. // you'll need to enable JUCE_SUPPORT_CARBON.
  1604. jassertfalse;
  1605. #endif
  1606. }
  1607. //==============================================================================
  1608. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1609. {
  1610. return new NSViewComponentPeer (*this, styleFlags, (NSView*) windowToAttachTo);
  1611. }
  1612. //==============================================================================
  1613. const int KeyPress::spaceKey = ' ';
  1614. const int KeyPress::returnKey = 0x0d;
  1615. const int KeyPress::escapeKey = 0x1b;
  1616. const int KeyPress::backspaceKey = 0x7f;
  1617. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  1618. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  1619. const int KeyPress::upKey = NSUpArrowFunctionKey;
  1620. const int KeyPress::downKey = NSDownArrowFunctionKey;
  1621. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  1622. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  1623. const int KeyPress::endKey = NSEndFunctionKey;
  1624. const int KeyPress::homeKey = NSHomeFunctionKey;
  1625. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  1626. const int KeyPress::insertKey = -1;
  1627. const int KeyPress::tabKey = 9;
  1628. const int KeyPress::F1Key = NSF1FunctionKey;
  1629. const int KeyPress::F2Key = NSF2FunctionKey;
  1630. const int KeyPress::F3Key = NSF3FunctionKey;
  1631. const int KeyPress::F4Key = NSF4FunctionKey;
  1632. const int KeyPress::F5Key = NSF5FunctionKey;
  1633. const int KeyPress::F6Key = NSF6FunctionKey;
  1634. const int KeyPress::F7Key = NSF7FunctionKey;
  1635. const int KeyPress::F8Key = NSF8FunctionKey;
  1636. const int KeyPress::F9Key = NSF9FunctionKey;
  1637. const int KeyPress::F10Key = NSF10FunctionKey;
  1638. const int KeyPress::F11Key = NSF1FunctionKey;
  1639. const int KeyPress::F12Key = NSF12FunctionKey;
  1640. const int KeyPress::F13Key = NSF13FunctionKey;
  1641. const int KeyPress::F14Key = NSF14FunctionKey;
  1642. const int KeyPress::F15Key = NSF15FunctionKey;
  1643. const int KeyPress::F16Key = NSF16FunctionKey;
  1644. const int KeyPress::numberPad0 = 0x30020;
  1645. const int KeyPress::numberPad1 = 0x30021;
  1646. const int KeyPress::numberPad2 = 0x30022;
  1647. const int KeyPress::numberPad3 = 0x30023;
  1648. const int KeyPress::numberPad4 = 0x30024;
  1649. const int KeyPress::numberPad5 = 0x30025;
  1650. const int KeyPress::numberPad6 = 0x30026;
  1651. const int KeyPress::numberPad7 = 0x30027;
  1652. const int KeyPress::numberPad8 = 0x30028;
  1653. const int KeyPress::numberPad9 = 0x30029;
  1654. const int KeyPress::numberPadAdd = 0x3002a;
  1655. const int KeyPress::numberPadSubtract = 0x3002b;
  1656. const int KeyPress::numberPadMultiply = 0x3002c;
  1657. const int KeyPress::numberPadDivide = 0x3002d;
  1658. const int KeyPress::numberPadSeparator = 0x3002e;
  1659. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  1660. const int KeyPress::numberPadEquals = 0x30030;
  1661. const int KeyPress::numberPadDelete = 0x30031;
  1662. const int KeyPress::playKey = 0x30000;
  1663. const int KeyPress::stopKey = 0x30001;
  1664. const int KeyPress::fastForwardKey = 0x30002;
  1665. const int KeyPress::rewindKey = 0x30003;