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

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