juce_mac_NSViewComponentPeer.mm 75 KB

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