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 ******************************************************************/
25 /* Python interpreter main program */
28 #include "pythonresources.h"
33 #ifdef WITHOUT_FRAMEWORKS
35 #include <Resources.h>
41 #if TARGET_API_MAC_CARBON
47 #endif /* TARGET_API_MAC_CARBON */
50 #include <Appearance.h>
51 #endif /* USE_APPEARANCE */
53 #include <Carbon/Carbon.h>
54 #endif /* WITHOUT_FRAMEWORKS */
59 extern int ccommand(char ***);
62 #endif /* __profile__ */
63 #endif /* __MWERKS__ */
66 #ifdef USE_MAC_SHARED_LIBRARY
67 extern PyMac_AddLibResources(void);
70 #define STARTUP "PythonStartup"
73 "Type \"copyright\", \"credits\" or \"license\" for more information."
75 short PyMac_AppRefNum
; /* RefNum of application resource fork */
77 /* For Py_GetArgcArgv(); set by main() */
78 static char **orig_argv
;
81 /* A flag which remembers whether the user has acknowledged all the console
82 ** output (by typing something)
84 #define STATE_UNKNOWN 0
85 #define STATE_LASTREAD 1
86 #define STATE_LASTWRITE 2
87 int console_output_state
= STATE_UNKNOWN
;
89 PyMac_PrefRecord PyMac_options
;
91 static void Py_Main(int, char **, char *); /* Forward */
92 void PyMac_Exit(int); /* Forward */
94 static void init_appearance(void)
100 err
= Gestalt(gestaltAppearanceAttr
,&response
);
101 if ( err
) goto no_appearance
;
102 if ( !(response
&(1<<gestaltAppearanceExists
)) ) goto no_appearance
;
103 /* XXXX Should we check the version? Compat-mode? */
104 PyMac_AppearanceCompliant
= 1;
107 #endif /* USE_APPEARANCE */
109 /* Initialize the Mac toolbox world */
114 #if !TARGET_API_MAC_CARBON
115 /* These aren't needed for carbon */
117 InitGraf(&qd
.thePort
);
121 InitDialogs((long)0);
129 ** PyMac_InteractiveOptions - Allow user to set options if option key is pressed
132 PyMac_InteractiveOptions(PyMac_PrefRecord
*p
, int *argcp
, char ***argvp
)
137 ControlHandle handle
;
142 ** If the preferences disallows interactive options we return,
143 ** similarly of <option> isn't pressed.
145 if (p
->nointopt
) return;
148 map
= (unsigned char *)rmap
;
149 if ( ( map
[0x3a>>3] & (1<<(0x3a&7)) ) == 0 ) /* option key is 3a */
152 dialog
= GetNewDialog(OPT_DIALOG
, NULL
, (WindowPtr
)-1);
153 if ( dialog
== NULL
) {
154 printf("Option dialog not found - cannot set options\n");
157 SetDialogDefaultItem(dialog
, OPT_OK
);
158 SetDialogCancelItem(dialog
, OPT_CANCEL
);
160 /* Set default values */
161 #define SET_OPT_ITEM(num, var) \
162 GetDialogItem(dialog, (num), &type, (Handle *)&handle, &rect); \
163 SetControlValue(handle, (short)p->var);
165 SET_OPT_ITEM(OPT_INSPECT
, inspect
);
166 SET_OPT_ITEM(OPT_VERBOSE
, verbose
);
167 /* OPT_VERBOSEVERBOSE is default off */
168 SET_OPT_ITEM(OPT_OPTIMIZE
, optimize
);
169 SET_OPT_ITEM(OPT_UNBUFFERED
, unbuffered
);
170 SET_OPT_ITEM(OPT_DEBUGGING
, debugging
);
171 GetDialogItem(dialog
, OPT_KEEPALWAYS
, &type
, (Handle
*)&handle
, &rect
);
172 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_ALWAYS
));
173 GetDialogItem(dialog
, OPT_KEEPOUTPUT
, &type
, (Handle
*)&handle
, &rect
);
174 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_OUTPUT
));
175 GetDialogItem(dialog
, OPT_KEEPERROR
, &type
, (Handle
*)&handle
, &rect
);
176 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_ERROR
));
177 GetDialogItem(dialog
, OPT_KEEPNEVER
, &type
, (Handle
*)&handle
, &rect
);
178 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_NEVER
));
179 /* SET_OPT_ITEM(OPT_KEEPCONSOLE, keep_console); */
180 SET_OPT_ITEM(OPT_TABWARN
, tabwarn
);
181 SET_OPT_ITEM(OPT_NOSITE
, nosite
);
182 SET_OPT_ITEM(OPT_DIVISIONWARN
, divisionwarn
);
183 SET_OPT_ITEM(OPT_UNIXNEWLINES
, unixnewlines
);
184 /* The rest are not settable interactively */
190 ModalDialog(NULL
, &item
);
191 if ( item
== OPT_OK
)
193 if ( item
== OPT_CANCEL
) {
194 DisposeDialog(dialog
);
197 #if !TARGET_API_MAC_CARBON
198 if ( item
== OPT_HELP
) {
199 HMSetBalloons(!HMGetBalloons());
202 #if !TARGET_API_MAC_OSX
203 if ( item
== OPT_CMDLINE
) {
204 int old_argc
= *argcp
;
206 int new_argc
, newer_argc
;
207 char **new_argv
, **newer_argv
;
209 new_argc
= ccommand(&new_argv
);
210 newer_argc
= (new_argc
-1) + old_argc
;
211 newer_argv
= malloc((newer_argc
+1)*sizeof(char *));
213 Py_FatalError("Cannot malloc argv\n");
214 for(i
=0; i
<old_argc
; i
++)
215 newer_argv
[i
] = (*argvp
)[i
];
216 for(i
=old_argc
; i
<=newer_argc
; i
++) /* Copy the NULL too */
217 newer_argv
[i
] = new_argv
[i
-old_argc
+1];
221 /* XXXX Is it not safe to use free() here, apparently */
223 #endif /* !TARGET_API_MAC_OSX */
224 #define OPT_ITEM(num, var) \
225 if ( item == (num) ) { \
227 GetDialogItem(dialog, (num), &type, (Handle *)&handle, &rect); \
228 SetControlValue(handle, (short)p->var); \
231 OPT_ITEM(OPT_INSPECT
, inspect
);
232 OPT_ITEM(OPT_VERBOSE
, verbose
);
233 if ( item
== OPT_VERBOSEVERBOSE
) {
234 if ( p
->verbose
== 2 )
238 GetDialogItem(dialog
, OPT_VERBOSE
, &type
, (Handle
*)&handle
, &rect
);
239 SetControlValue(handle
, 1);
241 GetDialogItem(dialog
, OPT_VERBOSEVERBOSE
, &type
, (Handle
*)&handle
, &rect
);
242 SetControlValue(handle
, p
->verbose
== 2);
243 OPT_ITEM(OPT_OPTIMIZE
, optimize
);
244 OPT_ITEM(OPT_UNBUFFERED
, unbuffered
);
245 OPT_ITEM(OPT_DEBUGGING
, debugging
);
246 if ( item
== OPT_KEEPALWAYS
) p
->keep_console
= POPT_KEEPCONSOLE_ALWAYS
;
247 if ( item
== OPT_KEEPOUTPUT
) p
->keep_console
= POPT_KEEPCONSOLE_OUTPUT
;
248 if ( item
== OPT_KEEPERROR
) p
->keep_console
= POPT_KEEPCONSOLE_ERROR
;
249 if ( item
== OPT_KEEPNEVER
) p
->keep_console
= POPT_KEEPCONSOLE_NEVER
;
250 GetDialogItem(dialog
, OPT_KEEPALWAYS
, &type
, (Handle
*)&handle
, &rect
);
251 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_ALWAYS
));
252 GetDialogItem(dialog
, OPT_KEEPOUTPUT
, &type
, (Handle
*)&handle
, &rect
);
253 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_OUTPUT
));
254 GetDialogItem(dialog
, OPT_KEEPERROR
, &type
, (Handle
*)&handle
, &rect
);
255 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_ERROR
));
256 GetDialogItem(dialog
, OPT_KEEPNEVER
, &type
, (Handle
*)&handle
, &rect
);
257 SetControlValue(handle
, (short)(p
->keep_console
== POPT_KEEPCONSOLE_NEVER
));
258 OPT_ITEM(OPT_TABWARN
, tabwarn
);
259 OPT_ITEM(OPT_NOSITE
, nosite
);
260 OPT_ITEM(OPT_DIVISIONWARN
, divisionwarn
);
261 OPT_ITEM(OPT_UNIXNEWLINES
, unixnewlines
);
265 DisposeDialog(dialog
);
269 ** Initialization code, shared by interpreter and applets
272 init_common(int *argcp
, char ***argvp
, int embedded
)
274 /* Remember resource fork refnum, for later */
275 PyMac_AppRefNum
= CurResFile();
277 /* Initialize toolboxes */
280 #ifdef USE_MAC_SHARED_LIBRARY
281 /* Add the shared library to the stack of resource files */
282 (void)PyMac_init_process_location();
283 PyMac_AddLibResources();
286 #if defined(USE_GUSI1)
290 PyMac_SetGUSIOptions();
292 #if defined(USE_GUSI)
293 atexit(PyMac_StopGUSISpin
);
297 /* Set various SIOUX flags. Some are changed later based on options */
299 SIOUXSettings
.standalone
= 0; /* XXXX Attempting to keep sioux from eating events */
301 SIOUXSettings
.asktosaveonclose
= 0;
302 SIOUXSettings
.showstatusline
= 0;
303 SIOUXSettings
.tabspaces
= 4;
306 /* Get options from preference file (or from applet resource fork) */
307 PyMac_options
.keep_console
= POPT_KEEPCONSOLE_OUTPUT
; /* default-default */
308 PyMac_options
.unixnewlines
= 1;
309 #if !TARGET_API_MAC_OSX
310 PyMac_PreferenceOptions(&PyMac_options
);
314 static char *emb_argv
[] = {"embedded-python", 0};
319 /* Create argc/argv. Do it before we go into the options event loop.
320 ** In MachoPython we skip this step if we already have plausible
321 ** command line arguments.
323 #if TARGET_API_MAC_OSX
324 if (*argcp
== 2 && strncmp((*argvp
)[1], "-psn_", 5) == 0)
326 *argcp
= PyMac_GetArgv(argvp
, PyMac_options
.noargs
);
327 #if !TARGET_API_MAC_OSX
328 #ifndef NO_ARGV0_CHDIR
329 if (*argcp
>= 1 && (*argvp
)[0] && (*argvp
)[0][0]) {
330 /* Workaround for MacOS X, which currently (DP4) doesn't set
331 ** the working folder correctly
333 char app_wd
[256], *p
;
335 strncpy(app_wd
, (*argvp
)[0], 256);
336 p
= strrchr(app_wd
, ':');
342 /* Do interactive option setting, if allowed and <option> depressed */
343 PyMac_InteractiveOptions(&PyMac_options
, argcp
, argvp
);
346 /* Copy selected options to where the machine-independent stuff wants it */
347 Py_VerboseFlag
= PyMac_options
.verbose
;
348 /* Py_SuppressPrintingFlag = PyMac_options.suppress_print; */
349 Py_OptimizeFlag
= PyMac_options
.optimize
;
350 Py_DebugFlag
= PyMac_options
.debugging
;
351 Py_NoSiteFlag
= PyMac_options
.nosite
;
352 Py_TabcheckFlag
= PyMac_options
.tabwarn
;
353 Py_DivisionWarningFlag
= PyMac_options
.divisionwarn
;
354 #if !TARGET_API_MAC_OSX
355 if ( PyMac_options
.noargs
) {
356 /* don't process events at all without the scripts permission */
357 PyMacSchedParams scp
;
359 PyMac_GetSchedParams(&scp
);
360 scp
.process_events
= 0;
361 /* Should we disable command-dot as well? */
362 PyMac_SetSchedParams(&scp
);
364 #endif /* !TARGET_API_MAC_OSX */
367 if (PyMac_options
.unbuffered
) {
369 setbuf(stdout
, (char *)NULL
);
370 setbuf(stderr
, (char *)NULL
);
372 /* On MPW (3.2) unbuffered seems to hang */
373 setvbuf(stdout
, (char *)NULL
, _IOLBF
, BUFSIZ
);
374 setvbuf(stderr
, (char *)NULL
, _IOLBF
, BUFSIZ
);
378 /* collectSummary or collectDetailed, timebase, #routines, max stack depth */
379 ProfilerInit(collectSummary
, bestTimeBase
, 8000, 250);
382 /* Tell the rest of python about our argc/argv */
383 orig_argc
= *argcp
; /* For Py_GetArgcArgv() */
385 Py_SetProgramName((*argvp
)[0]);
389 ** Inspection mode after script/applet termination
396 if (PyMac_options
.inspect
&& isatty((int)fileno(stdin
)))
397 sts
= PyRun_AnyFile(stdin
, "<stdin>") != 0;
401 #ifdef USE_MAC_APPLET_SUPPORT
404 /* Run a compiled Python Python script from 'PYC ' resource __main__ */
406 run_main_resource(void)
413 h
= GetNamedResource('PYC ', "\p__main__");
415 Alert(NOPYC_ALERT
, NULL
);
418 size
= GetResourceSizeOnDisk(h
);
420 code
= PyMarshal_ReadObjectFromString(*h
+ 8, (int)(size
- 8));
427 result
= PyImport_ExecCodeModule("__main__", code
);
429 if (result
== NULL
) {
437 /* Initialization sequence for applets */
439 PyMac_InitApplet(void)
445 init_common(&argc
, &argv
, 0);
448 PySys_SetArgv(argc
, argv
);
450 err
= run_main_resource();
452 err
= (run_inspect() || err
);
457 /* XXX Should we bother to Py_Exit(sts)? */
461 ** Hook for embedding python.
464 PyMac_Initialize(void)
469 init_common(&argc
, &argv
, 1);
471 PySys_SetArgv(argc
, argv
);
474 #endif /* USE_MAC_APPLET_SUPPORT */
476 #if TARGET_API_MAC_OSX /* Really: TARGET_API_MAC_CARBON */
479 locateResourcePy(char * resourceName
, char * resourceURLCStr
, int length
) {
480 CFBundleRef mainBundle
= NULL
;
481 CFURLRef URL
, absoluteURL
;
482 CFStringRef filenameString
, filepathString
, rsrcString
;
484 CFArrayRef arrayRef
= NULL
;
487 #if TARGET_API_MAC_OSX
488 CFURLPathStyle thePathStyle
= kCFURLPOSIXPathStyle
;
490 CFURLPathStyle thePathStyle
= kCFURLHFSPathStyle
;
493 /* Get a reference to our main bundle */
494 mainBundle
= CFBundleGetMainBundle();
496 /* If we are running inside a bundle, look through it. Otherwise, do nothing. */
498 /* Create a CFString with the resource name in it */
499 rsrcString
= CFStringCreateWithCString(0, resourceName
, kCFStringEncodingMacRoman
);
501 /* Look for py files in the main bundle by type */
502 arrayRef
= CFBundleCopyResourceURLsOfType( mainBundle
,
506 /* See if there are any filename matches */
507 size
= CFArrayGetCount(arrayRef
);
508 for (i
= 0; i
< size
; i
++) {
509 URL
= CFArrayGetValueAtIndex(arrayRef
, i
);
510 filenameString
= CFURLCopyLastPathComponent(URL
);
511 if (CFStringCompare(filenameString
, rsrcString
, 0) == kCFCompareEqualTo
) {
512 /* We found a match, get the file's full path */
513 absoluteURL
= CFURLCopyAbsoluteURL(URL
);
514 filepathString
= CFURLCopyFileSystemPath(absoluteURL
, thePathStyle
);
515 CFRelease(absoluteURL
);
517 /* Copy the full path into the caller's character buffer */
518 success
= CFStringGetCString(filepathString
, resourceURLCStr
, length
,
519 kCFStringEncodingMacRoman
);
521 CFRelease(filepathString
);
523 CFRelease(filenameString
);
526 CFRelease(rsrcString
);
531 #endif /* TARGET_API_MAC_CARBON */
533 #if TARGET_API_MAC_OSX
536 main(int argc
, char **argv
)
539 static char scriptpath
[1024];
542 /* First we see whether we have __rawmain__.py and run that if it
545 if (locateResourcePy("__rawmain__.py", scriptpath
, 1024)) {
546 /* If we have a raw main we don't do AppleEvent processing.
547 ** Notice that this also means we keep the -psn.... argv[1]
548 ** value intact. Not sure whether that is important to someone,
549 ** but you never know...
553 /* Otherwise we look for __main__.py. Whether that is
554 ** found or not we also process AppleEvent arguments.
556 if (locateResourcePy("__main__.py", scriptpath
, 1024))
559 printf("original argc=%d\n", argc
);
560 for(i
=0; i
<argc
; i
++) printf("original argv[%d] = \"%s\"\n", i
, argv
[i
]);
562 init_common(&argc
, &argv
, 0);
564 printf("modified argc=%d\n", argc
);
565 for(i
=0; i
<argc
; i
++) printf("modified argv[%d] = \"%s\"\n", i
, argv
[i
]);
568 Py_Main(argc
, argv
, script
);
574 /* For normal application */
576 PyMac_InitApplication(void)
581 static char scriptpath
[1024];
584 init_common(&argc
, &argv
, 0);
586 #if TARGET_API_MAC_OSX /* Really: TARGET_API_MAC_CARBON */
587 /* If we are running inside of a bundle, and a __main__.py is available, use it */
588 if (locateResourcePy("__main__.py", scriptpath
, 1024))
593 /* We're running a script. Attempt to change current directory */
594 char curwd
[256], *endp
;
596 strcpy(curwd
, argv
[1]);
597 endp
= strrchr(curwd
, ':');
598 if ( endp
&& endp
> curwd
) {
603 /* Change MacOS's idea of wd too */
607 /* Check that the first argument is a text file */
608 if ( PyMac_getfiletype(argv
[1]) != 'TEXT' ) {
609 Alert(NOTASCRIPT_ID
, NULL
);
613 Py_Main(argc
, argv
, script
);
615 #endif /* TARGET_API_MAC_OSX */
620 Py_Main(int argc
, char **argv
, char *filename
)
623 char *command
= NULL
;
627 /* Someone else has found our "script" already */
635 if (Py_VerboseFlag
||
636 (command
== NULL
&& filename
== NULL
&& isatty((int)fileno(fp
))))
637 fprintf(stderr
, "Python %s on %s\n%s\n",
638 Py_GetVersion(), Py_GetPlatform(), COPYRIGHT
);
640 if (filename
!= NULL
) {
641 if ((fp
= fopen(filename
, "r")) == NULL
) {
642 fprintf(stderr
, "%s: can't open file '%s'\n",
648 #if !TARGET_API_MAC_OSX
649 /* We initialize the menubar here, hoping SIOUX is initialized by now */
655 PyUnicode_SetDefaultEncoding(PyMac_getscript());
657 PySys_SetArgv(argc
, argv
);
659 if (filename
== NULL
&& isatty((int)fileno(fp
))) {
660 FILE *fp
= fopen(STARTUP
, "r");
662 (void) PyRun_SimpleFile(fp
, STARTUP
);
668 fp
, filename
== NULL
? "<stdin>" : filename
) != 0;
669 if (filename
!= NULL
)
672 if ( filename
!= NULL
|| command
!= NULL
)
673 sts
= (run_inspect() || sts
);
679 #if !TARGET_API_MAC_OSX
681 ** Reset the "unseen output" flag
684 PyMac_OutputSeen(void)
686 if ( console_output_state
== STATE_UNKNOWN
)
688 console_output_state
= STATE_LASTREAD
;
692 ** Set the "unseen output" flag
695 PyMac_OutputNotSeen(void)
697 if ( console_output_state
== STATE_UNKNOWN
)
699 console_output_state
= STATE_LASTWRITE
;
703 ** Override abort() - The default one is not what we want.
708 console_output_state
= STATE_LASTWRITE
;
711 #endif /* !TARGET_API_MAC_OSX */
714 ** Terminate application
717 PyMac_Exit(int status
)
724 ProfilerDump("\pPython Profiler Results");
729 switch (PyMac_options
.keep_console
) {
730 case POPT_KEEPCONSOLE_NEVER
:
733 case POPT_KEEPCONSOLE_OUTPUT
:
734 if (console_output_state
== STATE_LASTWRITE
||
735 console_output_state
== STATE_UNKNOWN
)
740 case POPT_KEEPCONSOLE_ERROR
:
741 keep
= (status
!= 0);
747 SIOUXSettings
.standalone
= 1;
748 SIOUXSettings
.autocloseonquit
= 0;
749 SIOUXSetTitle("\p\307terminated\310");
750 PyMac_RaiseConsoleWindow();
751 PyMac_RestoreMenuBar();
754 ** Temporary workaround: autocloseonquit clearing does not
755 ** currently work for the MSL/GUSI combo.
757 while(getchar() > 0);
761 SIOUXSettings
.autocloseonquit
= 1;
762 #endif /* USE_SIOUX */
767 #if !TARGET_API_MAC_OSX
768 /* Make the *original* argc/argv available to other modules.
769 This is rare, but it is needed by the secureware extension. */
772 Py_GetArgcArgv(int *argc
,char ***argv
)
779 /* More cruft that shouldn't really be here, used in sysmodule.c */
780 #if !TARGET_API_MAC_OSX
781 /* Return the program name -- some code out there needs this. */
783 Py_GetProgramFullPath(void)
791 return PyMac_GetPythonDir();
795 Py_GetExecPrefix(void)
797 return PyMac_GetPythonDir();
801 PyMac_GetDelayConsoleFlag(void)
803 return (int)PyMac_options
.delayconsole
;
806 #ifndef WITHOUT_UNIX_NEWLINES
808 ** Experimental feature (for 2.2a2): optionally allow unix newlines
809 ** as well as Mac newlines on input. We replace a lowlevel
810 ** MSL routine to accomplish this.
813 __convert_to_newlines(unsigned char * buf
, size_t * n_ptr
)
818 for(p
=buf
; n
> 0; p
++, n
--)
819 if ( *p
== '\r' ) *p
= '\n';
820 else if ( *p
== '\n' && !PyMac_options
.unixnewlines
)
823 #endif /* WITHOUT_UNIX_NEWLINES */
824 #endif /* !TARGET_API_MAC_OSX */