{{ message }}
Repository navigation
Expand file tree
/
Copy path_macosx.m
More file actions
executable file
·2026 lines (1797 loc) · 66.2 KB
/
Copy path_macosx.m
File metadata and controls
executable file
·2026 lines (1797 loc) · 66.2 KB
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
#define PY_SSIZE_T_CLEAN
#include <Cocoa/Cocoa.h>
#include <ApplicationServices/ApplicationServices.h>
#include <Python.h>
#if !__has_feature(objc_arc_fields)
#error "The macOS backend requires ARC C struct fields support (objc_arc_fields)."
#endif
/* Various NSApplicationDefined event subtypes */
#define STOP_EVENT_LOOP 2
/* When calling into Objective-C from Python, wrap the calls with
BEGIN_OBJC_ENTRY and END_OBJC_ENTRY. This will set up an autorelease
pool as well as catch any Obj-C exceptions thrown. These macros
should be used for any call exposed to Python via the external module
interface.
To avoid undefined behavior, each END_OBJC_ENTRY should be followed
by a return statement which handles the rare case when an Objective-C
exception was thrown.
As a convenience, the RETURN_NULL_OR_NONE macro can be used for functions
that return a PyObject* */
#define BEGIN_OBJC_ENTRY \
@autoreleasepool { @try {
#define END_OBJC_ENTRY \
} @catch (NSException *e) { errSetException(e); } }
#define RETURN_NULL_OR_NONE \
if (PyErr_Occurred()) { \
return NULL; \
} else { \
Py_RETURN_NONE; \
}
/* Variable for our delegate since it needs a +1 reference count. */
static id<NSApplicationDelegate> appDelegate = nil;
/* Variables to keep track of state and window count for show() */
static BOOL IsRunningFromShow = NO;
static NSHashTable<NSWindow *> *FigureWindowHashTable = nil;
/* Keep track of modifier key states for flagsChanged
to keep track of press vs release */
static bool lastCommand = false;
static bool lastControl = false;
static bool lastShift = false;
static bool lastOption = false;
static bool lastCapsLock = false;
/* Keep track of whether this specific key modifier was pressed or not */
static bool keyChangeCommand = false;
static bool keyChangeControl = false;
static bool keyChangeShift = false;
static bool keyChangeOption = false;
static bool keyChangeCapsLock = false;
/* Keep track of the current mouse up/down state for open/closed cursor hand */
static bool leftMouseGrabbing = false;
// Global variable to store the original SIGINT handler
static PyOS_sighandler_t originalSigintAction = NULL;
// Convert an Objective-C exception into a Python RuntimeError
static void errSetException(NSException *exception) {
PyErr_SetString(PyExc_RuntimeError, [[exception reason] UTF8String]);
}
// Stop the current app's run loop, sending an event to ensure it actually stops
static void stopWithEvent() {
[NSApp stop: nil];
// Post an event to trigger the actual stopping.
// +[NSEvent otherEventWithType:...] is declared nullable but will not return
// nil for these constant, valid arguments; guard defensively anyway.
NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
location: NSZeroPoint
modifierFlags: 0
timestamp: 0
windowNumber: 0
context: nil
subtype: 0
data1: 0
data2: 0];
if (event) {
[NSApp postEvent: event atStart: YES];
}
}
// Signal handler for SIGINT, only argument matching for stopWithEvent
static void handleSigint(int signal) {
stopWithEvent();
}
// Helper function to flush all events.
// This is needed in some instances to ensure e.g. that windows are properly closed.
// It is used in the input hook as well as wrapped in a version callable from Python.
static void flushEvents() {
while (true) {
@autoreleasepool {
NSEvent* event = [NSApp nextEventMatchingMask: NSEventMaskAny
untilDate: [NSDate distantPast]
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (!event) {
break;
}
[NSApp sendEvent:event];
}
}
}
static int wait_for_stdin() {
BEGIN_OBJC_ENTRY
// Short circuit if no windows are active
// Rely on Python's input handling to manage CPU usage
// This queries the NSApp, rather than using our FigureWindowHashTable because that is modified when events still
// need to be processed to properly close the windows.
@autoreleasepool {
if (![[NSApp windows] count]) {
flushEvents();
return 1;
}
}
// Set up a SIGINT handler to interrupt the event loop if ctrl+c comes in too
originalSigintAction = PyOS_setsig(SIGINT, handleSigint);
// Create an NSFileHandle for standard input
NSFileHandle *stdinHandle = [NSFileHandle fileHandleWithStandardInput];
// Register for data available notifications on standard input
id notificationID = [[NSNotificationCenter defaultCenter] addObserverForName: NSFileHandleDataAvailableNotification
object: stdinHandle
queue: [NSOperationQueue mainQueue] // Use the main queue
usingBlock: ^(NSNotification *notification) {stopWithEvent();}
];
// Wait in the background for anything that happens to stdin
[stdinHandle waitForDataInBackgroundAndNotify];
// Run the application's event loop, which will be interrupted on stdin or SIGINT
[NSApp run];
// Remove the input handler as an observer
[[NSNotificationCenter defaultCenter] removeObserver: notificationID];
// Restore the original SIGINT handler upon exiting the function
PyOS_setsig(SIGINT, originalSigintAction);
return 1;
END_OBJC_ENTRY
return 0;
}
/* ---------------------------- Cocoa classes ---------------------------- */
@interface MatplotlibAppDelegate : NSObject <NSApplicationDelegate>
- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app;
@end
@interface Window : NSWindow
- (NSRect)constrainFrameRect:(NSRect)rect toScreen:(NSScreen*)screen;
@property (nonatomic, assign) PyObject* manager;
@end
@interface View : NSView <NSWindowDelegate>
{ NSRect rubberband;
@public double device_scale;
}
- (void)drawRect:(NSRect)rect;
- (void)updateDevicePixelRatio:(double)scale;
- (void)windowDidChangeBackingProperties:(NSNotification*)notification;
- (void)windowDidResize:(NSNotification*)notification;
- (instancetype)initWithFrame:(NSRect)rect;
- (void)mouseEntered:(NSEvent*)event;
- (void)mouseExited:(NSEvent*)event;
- (void)mouseDown:(NSEvent*)event;
- (void)mouseUp:(NSEvent*)event;
- (void)mouseDragged:(NSEvent*)event;
- (void)mouseMoved:(NSEvent*)event;
- (void)rightMouseDown:(NSEvent*)event;
- (void)rightMouseUp:(NSEvent*)event;
- (void)rightMouseDragged:(NSEvent*)event;
- (void)otherMouseDown:(NSEvent*)event;
- (void)otherMouseUp:(NSEvent*)event;
- (void)otherMouseDragged:(NSEvent*)event;
- (void)setRubberband:(NSRect)rect;
- (void)removeRubberband;
- (NSString*)convertKeyEvent:(NSEvent*)event;
- (void)keyDown:(NSEvent*)event;
- (void)keyUp:(NSEvent*)event;
- (void)scrollWheel:(NSEvent *)event;
- (BOOL)acceptsFirstResponder;
- (void)flagsChanged:(NSEvent*)event;
@property (nonatomic, assign) PyObject* canvas;
@end
/* ---------------------------- Python classes ---------------------------- */
// Acquire the GIL, call a method with no args, discarding the result and
// printing any exception.
static void gil_call_method(PyObject* obj, const char* name)
{
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* result = PyObject_CallMethod(obj, name, NULL);
if (result) {
Py_DECREF(result);
} else {
PyErr_Print();
}
PyGILState_Release(gstate);
}
void process_event(char const* cls_name, char const* fmt, ...)
{
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* module = NULL, * cls = NULL,
* args = NULL, * kwargs = NULL,
* event = NULL, * result = NULL;
va_list argp;
va_start(argp, fmt);
if (!(module = PyImport_ImportModule("matplotlib.backend_bases"))
|| !(cls = PyObject_GetAttrString(module, cls_name))
|| !(args = PyTuple_New(0))
|| !(kwargs = Py_VaBuildValue(fmt, argp))
|| !(event = PyObject_Call(cls, args, kwargs))
|| !(result = PyObject_CallMethod(event, "_process", ""))) {
PyErr_Print();
}
va_end(argp);
Py_XDECREF(module);
Py_XDECREF(cls);
Py_XDECREF(args);
Py_XDECREF(kwargs);
Py_XDECREF(event);
Py_XDECREF(result);
PyGILState_Release(gstate);
}
static bool backend_inited = false;
static void lazy_init(void) {
if (backend_inited) { return; }
backend_inited = true;
NSApp = [NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
appDelegate = [[MatplotlibAppDelegate alloc] init];
[NSApp setDelegate:appDelegate];
// Run our own event loop while waiting for stdin on the Python side
// this is needed to keep the application responsive while waiting for input
PyOS_InputHook = wait_for_stdin;
}
static PyObject*
event_loop_is_running(PyObject* self)
{
BEGIN_OBJC_ENTRY
if (backend_inited) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
wake_on_fd_write(PyObject* unused, PyObject* args)
{
BEGIN_OBJC_ENTRY
int fd;
if (!PyArg_ParseTuple(args, "i", &fd)) { return NULL; }
NSFileHandle* fh = [[NSFileHandle alloc] initWithFileDescriptor: fd];
__block id notificationID = [[NSNotificationCenter defaultCenter]
addObserverForName: NSFileHandleDataAvailableNotification
object: fh
queue: nil
usingBlock: ^(NSNotification* note) {
NSFileHandle* strongFileHandle __attribute__((unused)) = fh;
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_CheckSignals();
PyGILState_Release(gstate);
[[NSNotificationCenter defaultCenter] removeObserver:notificationID];
}];
[fh waitForDataInBackgroundAndNotify];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
stop(PyObject* self, PyObject* _ /* ignored */)
{
BEGIN_OBJC_ENTRY
stopWithEvent();
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static CGFloat _get_device_scale(CGContextRef cr)
{
CGSize pixelSize = CGContextConvertSizeToDeviceSpace(cr, CGSizeMake(1, 1));
return pixelSize.width;
}
bool mpl_check_button(bool present, PyObject* set, char const* name) {
PyObject* module = NULL, * cls = NULL, * button = NULL;
bool failed = (
present
&& (!(module = PyImport_ImportModule("matplotlib.backend_bases"))
|| !(cls = PyObject_GetAttrString(module, "MouseButton"))
|| !(button = PyObject_GetAttrString(cls, name))
|| PySet_Add(set, button)));
Py_XDECREF(module);
Py_XDECREF(cls);
Py_XDECREF(button);
return failed;
}
PyObject* mpl_buttons()
{
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* set = NULL;
NSUInteger buttons = [NSEvent pressedMouseButtons];
if (!(set = PySet_New(NULL))
|| mpl_check_button(buttons & (1 << 0), set, "LEFT")
|| mpl_check_button(buttons & (1 << 1), set, "RIGHT")
|| mpl_check_button(buttons & (1 << 2), set, "MIDDLE")
|| mpl_check_button(buttons & (1 << 3), set, "BACK")
|| mpl_check_button(buttons & (1 << 4), set, "FORWARD")) {
Py_CLEAR(set); // On failure, return NULL with an exception set.
}
PyGILState_Release(gstate);
return set;
}
bool mpl_check_modifier(bool present, PyObject* list, char const* name)
{
PyObject* py_name = NULL;
bool failed = (
present
&& (!(py_name = PyUnicode_FromString(name))
|| (PyList_Append(list, py_name))));
Py_XDECREF(py_name);
return failed;
}
PyObject* mpl_modifiers(NSEvent* event)
{
PyGILState_STATE gstate = PyGILState_Ensure();
PyObject* list = NULL;
NSUInteger modifiers = [event modifierFlags];
if (!(list = PyList_New(0))
|| mpl_check_modifier(modifiers & NSEventModifierFlagControl, list, "ctrl")
|| mpl_check_modifier(modifiers & NSEventModifierFlagOption, list, "alt")
|| mpl_check_modifier(modifiers & NSEventModifierFlagShift, list, "shift")
|| mpl_check_modifier(modifiers & NSEventModifierFlagCommand, list, "cmd")) {
Py_CLEAR(list); // On failure, return NULL with an exception set.
}
PyGILState_Release(gstate);
return list;
}
typedef struct {
PyObject_HEAD
__strong View* view;
} FigureCanvas;
static PyTypeObject FigureCanvasType;
static PyObject*
FigureCanvas_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
BEGIN_OBJC_ENTRY
lazy_init();
FigureCanvas *self = (FigureCanvas*)type->tp_alloc(type, 0);
return (PyObject*)self;
END_OBJC_ENTRY
return NULL;
}
static int
FigureCanvas_init(FigureCanvas *self, PyObject *args, PyObject *kwds)
{
BEGIN_OBJC_ENTRY
View *view;
NSTrackingArea *trackingArea;
PyObject *builtins = NULL,
*super_obj = NULL,
*super_init = NULL,
*init_res = NULL,
*wh = NULL;
// super(FigureCanvasMac, self).__init__(*args, **kwargs)
if (!(builtins = PyImport_AddModule("builtins")) // borrowed.
|| !(super_obj = PyObject_CallMethod(builtins, "super", "OO", &FigureCanvasType, self))
|| !(super_init = PyObject_GetAttrString(super_obj, "__init__"))
|| !(init_res = PyObject_Call(super_init, args, kwds))) {
goto exit;
}
int width, height;
if (!(wh = PyObject_CallMethod((PyObject*)self, "get_width_height", ""))
|| !PyArg_ParseTuple(wh, "ii", &width, &height)) {
goto exit;
}
NSRect rect = NSMakeRect(0.0, 0.0, width, height);
view = [[View alloc] initWithFrame: rect];
view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
int opts = (NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect);
trackingArea = [[NSTrackingArea alloc] initWithRect: rect
options: opts
owner: view
userInfo: nil];
[view addTrackingArea:trackingArea];
[view setCanvas: (PyObject*)self];
self->view = view;
exit:
Py_XDECREF(super_obj);
Py_XDECREF(super_init);
Py_XDECREF(init_res);
Py_XDECREF(wh);
END_OBJC_ENTRY
return PyErr_Occurred() ? -1 : 0;
}
static void
FigureCanvas_dealloc(FigureCanvas* self)
{
BEGIN_OBJC_ENTRY
[self->view setCanvas: NULL];
self->view = nil;
END_OBJC_ENTRY
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject*
FigureCanvas_repr(FigureCanvas* self)
{
return PyUnicode_FromFormat("FigureCanvas object %p wrapping NSView %p",
(void*)self, (__bridge void*)(self->view));
}
static PyObject*
FigureCanvas_update(FigureCanvas* self)
{
BEGIN_OBJC_ENTRY
[self->view setNeedsDisplay: YES];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE;
}
static PyObject*
FigureCanvas_flush_events(FigureCanvas* self)
{
BEGIN_OBJC_ENTRY
// We run the app, matching any events that are waiting in the queue
// to process, breaking out of the loop when no events remain and
// displaying the canvas if needed.
Py_BEGIN_ALLOW_THREADS
flushEvents();
Py_END_ALLOW_THREADS
[self->view displayIfNeeded];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureCanvas_set_cursor(PyObject* unused, PyObject* args)
{
BEGIN_OBJC_ENTRY
int i;
if (!PyArg_ParseTuple(args, "i", &i)) { return NULL; }
switch (i) {
case 1: [[NSCursor arrowCursor] set]; break;
case 2: [[NSCursor pointingHandCursor] set]; break;
case 3: [[NSCursor crosshairCursor] set]; break;
case 4:
if (leftMouseGrabbing) {
[[NSCursor closedHandCursor] set];
} else {
[[NSCursor openHandCursor] set];
}
break;
/* macOS handles busy state itself so no need to set a cursor here */
case 5: break;
case 6: [[NSCursor resizeLeftRightCursor] set]; break;
case 7: [[NSCursor resizeUpDownCursor] set]; break;
default: return NULL;
}
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureCanvas_set_rubberband(FigureCanvas* self, PyObject *args)
{
BEGIN_OBJC_ENTRY
View* view = self->view;
if (!view) {
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return NULL;
}
int x0, y0, x1, y1;
if (!PyArg_ParseTuple(args, "iiii", &x0, &y0, &x1, &y1)) {
return NULL;
}
x0 /= view->device_scale;
x1 /= view->device_scale;
y0 /= view->device_scale;
y1 /= view->device_scale;
NSRect rubberband = NSMakeRect(x0 < x1 ? x0 : x1, y0 < y1 ? y0 : y1,
abs(x1 - x0), abs(y1 - y0));
[view setRubberband: rubberband];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureCanvas_remove_rubberband(FigureCanvas* self)
{
BEGIN_OBJC_ENTRY
[self->view removeRubberband];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureCanvas__start_event_loop(FigureCanvas* self, PyObject* args, PyObject* keywords)
{
BEGIN_OBJC_ENTRY
float timeout = 0.0;
static char* kwlist[] = {"timeout", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywords, "f", kwlist, &timeout)) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS
NSDate* date =
(timeout > 0.0) ? [NSDate dateWithTimeIntervalSinceNow: timeout]
: [NSDate distantFuture];
while (true) {
@autoreleasepool {
NSEvent* event = [NSApp nextEventMatchingMask: NSEventMaskAny
untilDate: date
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (!event || [event type]==NSEventTypeApplicationDefined) { break; }
[NSApp sendEvent: event];
}
}
Py_END_ALLOW_THREADS
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureCanvas_stop_event_loop(FigureCanvas* self)
{
BEGIN_OBJC_ENTRY
// +[NSEvent otherEventWithType:...] is declared nullable but will not return
// nil for these constant, valid arguments; guard defensively anyway.
NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
location: NSZeroPoint
modifierFlags: 0
timestamp: 0.0
windowNumber: 0
context: nil
subtype: STOP_EVENT_LOOP
data1: 0
data2: 0];
if (event) {
[NSApp postEvent: event atStart: true];
}
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyTypeObject FigureCanvasType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "matplotlib.backends._macosx.FigureCanvas",
.tp_doc = PyDoc_STR("A FigureCanvas object wraps a Cocoa NSView object."),
.tp_basicsize = sizeof(FigureCanvas),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_new = (newfunc)FigureCanvas_new,
.tp_init = (initproc)FigureCanvas_init,
.tp_dealloc = (destructor)FigureCanvas_dealloc,
.tp_repr = (reprfunc)FigureCanvas_repr,
.tp_methods = (PyMethodDef[]){
{"update",
(PyCFunction)FigureCanvas_update,
METH_NOARGS,
NULL}, // docstring inherited
{"flush_events",
(PyCFunction)FigureCanvas_flush_events,
METH_NOARGS,
NULL}, // docstring inherited
{"set_cursor",
(PyCFunction)FigureCanvas_set_cursor,
METH_VARARGS,
PyDoc_STR("Set the active cursor.")},
{"set_rubberband",
(PyCFunction)FigureCanvas_set_rubberband,
METH_VARARGS,
PyDoc_STR("Specify a new rubberband rectangle and invalidate it.")},
{"remove_rubberband",
(PyCFunction)FigureCanvas_remove_rubberband,
METH_NOARGS,
PyDoc_STR("Remove the current rubberband rectangle.")},
{"_start_event_loop",
(PyCFunction)FigureCanvas__start_event_loop,
METH_KEYWORDS | METH_VARARGS,
NULL}, // docstring inherited
{"stop_event_loop",
(PyCFunction)FigureCanvas_stop_event_loop,
METH_NOARGS,
NULL}, // docstring inherited
{} // sentinel
},
};
static PyTypeObject FigureManagerType; // forward declaration, needed in destroy()
typedef struct {
PyObject_HEAD
__strong Window* window;
} FigureManager;
static PyObject*
FigureManager_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
BEGIN_OBJC_ENTRY
if (![NSThread isMainThread]) {
PyErr_SetString(
PyExc_RuntimeError,
"Cannot create a GUI FigureManager outside the main thread "
"using the MacOS backend. Use a non-interactive "
"backend like 'agg' to make plots on worker threads."
);
return NULL;
}
lazy_init();
FigureManager *self = (FigureManager*)type->tp_alloc(type, 0);
if (!self) {
return NULL;
}
return (PyObject*)self;
END_OBJC_ENTRY
return NULL;
}
static int
FigureManager_init(FigureManager *self, PyObject *args, PyObject *kwds)
{
BEGIN_OBJC_ENTRY
PyObject* canvas;
if (!PyArg_ParseTuple(args, "O", &canvas)) {
return -1;
}
View* view = ((FigureCanvas*)canvas)->view;
if (!view) { /* Something really weird going on */
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return -1;
}
PyObject* size = PyObject_CallMethod(canvas, "get_width_height", "");
int width, height;
if (!size || !PyArg_ParseTuple(size, "ii", &width, &height)) {
Py_XDECREF(size);
return -1;
}
Py_DECREF(size);
NSRect rect = NSMakeRect( /* x */ 100, /* y */ 350, width, height);
Window* window = [[Window alloc] initWithContentRect: rect
styleMask: NSWindowStyleMaskTitled
| NSWindowStyleMaskClosable
| NSWindowStyleMaskResizable
| NSWindowStyleMaskMiniaturizable
backing: NSBackingStoreBuffered
defer: YES];
[window setDelegate: view];
[window setManager: (PyObject*)self];
[window makeFirstResponder: view];
[window setReleasedWhenClosed:NO];
[[window contentView] addSubview: view];
[view updateDevicePixelRatio: [window backingScaleFactor]];
self->window = window;
if (!FigureWindowHashTable) {
FigureWindowHashTable = [NSHashTable weakObjectsHashTable];
}
[FigureWindowHashTable addObject:window];
END_OBJC_ENTRY
return 0;
}
static PyObject*
FigureManager__set_window_mode(FigureManager* self, PyObject* args)
{
BEGIN_OBJC_ENTRY
const char* window_mode;
if (!PyArg_ParseTuple(args, "s", &window_mode) || !self->window) {
return NULL;
}
NSString* window_mode_str = [NSString stringWithUTF8String: window_mode];
if ([window_mode_str isEqualToString: @"tab"]) {
[self->window setTabbingMode: NSWindowTabbingModePreferred];
} else if ([window_mode_str isEqualToString: @"window"]) {
[self->window setTabbingMode: NSWindowTabbingModeDisallowed];
} else { // system settings
[self->window setTabbingMode: NSWindowTabbingModeAutomatic];
}
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_repr(FigureManager* self)
{
return PyUnicode_FromFormat("FigureManager object %p wrapping NSWindow %p",
(void*) self, (__bridge void*)(self->window));
}
static void
FigureManager__closeAndClearWindow(FigureManager* self)
{
if (self->window) {
[self->window close];
[self->window setDelegate:nil];
[self->window setManager:NULL];
[FigureWindowHashTable removeObject:self->window];
self->window = nil;
if ([FigureWindowHashTable count] == 0 && IsRunningFromShow) {
[NSApp stop:nil];
}
}
}
static void
FigureManager_dealloc(FigureManager* self)
{
BEGIN_OBJC_ENTRY
FigureManager__closeAndClearWindow(self);
END_OBJC_ENTRY
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject*
FigureManager__show(FigureManager* self)
{
BEGIN_OBJC_ENTRY
[self->window makeKeyAndOrderFront: nil];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager__raise(FigureManager* self)
{
BEGIN_OBJC_ENTRY
[self->window orderFrontRegardless];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_destroy(FigureManager* self)
{
BEGIN_OBJC_ENTRY
FigureManager__closeAndClearWindow(self);
// call super(self, FigureManager).destroy() - it seems we need the
// explicit arguments, and just super() doesn't work in the C API.
PyObject *super_obj = PyObject_CallFunctionObjArgs(
(PyObject *)&PySuper_Type,
(PyObject *)&FigureManagerType,
self,
NULL
);
if (super_obj == NULL) {
return NULL; // error
}
PyObject *result = PyObject_CallMethod(super_obj, "destroy", NULL);
Py_DECREF(super_obj);
if (result == NULL) {
return NULL; // error
}
Py_DECREF(result);
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_set_icon(PyObject* null, PyObject* args) {
BEGIN_OBJC_ENTRY
PyObject* icon_path;
if (!PyArg_ParseTuple(args, "O&", &PyUnicode_FSDecoder, &icon_path)) {
return NULL;
}
const char* icon_path_ptr = PyUnicode_AsUTF8(icon_path);
if (!icon_path_ptr) {
Py_DECREF(icon_path);
return NULL;
}
NSString* ns_icon_path = [NSString stringWithUTF8String: icon_path_ptr];
Py_DECREF(icon_path);
if (!ns_icon_path) {
PyErr_SetString(PyExc_RuntimeError, "Could not convert to NSString*");
return NULL;
}
NSImage* image = [[NSImage alloc] initByReferencingFile: ns_icon_path];
if (!image) {
PyErr_SetString(PyExc_RuntimeError, "Could not create NSImage*");
return NULL;
}
if (!image.valid) {
PyErr_SetString(PyExc_RuntimeError, "Image is not valid");
return NULL;
}
NSApplication* app = [NSApplication sharedApplication];
app.applicationIconImage = image;
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_set_window_title(FigureManager* self,
PyObject *args, PyObject *kwds)
{
BEGIN_OBJC_ENTRY
const char* title;
if (!PyArg_ParseTuple(args, "s", &title)) {
return NULL;
}
// PyArg_ParseTuple "s" guarantees valid UTF-8, so stringWithUTF8String: will
// not return nil here; the nullable annotation is a false positive.
// NOLINTNEXTLINE(clang-analyzer-nullability.NullablePassedToNonnull)
[self->window setTitle: [NSString stringWithUTF8String: title]];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_get_window_title(FigureManager* self)
{
BEGIN_OBJC_ENTRY
NSString* title = [self->window title];
if (title) {
return PyUnicode_FromString([title UTF8String]);
}
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_resize(FigureManager* self, PyObject *args, PyObject *kwds)
{
BEGIN_OBJC_ENTRY
int width, height;
if (!PyArg_ParseTuple(args, "ii", &width, &height)) {
return NULL;
}
Window* window = self->window;
if (window) {
CGFloat device_pixel_ratio = [window backingScaleFactor];
width /= device_pixel_ratio;
height /= device_pixel_ratio;
// 36 comes from hard-coded size of toolbar later in code
[window setContentSize: NSMakeSize(width, height + 36.)];
}
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyObject*
FigureManager_full_screen_toggle(FigureManager* self)
{
BEGIN_OBJC_ENTRY
[self->window toggleFullScreen: nil];
END_OBJC_ENTRY
RETURN_NULL_OR_NONE
}
static PyTypeObject FigureManagerType = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "matplotlib.backends._macosx.FigureManager",
.tp_doc = PyDoc_STR("A FigureManager object wraps a Cocoa NSWindow object."),
.tp_basicsize = sizeof(FigureManager),
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_new = (newfunc)FigureManager_new,
.tp_init = (initproc)FigureManager_init,
.tp_dealloc = (destructor)FigureManager_dealloc,
.tp_repr = (reprfunc)FigureManager_repr,
.tp_methods = (PyMethodDef[]){ // All docstrings are inherited.
{"_show",
(PyCFunction)FigureManager__show,
METH_NOARGS},
{"_raise",
(PyCFunction)FigureManager__raise,
METH_NOARGS},
{"destroy",
(PyCFunction)FigureManager_destroy,
METH_NOARGS},
{"_set_window_mode",
(PyCFunction)FigureManager__set_window_mode,
METH_VARARGS,
PyDoc_STR("Set the window open mode (system, tab, window)")},
{"set_icon",
(PyCFunction)FigureManager_set_icon,
METH_STATIC | METH_VARARGS,
PyDoc_STR("Set application icon")},
{"set_window_title",
(PyCFunction)FigureManager_set_window_title,
METH_VARARGS},
{"get_window_title",
(PyCFunction)FigureManager_get_window_title,
METH_NOARGS},
{"resize",
(PyCFunction)FigureManager_resize,
METH_VARARGS},
{"full_screen_toggle",
(PyCFunction)FigureManager_full_screen_toggle,
METH_NOARGS},
{} // sentinel
},
};
@implementation MatplotlibAppDelegate
- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app {
return YES;
}
@end
@interface NavigationToolbar2Handler : NSObject
- (void)installCallbacks:(SEL[7])actions forButtons:(__strong NSButton*[7])buttons;
- (void)home:(id)sender;
- (void)back:(id)sender;
- (void)forward:(id)sender;
- (void)pan:(id)sender;
- (void)zoom:(id)sender;
- (void)configure_subplots:(id)sender;
- (void)save_figure:(id)sender;
@property (nonatomic, assign) PyObject *toolbar;
@property (nonatomic, readonly) NSButton *panButton;
@property (nonatomic, readonly) NSButton *zoomButton;
@end
typedef struct {
PyObject_HEAD
__strong NSTextView* messagebox;
__strong NavigationToolbar2Handler* handler;
int height;
} NavigationToolbar2;
@implementation NavigationToolbar2Handler
- (void)installCallbacks:(SEL[7])actions forButtons:(__strong NSButton*[7])buttons
{
for (int i = 0; i < 7; i++) {
SEL action = actions[i];
NSButton* button = buttons[i];
[button setTarget: self];
[button setAction: action];
if (action == @selector(pan:)) { _panButton = button; }
if (action == @selector(zoom:)) { _zoomButton = button; }
You can’t perform that action at this time.
