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
}
16 # these types will have no methods and will merely be opaque blobs
17 # should write getattr and setattr for them?
19 StructObjectTypes
= ["EventTypeSpec",
25 for typ
in StructObjectTypes
:
26 execstr
= "%(name)s = OpaqueType('%(name)s')" % {"name": typ
}
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)
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)
44 EventTimeout
= EventTime
45 EventTimerInterval
= EventTime
46 EventAttributes
= UInt32
47 EventParamName
= OSType
48 EventParamType
= OSType
49 EventPriority
= SInt16
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
):
65 OutLbrace('if (_self->ob_itself == NULL)')
66 Output('PyErr_SetString(CarbonEvents_Error, "Handler has been removed");')
67 Output('return NULL;')
71 RgnHandle
= OpaqueByValueType("RgnHandle", "ResObj")
72 GrafPtr
= OpaqueByValueType("GrafPtr", "GrafObj")
73 MouseTrackingResult
= UInt16
77 #ifdef WITHOUT_FRAMEWORKS
78 #include <CarbonEvents.h>
80 #include <Carbon/Carbon.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"); \
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 *******/
111 EventTypeSpec_New(EventTypeSpec *in)
113 return Py_BuildValue("ll", in->eventClass, in->eventKind);
117 EventTypeSpec_Convert(PyObject *v, EventTypeSpec *out)
119 if (PyArg_Parse(v, "(O&l)",
120 PyMac_GetOSType, &(out->eventClass),
126 /********** end EventTypeSpec *******/
128 /********** HIPoint *******/
130 #if 0 /* XXX doesn't compile */
132 HIPoint_New(HIPoint *in)
134 return Py_BuildValue("ff", in->x, in->y);
138 HIPoint_Convert(PyObject *v, HIPoint *out)
140 if (PyArg_ParseTuple(v, "ff", &(out->x), &(out->y)))
146 /********** end HIPoint *******/
148 /********** EventHotKeyID *******/
151 EventHotKeyID_New(EventHotKeyID *in)
153 return Py_BuildValue("ll", in->signature, in->id);
157 EventHotKeyID_Convert(PyObject *v, EventHotKeyID *out)
159 if (PyArg_ParseTuple(v, "ll", &out->signature, &out->id))
164 /********** end EventHotKeyID *******/
166 /******** myEventHandler ***********/
168 static EventHandlerUPP myEventHandlerUPP;
170 static pascal OSStatus
171 myEventHandler(EventHandlerCallRef handlerRef, EventRef event, void *outPyObject) {
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? */
188 if (retValue == Py_None)
190 else if (PyInt_Check(retValue)) {
191 status = PyInt_AsLong(retValue);
193 status = noErr; /* wrong object type, complain? */
197 #if USE_MAC_MP_MULTITHREADING
198 _save = PyEval_SaveThread();
199 MPExitCriticalRegion(reentrantLock);
200 #endif /* USE_MAC_MP_MULTITHREADING */
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);")
231 class MyGlobalObjectDefinition(PEP253Mixin
, GlobalObjectDefinition
):
234 for typ
in RefObjectTypes
:
235 if typ
== 'EventHandlerRef':
236 EventHandlerRefobject
= EventHandlerRefObjectDefinition('EventHandlerRef')
238 execstr
= typ
+ 'object = MyGlobalObjectDefinition(typ)'
240 module
.addobject(eval(typ
+ 'object'))
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 = []'
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
= """
263 if (_self->ob_itself == NULL) {
264 PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
267 if (!PyArg_ParseTuple(_args, ""))
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;
278 f
= ManualGenerator("RemoveEventHandler", removeeventhandler
);
279 f
.docstring
= lambda: "() -> None"
280 EventHandlerRefobject
.add(f
)
283 installeventhandler
= """
284 EventTypeSpec inSpec;
286 EventHandlerRef outRef;
289 if (!PyArg_ParseTuple(_args, "O&O", EventTypeSpec_Convert, &inSpec, &callback))
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);
297 ((EventHandlerRefObject*)_res)->ob_callback = callback;
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
= """
310 EventParamName inName;
311 EventParamType inType;
315 if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &inName, PyMac_GetOSType, &inType))
318 /* Figure out the size by passing a null buffer to GetEventParameter */
319 _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, 0, &bufferSize, NULL);
322 return PyMac_Error(_err);
323 buffer = PyMem_NEW(char, bufferSize);
325 return PyErr_NoMemory();
327 _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, bufferSize, NULL, buffer);
331 return PyMac_Error(_err);
333 _res = Py_BuildValue("s#", buffer, bufferSize);
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");
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 */
364 f
= ManualGenerator("RunApplicationEventLoop", runappeventloop
);
365 f
.docstring
= lambda: "() -> ()"
368 SetOutputFileName('_CarbonEvtmodule.c')
372 ##os.system("python setup.py build")