_make_boundary(): Fix for SF bug #745478, broken boundary calculation
[python/dscho.git] / Mac / Modules / carbonevt / CarbonEvtsupport.py
blob492720f851a500ab457220b3c4a0a2506696bd78
1 # IBCarbonsupport.py
3 from macsupport import *
5 from CarbonEvtscan import RefObjectTypes
7 # where should this go? macsupport.py?
8 CFStringRef = OpaqueByValueType('CFStringRef')
10 for typ in RefObjectTypes:
11 execstr = "%(name)s = OpaqueByValueType('%(name)s')" % {"name": typ}
12 exec execstr
15 if 0:
16 # these types will have no methods and will merely be opaque blobs
17 # should write getattr and setattr for them?
19 StructObjectTypes = ["EventTypeSpec",
20 "HIPoint",
21 "HICommand",
22 "EventHotKeyID",
25 for typ in StructObjectTypes:
26 execstr = "%(name)s = OpaqueType('%(name)s')" % {"name": typ}
27 exec execstr
29 EventHotKeyID = OpaqueByValueType("EventHotKeyID", "EventHotKeyID")
30 EventTypeSpec_ptr = OpaqueType("EventTypeSpec", "EventTypeSpec")
32 # is this the right type for the void * in GetEventParameter
33 #void_ptr = FixedInputBufferType(1024)
34 void_ptr = stringptr
35 # here are some types that are really other types
37 class MyVarInputBufferType(VarInputBufferType):
38 def passInput(self, name):
39 return "%s__len__, %s__in__" % (name, name)
41 MyInBuffer = MyVarInputBufferType('char', 'long', 'l') # (buf, len)
43 EventTime = double
44 EventTimeout = EventTime
45 EventTimerInterval = EventTime
46 EventAttributes = UInt32
47 EventParamName = OSType
48 EventParamType = OSType
49 EventPriority = SInt16
50 EventMask = UInt16
52 EventComparatorUPP = FakeType("(EventComparatorUPP)0")
53 EventLoopTimerUPP = FakeType("(EventLoopTimerUPP)0")
54 EventHandlerUPP = FakeType("(EventHandlerUPP)0")
55 EventHandlerUPP = FakeType("(EventHandlerUPP)0")
56 EventComparatorProcPtr = FakeType("(EventComparatorProcPtr)0")
57 EventLoopTimerProcPtr = FakeType("(EventLoopTimerProcPtr)0")
58 EventHandlerProcPtr = FakeType("(EventHandlerProcPtr)0")
60 CarbonEventsFunction = OSErrFunctionGenerator
61 CarbonEventsMethod = OSErrMethodGenerator
63 class EventHandlerRefMethod(OSErrMethodGenerator):
64 def precheck(self):
65 OutLbrace('if (_self->ob_itself == NULL)')
66 Output('PyErr_SetString(CarbonEvents_Error, "Handler has been removed");')
67 Output('return NULL;')
68 OutRbrace()
71 RgnHandle = OpaqueByValueType("RgnHandle", "ResObj")
72 GrafPtr = OpaqueByValueType("GrafPtr", "GrafObj")
73 MouseTrackingResult = UInt16
76 includestuff = r"""
77 #ifdef WITHOUT_FRAMEWORKS
78 #include <CarbonEvents.h>
79 #else
80 #include <Carbon/Carbon.h>
81 #endif
83 #include "macglue.h"
85 /* Macro to test whether a weak-loaded CFM function exists */
86 #define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL ) {\
87 PyErr_SetString(PyExc_NotImplementedError, \
88 "Not available in this shared library/OS version"); \
89 return; \
90 }} while(0)
93 #define USE_MAC_MP_MULTITHREADING 0
95 #if USE_MAC_MP_MULTITHREADING
96 static PyThreadState *_save;
97 static MPCriticalRegionID reentrantLock;
98 #endif /* USE_MAC_MP_MULTITHREADING */
100 extern int CFStringRef_New(CFStringRef *);
102 extern int CFStringRef_Convert(PyObject *, CFStringRef *);
103 extern int CFBundleRef_Convert(PyObject *, CFBundleRef *);
105 int EventTargetRef_Convert(PyObject *, EventTargetRef *);
106 PyObject *EventHandlerCallRef_New(EventHandlerCallRef itself);
107 PyObject *EventRef_New(EventRef itself);
109 /********** EventTypeSpec *******/
110 static PyObject*
111 EventTypeSpec_New(EventTypeSpec *in)
113 return Py_BuildValue("ll", in->eventClass, in->eventKind);
116 static int
117 EventTypeSpec_Convert(PyObject *v, EventTypeSpec *out)
119 if (PyArg_Parse(v, "(O&l)",
120 PyMac_GetOSType, &(out->eventClass),
121 &(out->eventKind)))
122 return 1;
123 return NULL;
126 /********** end EventTypeSpec *******/
128 /********** HIPoint *******/
130 #if 0 /* XXX doesn't compile */
131 static PyObject*
132 HIPoint_New(HIPoint *in)
134 return Py_BuildValue("ff", in->x, in->y);
137 static int
138 HIPoint_Convert(PyObject *v, HIPoint *out)
140 if (PyArg_ParseTuple(v, "ff", &(out->x), &(out->y)))
141 return 1;
142 return NULL;
144 #endif
146 /********** end HIPoint *******/
148 /********** EventHotKeyID *******/
150 static PyObject*
151 EventHotKeyID_New(EventHotKeyID *in)
153 return Py_BuildValue("ll", in->signature, in->id);
156 static int
157 EventHotKeyID_Convert(PyObject *v, EventHotKeyID *out)
159 if (PyArg_ParseTuple(v, "ll", &out->signature, &out->id))
160 return 1;
161 return NULL;
164 /********** end EventHotKeyID *******/
166 /******** myEventHandler ***********/
168 static EventHandlerUPP myEventHandlerUPP;
170 static pascal OSStatus
171 myEventHandler(EventHandlerCallRef handlerRef, EventRef event, void *outPyObject) {
172 PyObject *retValue;
173 int status;
175 #if USE_MAC_MP_MULTITHREADING
176 MPEnterCriticalRegion(reentrantLock, kDurationForever);
177 PyEval_RestoreThread(_save);
178 #endif /* USE_MAC_MP_MULTITHREADING */
180 retValue = PyObject_CallFunction((PyObject *)outPyObject, "O&O&",
181 EventHandlerCallRef_New, handlerRef,
182 EventRef_New, event);
183 if (retValue == NULL) {
184 PySys_WriteStderr("Error in event handler callback:\n");
185 PyErr_Print(); /* this also clears the error */
186 status = noErr; /* complain? how? */
187 } else {
188 if (retValue == Py_None)
189 status = noErr;
190 else if (PyInt_Check(retValue)) {
191 status = PyInt_AsLong(retValue);
192 } else
193 status = noErr; /* wrong object type, complain? */
194 Py_DECREF(retValue);
197 #if USE_MAC_MP_MULTITHREADING
198 _save = PyEval_SaveThread();
199 MPExitCriticalRegion(reentrantLock);
200 #endif /* USE_MAC_MP_MULTITHREADING */
202 return status;
205 /******** end myEventHandler ***********/
209 initstuff = initstuff + """
210 PyMac_PRECHECK(NewEventHandlerUPP); /* This can fail if CarbonLib is too old */
211 myEventHandlerUPP = NewEventHandlerUPP(myEventHandler);
213 module = MacModule('_CarbonEvt', 'CarbonEvents', includestuff, finalstuff, initstuff)
218 class EventHandlerRefObjectDefinition(PEP253Mixin, GlobalObjectDefinition):
219 def outputStructMembers(self):
220 Output("%s ob_itself;", self.itselftype)
221 Output("PyObject *ob_callback;")
222 def outputInitStructMembers(self):
223 Output("it->ob_itself = %sitself;", self.argref)
224 Output("it->ob_callback = NULL;")
225 def outputFreeIt(self, name):
226 OutLbrace("if (self->ob_itself != NULL)")
227 Output("RemoveEventHandler(self->ob_itself);")
228 Output("Py_DECREF(self->ob_callback);")
229 OutRbrace()
231 class MyGlobalObjectDefinition(PEP253Mixin, GlobalObjectDefinition):
232 pass
234 for typ in RefObjectTypes:
235 if typ == 'EventHandlerRef':
236 EventHandlerRefobject = EventHandlerRefObjectDefinition('EventHandlerRef')
237 else:
238 execstr = typ + 'object = MyGlobalObjectDefinition(typ)'
239 exec execstr
240 module.addobject(eval(typ + 'object'))
243 functions = []
244 for typ in RefObjectTypes: ## go thru all ObjectTypes as defined in CarbonEventsscan.py
245 # initialize the lists for carbongen to fill
246 execstr = typ + 'methods = []'
247 exec execstr
249 execfile('CarbonEventsgen.py')
253 for f in functions: module.add(f) # add all the functions carboneventsgen put in the list
255 for typ in RefObjectTypes: ## go thru all ObjectTypes as defined in CarbonEventsscan.py
256 methods = eval(typ + 'methods') ## get a reference to the method list from the main namespace
257 obj = eval(typ + 'object') ## get a reference to the object
258 for m in methods: obj.add(m) ## add each method in the list to the object
261 removeeventhandler = """
262 OSStatus _err;
263 if (_self->ob_itself == NULL) {
264 PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
265 return NULL;
267 if (!PyArg_ParseTuple(_args, ""))
268 return NULL;
269 _err = RemoveEventHandler(_self->ob_itself);
270 if (_err != noErr) return PyMac_Error(_err);
271 _self->ob_itself = NULL;
272 Py_DECREF(_self->ob_callback);
273 _self->ob_callback = NULL;
274 Py_INCREF(Py_None);
275 _res = Py_None;
276 return _res;"""
278 f = ManualGenerator("RemoveEventHandler", removeeventhandler);
279 f.docstring = lambda: "() -> None"
280 EventHandlerRefobject.add(f)
283 installeventhandler = """
284 EventTypeSpec inSpec;
285 PyObject *callback;
286 EventHandlerRef outRef;
287 OSStatus _err;
289 if (!PyArg_ParseTuple(_args, "O&O", EventTypeSpec_Convert, &inSpec, &callback))
290 return NULL;
292 _err = InstallEventHandler(_self->ob_itself, myEventHandlerUPP, 1, &inSpec, (void *)callback, &outRef);
293 if (_err != noErr) return PyMac_Error(_err);
295 _res = EventHandlerRef_New(outRef);
296 if (_res != NULL) {
297 ((EventHandlerRefObject*)_res)->ob_callback = callback;
298 Py_INCREF(callback);
300 return _res;"""
302 f = ManualGenerator("InstallEventHandler", installeventhandler);
303 f.docstring = lambda: "(EventTypeSpec inSpec, Method callback) -> (EventHandlerRef outRef)"
304 EventTargetRefobject.add(f)
306 # This may not be the best, but at least it lets you get the raw data back into python as a string. You'll have to cut it up yourself and parse the result.
308 geteventparameter = """
309 UInt32 bufferSize;
310 EventParamName inName;
311 EventParamType inType;
312 OSErr _err;
313 void * buffer;
315 if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &inName, PyMac_GetOSType, &inType))
316 return NULL;
318 /* Figure out the size by passing a null buffer to GetEventParameter */
319 _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, 0, &bufferSize, NULL);
321 if (_err != noErr)
322 return PyMac_Error(_err);
323 buffer = PyMem_NEW(char, bufferSize);
324 if (buffer == NULL)
325 return PyErr_NoMemory();
327 _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, bufferSize, NULL, buffer);
329 if (_err != noErr) {
330 PyMem_DEL(buffer);
331 return PyMac_Error(_err);
333 _res = Py_BuildValue("s#", buffer, bufferSize);
334 PyMem_DEL(buffer);
335 return _res;
338 f = ManualGenerator("GetEventParameter", geteventparameter);
339 f.docstring = lambda: "(EventParamName eventName, EventParamType eventType) -> (String eventParamData)"
340 EventRefobject.add(f)
342 runappeventloop = """
343 #if USE_MAC_MP_MULTITHREADING
344 if (MPCreateCriticalRegion(&reentrantLock) != noErr) {
345 PySys_WriteStderr("lock failure\\n");
346 return NULL;
348 _save = PyEval_SaveThread();
349 #endif /* USE_MAC_MP_MULTITHREADING */
351 RunApplicationEventLoop();
353 #if USE_MAC_MP_MULTITHREADING
354 PyEval_RestoreThread(_save);
356 MPDeleteCriticalRegion(reentrantLock);
357 #endif /* USE_MAC_MP_MULTITHREADING */
359 Py_INCREF(Py_None);
360 _res = Py_None;
361 return _res;
362 """
364 f = ManualGenerator("RunApplicationEventLoop", runappeventloop);
365 f.docstring = lambda: "() -> ()"
366 module.add(f)
368 SetOutputFileName('_CarbonEvtmodule.c')
369 module.generate()
371 ##import os
372 ##os.system("python setup.py build")