-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
juce_mac_NSViewComponentPeer.mm
2163 lines (1794 loc) · 81.9 KB
/
juce_mac_NSViewComponentPeer.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
typedef void (*AppFocusChangeCallback)();
extern AppFocusChangeCallback appFocusChangeCallback;
typedef bool (*CheckEventBlockedByModalComps) (NSEvent*);
extern CheckEventBlockedByModalComps isEventBlockedByModalComps;
//==============================================================================
#if ! (defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
} // (juce namespace)
@interface NSEvent (JuceDeviceDelta)
- (CGFloat) scrollingDeltaX;
- (CGFloat) scrollingDeltaY;
- (BOOL) hasPreciseScrollingDeltas;
- (BOOL) isDirectionInvertedFromDevice;
@end
namespace juce {
#endif
//==============================================================================
static CGFloat getMainScreenHeight() noexcept
{
return [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
}
static void flipScreenRect (NSRect& r) noexcept
{
r.origin.y = getMainScreenHeight() - (r.origin.y + r.size.height);
}
static NSRect flippedScreenRect (NSRect r) noexcept
{
flipScreenRect (r);
return r;
}
#if JUCE_MODULE_AVAILABLE_juce_opengl
void componentPeerAboutToBeRemovedFromScreen (ComponentPeer&);
#endif
//==============================================================================
class NSViewComponentPeer : public ComponentPeer,
private AsyncUpdater
{
public:
NSViewComponentPeer (Component& comp, const int windowStyleFlags, NSView* viewToAttachTo)
: ComponentPeer (comp, windowStyleFlags),
window (nil),
view (nil),
isSharedWindow (viewToAttachTo != nil),
fullScreen (false),
#if USE_COREGRAPHICS_RENDERING
usingCoreGraphics (true),
#else
usingCoreGraphics (false),
#endif
isZooming (false),
isFirstLiveResize (false),
textWasInserted (false),
isStretchingTop (false), isStretchingLeft (false),
isStretchingBottom (false), isStretchingRight (false),
notificationCenter (nil)
{
appFocusChangeCallback = appFocusChanged;
isEventBlockedByModalComps = checkEventBlockedByModalComps;
NSRect r = makeNSRect (component.getLocalBounds());
view = [createViewInstance() initWithFrame: r];
setOwner (view, this);
[view registerForDraggedTypes: getSupportedDragTypes()];
notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver: view
selector: @selector (frameChanged:)
name: NSViewFrameDidChangeNotification
object: view];
if (! isSharedWindow)
{
[notificationCenter addObserver: view
selector: @selector (frameChanged:)
name: NSWindowDidMoveNotification
object: window];
[notificationCenter addObserver: view
selector: @selector (frameChanged:)
name: NSWindowDidMiniaturizeNotification
object: window];
[notificationCenter addObserver: view
selector: @selector (frameChanged:)
name: NSWindowDidDeminiaturizeNotification
object: window];
}
[view setPostsFrameChangedNotifications: YES];
if (isSharedWindow)
{
window = [viewToAttachTo window];
[viewToAttachTo addSubview: view];
}
else
{
r.origin.x = (CGFloat) component.getX();
r.origin.y = (CGFloat) component.getY();
flipScreenRect (r);
window = [createWindowInstance() initWithContentRect: r
styleMask: getNSWindowStyleMask (windowStyleFlags)
backing: NSBackingStoreBuffered
defer: YES];
setOwner (window, this);
[window orderOut: nil];
#if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
[window setDelegate: (id<NSWindowDelegate>) window];
#else
[window setDelegate: window];
#endif
[window setOpaque: component.isOpaque()];
[window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
if (component.isAlwaysOnTop())
setAlwaysOnTop (true);
[window setContentView: view];
[window setAutodisplay: YES];
[window setAcceptsMouseMovedEvents: YES];
// We'll both retain and also release this on closing because plugin hosts can unexpectedly
// close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
[window setReleasedWhenClosed: YES];
[window retain];
[window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
[window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
#if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
if ((windowStyleFlags & (windowHasMaximiseButton | windowHasTitleBar)) == (windowHasMaximiseButton | windowHasTitleBar))
[window setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
if ([window respondsToSelector: @selector (setRestorable:)])
[window setRestorable: NO];
#endif
}
const float alpha = component.getAlpha();
if (alpha < 1.0f)
setAlpha (alpha);
setTitle (component.getName());
}
~NSViewComponentPeer()
{
[notificationCenter removeObserver: view];
setOwner (view, nullptr);
if ([view superview] != nil)
[view removeFromSuperview];
[view release];
if (! isSharedWindow)
{
setOwner (window, nullptr);
[window close];
[window release];
}
}
//==============================================================================
void* getNativeHandle() const override { return view; }
void setVisible (bool shouldBeVisible) override
{
if (isSharedWindow)
{
[view setHidden: ! shouldBeVisible];
}
else
{
if (shouldBeVisible)
{
++insideToFrontCall;
[window orderFront: nil];
--insideToFrontCall;
handleBroughtToFront();
}
else
{
[window orderOut: nil];
}
}
}
void setTitle (const String& title) override
{
JUCE_AUTORELEASEPOOL
{
if (! isSharedWindow)
[window setTitle: juceStringToNS (title)];
}
}
bool setDocumentEditedStatus (bool edited) override
{
if (! hasNativeTitleBar())
return false;
[window setDocumentEdited: edited];
return true;
}
void setRepresentedFile (const File& file) override
{
if (! isSharedWindow)
[window setRepresentedFilename: juceStringToNS (file != File::nonexistent
? file.getFullPathName()
: String::empty)];
}
void setBounds (const Rectangle<int>& newBounds, bool isNowFullScreen) override
{
fullScreen = isNowFullScreen;
NSRect r = makeNSRect (newBounds);
NSSize oldViewSize = [view frame].size;
if (isSharedWindow)
{
r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
[view setFrame: r];
}
else
{
// Repaint behaviour of setFrame seemed to change in 10.11, and the drawing became synchronous,
// causing performance issues. But sending an async update causes flickering in older versions,
// hence this version check to use the old behaviour on pre 10.11 machines
static bool isPre10_11 = SystemStats::getOperatingSystemType() <= SystemStats::MacOSX_10_10;
[window setFrame: [window frameRectForContentRect: flippedScreenRect (r)]
display: isPre10_11];
}
if (oldViewSize.width != r.size.width || oldViewSize.height != r.size.height)
[view setNeedsDisplay: true];
}
Rectangle<int> getBounds (const bool global) const
{
NSRect r = [view frame];
NSWindow* viewWindow = [view window];
if (global && viewWindow != nil)
{
r = [[view superview] convertRect: r toView: nil];
#if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
r = [viewWindow convertRectToScreen: r];
#else
r.origin = [viewWindow convertBaseToScreen: r.origin];
#endif
flipScreenRect (r);
}
else
{
r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
}
return convertToRectInt (r);
}
Rectangle<int> getBounds() const override
{
return getBounds (! isSharedWindow);
}
Point<float> localToGlobal (Point<float> relativePosition) override
{
return relativePosition + getBounds (true).getPosition().toFloat();
}
Point<float> globalToLocal (Point<float> screenPosition) override
{
return screenPosition - getBounds (true).getPosition().toFloat();
}
void setAlpha (float newAlpha) override
{
if (isSharedWindow)
[view setAlphaValue: (CGFloat) newAlpha];
else
[window setAlphaValue: (CGFloat) newAlpha];
}
void setMinimised (bool shouldBeMinimised) override
{
if (! isSharedWindow)
{
if (shouldBeMinimised)
[window miniaturize: nil];
else
[window deminiaturize: nil];
}
}
bool isMinimised() const override
{
return [window isMiniaturized];
}
void setFullScreen (bool shouldBeFullScreen) override
{
if (! isSharedWindow)
{
Rectangle<int> r (lastNonFullscreenBounds);
if (isMinimised())
setMinimised (false);
if (fullScreen != shouldBeFullScreen)
{
if (shouldBeFullScreen && hasNativeTitleBar())
{
fullScreen = true;
[window performZoom: nil];
}
else
{
if (shouldBeFullScreen)
r = component.getParentMonitorArea();
// (can't call the component's setBounds method because that'll reset our fullscreen flag)
if (r != component.getBounds() && ! r.isEmpty())
setBounds (ScalingHelpers::scaledScreenPosToUnscaled (component, r), shouldBeFullScreen);
}
}
}
}
bool isFullScreen() const override
{
return fullScreen;
}
bool isKioskMode() const override
{
#if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
if (hasNativeTitleBar() && ([window styleMask] & NSFullScreenWindowMask) != 0)
return true;
#endif
return ComponentPeer::isKioskMode();
}
static bool isWindowAtPoint (NSWindow* w, NSPoint screenPoint)
{
#if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
if ([NSWindow respondsToSelector: @selector (windowNumberAtPoint:belowWindowWithWindowNumber:)])
return [NSWindow windowNumberAtPoint: screenPoint belowWindowWithWindowNumber: 0] == [w windowNumber];
#endif
return true;
}
bool contains (Point<int> localPos, bool trueIfInAChildWindow) const override
{
NSRect viewFrame = [view frame];
if (! (isPositiveAndBelow (localPos.getX(), (int) viewFrame.size.width)
&& isPositiveAndBelow (localPos.getY(), (int) viewFrame.size.height)))
return false;
if (! SystemStats::isRunningInAppExtensionSandbox())
{
if (NSWindow* const viewWindow = [view window])
{
const NSRect windowFrame = [viewWindow frame];
const NSPoint windowPoint = [view convertPoint: NSMakePoint (localPos.x, viewFrame.size.height - localPos.y) toView: nil];
const NSPoint screenPoint = NSMakePoint (windowFrame.origin.x + windowPoint.x,
windowFrame.origin.y + windowPoint.y);
if (! isWindowAtPoint (viewWindow, screenPoint))
return false;
}
}
NSView* v = [view hitTest: NSMakePoint (viewFrame.origin.x + localPos.getX(),
viewFrame.origin.y + viewFrame.size.height - localPos.getY())];
return trueIfInAChildWindow ? (v != nil)
: (v == view);
}
BorderSize<int> getFrameSize() const override
{
BorderSize<int> b;
if (! isSharedWindow)
{
NSRect v = [view convertRect: [view frame] toView: nil];
NSRect w = [window frame];
b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
b.setBottom ((int) v.origin.y);
b.setLeft ((int) v.origin.x);
b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
}
return b;
}
void updateFullscreenStatus()
{
if (hasNativeTitleBar())
{
const Rectangle<int> screen (getFrameSize().subtractedFrom (component.getParentMonitorArea()));
fullScreen = component.getScreenBounds().expanded (2, 2).contains (screen);
}
}
bool hasNativeTitleBar() const
{
return (getStyleFlags() & windowHasTitleBar) != 0;
}
bool setAlwaysOnTop (bool alwaysOnTop) override
{
if (! isSharedWindow)
[window setLevel: alwaysOnTop ? ((getStyleFlags() & windowIsTemporary) != 0 ? NSPopUpMenuWindowLevel
: NSFloatingWindowLevel)
: NSNormalWindowLevel];
return true;
}
void toFront (bool makeActiveWindow) override
{
if (isSharedWindow)
[[view superview] addSubview: view
positioned: NSWindowAbove
relativeTo: nil];
if (window != nil && component.isVisible())
{
++insideToFrontCall;
if (makeActiveWindow)
[window makeKeyAndOrderFront: nil];
else
[window orderFront: nil];
if (insideToFrontCall <= 1)
{
Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
handleBroughtToFront();
}
--insideToFrontCall;
}
}
void toBehind (ComponentPeer* other) override
{
if (NSViewComponentPeer* const otherPeer = dynamic_cast<NSViewComponentPeer*> (other))
{
if (isSharedWindow)
{
[[view superview] addSubview: view
positioned: NSWindowBelow
relativeTo: otherPeer->view];
}
else if (component.isVisible())
{
[window orderWindow: NSWindowBelow
relativeTo: [otherPeer->window windowNumber]];
}
}
else
{
jassertfalse; // wrong type of window?
}
}
void setIcon (const Image&) override
{
// to do..
}
StringArray getAvailableRenderingEngines() override
{
StringArray s ("Software Renderer");
#if USE_COREGRAPHICS_RENDERING
s.add ("CoreGraphics Renderer");
#endif
return s;
}
int getCurrentRenderingEngine() const override
{
return usingCoreGraphics ? 1 : 0;
}
void setCurrentRenderingEngine (int index) override
{
#if USE_COREGRAPHICS_RENDERING
if (usingCoreGraphics != (index > 0))
{
usingCoreGraphics = index > 0;
[view setNeedsDisplay: true];
}
#else
ignoreUnused (index);
#endif
}
void redirectMouseDown (NSEvent* ev)
{
if (! Process::isForegroundProcess())
Process::makeForegroundProcess();
currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
sendMouseEvent (ev);
}
void redirectMouseUp (NSEvent* ev)
{
currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
sendMouseEvent (ev);
showArrowCursorIfNeeded();
}
void redirectMouseDrag (NSEvent* ev)
{
currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
sendMouseEvent (ev);
}
void redirectMouseMove (NSEvent* ev)
{
currentModifiers = currentModifiers.withoutMouseButtons();
NSPoint windowPos = [ev locationInWindow];
#if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
NSPoint screenPos = [[ev window] convertRectToScreen: NSMakeRect (windowPos.x, windowPos.y, 1.0f, 1.0f)].origin;
#else
NSPoint screenPos = [[ev window] convertBaseToScreen: windowPos];
#endif
if (isWindowAtPoint ([ev window], screenPos))
sendMouseEvent (ev);
else
// moved into another window which overlaps this one, so trigger an exit
handleMouseEvent (0, Point<float> (-1.0f, -1.0f), currentModifiers,
getMousePressure (ev), getMouseTime (ev));
showArrowCursorIfNeeded();
}
void redirectMouseEnter (NSEvent* ev)
{
Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
currentModifiers = currentModifiers.withoutMouseButtons();
sendMouseEvent (ev);
}
void redirectMouseExit (NSEvent* ev)
{
currentModifiers = currentModifiers.withoutMouseButtons();
sendMouseEvent (ev);
}
static float checkDeviceDeltaReturnValue (float v) noexcept
{
// (deviceDeltaX can fail and return NaN, so need to sanity-check the result)
v *= 0.5f / 256.0f;
return (v > -1000.0f && v < 1000.0f) ? v : 0.0f;
}
void redirectMouseWheel (NSEvent* ev)
{
updateModifiers (ev);
MouseWheelDetails wheel;
wheel.deltaX = 0;
wheel.deltaY = 0;
wheel.isReversed = false;
wheel.isSmooth = false;
wheel.isInertial = false;
@try
{
#if defined (MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
if ([ev respondsToSelector: @selector (isDirectionInvertedFromDevice)])
wheel.isReversed = [ev isDirectionInvertedFromDevice];
wheel.isInertial = ([ev momentumPhase] != NSEventPhaseNone);
if ([ev respondsToSelector: @selector (hasPreciseScrollingDeltas)])
{
if ([ev hasPreciseScrollingDeltas])
{
const float scale = 0.5f / 256.0f;
wheel.deltaX = scale * (float) [ev scrollingDeltaX];
wheel.deltaY = scale * (float) [ev scrollingDeltaY];
wheel.isSmooth = true;
}
}
else
#endif
if ([ev respondsToSelector: @selector (deviceDeltaX)])
{
wheel.deltaX = checkDeviceDeltaReturnValue ((float) getMsgSendFPRetFn() (ev, @selector (deviceDeltaX)));
wheel.deltaY = checkDeviceDeltaReturnValue ((float) getMsgSendFPRetFn() (ev, @selector (deviceDeltaY)));
}
}
@catch (...)
{}
if (wheel.deltaX == 0 && wheel.deltaY == 0)
{
const float scale = 10.0f / 256.0f;
wheel.deltaX = scale * (float) [ev deltaX];
wheel.deltaY = scale * (float) [ev deltaY];
}
handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), wheel);
}
void redirectMagnify (NSEvent* ev)
{
#if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
const float invScale = 1.0f - (float) [ev magnification];
if (invScale > 0.0f)
handleMagnifyGesture (0, getMousePos (ev, view), getMouseTime (ev), 1.0f / invScale);
#endif
ignoreUnused (ev);
}
void redirectCopy (NSObject*) { handleKeyPress (KeyPress ('c', ModifierKeys (ModifierKeys::commandModifier), 'c')); }
void redirectPaste (NSObject*) { handleKeyPress (KeyPress ('v', ModifierKeys (ModifierKeys::commandModifier), 'v')); }
void redirectCut (NSObject*) { handleKeyPress (KeyPress ('x', ModifierKeys (ModifierKeys::commandModifier), 'x')); }
void redirectWillMoveToWindow (NSWindow* newWindow)
{
#if JUCE_MODULE_AVAILABLE_juce_opengl
if ([view window] == window && newWindow == nullptr)
componentPeerAboutToBeRemovedFromScreen (*this);
#else
ignoreUnused (newWindow);
#endif
}
void sendMouseEvent (NSEvent* ev)
{
updateModifiers (ev);
handleMouseEvent (0, getMousePos (ev, view), currentModifiers,
getMousePressure (ev), getMouseTime (ev));
}
bool handleKeyEvent (NSEvent* ev, bool isKeyDown)
{
const String unicode (nsStringToJuce ([ev characters]));
const int keyCode = getKeyCodeFromEvent (ev);
#if JUCE_DEBUG_KEYCODES
DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
#endif
if (keyCode != 0 || unicode.isNotEmpty())
{
if (isKeyDown)
{
bool used = false;
for (String::CharPointerType u (unicode.getCharPointer()); ! u.isEmpty();)
{
juce_wchar textCharacter = u.getAndAdvance();
switch (keyCode)
{
case NSLeftArrowFunctionKey:
case NSRightArrowFunctionKey:
case NSUpArrowFunctionKey:
case NSDownArrowFunctionKey:
case NSPageUpFunctionKey:
case NSPageDownFunctionKey:
case NSEndFunctionKey:
case NSHomeFunctionKey:
case NSDeleteFunctionKey:
textCharacter = 0;
break; // (these all seem to generate unwanted garbage unicode strings)
default:
if (([ev modifierFlags] & NSCommandKeyMask) != 0
|| (keyCode >= NSF1FunctionKey && keyCode <= NSF35FunctionKey))
textCharacter = 0;
break;
}
used = handleKeyUpOrDown (true) || used;
used = handleKeyPress (keyCode, textCharacter) || used;
}
return used;
}
if (handleKeyUpOrDown (false))
return true;
}
return false;
}
bool redirectKeyDown (NSEvent* ev)
{
// (need to retain this in case a modal loop runs in handleKeyEvent and
// our event object gets lost)
const NSObjectRetainer<NSEvent> r (ev);
updateKeysDown (ev, true);
bool used = handleKeyEvent (ev, true);
if (([ev modifierFlags] & NSCommandKeyMask) != 0)
{
// for command keys, the key-up event is thrown away, so simulate one..
updateKeysDown (ev, false);
used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
}
// (If we're running modally, don't allow unused keystrokes to be passed
// along to other blocked views..)
if (Component::getCurrentlyModalComponent() != nullptr)
used = true;
return used;
}
bool redirectKeyUp (NSEvent* ev)
{
updateKeysDown (ev, false);
return handleKeyEvent (ev, false)
|| Component::getCurrentlyModalComponent() != nullptr;
}
void redirectModKeyChange (NSEvent* ev)
{
// (need to retain this in case a modal loop runs and our event object gets lost)
const NSObjectRetainer<NSEvent> r (ev);
keysCurrentlyDown.clear();
handleKeyUpOrDown (true);
updateModifiers (ev);
handleModifierKeysChange();
}
//==============================================================================
void drawRect (NSRect r)
{
if (r.size.width < 1.0f || r.size.height < 1.0f)
return;
CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
if (! component.isOpaque())
CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
float displayScale = 1.0f;
#if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
NSScreen* screen = [[view window] screen];
if ([screen respondsToSelector: @selector (backingScaleFactor)])
displayScale = (float) screen.backingScaleFactor;
#endif
#if USE_COREGRAPHICS_RENDERING && JUCE_COREGRAPHICS_RENDER_WITH_MULTIPLE_PAINT_CALLS
// This option invokes a separate paint call for each rectangle of the clip region.
// It's a long story, but this is a basically a workaround for a CGContext not having
// a way of finding whether a rectangle falls within its clip region
if (usingCoreGraphics)
{
const NSRect* rects = nullptr;
NSInteger numRects = 0;
[view getRectsBeingDrawn: &rects count: &numRects];
if (numRects > 1)
{
for (int i = 0; i < numRects; ++i)
{
NSRect rect = rects[i];
CGContextSaveGState (cg);
CGContextClipToRect (cg, CGRectMake (rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));
drawRect (cg, rect, displayScale);
CGContextRestoreGState (cg);
}
return;
}
}
#endif
drawRect (cg, r, displayScale);
}
void drawRect (CGContextRef cg, NSRect r, float displayScale)
{
#if USE_COREGRAPHICS_RENDERING
if (usingCoreGraphics)
{
CoreGraphicsContext context (cg, (float) [view frame].size.height, displayScale);
invokePaint (context);
}
else
#endif
{
const Point<int> offset (-roundToInt (r.origin.x),
-roundToInt ([view frame].size.height - (r.origin.y + r.size.height)));
const int clipW = (int) (r.size.width + 0.5f);
const int clipH = (int) (r.size.height + 0.5f);
RectangleList<int> clip;
getClipRects (clip, offset, clipW, clipH);
if (! clip.isEmpty())
{
Image temp (component.isOpaque() ? Image::RGB : Image::ARGB,
roundToInt (clipW * displayScale),
roundToInt (clipH * displayScale),
! component.isOpaque());
{
const int intScale = roundToInt (displayScale);
if (intScale != 1)
clip.scaleAll (intScale);
ScopedPointer<LowLevelGraphicsContext> context (component.getLookAndFeel()
.createGraphicsContext (temp, offset * intScale, clip));
if (intScale != 1)
context->addTransform (AffineTransform::scale (displayScale));
invokePaint (*context);
}
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef image = juce_createCoreGraphicsImage (temp, colourSpace, false);
CGColorSpaceRelease (colourSpace);
CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, clipW, clipH), image);
CGImageRelease (image);
}
}
}
void handleAsyncUpdate() override
{
#if JucePlugin_Build_AAX || JucePlugin_Build_RTAS || JucePlugin_Build_AUv3 || JucePlugin_Build_AU || JucePlugin_Build_VST3 || JucePlugin_Build_VST
const bool shouldThrottle = true;
#else
const bool shouldThrottle = areAnyWindowsInLiveResize();
#endif
// When windows are being resized, artificially throttling high-frequency repaints helps
// to stop the event queue getting clogged, and keeps everything working smoothly.
// For some reason Logic also needs this throttling to recored parameter events correctly.
if (shouldThrottle
&& Time::getCurrentTime() < lastRepaintTime + RelativeTime::milliseconds (1000 / 30))
{
triggerAsyncUpdate();
return;
}
for (const Rectangle<float>* i = deferredRepaints.begin(), *e = deferredRepaints.end(); i != e; ++i)
[view setNeedsDisplayInRect: makeNSRect (*i)];
deferredRepaints.clear();
}
void repaint (const Rectangle<int>& area) override
{
// In 10.11 changes were made to the way the OS handles repaint regions, and it seems that it can
// no longer be trusted to coalesce all the regions, or to even remember them all without losing
// a few when there's a lot of activity.
// As a work around for this, we use a RectangleList to do our own coalescing of regions before
// asynchronously asking the OS to repaint them.
deferredRepaints.add ((float) area.getX(), (float) ([view frame].size.height - area.getBottom()),
(float) area.getWidth(), (float) area.getHeight());
triggerAsyncUpdate();
}
void invokePaint (LowLevelGraphicsContext& context)
{
lastRepaintTime = Time::getCurrentTime();
handlePaint (context);
}
void performAnyPendingRepaintsNow() override
{
[view displayIfNeeded];
}
static bool areAnyWindowsInLiveResize() noexcept
{
for (NSWindow* w in [NSApp windows])
if ([w inLiveResize])
return true;
return false;
}
//==============================================================================
bool sendModalInputAttemptIfBlocked()
{
if (Component* modal = Component::getCurrentlyModalComponent())
{
if (insideToFrontCall == 0
&& (! getComponent().isParentOf (modal))
&& getComponent().isCurrentlyBlockedByAnotherModalComponent())
{
modal->inputAttemptWhenModal();
return true;
}
}
return false;
}
bool canBecomeKeyWindow()
{
return (getStyleFlags() & juce::ComponentPeer::windowIgnoresKeyPresses) == 0;
}
bool canBecomeMainWindow()
{
return dynamic_cast<ResizableWindow*> (&component) != nullptr;
}
bool worksWhenModal() const
{
// In plugins, the host could put our plugin window inside a modal window, so this
// allows us to successfully open other popups. Feels like there could be edge-case
// problems caused by this, so let us know if you spot any issues..
return ! JUCEApplication::isStandaloneApp();
}
void becomeKeyWindow()
{
handleBroughtToFront();
grabFocus();
}
bool windowShouldClose()
{
if (! isValidPeer (this))
return YES;
handleUserClosingWindow();
return NO;
}
void redirectMovedOrResized()
{
updateFullscreenStatus();