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

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