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

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