forked from matplotlib/matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_macosx.m
3113 lines (2802 loc) · 93.3 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
#include <Cocoa/Cocoa.h>
#include <ApplicationServices/ApplicationServices.h>
#include <sys/socket.h>
#include <Python.h>
/* Remove this once Python is fixed: https://bugs.python.org/issue23237 */
#define PYOSINPUTHOOK_REPETITIVE 1
/* Proper way to check for the OS X version we are compiling for, from
http://developer.apple.com/documentation/DeveloperTools/Conceptual/cross_development */
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
#define COMPILING_FOR_10_6
#endif
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
#define COMPILING_FOR_10_7
#endif
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 10100
#define COMPILING_FOR_10_10
#endif
/* CGFloat was defined in Mac OS X 10.5 */
#ifndef CGFLOAT_DEFINED
#define CGFloat float
#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;
/* -------------------------- Helper function ---------------------------- */
static void
_stdin_callback(CFReadStreamRef stream, CFStreamEventType eventType, void* info)
{
CFRunLoopRef runloop = info;
CFRunLoopStop(runloop);
}
static int sigint_fd = -1;
static void _sigint_handler(int sig)
{
const char c = 'i';
write(sigint_fd, &c, 1);
}
static void _sigint_callback(CFSocketRef s,
CFSocketCallBackType type,
CFDataRef address,
const void * data,
void *info)
{
char c;
int* interrupted = info;
CFSocketNativeHandle handle = CFSocketGetNative(s);
CFRunLoopRef runloop = CFRunLoopGetCurrent();
read(handle, &c, 1);
*interrupted = 1;
CFRunLoopStop(runloop);
}
static CGEventRef _eventtap_callback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
CFRunLoopRef runloop = refcon;
CFRunLoopStop(runloop);
return event;
}
static int wait_for_stdin(void)
{
int interrupted = 0;
const UInt8 buffer[] = "/dev/fd/0";
const CFIndex n = (CFIndex)strlen((char*)buffer);
CFRunLoopRef runloop = CFRunLoopGetCurrent();
CFURLRef url = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,
buffer,
n,
false);
CFReadStreamRef stream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
url);
CFRelease(url);
CFReadStreamOpen(stream);
#ifdef PYOSINPUTHOOK_REPETITIVE
if (!CFReadStreamHasBytesAvailable(stream))
/* This is possible because of how PyOS_InputHook is called from Python */
{
#endif
int error;
int channel[2];
CFSocketRef sigint_socket = NULL;
PyOS_sighandler_t py_sigint_handler = NULL;
CFStreamClientContext clientContext = {0, NULL, NULL, NULL, NULL};
clientContext.info = runloop;
CFReadStreamSetClient(stream,
kCFStreamEventHasBytesAvailable,
_stdin_callback,
&clientContext);
CFReadStreamScheduleWithRunLoop(stream, runloop, kCFRunLoopDefaultMode);
error = socketpair(AF_UNIX, SOCK_STREAM, 0, channel);
if (error==0)
{
CFSocketContext context;
context.version = 0;
context.info = &interrupted;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
fcntl(channel[0], F_SETFL, O_WRONLY | O_NONBLOCK);
sigint_socket = CFSocketCreateWithNative(
kCFAllocatorDefault,
channel[1],
kCFSocketReadCallBack,
_sigint_callback,
&context);
if (sigint_socket)
{
CFRunLoopSourceRef source;
source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,
sigint_socket,
0);
CFRelease(sigint_socket);
if (source)
{
CFRunLoopAddSource(runloop, source, kCFRunLoopDefaultMode);
CFRelease(source);
sigint_fd = channel[0];
py_sigint_handler = PyOS_setsig(SIGINT, _sigint_handler);
}
}
}
NSEvent* event;
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
while (true) {
while (true) {
event = [NSApp nextEventMatchingMask: NSAnyEventMask
untilDate: [NSDate distantPast]
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (!event) break;
[NSApp sendEvent: event];
}
CFRunLoopRun();
if (interrupted || CFReadStreamHasBytesAvailable(stream)) break;
}
[pool release];
if (py_sigint_handler) PyOS_setsig(SIGINT, py_sigint_handler);
CFReadStreamUnscheduleFromRunLoop(stream,
runloop,
kCFRunLoopCommonModes);
if (sigint_socket) CFSocketInvalidate(sigint_socket);
if (error==0) {
close(channel[0]);
close(channel[1]);
}
#ifdef PYOSINPUTHOOK_REPETITIVE
}
#endif
CFReadStreamClose(stream);
CFRelease(stream);
if (interrupted) {
errno = EINTR;
raise(SIGINT);
return -1;
}
return 1;
}
/* ---------------------------- Cocoa classes ---------------------------- */
@interface WindowServerConnectionManager : NSObject
{
}
+ (WindowServerConnectionManager*)sharedManager;
- (void)launch:(NSNotification*)notification;
@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;
- (void)dealloc;
@end
@interface ToolWindow : NSWindow
{
}
- (ToolWindow*)initWithContentRect:(NSRect)rect master:(NSWindow*)window;
- (void)masterCloses:(NSNotification*)notification;
- (void)close;
@end
#ifdef COMPILING_FOR_10_6
@interface View : NSView <NSWindowDelegate>
#else
@interface View : NSView
#endif
{ PyObject* canvas;
NSRect rubberband;
BOOL inside;
NSTrackingRectTag tracking;
@public double device_scale;
}
- (void)dealloc;
- (void)drawRect:(NSRect)rect;
- (void)windowDidResize:(NSNotification*)notification;
- (View*)initWithFrame:(NSRect)rect;
- (void)setCanvas: (PyObject*)newCanvas;
- (void)windowWillClose:(NSNotification*)notification;
- (BOOL)windowShouldClose:(NSNotification*)notification;
- (BOOL)isFlipped;
- (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
@interface ScrollableButton : NSButton
{
SEL scrollWheelUpAction;
SEL scrollWheelDownAction;
}
- (void)setScrollWheelUpAction:(SEL)action;
- (void)setScrollWheelDownAction:(SEL)action;
- (void)scrollWheel:(NSEvent *)event;
@end
@interface MenuItem: NSMenuItem
{ int index;
}
+ (MenuItem*)menuItemWithTitle:(NSString*)title;
+ (MenuItem*)menuItemSelectAll;
+ (MenuItem*)menuItemInvertAll;
+ (MenuItem*)menuItemForAxis:(int)i;
- (void)toggle:(id)sender;
- (void)selectAll:(id)sender;
- (void)invertAll:(id)sender;
- (int)index;
@end
/* ---------------------------- Python classes ---------------------------- */
static CGFloat _get_device_scale(CGContextRef cr)
{
CGSize pixelSize = CGContextConvertSizeToDeviceSpace(cr, CGSizeMake(1, 1));
return pixelSize.width;
}
typedef struct {
PyObject_HEAD
View* view;
} FigureCanvas;
static PyObject*
FigureCanvas_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
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)
{
int width;
int height;
if(!self->view)
{
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return -1;
}
if(!PyArg_ParseTuple(args, "ii", &width, &height)) return -1;
NSRect rect = NSMakeRect(0.0, 0.0, width, height);
self->view = [self->view initWithFrame: rect];
[self->view setCanvas: (PyObject*)self];
return 0;
}
static void
FigureCanvas_dealloc(FigureCanvas* self)
{
if (self->view)
{
[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_draw(FigureCanvas* self)
{
View* view = self->view;
if(view) /* The figure may have been closed already */
{
/* Whereas drawRect creates its own autorelease pool, apparently
* [view display] also needs one. Create and release it here. */
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[view display];
[pool release];
}
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_invalidate(FigureCanvas* self)
{
View* view = self->view;
if(!view)
{
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return NULL;
}
[view setNeedsDisplay: YES];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_flush_events(FigureCanvas* self)
{
View* view = self->view;
if(!view)
{
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return NULL;
}
[view displayIfNeeded];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_set_rubberband(FigureCanvas* self, PyObject *args)
{
View* view = self->view;
int x0, y0, x1, y1;
NSRect rubberband;
if(!view)
{
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return NULL;
}
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;
if (x1 > x0)
{
rubberband.origin.x = x0;
rubberband.size.width = x1 - x0;
}
else
{
rubberband.origin.x = x1;
rubberband.size.width = x0 - x1;
}
if (y1 > y0)
{
rubberband.origin.y = y0;
rubberband.size.height = y1 - y0;
}
else
{
rubberband.origin.y = y1;
rubberband.size.height = y0 - y1;
}
[view setRubberband: rubberband];
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_remove_rubberband(FigureCanvas* self)
{
View* view = self->view;
if(!view)
{
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return NULL;
}
[view removeRubberband];
Py_RETURN_NONE;
}
static NSImage* _read_ppm_image(PyObject* obj)
{
int width;
int height;
const char* data;
int n;
int i;
NSBitmapImageRep* bitmap;
unsigned char* bitmapdata;
if (!obj) return NULL;
if (!PyTuple_Check(obj)) return NULL;
if (!PyArg_ParseTuple(obj, "iit#", &width, &height, &data, &n)) return NULL;
if (width*height*3 != n) return NULL; /* RGB image uses 3 colors / pixel */
bitmap = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes: NULL
pixelsWide: width
pixelsHigh: height
bitsPerSample: 8
samplesPerPixel: 3
hasAlpha: NO
isPlanar: NO
colorSpaceName: NSDeviceRGBColorSpace
bitmapFormat: 0
bytesPerRow: width*3
bitsPerPixel: 24];
if (!bitmap) return NULL;
bitmapdata = [bitmap bitmapData];
for (i = 0; i < n; i++) bitmapdata[i] = data[i];
NSSize size = NSMakeSize(width, height);
NSImage* image = [[NSImage alloc] initWithSize: size];
if (image) [image addRepresentation: bitmap];
[bitmap release];
return image;
}
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;
int error;
int interrupted = 0;
int channel[2];
CFSocketRef sigint_socket = NULL;
PyOS_sighandler_t py_sigint_handler = NULL;
CFRunLoopRef runloop = CFRunLoopGetCurrent();
error = pipe(channel);
if (error==0)
{
CFSocketContext context = {0, NULL, NULL, NULL, NULL};
fcntl(channel[1], F_SETFL, O_WRONLY | O_NONBLOCK);
context.info = &interrupted;
sigint_socket = CFSocketCreateWithNative(kCFAllocatorDefault,
channel[0],
kCFSocketReadCallBack,
_sigint_callback,
&context);
if (sigint_socket)
{
CFRunLoopSourceRef source;
source = CFSocketCreateRunLoopSource(kCFAllocatorDefault,
sigint_socket,
0);
CFRelease(sigint_socket);
if (source)
{
CFRunLoopAddSource(runloop, source, kCFRunLoopDefaultMode);
CFRelease(source);
sigint_fd = channel[1];
py_sigint_handler = PyOS_setsig(SIGINT, _sigint_handler);
}
}
else
close(channel[0]);
}
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSDate* date =
(timeout > 0.0) ? [NSDate dateWithTimeIntervalSinceNow: timeout]
: [NSDate distantFuture];
while (true)
{ NSEvent* event = [NSApp nextEventMatchingMask: NSAnyEventMask
untilDate: date
inMode: NSDefaultRunLoopMode
dequeue: YES];
if (!event || [event type]==NSApplicationDefined) break;
[NSApp sendEvent: event];
}
[pool release];
if (py_sigint_handler) PyOS_setsig(SIGINT, py_sigint_handler);
if (sigint_socket) CFSocketInvalidate(sigint_socket);
if (error==0) close(channel[1]);
if (interrupted) raise(SIGINT);
Py_RETURN_NONE;
}
static PyObject*
FigureCanvas_stop_event_loop(FigureCanvas* self)
{
NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
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 PyMethodDef FigureCanvas_methods[] = {
{"draw",
(PyCFunction)FigureCanvas_draw,
METH_NOARGS,
"Draws the canvas."
},
{"invalidate",
(PyCFunction)FigureCanvas_invalidate,
METH_NOARGS,
"Invalidates the canvas."
},
{"flush_events",
(PyCFunction)FigureCanvas_flush_events,
METH_NOARGS,
"Flush the GUI events for the figure."
},
{"set_rubberband",
(PyCFunction)FigureCanvas_set_rubberband,
METH_VARARGS,
"Specifies a new rubberband rectangle and invalidates it."
},
{"remove_rubberband",
(PyCFunction)FigureCanvas_remove_rubberband,
METH_NOARGS,
"Removes the current rubberband rectangle."
},
{"start_event_loop",
(PyCFunction)FigureCanvas_start_event_loop,
METH_KEYWORDS | METH_VARARGS,
"Runs the event loop until the timeout or until stop_event_loop is called.\n",
},
{"stop_event_loop",
(PyCFunction)FigureCanvas_stop_event_loop,
METH_NOARGS,
"Stops the event loop that was started by start_event_loop.\n",
},
{NULL} /* Sentinel */
};
static char FigureCanvas_doc[] =
"A FigureCanvas object wraps a Cocoa NSView object.\n";
static PyTypeObject FigureCanvasType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_macosx.FigureCanvas", /*tp_name*/
sizeof(FigureCanvas), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)FigureCanvas_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
(reprfunc)FigureCanvas_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
FigureCanvas_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
FigureCanvas_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)FigureCanvas_init, /* tp_init */
0, /* tp_alloc */
FigureCanvas_new, /* tp_new */
};
typedef struct {
PyObject_HEAD
Window* window;
} FigureManager;
static PyObject*
FigureManager_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
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)
{
NSRect rect;
Window* window;
View* view;
const char* title;
PyObject* size;
int width, height;
PyObject* obj;
FigureCanvas* canvas;
if(!self->window)
{
PyErr_SetString(PyExc_RuntimeError, "NSWindow* is NULL");
return -1;
}
if(!PyArg_ParseTuple(args, "Os", &obj, &title)) return -1;
canvas = (FigureCanvas*)obj;
view = canvas->view;
if (!view) /* Something really weird going on */
{
PyErr_SetString(PyExc_RuntimeError, "NSView* is NULL");
return -1;
}
size = PyObject_CallMethod(obj, "get_width_height", "");
if(!size) return -1;
if(!PyArg_ParseTuple(size, "ii", &width, &height))
{ Py_DECREF(size);
return -1;
}
Py_DECREF(size);
rect.origin.x = 100;
rect.origin.y = 350;
rect.size.height = height;
rect.size.width = width;
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
self->window = [self->window initWithContentRect: rect
styleMask: NSTitledWindowMask
| NSClosableWindowMask
| NSResizableWindowMask
| NSMiniaturizableWindowMask
backing: NSBackingStoreBuffered
defer: YES
withManager: (PyObject*)self];
window = self->window;
[window setTitle: [NSString stringWithCString: title
encoding: NSASCIIStringEncoding]];
[window setAcceptsMouseMovedEvents: YES];
[window setDelegate: view];
[window makeFirstResponder: view];
[[window contentView] addSubview: view];
[pool release];
return 0;
}
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)
{
Window* window = self->window;
if(window)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[window close];
[pool release];
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject*
FigureManager_show(FigureManager* self)
{
Window* window = self->window;
if(window)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[window makeKeyAndOrderFront: nil];
[window orderFrontRegardless];
[pool release];
}
Py_RETURN_NONE;
}
static PyObject*
FigureManager_destroy(FigureManager* self)
{
Window* window = self->window;
if(window)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[window close];
[pool release];
self->window = NULL;
}
Py_RETURN_NONE;
}
static PyObject*
FigureManager_set_window_title(FigureManager* self,
PyObject *args, PyObject *kwds)
{
char* title;
if(!PyArg_ParseTuple(args, "es", "UTF-8", &title))
return NULL;
Window* window = self->window;
if(window)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSString* ns_title = [[[NSString alloc]
initWithCString: title
encoding: NSUTF8StringEncoding] autorelease];
[window setTitle: ns_title];
[pool release];
}
PyMem_Free(title);
Py_RETURN_NONE;
}
static PyObject*
FigureManager_get_window_title(FigureManager* self)
{
Window* window = self->window;
PyObject* result = NULL;
if(window)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSString* title = [window title];
if (title) {
const char* cTitle = [title UTF8String];
result = PyUnicode_FromString(cTitle);
}
[pool release];
}
if (result) {
return result;
} else {
Py_RETURN_NONE;
}
}
static PyMethodDef FigureManager_methods[] = {
{"show",
(PyCFunction)FigureManager_show,
METH_NOARGS,
"Shows the window associated with the figure manager."
},
{"destroy",
(PyCFunction)FigureManager_destroy,
METH_NOARGS,
"Closes the window associated with the figure manager."
},
{"set_window_title",
(PyCFunction)FigureManager_set_window_title,
METH_VARARGS,
"Sets the title of the window associated with the figure manager."
},
{"get_window_title",
(PyCFunction)FigureManager_get_window_title,
METH_NOARGS,
"Returns the title of the window associated with the figure manager."
},
{NULL} /* Sentinel */
};
static char FigureManager_doc[] =
"A FigureManager object wraps a Cocoa NSWindow object.\n";
static PyTypeObject FigureManagerType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_macosx.FigureManager", /*tp_name*/
sizeof(FigureManager), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)FigureManager_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
(reprfunc)FigureManager_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
FigureManager_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
FigureManager_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)FigureManager_init, /* tp_init */
0, /* tp_alloc */
FigureManager_new, /* tp_new */
};
@interface NavigationToolbarHandler : NSObject
{ PyObject* toolbar;
}
- (NavigationToolbarHandler*)initWithToolbar:(PyObject*)toolbar;
-(void)left:(id)sender;
-(void)right:(id)sender;
-(void)up:(id)sender;
-(void)down:(id)sender;
-(void)zoominx:(id)sender;
-(void)zoominy:(id)sender;
-(void)zoomoutx:(id)sender;
-(void)zoomouty:(id)sender;
@end
typedef struct {
PyObject_HEAD
NSPopUpButton* menu;
NavigationToolbarHandler* handler;
} NavigationToolbar;
@implementation NavigationToolbarHandler
- (NavigationToolbarHandler*)initWithToolbar:(PyObject*)theToolbar
{ [self init];
toolbar = theToolbar;
return self;
}
-(void)left:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "panx", "i", -1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)right:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "panx", "i", 1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)up:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "pany", "i", 1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)down:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "pany", "i", -1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)zoominx:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "zoomx", "i", 1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)zoomoutx:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "zoomx", "i", -1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)zoominy:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "zoomy", "i", 1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);
}
-(void)zoomouty:(id)sender
{ PyObject* result;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
result = PyObject_CallMethod(toolbar, "zoomy", "i", -1);
if(result)
Py_DECREF(result);
else
PyErr_Print();
PyGILState_Release(gstate);