1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
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 ******************************************************************/
31 #include "pythonresources.h"
33 #include <OSUtils.h> /* for Set(Current)A5 */
35 #include <StandardFile.h>
36 #include <Resources.h>
42 #include <Processes.h>
45 #include <TextUtils.h>
47 #include <OSEvents.h> /* For EvQElPtr */
53 #include <TFileSpec.h> /* For Path2FSSpec */
54 #include <LowMem.h> /* For SetSFCurDir, etc */
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
;
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)
77 /* XXX We should include Errors.h here, but it has a name conflict
78 ** with the python errors.h. */
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
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;
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.
134 if ( Path2FSSpec(":x", &curdirfss
) != noErr
)
137 /* Set MacOS "working directory" */
139 pb
.ioVRefNum
= curdirfss
.vRefNum
;
140 pb
.ioWDDirID
= curdirfss
.parID
;
141 if (PBHSetVol(&pb
, 0) != noErr
)
145 /* Set standard-file working directory */
146 LMSetSFSaveDisk(-curdirfss
.vRefNum
);
147 LMSetCurDirStore(curdirfss
.parID
);
153 /* Convert C to Pascal string. Returns pointer to static buffer. */
163 buf
[0] = (unsigned char)len
;
164 strncpy((char *)buf
+1, str
, len
);
168 /* Like strerror() but for Mac OS error numbers */
169 char *PyMac_StrError(int err
)
171 static char buf
[256];
175 h
= GetResource('Estr', err
);
179 memcpy(buf
, str
+1, (unsigned char)str
[0]);
180 buf
[(unsigned char)str
[0]] = '\0';
184 sprintf(buf
, "Mac OS error code %d", err
);
189 /* Exception object shared by all Mac specific modules for Mac OS errors */
190 PyObject
*PyMac_OSErrException
;
192 /* Initialize and return PyMac_OSErrException */
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 */
203 PyErr_Mac(PyObject
*eobj
, int err
)
208 if (err
== 0 && !PyErr_Occurred()) {
212 if (err
== -1 && PyErr_Occurred())
214 msg
= PyMac_StrError(err
);
215 v
= Py_BuildValue("(is)", err
, msg
);
216 PyErr_SetObject(eobj
, v
);
221 /* Call PyErr_Mac with PyMac_OSErrException */
223 PyMac_Error(OSErr err
)
225 return PyErr_Mac(PyMac_GetOSErrException(), err
);
228 /* The catcher routine (which may not be used for all compilers) */
234 signal(SIGINT
, intcatcher
);
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.
252 scan_event_queue(flush
)
255 #if defined(__MWERKS__) && defined(__CFM68K__)
256 return; /* No GetEvQHdr yet */
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) {
267 FlushEvents(keyDownMask
, 0);
276 PyOS_InterruptOccurred()
278 if (PyMac_DoYieldEnabled
< 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
305 /* Check whether we are in the foreground */
309 static ProcessSerialNumber ours
;
311 ProcessSerialNumber curfg
;
315 (void)GetCurrentProcess(&ours
);
317 if ( GetFrontProcess(&curfg
) < 0 )
319 else if ( SameProcess(&ours
, &curfg
, &eq
) < 0 )
326 ** Set yield timeouts
329 PyMac_SetYield(long fgi
, long fgy
, long bgi
, long bgy
)
338 ** Handle an event, either one found in the mainloop eventhandler or
339 ** one passed back from the python program.
342 PyMac_HandleEvent(evp
)
350 /* If SIOUX wants it we're done */
351 siouxdidit
= SIOUXHandleOneEvent(evp
);
356 /* Other compilers are just unlucky: we only weed out clicks in other applications */
357 if ( evp
->what
== mouseDown
) {
360 if ( FindWindow(evp
->where
, &wp
) == inSysWindow
) {
361 SystemClick(evp
, wp
);
365 #endif /* !__MWERKS__ */
369 ** Yield the CPU to other tasks.
376 static int no_waitnextevent
= -1;
379 if ( no_waitnextevent
< 0 ) {
380 no_waitnextevent
= (NGetTrapAddress(_WaitNextEvent
, ToolTrap
) ==
381 NGetTrapAddress(_Unimplemented
, ToolTrap
));
384 if ( !PyMac_DoYieldEnabled
) {
386 /* Under think this has been done before in intrcheck() or intrpeek() */
392 in_foreground
= PyMac_InForeground();
398 if ( no_waitnextevent
) {
400 gotone
= GetNextEvent(MAINLOOP_EVENTMASK
, &ev
);
402 gotone
= WaitNextEvent(MAINLOOP_EVENTMASK
, &ev
, yield
, NULL
);
404 /* Get out quickly if nothing interesting is happening */
405 if ( !gotone
|| ev
.what
== nullEvent
)
407 PyMac_HandleEvent(&ev
);
409 lastyield
= TickCount();
413 ** Yield the CPU to other tasks if opportune
423 if ( TickCount() > lastyield
+ iv
)
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).
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
)
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
);
463 h
= Get1NamedResource('PYC ', Pstring(module
));
466 CloseResFile(filerh
);
472 ** Load the specified module from a resource
475 PyMac_LoadResourceModule(module
, filename
)
487 if ( (err
=FSMakeFSSpec(0, 0, Pstring(filename
), &fss
)) != noErr
)
489 if ( (err
=FSpGetFInfo(&fss
, &finfo
)) != noErr
)
491 oldrh
= CurResFile();
492 filerh
= FSpOpenResFile(&fss
, fsRdPerm
);
493 if ( filerh
== -1 ) {
498 h
= Get1NamedResource('PYC ', Pstring(module
));
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
);
510 PyErr_SetString(PyExc_ImportError
, "Resource too small");
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");
521 co
= PyMarshal_ReadObjectFromString((*h
)+8, size
-8);
525 CloseResFile(filerh
);
528 m
= PyImport_ExecCodeModule(module
, co
);
538 sprintf(buf
, "%s: %s", filename
, PyMac_StrError(err
));
539 PyErr_SetString(PyExc_ImportError
, buf
);
545 ** Helper routine for GetDirectory
548 myhook_proc(short item
, DialogPtr theDialog
, struct hook_args
*dataptr
)
550 if ( item
== sfHookFirstCall
&& dataptr
->prompt
) {
555 GetDialogItem(theDialog
, PROMPT_ITEM
, &type
, &prompth
, &rect
);
557 SetDialogItemText(prompth
, (unsigned char *)dataptr
->prompt
);
559 if ( item
== SELECTCUR_ITEM
) {
560 item
= sfItemCancelButton
;
561 dataptr
->selectcur_hit
= 1;
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
)
575 static SFTypeList list
= {'fldr', 0, 0, 0};
576 static Point where
= {-1, -1};
577 StandardFileReply reply
;
578 struct hook_args hook_args
;
581 myhook_upp
= NewDlgHookYDProc(myhook_proc
);
584 if ( prompt
&& *prompt
)
585 hook_args
.prompt
= (char *)Pstring(prompt
);
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
) )
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
;
607 myhook_upp
= NewDlgHookYDProc(myhook_proc
);
610 if ( prompt
&& *prompt
)
611 hook_args
.prompt
= (char *)Pstring(prompt
);
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");
628 memcpy((char *)pr
, PyString_AsString(v
), 4);
632 /* Convert an OSType value to a 4-char string object */
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
)
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");
651 memcpy((char *)(pbuf
+1), PyString_AsString(v
), len
);
655 /* Convert a Str255 to a Python string object */
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
)
681 /* first check whether it already is an FSSpec */
682 fs2
= mfs_GetFSSpecFSSpec(v
);
684 (void)FSMakeFSSpec(fs2
->vRefNum
, fs2
->parID
, fs2
->name
, fs
);
687 if ( PyString_Check(v
) ) {
688 /* It's a pathname */
689 if( !PyArg_Parse(v
, "O&", PyMac_GetStr255
, &path
) )
691 refnum
= 0; /* XXXX Should get CurWD here?? */
694 if( !PyArg_Parse(v
, "(hlO&); FSSpec should be fullpath or (vrefnum,dirid,path)",
695 &refnum
, &parid
, PyMac_GetStr255
, &path
)) {
699 err
= FSMakeFSSpec(refnum
, parid
, path
, fs
);
700 if ( err
&& err
!= fnfErr
) {
701 PyErr_Mac(PyExc_ValueError
, err
);
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 */
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 */
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)",
758 /* Convert a Rect to an EventRecord object */
760 PyMac_BuildEventRecord(EventRecord
*e
)
762 return Py_BuildValue("(hll(hh)h)",
771 /* Convert Python object to Fixed */
773 PyMac_GetFixed(PyObject
*v
, Fixed
*f
)
777 if( !PyArg_Parse(v
, "d", &d
))
779 *f
= (Fixed
)(d
* 0x10000);
783 /* Convert a Point to a Python object */
785 PyMac_BuildFixed(Fixed f
)
791 return Py_BuildValue("d", d
);