PyMac_GetFixed() didn't return 1 on success
[python/dscho.git] / Mac / Python / macglue.c
blob74fa2eef732183bbc1993c4d8d5ed458593ae944
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI not be used in advertising or publicity pertaining to
13 distribution of the software without specific, written prior permission.
15 STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
16 THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17 FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
18 FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
20 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
21 OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 ******************************************************************/
25 #include "Python.h"
27 #include "macglue.h"
28 #include "marshal.h"
29 #include "import.h"
31 #include "pythonresources.h"
33 #include <OSUtils.h> /* for Set(Current)A5 */
34 #include <Files.h>
35 #include <StandardFile.h>
36 #include <Resources.h>
37 #include <Memory.h>
38 #include <Events.h>
39 #include <Windows.h>
40 #include <Desk.h>
41 #include <Traps.h>
42 #include <Processes.h>
43 #include <Fonts.h>
44 #include <Menus.h>
45 #include <TextUtils.h>
46 #ifdef THINK_C
47 #include <OSEvents.h> /* For EvQElPtr */
48 #endif
49 #ifdef __MWERKS__
50 #include <SIOUX.h>
51 #endif
52 #ifdef USE_GUSI
53 #include <TFileSpec.h> /* For Path2FSSpec */
54 #include <LowMem.h> /* For SetSFCurDir, etc */
55 #endif
57 #ifndef HAVE_UNIVERSAL_HEADERS
58 #define GetResourceSizeOnDisk(x) SizeResource(x)
59 typedef DlgHookYDProcPtr DlgHookYDUPP;
60 #define NewDlgHookYDProc(userRoutine) ((DlgHookYDUPP) (userRoutine))
61 typedef FileFilterYDProcPtr FileFilterYDUPP;
62 #endif
64 #include <signal.h>
65 #include <stdio.h>
68 ** We have to be careful, since we can't handle
69 ** things like updates (and they'll keep coming back if we don't
70 ** handle them). Note that we don't know who has windows open, so
71 ** even handing updates off to SIOUX under MW isn't going to work.
73 #define MAINLOOP_EVENTMASK (mDownMask|keyDownMask|osMask)
75 #include <signal.h>
77 /* XXX We should include Errors.h here, but it has a name conflict
78 ** with the python errors.h. */
79 #define fnfErr -43
81 /* Declared in macfsmodule.c: */
82 extern FSSpec *mfs_GetFSSpecFSSpec();
84 /* Interrupt code variables: */
85 static int interrupted; /* Set to true when cmd-. seen */
86 static RETSIGTYPE intcatcher Py_PROTO((int));
89 ** We attempt to be a good citizen by giving up the CPU periodically.
90 ** When in the foreground we do this less often and for shorter periods
91 ** than when in the background. At this time we also check for events and
92 ** pass them off to SIOUX, if compiling with mwerks.
93 ** The counts here are in ticks of 1/60th second.
94 ** XXXX The initial values here are not based on anything.
95 ** FG-python gives up the cpu for 1/60th 5 times per second,
96 ** BG-python for .2 second 10 times per second.
98 static long interval_fg = 12;
99 static long interval_bg = 6;
100 static long yield_fg = 1;
101 static long yield_bg = 12;
102 static long lastyield;
103 static int in_foreground;
106 ** When > 0, do full scanning for events (program is not event aware)
107 ** when == 0, only scan for Command-period
108 ** when < 0, don't do any event scanning
110 int PyMac_DoYieldEnabled = 1;
113 ** Some stuff for our GetDirectory and PromptGetFile routines
115 struct hook_args {
116 int selectcur_hit; /* Set to true when "select current" selected */
117 char *prompt; /* The prompt */
119 static DlgHookYDUPP myhook_upp;
120 static int upp_inited = 0;
122 #ifdef USE_GUSI
124 ** GUSI (1.6.0 and earlier, at the least) do not set the MacOS idea of
125 ** the working directory. Hence, we call this routine after each call
126 ** to chdir() to rectify things.
128 void
129 PyMac_FixGUSIcd()
131 WDPBRec pb;
132 FSSpec curdirfss;
134 if ( Path2FSSpec(":x", &curdirfss) != noErr )
135 return;
137 /* Set MacOS "working directory" */
138 pb.ioNamePtr= "\p";
139 pb.ioVRefNum= curdirfss.vRefNum;
140 pb.ioWDDirID= curdirfss.parID;
141 if (PBHSetVol(&pb, 0) != noErr)
142 return;
144 #if 0
145 /* Set standard-file working directory */
146 LMSetSFSaveDisk(-curdirfss.vRefNum);
147 LMSetCurDirStore(curdirfss.parID);
148 #endif
150 #endif
153 /* Convert C to Pascal string. Returns pointer to static buffer. */
154 unsigned char *
155 Pstring(char *str)
157 static Str255 buf;
158 int len;
160 len = strlen(str);
161 if (len > 255)
162 len = 255;
163 buf[0] = (unsigned char)len;
164 strncpy((char *)buf+1, str, len);
165 return buf;
168 /* Like strerror() but for Mac OS error numbers */
169 char *PyMac_StrError(int err)
171 static char buf[256];
172 Handle h;
173 char *str;
175 h = GetResource('Estr', err);
176 if ( h ) {
177 HLock(h);
178 str = (char *)*h;
179 memcpy(buf, str+1, (unsigned char)str[0]);
180 buf[(unsigned char)str[0]] = '\0';
181 HUnlock(h);
182 ReleaseResource(h);
183 } else {
184 sprintf(buf, "Mac OS error code %d", err);
186 return buf;
189 /* Exception object shared by all Mac specific modules for Mac OS errors */
190 PyObject *PyMac_OSErrException;
192 /* Initialize and return PyMac_OSErrException */
193 PyObject *
194 PyMac_GetOSErrException()
196 if (PyMac_OSErrException == NULL)
197 PyMac_OSErrException = PyString_FromString("Mac OS Error");
198 return PyMac_OSErrException;
201 /* Set a MAC-specific error from errno, and return NULL; return None if no error */
202 PyObject *
203 PyErr_Mac(PyObject *eobj, int err)
205 char *msg;
206 PyObject *v;
208 if (err == 0 && !PyErr_Occurred()) {
209 Py_INCREF(Py_None);
210 return Py_None;
212 if (err == -1 && PyErr_Occurred())
213 return NULL;
214 msg = PyMac_StrError(err);
215 v = Py_BuildValue("(is)", err, msg);
216 PyErr_SetObject(eobj, v);
217 Py_DECREF(v);
218 return NULL;
221 /* Call PyErr_Mac with PyMac_OSErrException */
222 PyObject *
223 PyMac_Error(OSErr err)
225 return PyErr_Mac(PyMac_GetOSErrException(), err);
228 /* The catcher routine (which may not be used for all compilers) */
229 static RETSIGTYPE
230 intcatcher(sig)
231 int sig;
233 interrupted = 1;
234 signal(SIGINT, intcatcher);
237 void
238 PyOS_InitInterrupts()
240 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
241 signal(SIGINT, intcatcher);
245 ** This routine scans the event queue looking for cmd-.
246 ** This is the only way to get an interrupt under THINK (since it
247 ** doesn't do SIGINT handling), but is also used under MW, when
248 ** the full-fledged event loop is disabled. This way, we can at least
249 ** interrupt a runaway python program.
251 static void
252 scan_event_queue(flush)
253 int flush;
255 #if defined(__MWERKS__) && defined(__CFM68K__)
256 return; /* No GetEvQHdr yet */
257 #else
258 register EvQElPtr q;
260 q = (EvQElPtr) GetEvQHdr()->qHead;
262 for (; q; q = (EvQElPtr)q->qLink) {
263 if (q->evtQWhat == keyDown &&
264 (char)q->evtQMessage == '.' &&
265 (q->evtQModifiers & cmdKey) != 0) {
266 if ( flush )
267 FlushEvents(keyDownMask, 0);
268 interrupted = 1;
269 break;
272 #endif
276 PyOS_InterruptOccurred()
278 if (PyMac_DoYieldEnabled < 0)
279 return 0;
280 #ifdef THINK_C
281 scan_event_queue(1);
282 #endif
283 PyMac_Yield();
284 if (interrupted) {
285 interrupted = 0;
286 return 1;
288 return 0;
291 /* intrpeek() is like intrcheck(), but it doesn't flush the events. The
292 ** idea is that you call intrpeek() somewhere in a busy-wait loop, and return
293 ** None as soon as it returns 1. The mainloop will then pick up the cmd-. soon
294 ** thereafter.
296 static int
297 intrpeek()
299 #ifdef THINK_C
300 scan_event_queue(0);
301 #endif
302 return interrupted;
305 /* Check whether we are in the foreground */
307 PyMac_InForeground()
309 static ProcessSerialNumber ours;
310 static inited;
311 ProcessSerialNumber curfg;
312 Boolean eq;
314 if ( inited == 0 )
315 (void)GetCurrentProcess(&ours);
316 inited = 1;
317 if ( GetFrontProcess(&curfg) < 0 )
318 eq = 1;
319 else if ( SameProcess(&ours, &curfg, &eq) < 0 )
320 eq = 1;
321 return (int)eq;
326 ** Set yield timeouts
328 void
329 PyMac_SetYield(long fgi, long fgy, long bgi, long bgy)
331 interval_fg = fgi;
332 yield_fg = fgy;
333 interval_bg = bgi;
334 yield_bg = bgy;
338 ** Handle an event, either one found in the mainloop eventhandler or
339 ** one passed back from the python program.
341 void
342 PyMac_HandleEvent(evp)
343 EventRecord *evp;
346 #ifdef __MWERKS__
348 int siouxdidit;
350 /* If SIOUX wants it we're done */
351 siouxdidit = SIOUXHandleOneEvent(evp);
352 if ( siouxdidit )
353 return;
355 #else
356 /* Other compilers are just unlucky: we only weed out clicks in other applications */
357 if ( evp->what == mouseDown ) {
358 WindowPtr wp;
360 if ( FindWindow(evp->where, &wp) == inSysWindow ) {
361 SystemClick(evp, wp);
362 return;
365 #endif /* !__MWERKS__ */
369 ** Yield the CPU to other tasks.
371 static
372 PyMac_DoYield()
374 EventRecord ev;
375 long yield;
376 static int no_waitnextevent = -1;
377 int gotone;
379 if ( no_waitnextevent < 0 ) {
380 no_waitnextevent = (NGetTrapAddress(_WaitNextEvent, ToolTrap) ==
381 NGetTrapAddress(_Unimplemented, ToolTrap));
384 if ( !PyMac_DoYieldEnabled ) {
385 #ifndef THINK_C
386 /* Under think this has been done before in intrcheck() or intrpeek() */
387 scan_event_queue(0);
388 #endif
389 return;
392 in_foreground = PyMac_InForeground();
393 if ( in_foreground )
394 yield = yield_fg;
395 else
396 yield = yield_bg;
397 while ( 1 ) {
398 if ( no_waitnextevent ) {
399 SystemTask();
400 gotone = GetNextEvent(MAINLOOP_EVENTMASK, &ev);
401 } else {
402 gotone = WaitNextEvent(MAINLOOP_EVENTMASK, &ev, yield, NULL);
404 /* Get out quickly if nothing interesting is happening */
405 if ( !gotone || ev.what == nullEvent )
406 break;
407 PyMac_HandleEvent(&ev);
409 lastyield = TickCount();
413 ** Yield the CPU to other tasks if opportune
415 void
416 PyMac_Yield() {
417 long iv;
419 if ( in_foreground )
420 iv = interval_fg;
421 else
422 iv = interval_bg;
423 if ( TickCount() > lastyield + iv )
424 PyMac_DoYield();
428 ** Idle routine for busy-wait loops.
429 ** Gives up CPU, handles events and returns true if an interrupt is pending
430 ** (but not actually handled yet).
433 PyMac_Idle()
435 PyMac_DoYield();
436 return intrpeek();
439 ** Returns true if the argument has a resource fork, and it contains
440 ** a 'PYC ' resource of the correct name
443 PyMac_FindResourceModule(module, filename)
444 char *module;
445 char *filename;
447 FSSpec fss;
448 FInfo finfo;
449 short oldrh, filerh;
450 int ok;
451 Handle h;
453 if ( FSMakeFSSpec(0, 0, Pstring(filename), &fss) != noErr )
454 return 0; /* It doesn't exist */
455 if ( FSpGetFInfo(&fss, &finfo) != noErr )
456 return 0; /* shouldn't happen, I guess */
457 oldrh = CurResFile();
458 filerh = FSpOpenResFile(&fss, fsRdPerm);
459 if ( filerh == -1 )
460 return 0;
461 UseResFile(filerh);
462 SetResLoad(0);
463 h = Get1NamedResource('PYC ', Pstring(module));
464 SetResLoad(1);
465 ok = (h != NULL);
466 CloseResFile(filerh);
467 UseResFile(oldrh);
468 return ok;
472 ** Load the specified module from a resource
474 PyObject *
475 PyMac_LoadResourceModule(module, filename)
476 char *module;
477 char *filename;
479 FSSpec fss;
480 FInfo finfo;
481 short oldrh, filerh;
482 Handle h;
483 OSErr err;
484 PyObject *m, *co;
485 long num, size;
487 if ( (err=FSMakeFSSpec(0, 0, Pstring(filename), &fss)) != noErr )
488 goto error;
489 if ( (err=FSpGetFInfo(&fss, &finfo)) != noErr )
490 goto error;
491 oldrh = CurResFile();
492 filerh = FSpOpenResFile(&fss, fsRdPerm);
493 if ( filerh == -1 ) {
494 err = ResError();
495 goto error;
497 UseResFile(filerh);
498 h = Get1NamedResource('PYC ', Pstring(module));
499 if ( h == NULL ) {
500 err = ResError();
501 goto error;
503 HLock(h);
505 ** XXXX The next few lines are intimately tied to the format of pyc
506 ** files. I'm not sure whether this code should be here or in import.c -- Jack
508 size = GetHandleSize(h);
509 if ( size < 8 ) {
510 PyErr_SetString(PyExc_ImportError, "Resource too small");
511 co = NULL;
512 } else {
513 num = (*h)[0] & 0xff;
514 num = num | (((*h)[1] & 0xff) << 8);
515 num = num | (((*h)[2] & 0xff) << 16);
516 num = num | (((*h)[3] & 0xff) << 24);
517 if ( num != PyImport_GetMagicNumber() ) {
518 PyErr_SetString(PyExc_ImportError, "Bad MAGIC in resource");
519 co = NULL;
520 } else {
521 co = PyMarshal_ReadObjectFromString((*h)+8, size-8);
524 HUnlock(h);
525 CloseResFile(filerh);
526 UseResFile(oldrh);
527 if ( co ) {
528 m = PyImport_ExecCodeModule(module, co);
529 Py_DECREF(co);
530 } else {
531 m = NULL;
533 return m;
534 error:
536 char buf[512];
538 sprintf(buf, "%s: %s", filename, PyMac_StrError(err));
539 PyErr_SetString(PyExc_ImportError, buf);
540 return NULL;
545 ** Helper routine for GetDirectory
547 static pascal short
548 myhook_proc(short item, DialogPtr theDialog, struct hook_args *dataptr)
550 if ( item == sfHookFirstCall && dataptr->prompt) {
551 Handle prompth;
552 short type;
553 Rect rect;
555 GetDialogItem(theDialog, PROMPT_ITEM, &type, &prompth, &rect);
556 if ( prompth )
557 SetDialogItemText(prompth, (unsigned char *)dataptr->prompt);
558 } else
559 if ( item == SELECTCUR_ITEM ) {
560 item = sfItemCancelButton;
561 dataptr->selectcur_hit = 1;
563 return item;
567 ** Ask the user for a directory. I still can't understand
568 ** why Apple doesn't provide a standard solution for this...
571 PyMac_GetDirectory(dirfss, prompt)
572 FSSpec *dirfss;
573 char *prompt;
575 static SFTypeList list = {'fldr', 0, 0, 0};
576 static Point where = {-1, -1};
577 StandardFileReply reply;
578 struct hook_args hook_args;
580 if ( !upp_inited ) {
581 myhook_upp = NewDlgHookYDProc(myhook_proc);
582 upp_inited = 1;
584 if ( prompt && *prompt )
585 hook_args.prompt = (char *)Pstring(prompt);
586 else
587 hook_args.prompt = NULL;
588 hook_args.selectcur_hit = 0;
589 CustomGetFile((FileFilterYDUPP)0, 1, list, &reply, GETDIR_ID, where, myhook_upp,
590 NULL, NULL, NULL, (void *)&hook_args);
592 reply.sfFile.name[0] = 0;
593 if( FSMakeFSSpec(reply.sfFile.vRefNum, reply.sfFile.parID, reply.sfFile.name, dirfss) )
594 return 0;
595 return hook_args.selectcur_hit;
599 ** Slightly extended StandardGetFile: accepts a prompt */
600 void PyMac_PromptGetFile(short numTypes, ConstSFTypeListPtr typeList,
601 StandardFileReply *reply, char *prompt)
603 static Point where = {-1, -1};
604 struct hook_args hook_args;
606 if ( !upp_inited ) {
607 myhook_upp = NewDlgHookYDProc(myhook_proc);
608 upp_inited = 1;
610 if ( prompt && *prompt )
611 hook_args.prompt = (char *)Pstring(prompt);
612 else
613 hook_args.prompt = NULL;
614 hook_args.selectcur_hit = 0;
615 CustomGetFile((FileFilterYDUPP)0, numTypes, typeList, reply, GETFILEPROMPT_ID, where,
616 myhook_upp, NULL, NULL, NULL, (void *)&hook_args);
619 /* Convert a 4-char string object argument to an OSType value */
621 PyMac_GetOSType(PyObject *v, OSType *pr)
623 if (!PyString_Check(v) || PyString_Size(v) != 4) {
624 PyErr_SetString(PyExc_TypeError,
625 "OSType arg must be string of 4 chars");
626 return 0;
628 memcpy((char *)pr, PyString_AsString(v), 4);
629 return 1;
632 /* Convert an OSType value to a 4-char string object */
633 PyObject *
634 PyMac_BuildOSType(OSType t)
636 return PyString_FromStringAndSize((char *)&t, 4);
640 /* Convert a Python string object to a Str255 */
642 PyMac_GetStr255(PyObject *v, Str255 pbuf)
644 int len;
645 if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
646 PyErr_SetString(PyExc_TypeError,
647 "Str255 arg must be string of at most 255 chars");
648 return 0;
650 pbuf[0] = len;
651 memcpy((char *)(pbuf+1), PyString_AsString(v), len);
652 return 1;
655 /* Convert a Str255 to a Python string object */
656 PyObject *
657 PyMac_BuildStr255(Str255 s)
659 return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
664 ** Convert a Python object to an FSSpec.
665 ** The object may either be a full pathname or a triple
666 ** (vrefnum, dirid, path).
667 ** NOTE: This routine will fail on pre-sys7 machines.
668 ** The caller is responsible for not calling this routine
669 ** in those cases (which is fine, since everyone calling
670 ** this is probably sys7 dependent anyway).
673 PyMac_GetFSSpec(PyObject *v, FSSpec *fs)
675 Str255 path;
676 short refnum;
677 long parid;
678 OSErr err;
679 FSSpec *fs2;
681 /* first check whether it already is an FSSpec */
682 fs2 = mfs_GetFSSpecFSSpec(v);
683 if ( fs2 ) {
684 (void)FSMakeFSSpec(fs2->vRefNum, fs2->parID, fs2->name, fs);
685 return 1;
687 if ( PyString_Check(v) ) {
688 /* It's a pathname */
689 if( !PyArg_Parse(v, "O&", PyMac_GetStr255, &path) )
690 return 0;
691 refnum = 0; /* XXXX Should get CurWD here?? */
692 parid = 0;
693 } else {
694 if( !PyArg_Parse(v, "(hlO&); FSSpec should be fullpath or (vrefnum,dirid,path)",
695 &refnum, &parid, PyMac_GetStr255, &path)) {
696 return 0;
699 err = FSMakeFSSpec(refnum, parid, path, fs);
700 if ( err && err != fnfErr ) {
701 PyErr_Mac(PyExc_ValueError, err);
702 return 0;
704 return 1;
708 /* Convert a Python object to a Rect.
709 The object must be a (left, top, right, bottom) tuple.
710 (This differs from the order in the struct but is consistent with
711 the arguments to SetRect(), and also with STDWIN). */
713 PyMac_GetRect(PyObject *v, Rect *r)
715 return PyArg_Parse(v, "(hhhh)", &r->left, &r->top, &r->right, &r->bottom);
718 /* Convert a Rect to a Python object */
719 PyObject *
720 PyMac_BuildRect(Rect *r)
722 return Py_BuildValue("(hhhh)", r->left, r->top, r->right, r->bottom);
726 /* Convert a Python object to a Point.
727 The object must be a (h, v) tuple.
728 (This differs from the order in the struct but is consistent with
729 the arguments to SetPoint(), and also with STDWIN). */
731 PyMac_GetPoint(PyObject *v, Point *p)
733 return PyArg_Parse(v, "(hh)", &p->h, &p->v);
736 /* Convert a Point to a Python object */
737 PyObject *
738 PyMac_BuildPoint(Point p)
740 return Py_BuildValue("(hh)", p.h, p.v);
744 /* Convert a Python object to an EventRecord.
745 The object must be a (what, message, when, (v, h), modifiers) tuple. */
747 PyMac_GetEventRecord(PyObject *v, EventRecord *e)
749 return PyArg_Parse(v, "(hll(hh)h)",
750 &e->what,
751 &e->message,
752 &e->when,
753 &e->where.h,
754 &e->where.v,
755 &e->modifiers);
758 /* Convert a Rect to an EventRecord object */
759 PyObject *
760 PyMac_BuildEventRecord(EventRecord *e)
762 return Py_BuildValue("(hll(hh)h)",
763 e->what,
764 e->message,
765 e->when,
766 e->where.h,
767 e->where.v,
768 e->modifiers);
771 /* Convert Python object to Fixed */
773 PyMac_GetFixed(PyObject *v, Fixed *f)
775 double d;
777 if( !PyArg_Parse(v, "d", &d))
778 return 0;
779 *f = (Fixed)(d * 0x10000);
780 return 1;
783 /* Convert a Point to a Python object */
784 PyObject *
785 PyMac_BuildFixed(Fixed f)
787 double d;
789 d = f;
790 d = d / 0x10000;
791 return Py_BuildValue("d", d);