-
-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
Copy path_macosx.m
executable file
·1901 lines (1702 loc) · 62.8 KB
/
_macosx.m
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>
/* Proper way to check for the OS X version we are compiling for, from
* https://developer.apple.com/library/archive/documentation/DeveloperTools/Conceptual/cross_development/Using/using.html
* Renamed symbols cause deprecation warnings, so define macros for the new
* names if we are compiling on an older SDK */
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 101400
#define NSButtonTypeMomentaryLight NSMomentaryLightButton
#define NSButtonTypePushOnPushOff NSPushOnPushOffButton
#define NSBezelStyleShadowlessSquare NSShadowlessSquareBezelStyle
#define CGContext graphicsPort
#endif
/* Various NSApplicationDefined event subtypes */
#define STOP_EVENT_LOOP 2
#define WINDOW_CLOSING 3
/* Keep track of number of windows present
Needed to know when to stop the NSApp */
static long FigureWindowCount = 0;
/* 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;
// 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.
[NSApp postEvent: [NSEvent otherEventWithType: NSEventTypeApplicationDefined
location: NSZeroPoint
modifierFlags: 0
timestamp: 0
windowNumber: 0
context: nil
subtype: 0
data1: 0
data2: 0]
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) {
NSEvent* event = [NSApp nextEventMatchingMask: NSEventMaskAny
untilDate: [NSDate distantPast]
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (!event) {
break;
}
[NSApp sendEvent:event];
}
}
static int wait_for_stdin() {
// 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 FigureWindowCount because that is decremented when events still
// need to be processed to properly close the windows.
if (![[NSApp windows] count]) {
flushEvents();
return 1;
}
@autoreleasepool {
// 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;
}
}
/* ---------------------------- Cocoa classes ---------------------------- */
@interface MatplotlibAppDelegate : NSObject <NSApplicationDelegate>
- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app;
@end
@interface Window : NSWindow
{ PyObject* manager;
}
- (Window*)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation withManager: (PyObject*)theManager;
- (NSRect)constrainFrameRect:(NSRect)rect toScreen:(NSScreen*)screen;
- (BOOL)closeButtonPressed;
@end
@interface View : NSView <NSWindowDelegate>
{ PyObject* canvas;
NSRect rubberband;
@public double device_scale;
}
- (void)dealloc;
- (void)drawRect:(NSRect)rect;
- (void)updateDevicePixelRatio:(double)scale;
- (void)windowDidChangeBackingProperties:(NSNotification*)notification;
- (void)windowDidResize:(NSNotification*)notification;
- (View*)initWithFrame:(NSRect)rect;
- (void)setCanvas: (PyObject*)newCanvas;
- (void)windowWillClose:(NSNotification*)notification;
- (BOOL)windowShouldClose:(NSNotification*)notification;
- (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;
- (const char*)convertKeyEvent:(NSEvent*)event;
- (void)keyDown:(NSEvent*)event;
- (void)keyUp:(NSEvent*)event;
- (void)scrollWheel:(NSEvent *)event;
- (BOOL)acceptsFirstResponder;
- (void)flagsChanged:(NSEvent*)event;
@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];
[NSApp setDelegate: [[[MatplotlibAppDelegate alloc] init] autorelease]];
// 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)
{
if (backend_inited) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
}
static PyObject*
wake_on_fd_write(PyObject* unused, PyObject* args)
{
int fd;
if (!PyArg_ParseTuple(args, "i", &fd)) { return NULL; }
NSFileHandle* fh = [[NSFileHandle alloc] initWithFileDescriptor: fd];
[fh waitForDataInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter]
addObserverForName: NSFileHandleDataAvailableNotification
object: fh
queue: nil
usingBlock: ^(NSNotification* note) {
PyGILState_STATE gstate = PyGILState_Ensure();
PyErr_CheckSignals();
PyGILState_Release(gstate);
}];
Py_RETURN_NONE;
}
static PyObject*
stop(PyObject* self)
{
stopWithEvent();
Py_RETURN_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
View* view;
} FigureCanvas;
static PyTypeObject FigureCanvasType;
static PyObject*
FigureCanvas_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
lazy_init();
FigureCanvas *self = (FigureCanvas*)type->tp_alloc(type, 0);
if (!self) { return NULL; }
self->view = [View alloc];
return (PyObject*)self;
}
static int
FigureCanvas_init(FigureCanvas *self, PyObject *args, PyObject *kwds)
{
if (!self->view) {
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return -1;
}
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);
self->view = [self->view initWithFrame: rect];
self->view.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
int opts = (NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
NSTrackingActiveInKeyWindow | NSTrackingInVisibleRect);
[self->view addTrackingArea: [
[NSTrackingArea alloc] initWithRect: rect
options: opts
owner: self->view
userInfo: nil]];
[self->view setCanvas: (PyObject*)self];
exit:
Py_XDECREF(super_obj);
Py_XDECREF(super_init);
Py_XDECREF(init_res);
Py_XDECREF(wh);
return PyErr_Occurred() ? -1 : 0;
}
static void
FigureCanvas_dealloc(FigureCanvas* self)
{
[self->view setCanvas: NULL];
[self->view release];
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject*
FigureCanvas_repr(FigureCanvas* self)
{
return PyUnicode_FromFormat("FigureCanvas object %p wrapping NSView %p",
(void*)self, (void*)(self->view));
}
static PyObject*
FigureCanvas_update(FigureCanvas* self)
{
[self->view setNeedsDisplay: YES];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_flush_events(FigureCanvas* self)
{
// 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];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_set_cursor(PyObject* unused, PyObject* args)
{
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;
}
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_set_rubberband(FigureCanvas* self, PyObject *args)
{
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];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_remove_rubberband(FigureCanvas* self)
{
[self->view removeRubberband];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas__start_event_loop(FigureCanvas* self, PyObject* args, PyObject* keywords)
{
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)
{ NSEvent* event = [NSApp nextEventMatchingMask: NSEventMaskAny
untilDate: date
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (!event || [event type]==NSEventTypeApplicationDefined) { break; }
[NSApp sendEvent: event];
}
Py_END_ALLOW_THREADS
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_stop_event_loop(FigureCanvas* self)
{
NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
location: NSZeroPoint
modifierFlags: 0
timestamp: 0.0
windowNumber: 0
context: nil
subtype: STOP_EVENT_LOOP
data1: 0
data2: 0];
[NSApp postEvent: event atStart: true];
Py_RETURN_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
},
};
typedef struct {
PyObject_HEAD
Window* window;
} FigureManager;
static PyObject*
FigureManager_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
lazy_init();
Window* window = [Window alloc];
if (!window) { return NULL; }
FigureManager *self = (FigureManager*)type->tp_alloc(type, 0);
if (!self) {
[window release];
return NULL;
}
self->window = window;
++FigureWindowCount;
return (PyObject*)self;
}
static int
FigureManager_init(FigureManager *self, PyObject *args, PyObject *kwds)
{
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);
self->window = [self->window initWithContentRect: rect
styleMask: NSWindowStyleMaskTitled
| NSWindowStyleMaskClosable
| NSWindowStyleMaskResizable
| NSWindowStyleMaskMiniaturizable
backing: NSBackingStoreBuffered
defer: YES
withManager: (PyObject*)self];
Window* window = self->window;
[window setDelegate: view];
[window makeFirstResponder: view];
[[window contentView] addSubview: view];
[view updateDevicePixelRatio: [window backingScaleFactor]];
return 0;
}
static PyObject*
FigureManager__set_window_mode(FigureManager* self, PyObject* args)
{
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];
}
Py_RETURN_NONE;
}
static PyObject*
FigureManager_repr(FigureManager* self)
{
return PyUnicode_FromFormat("FigureManager object %p wrapping NSWindow %p",
(void*) self, (void*)(self->window));
}
static void
FigureManager_dealloc(FigureManager* self)
{
[self->window close];
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject*
FigureManager__show(FigureManager* self)
{
[self->window makeKeyAndOrderFront: nil];
Py_RETURN_NONE;
}
static PyObject*
FigureManager__raise(FigureManager* self)
{
[self->window orderFrontRegardless];
Py_RETURN_NONE;
}
static PyObject*
FigureManager_destroy(FigureManager* self)
{
[self->window close];
self->window = NULL;
Py_RETURN_NONE;
}
static PyObject*
FigureManager_set_icon(PyObject* null, PyObject* args) {
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;
}
@autoreleasepool {
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] autorelease];
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;
}
@try {
NSApplication* app = [NSApplication sharedApplication];
app.applicationIconImage = image;
}
@catch (NSException* exception) {
PyErr_SetString(PyExc_RuntimeError, exception.reason.UTF8String);
return NULL;
}
}
Py_RETURN_NONE;
}
static PyObject*
FigureManager_set_window_title(FigureManager* self,
PyObject *args, PyObject *kwds)
{
const char* title;
if (!PyArg_ParseTuple(args, "s", &title)) {
return NULL;
}
[self->window setTitle: [NSString stringWithUTF8String: title]];
Py_RETURN_NONE;
}
static PyObject*
FigureManager_get_window_title(FigureManager* self)
{
NSString* title = [self->window title];
if (title) {
return PyUnicode_FromString([title UTF8String]);
} else {
Py_RETURN_NONE;
}
}
static PyObject*
FigureManager_resize(FigureManager* self, PyObject *args, PyObject *kwds)
{
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.)];
}
Py_RETURN_NONE;
}
static PyObject*
FigureManager_full_screen_toggle(FigureManager* self)
{
[self->window toggleFullScreen: nil];
Py_RETURN_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
{ PyObject* toolbar;
NSButton* panbutton;
NSButton* zoombutton;
}
- (NavigationToolbar2Handler*)initWithToolbar:(PyObject*)toolbar;
- (void)installCallbacks:(SEL[7])actions forButtons:(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;
@end
typedef struct {
PyObject_HEAD
NSTextView* messagebox;
NavigationToolbar2Handler* handler;
int height;
} NavigationToolbar2;
@implementation NavigationToolbar2Handler
- (NavigationToolbar2Handler*)initWithToolbar:(PyObject*)theToolbar
{
[self init];
toolbar = theToolbar;
return self;
}
- (void)installCallbacks:(SEL[7])actions forButtons:(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; }
}
}
-(void)home:(id)sender { gil_call_method(toolbar, "home"); }
-(void)back:(id)sender { gil_call_method(toolbar, "back"); }
-(void)forward:(id)sender { gil_call_method(toolbar, "forward"); }
-(void)pan:(id)sender
{
if ([sender state]) { [zoombutton setState:NO]; }
gil_call_method(toolbar, "pan");
}
-(void)zoom:(id)sender
{
if ([sender state]) { [panbutton setState:NO]; }
gil_call_method(toolbar, "zoom");
}
-(void)configure_subplots:(id)sender { gil_call_method(toolbar, "configure_subplots"); }
-(void)save_figure:(id)sender { gil_call_method(toolbar, "save_figure"); }
@end
static PyObject*
NavigationToolbar2_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
lazy_init();
NavigationToolbar2Handler* handler = [NavigationToolbar2Handler alloc];
if (!handler) { return NULL; }
NavigationToolbar2 *self = (NavigationToolbar2*)type->tp_alloc(type, 0);
if (!self) {
[handler release];
return NULL;
}
self->handler = handler;
return (PyObject*)self;
}
static int
NavigationToolbar2_init(NavigationToolbar2 *self, PyObject *args, PyObject *kwds)
{
FigureCanvas* canvas;
const char* images[7];
const char* tooltips[7];
const float gap = 2;
const int height = 36;
const int imagesize = 24;
if (!PyArg_ParseTuple(args, "O!(sssssss)(sssssss)",
&FigureCanvasType, &canvas,
&images[0], &images[1], &images[2], &images[3],
&images[4], &images[5], &images[6],
&tooltips[0], &tooltips[1], &tooltips[2], &tooltips[3],
&tooltips[4], &tooltips[5], &tooltips[6])) {
return -1;
}
View* view = canvas->view;
if (!view) {
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return -1;
}
self->height = height;
NSRect bounds = [view bounds];
NSWindow* window = [view window];
bounds.origin.y += height;
[view setFrame: bounds];
bounds.size.height += height;
[window setContentSize: bounds.size];
NSButton* buttons[7];
SEL actions[7] = {@selector(home:),
@selector(back:),
@selector(forward:),
@selector(pan:),
@selector(zoom:),
@selector(configure_subplots:),
@selector(save_figure:)};
NSButtonType buttontypes[7] = {NSButtonTypeMomentaryLight,
NSButtonTypeMomentaryLight,
NSButtonTypeMomentaryLight,
NSButtonTypePushOnPushOff,
NSButtonTypePushOnPushOff,
NSButtonTypeMomentaryLight,
NSButtonTypeMomentaryLight};
NSRect rect;
NSSize size;
NSSize scale;
rect = NSMakeRect(0, 0, imagesize, imagesize);
rect = [window convertRectToBacking: rect];
size = rect.size;
scale = NSMakeSize(imagesize / size.width, imagesize / size.height);
rect.size.width = 32;
rect.size.height = 32;
rect.origin.x = gap;
rect.origin.y = 0.5*(height - rect.size.height);
for (int i = 0; i < 7; i++) {
NSString* filename = [NSString stringWithUTF8String: images[i]];
NSString* tooltip = [NSString stringWithUTF8String: tooltips[i]];
NSImage* image = [[NSImage alloc] initWithContentsOfFile: filename];
buttons[i] = [[NSButton alloc] initWithFrame: rect];
[image setSize: size];
// Specify that it is a template image so the content tint
// color gets updated with the system theme (dark/light)
[image setTemplate: YES];
[buttons[i] setBezelStyle: NSBezelStyleShadowlessSquare];
[buttons[i] setButtonType: buttontypes[i]];
[buttons[i] setImage: image];
[buttons[i] scaleUnitSquareToSize: scale];
[buttons[i] setImagePosition: NSImageOnly];
[buttons[i] setToolTip: tooltip];
[[window contentView] addSubview: buttons[i]];
[buttons[i] release];
[image release];
rect.origin.x += rect.size.width + gap;
}
self->handler = [self->handler initWithToolbar: (PyObject*)self];
[self->handler installCallbacks: actions forButtons: buttons];
NSFont* font = [NSFont systemFontOfSize: 0.0];