1 /***********************************************************
2 Copyright 1991-1997 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 ******************************************************************/
26 /* cfm68k InterfaceLib exports GetEventQueue, but Events.h doesn't know this
27 ** and defines it as GetEvQHdr (which is correct for PPC). This fix is for
28 ** CW9, check that the workaround is still needed for the next release.
30 #define GetEvQHdr GetEventQueue
31 #endif /* __CFM68K__ */
37 #endif /* __CFM68K__ */
46 #include "pythonresources.h"
48 #include <OSUtils.h> /* for Set(Current)A5 */
50 #include <StandardFile.h>
51 #include <Resources.h>
55 #include <Processes.h>
58 #include <TextUtils.h>
60 #include <OSEvents.h> /* For EvQElPtr */
66 #include <TFileSpec.h> /* For Path2FSSpec */
67 #include <LowMem.h> /* For SetSFCurDir, etc */
71 /* The ID of the Sioux apple menu */
72 #define SIOUX_APPLEID 32000
78 ** When less than this amount of stackspace is left we
79 ** raise a MemoryError.
81 #ifndef MINIMUM_STACK_SIZE
83 #define MINIMUM_STACK_SIZE 8192
85 #define MINIMUM_STACK_SIZE 4096
90 ** We have to be careful, since we can't handle
91 ** things like updates (and they'll keep coming back if we don't
92 ** handle them). Note that we don't know who has windows open, so
93 ** even handing updates off to SIOUX under MW isn't going to work.
95 #define MAINLOOP_EVENTMASK (mDownMask|keyDownMask|osMask|activMask)
99 /* XXX We should include Errors.h here, but it has a name conflict
100 ** with the python errors.h. */
103 /* Declared in macfsmodule.c: */
104 extern FSSpec
*mfs_GetFSSpecFSSpec();
106 /* Interrupt code variables: */
107 static int interrupted
; /* Set to true when cmd-. seen */
108 static RETSIGTYPE intcatcher
Py_PROTO((int));
110 static int PyMac_DoYield
Py_PROTO((int, int));
111 static int PyMac_Yield
Py_PROTO((void));
114 ** These are the real scheduling parameters that control what we check
115 ** in the event loop, and how often we check. The values are initialized
116 ** from pyMac_SchedParamStruct.
119 struct real_sched_param_struct
{
120 int check_interrupt
; /* if true check for command-dot */
121 int process_events
; /* if nonzero enable evt processing, this mask */
122 int besocial
; /* if nonzero be a little social with CPU */
123 unsigned long check_interval
; /* how often to check, in ticks */
124 unsigned long bg_yield
; /* yield so long when in background */
125 /* these are computed from previous and clock and such */
126 int enabled
; /* check_interrupt OR process_event OR yield */
127 unsigned long next_check
; /* when to check/yield next, in ticks */
130 static struct real_sched_param_struct schedparams
=
131 { 1, MAINLOOP_EVENTMASK
, 1, 15, 15, 1, 0};
134 ** Workaround for sioux/gusi combo: set when we are exiting
136 int PyMac_ConsoleIsDead
;
139 ** Sioux menu bar, saved early so we can restore it
141 static Handle sioux_mbar
;
144 ** Some stuff for our GetDirectory and PromptGetFile routines
147 int selectcur_hit
; /* Set to true when "select current" selected */
148 char *prompt
; /* The prompt */
150 static DlgHookYDUPP myhook_upp
;
151 static int upp_inited
= 0;
154 ** The python-code event handler
156 static PyObject
*python_event_handler
;
160 ** GUSI (1.6.0 and earlier, at the least) do not set the MacOS idea of
161 ** the working directory. Hence, we call this routine after each call
162 ** to chdir() to rectify things.
170 if ( Path2FSSpec(":x", &curdirfss
) != noErr
)
173 /* Set MacOS "working directory" */
175 pb
.ioVRefNum
= curdirfss
.vRefNum
;
176 pb
.ioWDDirID
= curdirfss
.parID
;
177 if (PBHSetVolSync(&pb
) != noErr
)
182 ** SpinCursor (needed by GUSI) drags in heaps of stuff, so we
183 ** provide a dummy here.
185 void SpinCursor(short x
) { /* Dummy */ }
186 void RotateCursor(short x
) { /* Dummy */ }
189 ** Replacement GUSI Spin function
192 PyMac_GUSISpin(spin_msg msg
, long arg
)
194 static Boolean inForeground
= true;
195 int maxsleep
= 6; /* 6 ticks is "normal" sleeptime */
197 if (PyMac_ConsoleIsDead
) return 0;
200 SpinCursor(msg
== SP_AUTO_SPIN
? short(arg
) : 1);
203 if (interrupted
) return -1;
205 if ( msg
== SP_AUTO_SPIN
)
207 if ( msg
==SP_SLEEP
||msg
==SP_SELECT
)
210 PyMac_DoYield(maxsleep
, 0); /* XXXX or is it safe to call python here? */
216 PyMac_SetGUSISpin() {
217 GUSISetHook(GUSI_SpinHook
, (GUSIHook
)PyMac_GUSISpin
);
220 /* Called at exit() time thru atexit(), to stop event processing */
222 PyMac_StopGUSISpin() {
223 PyMac_ConsoleIsDead
= 1;
227 ** Replacement routines for the PLstr... functions so we don't need
228 ** StdCLib. Moreover, that implementation is broken under cfm68k...
232 unsigned char *to
, *fr
;
234 memcpy(to
, fr
, fr
[0]+1);
239 unsigned char *s1
, *s2
;
242 int l
= s1
[0] < s2
[0] ? s1
[0] : s2
[0];
244 res
= memcmp(s1
+1, s2
+1, l
);
250 else if ( s1
[0] > s2
[0] )
261 unsigned char *ptr
= 0;
264 for(p
=str
+1; p
<str
+str
[0]; p
++)
270 #endif /* USE_GUSI */
273 /* Convert C to Pascal string. Returns pointer to static buffer. */
283 buf
[0] = (unsigned char)len
;
284 strncpy((char *)buf
+1, str
, len
);
288 /* Like strerror() but for Mac OS error numbers */
289 char *PyMac_StrError(int err
)
291 static char buf
[256];
295 h
= GetResource('Estr', err
);
299 memcpy(buf
, str
+1, (unsigned char)str
[0]);
300 buf
[(unsigned char)str
[0]] = '\0';
304 sprintf(buf
, "Mac OS error code %d", err
);
309 /* Exception object shared by all Mac specific modules for Mac OS errors */
310 PyObject
*PyMac_OSErrException
;
312 /* Initialize and return PyMac_OSErrException */
314 PyMac_GetOSErrException()
316 if (PyMac_OSErrException
== NULL
)
317 PyMac_OSErrException
= PyString_FromString("Mac OS Error");
318 return PyMac_OSErrException
;
321 /* Set a MAC-specific error from errno, and return NULL; return None if no error */
323 PyErr_Mac(PyObject
*eobj
, int err
)
328 if (err
== 0 && !PyErr_Occurred()) {
332 if (err
== -1 && PyErr_Occurred())
334 msg
= PyMac_StrError(err
);
335 v
= Py_BuildValue("(is)", err
, msg
);
336 PyErr_SetObject(eobj
, v
);
341 /* Call PyErr_Mac with PyMac_OSErrException */
343 PyMac_Error(OSErr err
)
345 return PyErr_Mac(PyMac_GetOSErrException(), err
);
348 #ifdef USE_STACKCHECK
349 /* Check for stack overflow */
356 if ( left
< MINIMUM_STACK_SIZE
)
360 #endif /* USE_STACKCHECK */
362 /* The catcher routine (which may not be used for all compilers) */
368 signal(SIGINT
, intcatcher
);
372 PyOS_InitInterrupts()
374 if (signal(SIGINT
, SIG_IGN
) != SIG_IGN
)
375 signal(SIGINT
, intcatcher
);
379 PyOS_FiniInterrupts()
384 ** This routine scans the event queue looking for cmd-.
385 ** This is the only way to get an interrupt under THINK (since it
386 ** doesn't do SIGINT handling), but is also used under MW, when
387 ** the full-fledged event loop is disabled. This way, we can at least
388 ** interrupt a runaway python program.
391 scan_event_queue(flush
)
396 q
= (EvQElPtr
) LMGetEventQueue()->qHead
;
398 for (; q
; q
= (EvQElPtr
)q
->qLink
) {
399 if (q
->evtQWhat
== keyDown
&&
400 (char)q
->evtQMessage
== '.' &&
401 (q
->evtQModifiers
& cmdKey
) != 0) {
403 FlushEvents(keyDownMask
, 0);
413 if (schedparams
.enabled
) {
414 if ( (unsigned long)LMGetTicks() > schedparams
.next_check
) {
415 if ( PyMac_Yield() < 0)
417 schedparams
.next_check
= (unsigned long)LMGetTicks()
418 + schedparams
.check_interval
;
420 scan_event_queue(1); /* Eat events up to cmd-. */
422 PyErr_SetNone(PyExc_KeyboardInterrupt
);
431 PyOS_InterruptOccurred()
436 /* Check whether we are in the foreground */
440 static ProcessSerialNumber ours
;
442 ProcessSerialNumber curfg
;
446 (void)GetCurrentProcess(&ours
);
449 if ( GetFrontProcess(&curfg
) < 0 )
451 else if ( SameProcess(&ours
, &curfg
, &eq
) < 0 )
458 PyMac_SetEventHandler(PyObject
*evh
)
460 if ( evh
&& python_event_handler
) {
461 PyErr_SetString(PyExc_RuntimeError
, "Python event handler already set");
464 if ( python_event_handler
)
465 Py_DECREF(python_event_handler
);
468 python_event_handler
= evh
;
473 ** Handle an event, either one found in the mainloop eventhandler or
474 ** one passed back from the python program.
477 PyMac_HandleEventIntern(evp
)
480 if ( evp
->what
== mouseDown
) {
483 if ( FindWindow(evp
->where
, &wp
) == inSysWindow
) {
484 SystemClick(evp
, wp
);
492 /* If SIOUX wants it we're done */
493 siouxdidit
= SIOUXHandleOneEvent(evp
);
498 /* Other compilers are just unlucky... */
499 #endif /* !__MWERKS__ */
503 ** Handle an event, either through HandleEvent or by passing it to the Python
507 PyMac_HandleEvent(evp
)
512 if ( python_event_handler
) {
513 rv
= PyObject_CallFunction(python_event_handler
, "(O&)",
514 PyMac_BuildEventRecord
, evp
);
518 return -1; /* Propagate exception */
520 PyMac_HandleEventIntern(evp
);
526 ** Yield the CPU to other tasks without processing events.
529 PyMac_DoYield(int maxsleep
, int maycallpython
)
533 long latest_time_ready
;
534 static int in_here
= 0;
538 ** First check for interrupts, if wanted.
539 ** This sets a flag that will be picked up at an appropriate
540 ** moment in the mainloop.
542 if (schedparams
.check_interrupt
)
545 /* XXXX Implementing an idle routine goes here */
548 ** Check which of the eventloop cases we have:
550 ** - don't process events but do yield
553 if( in_here
> 1 || !schedparams
.process_events
||
554 (python_event_handler
&& !maycallpython
) ) {
555 if ( maxsleep
>= 0 ) {
559 latest_time_ready
= LMGetTicks() + maxsleep
;
560 while ( maxsleep
>= 0 ) {
561 /* XXXX Hack by Jack.
562 ** In time.sleep() you can click to another application
563 ** once only. If you come back to Python you cannot get away
566 gotone
= WaitNextEvent(schedparams
.process_events
, &ev
, maxsleep
, NULL
);
567 /* Get out quickly if nothing interesting is happening */
568 if ( !gotone
|| ev
.what
== nullEvent
)
570 if ( PyMac_HandleEvent(&ev
) < 0 ) {
574 maxsleep
= latest_time_ready
- LMGetTicks();
582 ** Process events and/or yield the CPU to other tasks if opportune
586 unsigned long maxsleep
;
588 if( PyMac_InForeground() )
591 maxsleep
= schedparams
.bg_yield
;
593 return PyMac_DoYield(maxsleep
, 1);
597 ** Return current scheduler parameters
600 PyMac_GetSchedParams(PyMacSchedParams
*sp
)
602 sp
->check_interrupt
= schedparams
.check_interrupt
;
603 sp
->process_events
= schedparams
.process_events
;
604 sp
->besocial
= schedparams
.besocial
;
605 sp
->check_interval
= schedparams
.check_interval
/ 60.0;
606 sp
->bg_yield
= schedparams
.bg_yield
/ 60.0;
610 ** Set current scheduler parameters
613 PyMac_SetSchedParams(PyMacSchedParams
*sp
)
615 schedparams
.check_interrupt
= sp
->check_interrupt
;
616 schedparams
.process_events
= sp
->process_events
;
617 schedparams
.besocial
= sp
->besocial
;
618 schedparams
.check_interval
= (unsigned long)(sp
->check_interval
*60);
619 schedparams
.bg_yield
= (unsigned long)(sp
->bg_yield
*60);
620 if ( schedparams
.check_interrupt
|| schedparams
.process_events
||
621 schedparams
.besocial
)
622 schedparams
.enabled
= 1;
624 schedparams
.enabled
= 0;
625 schedparams
.next_check
= 0; /* Check immedeately */
629 ** Install our menu bar.
634 MenuHandle applemenu
;
636 if ( (sioux_mbar
=GetMenuBar()) == NULL
) {
637 /* Sioux menu not installed yet. Do so */
639 if ( (sioux_mbar
=GetMenuBar()) == NULL
)
642 if ( (applemenu
=GetMenuHandle(SIOUX_APPLEID
)) == NULL
) return;
643 SetMenuItemText(applemenu
, 1, "\pAbout Python...");
647 ** Restore sioux menu bar
650 PyMac_RestoreMenuBar()
653 SetMenuBar(sioux_mbar
);
661 ** Our replacement about box
664 #include "patchlevel.h"
667 SIOUXDoAboutBox(void)
674 if( (theDialog
= GetNewDialog(ABOUT_ID
, NULL
, (WindowPtr
)-1)) == NULL
)
676 theWindow
= GetDialogWindow(theDialog
);
677 SetPortWindowPort(theWindow
);
678 GetFNum("\pPython-Sans", &fontID
);
680 fontID
= kFontIDGeneva
;
683 ParamText(Pstring(PATCHLEVEL
), "\p", "\p", "\p");
684 ShowWindow(theWindow
);
685 ModalDialog(NULL
, &item
);
686 DisposeDialog(theDialog
);
691 PyMac_FileExists(char *name
)
695 if ( FSMakeFSSpec(0, 0, Pstring(name
), &fss
) == noErr
)
702 ** Helper routine for GetDirectory
705 myhook_proc(short item
, DialogPtr theDialog
, struct hook_args
*dataptr
)
707 if ( item
== sfHookFirstCall
&& dataptr
->prompt
) {
712 GetDialogItem(theDialog
, PROMPT_ITEM
, &type
, &prompth
, &rect
);
714 SetDialogItemText(prompth
, (unsigned char *)dataptr
->prompt
);
716 if ( item
== SELECTCUR_ITEM
) {
717 item
= sfItemCancelButton
;
718 dataptr
->selectcur_hit
= 1;
724 ** Ask the user for a directory. I still can't understand
725 ** why Apple doesn't provide a standard solution for this...
728 PyMac_GetDirectory(dirfss
, prompt
)
732 static SFTypeList list
= {'fldr', 0, 0, 0};
733 static Point where
= {-1, -1};
734 StandardFileReply reply
;
735 struct hook_args hook_args
;
738 myhook_upp
= NewDlgHookYDProc(myhook_proc
);
741 if ( prompt
&& *prompt
)
742 hook_args
.prompt
= (char *)Pstring(prompt
);
744 hook_args
.prompt
= NULL
;
745 hook_args
.selectcur_hit
= 0;
746 CustomGetFile((FileFilterYDUPP
)0, 1, list
, &reply
, GETDIR_ID
, where
, myhook_upp
,
747 NULL
, NULL
, NULL
, (void *)&hook_args
);
749 reply
.sfFile
.name
[0] = 0;
750 if( FSMakeFSSpec(reply
.sfFile
.vRefNum
, reply
.sfFile
.parID
, reply
.sfFile
.name
, dirfss
) )
752 return hook_args
.selectcur_hit
;
756 ** Slightly extended StandardGetFile: accepts a prompt */
757 void PyMac_PromptGetFile(short numTypes
, ConstSFTypeListPtr typeList
,
758 StandardFileReply
*reply
, char *prompt
)
760 static Point where
= {-1, -1};
761 struct hook_args hook_args
;
764 myhook_upp
= NewDlgHookYDProc(myhook_proc
);
767 if ( prompt
&& *prompt
)
768 hook_args
.prompt
= (char *)Pstring(prompt
);
770 hook_args
.prompt
= NULL
;
771 hook_args
.selectcur_hit
= 0;
772 CustomGetFile((FileFilterYDUPP
)0, numTypes
, typeList
, reply
, GETFILEPROMPT_ID
, where
,
773 myhook_upp
, NULL
, NULL
, NULL
, (void *)&hook_args
);
776 /* Convert a 4-char string object argument to an OSType value */
778 PyMac_GetOSType(PyObject
*v
, OSType
*pr
)
780 if (!PyString_Check(v
) || PyString_Size(v
) != 4) {
781 PyErr_SetString(PyExc_TypeError
,
782 "OSType arg must be string of 4 chars");
785 memcpy((char *)pr
, PyString_AsString(v
), 4);
789 /* Convert an OSType value to a 4-char string object */
791 PyMac_BuildOSType(OSType t
)
793 return PyString_FromStringAndSize((char *)&t
, 4);
796 /* Convert an NumVersion value to a 4-element tuple */
798 PyMac_BuildNumVersion(NumVersion t
)
800 return Py_BuildValue("(hhhh)", t
.majorRev
, t
.minorAndBugRev
, t
.stage
, t
.nonRelRev
);
804 /* Convert a Python string object to a Str255 */
806 PyMac_GetStr255(PyObject
*v
, Str255 pbuf
)
809 if (!PyString_Check(v
) || (len
= PyString_Size(v
)) > 255) {
810 PyErr_SetString(PyExc_TypeError
,
811 "Str255 arg must be string of at most 255 chars");
815 memcpy((char *)(pbuf
+1), PyString_AsString(v
), len
);
819 /* Convert a Str255 to a Python string object */
821 PyMac_BuildStr255(Str255 s
)
823 return PyString_FromStringAndSize((char *)&s
[1], (int)s
[0]);
828 ** Convert a Python object to an FSSpec.
829 ** The object may either be a full pathname or a triple
830 ** (vrefnum, dirid, path).
831 ** NOTE: This routine will fail on pre-sys7 machines.
832 ** The caller is responsible for not calling this routine
833 ** in those cases (which is fine, since everyone calling
834 ** this is probably sys7 dependent anyway).
837 PyMac_GetFSSpec(PyObject
*v
, FSSpec
*fs
)
845 /* first check whether it already is an FSSpec */
846 fs2
= mfs_GetFSSpecFSSpec(v
);
848 (void)FSMakeFSSpec(fs2
->vRefNum
, fs2
->parID
, fs2
->name
, fs
);
851 if ( PyString_Check(v
) ) {
852 /* It's a pathname */
853 if( !PyArg_Parse(v
, "O&", PyMac_GetStr255
, &path
) )
855 refnum
= 0; /* XXXX Should get CurWD here?? */
858 if( !PyArg_Parse(v
, "(hlO&); FSSpec should be fullpath or (vrefnum,dirid,path)",
859 &refnum
, &parid
, PyMac_GetStr255
, &path
)) {
863 err
= FSMakeFSSpec(refnum
, parid
, path
, fs
);
864 if ( err
&& err
!= fnfErr
) {
865 PyErr_Mac(PyExc_ValueError
, err
);
872 /* Convert a Python object to a Rect.
873 The object must be a (left, top, right, bottom) tuple.
874 (This differs from the order in the struct but is consistent with
875 the arguments to SetRect(), and also with STDWIN). */
877 PyMac_GetRect(PyObject
*v
, Rect
*r
)
879 return PyArg_Parse(v
, "(hhhh)", &r
->left
, &r
->top
, &r
->right
, &r
->bottom
);
882 /* Convert a Rect to a Python object */
884 PyMac_BuildRect(Rect
*r
)
886 return Py_BuildValue("(hhhh)", r
->left
, r
->top
, r
->right
, r
->bottom
);
890 /* Convert a Python object to a Point.
891 The object must be a (h, v) tuple.
892 (This differs from the order in the struct but is consistent with
893 the arguments to SetPoint(), and also with STDWIN). */
895 PyMac_GetPoint(PyObject
*v
, Point
*p
)
897 return PyArg_Parse(v
, "(hh)", &p
->h
, &p
->v
);
900 /* Convert a Point to a Python object */
902 PyMac_BuildPoint(Point p
)
904 return Py_BuildValue("(hh)", p
.h
, p
.v
);
908 /* Convert a Python object to an EventRecord.
909 The object must be a (what, message, when, (v, h), modifiers) tuple. */
911 PyMac_GetEventRecord(PyObject
*v
, EventRecord
*e
)
913 return PyArg_Parse(v
, "(hll(hh)h)",
922 /* Convert a Rect to an EventRecord object */
924 PyMac_BuildEventRecord(EventRecord
*e
)
926 return Py_BuildValue("(hll(hh)h)",
935 /* Convert Python object to Fixed */
937 PyMac_GetFixed(PyObject
*v
, Fixed
*f
)
941 if( !PyArg_Parse(v
, "d", &d
))
943 *f
= (Fixed
)(d
* 0x10000);
947 /* Convert a Point to a Python object */
949 PyMac_BuildFixed(Fixed f
)
955 return Py_BuildValue("d", d
);
958 /* Convert wide to/from Python int or (hi, lo) tuple. XXXX Should use Python longs */
960 PyMac_Getwide(PyObject
*v
, wide
*rv
)
962 if (PyInt_Check(v
)) {
964 rv
->lo
= PyInt_AsLong(v
);
965 if( rv
->lo
& 0x80000000 )
969 return PyArg_Parse(v
, "(ll)", &rv
->hi
, &rv
->lo
);
974 PyMac_Buildwide(wide
*w
)
976 if ( (w
->hi
== 0 && (w
->lo
& 0x80000000) == 0) ||
977 (w
->hi
== -1 && (w
->lo
& 0x80000000) ) )
978 return PyInt_FromLong(w
->lo
);
979 return Py_BuildValue("(ll)", w
->hi
, w
->lo
);