Maintain backwards compatibility with python < 2.3 by dynamically
[python/dscho.git] / Mac / Python / macmain.c
blobd257142976ecb7e548798fec17a470dde0730b0a
1 /***********************************************************
2 Copyright 1991-1997 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 /* Python interpreter main program */
27 #include "Python.h"
28 #include "pythonresources.h"
29 #include "import.h"
30 #include "marshal.h"
31 #include "macglue.h"
33 #ifdef WITHOUT_FRAMEWORKS
34 #include <Memory.h>
35 #include <Resources.h>
36 #include <stdio.h>
37 #include <Events.h>
38 #include <Windows.h>
39 #include <Fonts.h>
40 #include <Balloons.h>
41 #include <CFBundle.h>
42 #include <CFURL.h>
43 #include <CFString.h>
44 #include <CFBase.h>
45 #include <CFArray.h>
46 #include <Gestalt.h>
47 #include <Appearance.h>
48 #else
49 #include <Carbon/Carbon.h>
50 #endif /* WITHOUT_FRAMEWORKS */
52 #ifdef __MWERKS__
53 #include <SIOUX.h>
54 #define USE_SIOUX
55 extern int ccommand(char ***);
56 #if __profile__ == 1
57 #include <profiler.h>
58 #endif /* __profile__ */
59 #endif /* __MWERKS__ */
61 #include <unistd.h>
62 #ifdef USE_MAC_SHARED_LIBRARY
63 extern PyMac_AddLibResources(void);
64 #endif
66 #define STARTUP "PythonStartup"
68 #define COPYRIGHT \
69 "Type \"copyright\", \"credits\" or \"license\" for more information."
71 short PyMac_AppRefNum; /* RefNum of application resource fork */
73 /* For Py_GetArgcArgv(); set by main() */
74 static char **orig_argv;
75 static int orig_argc;
77 /* A flag which remembers whether the user has acknowledged all the console
78 ** output (by typing something)
80 #define STATE_UNKNOWN 0
81 #define STATE_LASTREAD 1
82 #define STATE_LASTWRITE 2
83 int console_output_state = STATE_UNKNOWN;
85 PyMac_PrefRecord PyMac_options;
87 static void PyMac_Main(int, char **, char *); /* Forward */
88 void PyMac_Exit(int); /* Forward */
90 /* Initialize the Mac toolbox world */
92 static void
93 init_mac_world(void)
95 InitCursor();
99 ** PyMac_InteractiveOptions - Allow user to set options if option key is pressed
101 static void
102 PyMac_InteractiveOptions(PyMac_PrefRecord *p, int *argcp, char ***argvp)
104 KeyMap rmap;
105 unsigned char *map;
106 short item, type;
107 ControlHandle handle;
108 DialogPtr dialog;
109 Rect rect;
112 ** If the preferences disallows interactive options we return,
113 ** similarly of <option> isn't pressed.
115 if (p->nointopt) return;
117 GetKeys(rmap);
118 map = (unsigned char *)rmap;
119 if ( ( map[0x3a>>3] & (1<<(0x3a&7)) ) == 0 ) /* option key is 3a */
120 return;
122 dialog = GetNewDialog(OPT_DIALOG, NULL, (WindowPtr)-1);
123 if ( dialog == NULL ) {
124 printf("Option dialog not found - cannot set options\n");
125 return;
127 SetDialogDefaultItem(dialog, OPT_OK);
128 SetDialogCancelItem(dialog, OPT_CANCEL);
130 /* Set default values */
131 #define SET_OPT_ITEM(num, var) \
132 GetDialogItem(dialog, (num), &type, (Handle *)&handle, &rect); \
133 SetControlValue(handle, (short)p->var);
135 SET_OPT_ITEM(OPT_INSPECT, inspect);
136 SET_OPT_ITEM(OPT_VERBOSE, verbose);
137 /* OPT_VERBOSEVERBOSE is default off */
138 SET_OPT_ITEM(OPT_OPTIMIZE, optimize);
139 SET_OPT_ITEM(OPT_UNBUFFERED, unbuffered);
140 SET_OPT_ITEM(OPT_DEBUGGING, debugging);
141 GetDialogItem(dialog, OPT_KEEPALWAYS, &type, (Handle *)&handle, &rect);
142 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_ALWAYS));
143 GetDialogItem(dialog, OPT_KEEPOUTPUT, &type, (Handle *)&handle, &rect);
144 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_OUTPUT));
145 GetDialogItem(dialog, OPT_KEEPERROR, &type, (Handle *)&handle, &rect);
146 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_ERROR));
147 GetDialogItem(dialog, OPT_KEEPNEVER, &type, (Handle *)&handle, &rect);
148 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_NEVER));
149 /* SET_OPT_ITEM(OPT_KEEPCONSOLE, keep_console); */
150 SET_OPT_ITEM(OPT_TABWARN, tabwarn);
151 SET_OPT_ITEM(OPT_NOSITE, nosite);
152 SET_OPT_ITEM(OPT_DIVISIONWARN, divisionwarn);
153 SET_OPT_ITEM(OPT_UNIXNEWLINES, unixnewlines);
154 /* The rest are not settable interactively */
156 #undef SET_OPT_ITEM
158 while (1) {
159 handle = NULL;
160 ModalDialog(NULL, &item);
161 if ( item == OPT_OK )
162 break;
163 if ( item == OPT_CANCEL ) {
164 DisposeDialog(dialog);
165 exit(0);
167 if ( item == OPT_CMDLINE ) {
168 int old_argc = *argcp;
169 int i;
170 int new_argc, newer_argc;
171 char **new_argv, **newer_argv;
173 new_argc = ccommand(&new_argv);
174 newer_argc = (new_argc-1) + old_argc;
175 newer_argv = malloc((newer_argc+1)*sizeof(char *));
176 if( !newer_argv )
177 Py_FatalError("Cannot malloc argv\n");
178 for(i=0; i<old_argc; i++)
179 newer_argv[i] = (*argvp)[i];
180 for(i=old_argc; i<=newer_argc; i++) /* Copy the NULL too */
181 newer_argv[i] = new_argv[i-old_argc+1];
182 *argvp = newer_argv;
183 *argcp = newer_argc;
185 /* XXXX Is it not safe to use free() here, apparently */
187 #define OPT_ITEM(num, var) \
188 if ( item == (num) ) { \
189 p->var = !p->var; \
190 GetDialogItem(dialog, (num), &type, (Handle *)&handle, &rect); \
191 SetControlValue(handle, (short)p->var); \
194 OPT_ITEM(OPT_INSPECT, inspect);
195 OPT_ITEM(OPT_VERBOSE, verbose);
196 if ( item == OPT_VERBOSEVERBOSE ) {
197 if ( p->verbose == 2 )
198 p->verbose = 1;
199 else
200 p->verbose = 2;
201 GetDialogItem(dialog, OPT_VERBOSE, &type, (Handle *)&handle, &rect);
202 SetControlValue(handle, 1);
204 GetDialogItem(dialog, OPT_VERBOSEVERBOSE, &type, (Handle *)&handle, &rect);
205 SetControlValue(handle, p->verbose == 2);
206 OPT_ITEM(OPT_OPTIMIZE, optimize);
207 OPT_ITEM(OPT_UNBUFFERED, unbuffered);
208 OPT_ITEM(OPT_DEBUGGING, debugging);
209 if ( item == OPT_KEEPALWAYS ) p->keep_console = POPT_KEEPCONSOLE_ALWAYS;
210 if ( item == OPT_KEEPOUTPUT ) p->keep_console = POPT_KEEPCONSOLE_OUTPUT;
211 if ( item == OPT_KEEPERROR ) p->keep_console = POPT_KEEPCONSOLE_ERROR;
212 if ( item == OPT_KEEPNEVER ) p->keep_console = POPT_KEEPCONSOLE_NEVER;
213 GetDialogItem(dialog, OPT_KEEPALWAYS, &type, (Handle *)&handle, &rect);
214 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_ALWAYS));
215 GetDialogItem(dialog, OPT_KEEPOUTPUT, &type, (Handle *)&handle, &rect);
216 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_OUTPUT));
217 GetDialogItem(dialog, OPT_KEEPERROR, &type, (Handle *)&handle, &rect);
218 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_ERROR));
219 GetDialogItem(dialog, OPT_KEEPNEVER, &type, (Handle *)&handle, &rect);
220 SetControlValue(handle, (short)(p->keep_console == POPT_KEEPCONSOLE_NEVER));
221 OPT_ITEM(OPT_TABWARN, tabwarn);
222 OPT_ITEM(OPT_NOSITE, nosite);
223 OPT_ITEM(OPT_DIVISIONWARN, divisionwarn);
224 OPT_ITEM(OPT_UNIXNEWLINES, unixnewlines);
226 #undef OPT_ITEM
228 DisposeDialog(dialog);
232 ** Initialization code, shared by interpreter and applets
234 static void
235 init_common(int *argcp, char ***argvp, int embedded)
237 /* Remember resource fork refnum, for later */
238 PyMac_AppRefNum = CurResFile();
240 /* Initialize toolboxes */
241 init_mac_world();
243 #ifdef USE_MAC_SHARED_LIBRARY
244 /* Add the shared library to the stack of resource files */
245 (void)PyMac_init_process_location();
246 PyMac_AddLibResources();
247 #endif
249 #if defined(USE_GUSI)
250 atexit(PyMac_StopGUSISpin);
251 #endif
253 #ifdef USE_SIOUX
254 /* Set various SIOUX flags. Some are changed later based on options */
255 SIOUXSettings.asktosaveonclose = 0;
256 SIOUXSettings.showstatusline = 0;
257 SIOUXSettings.tabspaces = 4;
258 #endif
260 /* Get options from preference file (or from applet resource fork) */
261 PyMac_options.keep_console = POPT_KEEPCONSOLE_OUTPUT; /* default-default */
262 PyMac_options.unixnewlines = 1;
263 PyMac_PreferenceOptions(&PyMac_options);
265 if ( embedded ) {
266 static char *emb_argv[] = {"embedded-python", 0};
268 *argcp = 1;
269 *argvp = emb_argv;
270 } else {
271 /* Create argc/argv. Do it before we go into the options event loop.
272 ** In MachoPython we skip this step if we already have plausible
273 ** command line arguments.
275 *argcp = PyMac_GetArgv(argvp, PyMac_options.noargs);
276 #ifndef NO_ARGV0_CHDIR
277 if (*argcp >= 1 && (*argvp)[0] && (*argvp)[0][0]) {
278 /* Workaround for MacOS X, which currently (DP4) doesn't set
279 ** the working folder correctly
281 char app_wd[256], *p;
283 strncpy(app_wd, (*argvp)[0], 256);
284 p = strrchr(app_wd, ':');
285 if ( p ) *p = 0;
286 chdir(app_wd);
288 #endif
289 /* Do interactive option setting, if allowed and <option> depressed */
290 PyMac_InteractiveOptions(&PyMac_options, argcp, argvp);
293 /* Copy selected options to where the machine-independent stuff wants it */
294 Py_VerboseFlag = PyMac_options.verbose;
295 /* Py_SuppressPrintingFlag = PyMac_options.suppress_print; */
296 Py_OptimizeFlag = PyMac_options.optimize;
297 Py_DebugFlag = PyMac_options.debugging;
298 Py_NoSiteFlag = PyMac_options.nosite;
299 Py_TabcheckFlag = PyMac_options.tabwarn;
300 Py_DivisionWarningFlag = PyMac_options.divisionwarn;
301 if ( PyMac_options.noargs ) {
302 /* don't process events at all without the scripts permission */
303 PyMacSchedParams scp;
305 PyMac_GetSchedParams(&scp);
306 scp.process_events = 0;
307 /* Should we disable command-dot as well? */
308 PyMac_SetSchedParams(&scp);
311 /* Set buffering */
312 if (PyMac_options.unbuffered) {
313 #ifndef MPW
314 setbuf(stdout, (char *)NULL);
315 setbuf(stderr, (char *)NULL);
316 #else
317 /* On MPW (3.2) unbuffered seems to hang */
318 setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
319 setvbuf(stderr, (char *)NULL, _IOLBF, BUFSIZ);
320 #endif
322 #if __profile__ == 1
323 /* collectSummary or collectDetailed, timebase, #routines, max stack depth */
324 ProfilerInit(collectSummary, bestTimeBase, 8000, 250);
325 #endif
327 /* Tell the rest of python about our argc/argv */
328 orig_argc = *argcp; /* For Py_GetArgcArgv() */
329 orig_argv = *argvp;
330 Py_SetProgramName((*argvp)[0]);
334 ** Inspection mode after script/applet termination
336 static int
337 run_inspect(void)
339 int sts = 0;
341 if (PyMac_options.inspect && isatty((int)fileno(stdin)))
342 sts = PyRun_AnyFile(stdin, "<stdin>") != 0;
343 return sts;
346 #ifdef USE_MAC_APPLET_SUPPORT
347 /* Applet support */
349 /* Run a compiled Python Python script from 'PYC ' resource __main__ */
350 static int
351 run_main_resource(void)
353 Handle h;
354 long size;
355 PyObject *code;
356 PyObject *result;
358 h = GetNamedResource('PYC ', "\p__main__");
359 if (h == NULL) {
360 Alert(NOPYC_ALERT, NULL);
361 return 1;
363 size = GetResourceSizeOnDisk(h);
364 HLock(h);
365 code = PyMarshal_ReadObjectFromString(*h + 8, (int)(size - 8));
366 HUnlock(h);
367 ReleaseResource(h);
368 if (code == NULL) {
369 PyErr_Print();
370 return 1;
372 result = PyImport_ExecCodeModule("__main__", code);
373 Py_DECREF(code);
374 if (result == NULL) {
375 PyErr_Print();
376 return 1;
378 Py_DECREF(result);
379 return 0;
382 /* Initialization sequence for applets */
383 void
384 PyMac_InitApplet(void)
386 int argc;
387 char **argv;
388 int err;
390 init_common(&argc, &argv, 0);
392 Py_Initialize();
393 PySys_SetArgv(argc, argv);
395 err = run_main_resource();
397 err = (run_inspect() || err);
399 fflush(stderr);
400 fflush(stdout);
401 PyMac_Exit(err);
402 /* XXX Should we bother to Py_Exit(sts)? */
406 ** Hook for embedding python.
408 void
409 PyMac_Initialize(void)
411 int argc;
412 char **argv;
414 init_common(&argc, &argv, 1);
415 Py_Initialize();
416 PySys_SetArgv(argc, argv);
419 #endif /* USE_MAC_APPLET_SUPPORT */
421 /* For normal application */
422 void
423 PyMac_InitApplication(void)
425 int argc;
426 char **argv;
427 OSType filetype;
429 static char scriptpath[1024];
430 char *script = NULL;
432 init_common(&argc, &argv, 0);
434 if ( argc > 1 ) {
435 /* We're running a script. Attempt to change current directory */
436 char curwd[256], *endp;
438 strcpy(curwd, argv[1]);
439 endp = strrchr(curwd, ':');
440 if ( endp && endp > curwd ) {
441 *endp = '\0';
443 chdir(curwd);
445 /* Check that the first argument is a text file */
446 filetype = PyMac_getfiletype(argv[1]);
447 if ( filetype != 'TEXT' && filetype != 0 ) {
448 Alert(NOTASCRIPT_ID, NULL);
449 exit(0);
452 PyMac_Main(argc, argv, script);
455 /* Main program */
457 static void
458 PyMac_Main(int argc, char **argv, char *filename)
460 int sts;
461 char *command = NULL;
462 FILE *fp = stdin;
464 if ( filename ) {
465 /* Someone else has found our "script" already */
466 argv[0] = filename;
467 } else {
468 filename = argv[1];
469 argv++;
470 argc--;
473 if (Py_VerboseFlag ||
474 (command == NULL && filename == NULL && isatty((int)fileno(fp))))
475 fprintf(stderr, "%s %s on %s\n%s\n",
476 "Python",
477 Py_GetVersion(), Py_GetPlatform(), COPYRIGHT);
479 if (filename != NULL) {
480 if ((fp = fopen(filename, "r" PY_STDIOTEXTMODE)) == NULL) {
481 fprintf(stderr, "%s: can't open file '%s'\n",
482 argv[0], filename);
483 PyMac_Exit(2);
487 /* We initialize the menubar here, hoping SIOUX is initialized by now */
488 PyMac_InitMenuBar();
490 Py_Initialize();
492 #if 0
493 /* According to Martin v. Loewis this is a bad idea... */
494 PyUnicode_SetDefaultEncoding(PyMac_getscript());
495 #endif
497 PySys_SetArgv(argc, argv);
499 if (filename == NULL && isatty((int)fileno(fp))) {
500 FILE *fp = fopen(STARTUP, "r" PY_STDIOTEXTMODE);
501 if (fp != NULL) {
502 (void) PyRun_SimpleFile(fp, STARTUP);
503 PyErr_Clear();
504 fclose(fp);
507 sts = PyRun_AnyFile(
508 fp, filename == NULL ? "<stdin>" : filename) != 0;
509 if (filename != NULL)
510 fclose(fp);
512 if ( filename != NULL || command != NULL )
513 sts = (run_inspect() || sts);
515 Py_Exit(sts);
516 /*NOTREACHED*/
520 ** Reset the "unseen output" flag
522 void
523 PyMac_OutputSeen(void)
525 if ( console_output_state == STATE_UNKNOWN )
526 PyMac_InitMenuBar();
527 console_output_state = STATE_LASTREAD;
531 ** Set the "unseen output" flag
533 void
534 PyMac_OutputNotSeen(void)
536 if ( console_output_state == STATE_UNKNOWN )
537 PyMac_InitMenuBar();
538 console_output_state = STATE_LASTWRITE;
542 ** Override abort() - The default one is not what we want.
544 void
545 abort(void)
547 console_output_state = STATE_LASTWRITE;
548 PyMac_Exit(1);
552 ** Terminate application
554 void
555 PyMac_Exit(int status)
557 #ifdef USE_SIOUX
558 int keep = 0;
559 #endif
561 #if __profile__ == 1
562 ProfilerDump("\pPython Profiler Results");
563 ProfilerTerm();
564 #endif
566 #ifdef USE_SIOUX
567 switch (PyMac_options.keep_console) {
568 case POPT_KEEPCONSOLE_NEVER:
569 keep = 0;
570 break;
571 case POPT_KEEPCONSOLE_OUTPUT:
572 if (console_output_state == STATE_LASTWRITE ||
573 console_output_state == STATE_UNKNOWN )
574 keep = 1;
575 else
576 keep = 0;
577 break;
578 case POPT_KEEPCONSOLE_ERROR:
579 keep = (status != 0);
580 break;
581 default:
582 keep = 1;
584 if (keep) {
585 SIOUXSettings.standalone = 1;
586 SIOUXSettings.autocloseonquit = 0;
587 SIOUXSetTitle("\p\307terminated\310");
588 PyMac_RaiseConsoleWindow();
589 PyMac_RestoreMenuBar();
590 #ifdef USE_MSL
592 ** Temporary workaround: autocloseonquit clearing does not
593 ** currently work for the MSL/GUSI combo.
595 while(getchar() > 0);
596 #endif
598 else
599 SIOUXSettings.autocloseonquit = 1;
600 #endif /* USE_SIOUX */
602 exit(status);
605 /* Make the *original* argc/argv available to other modules.
606 This is rare, but it is needed by the secureware extension. */
608 void
609 Py_GetArgcArgv(int *argc,char ***argv)
611 *argc = orig_argc;
612 *argv = orig_argv;
615 /* More cruft that shouldn't really be here, used in sysmodule.c */
616 /* Return the program name -- some code out there needs this. */
617 char *
618 Py_GetProgramFullPath(void)
620 return orig_argv[0];
623 char *
624 Py_GetPrefix(void)
626 return PyMac_GetPythonDir();
629 char *
630 Py_GetExecPrefix(void)
632 return PyMac_GetPythonDir();
636 PyMac_GetDelayConsoleFlag(void)
638 return (int)PyMac_options.delayconsole;