macglue.c 23.9 KB
Newer Older
1
/***********************************************************
2
Copyright 1991-1997 by Stichting Mathematisch Centrum, Amsterdam,
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
The Netherlands.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

******************************************************************/
Jack Jansen's avatar
Jack Jansen committed
24

Jack Jansen's avatar
Jack Jansen committed
25 26 27 28 29 30 31 32 33 34
#ifdef __CFM68K__
/* cfm68k InterfaceLib exports GetEventQueue, but Events.h doesn't know this
** and defines it as GetEvQHdr (which is correct for PPC). This fix is for
** CW9, check that the workaround is still needed for the next release.
*/
#define GetEvQHdr GetEventQueue
#endif /* __CFM68K__ */

#include <Events.h>

35
#if TARGET_API_MAC_CARBON
36 37 38 39
/* Unfortunately this call is probably slower... */
#define LMGetTicks() TickCount()
#endif

Jack Jansen's avatar
Jack Jansen committed
40 41 42 43
#ifdef __CFM68K__
#undef GetEventQueue
#endif /* __CFM68K__ */

Jack Jansen's avatar
Jack Jansen committed
44
#include "Python.h"
Guido van Rossum's avatar
Guido van Rossum committed
45

Jack Jansen's avatar
Jack Jansen committed
46
#include "macglue.h"
47 48
#include "marshal.h"
#include "import.h"
49
#include "importdl.h"
Jack Jansen's avatar
Jack Jansen committed
50

51 52
#include "pythonresources.h"

Jack Jansen's avatar
Jack Jansen committed
53
#include <OSUtils.h> /* for Set(Current)A5 */
54
#include <Files.h>
55
#include <StandardFile.h>
Jack Jansen's avatar
Jack Jansen committed
56 57 58
#include <Resources.h>
#include <Memory.h>
#include <Windows.h>
59
#include <Traps.h>
60
#include <Processes.h>
61 62
#include <Fonts.h>
#include <Menus.h>
63
#include <TextUtils.h>
64 65
#ifdef __MWERKS__
#include <SIOUX.h>
66 67
extern void SIOUXSetupMenus(void);
extern void SIOUXDoAboutBox(void);
68
#endif
69 70 71 72 73 74 75 76 77 78
#ifdef USE_GUSI
/* Functions we redefine because they're in obscure libraries */
extern void SpinCursor(short x);
extern void RotateCursor(short x);
extern pascal void PLstrcpy(unsigned char *, unsigned char *);
extern pascal int PLstrcmp(unsigned char *, unsigned char *);
extern pascal unsigned char *PLstrrchr(unsigned char *, unsigned char);

#endif

79
#ifdef USE_GUSI1
80
#include <TFileSpec.h> /* For Path2FSSpec */
Jack Jansen's avatar
Jack Jansen committed
81
#include <GUSI.h>
82
#endif
83
#include <LowMem.h>
84

85 86 87
/* The ID of the Sioux apple menu */
#define SIOUX_APPLEID	32000

88
#include <signal.h>
89
#include <stdio.h>
90

91 92 93 94 95 96 97 98 99 100 101 102
/*
** When less than this amount of stackspace is left we
** raise a MemoryError.
*/
#ifndef MINIMUM_STACK_SIZE
#ifdef __powerc
#define MINIMUM_STACK_SIZE 8192
#else
#define MINIMUM_STACK_SIZE 4096
#endif
#endif

103
/*
104
** We have to be careful, since we can't handle
105
** things like updates (and they'll keep coming back if we don't
106 107
** handle them). Note that we don't know who has windows open, so
** even handing updates off to SIOUX under MW isn't going to work.
108
*/
109
#define MAINLOOP_EVENTMASK (mDownMask|keyDownMask|osMask|activMask)
110 111

#include <signal.h>
Jack Jansen's avatar
Jack Jansen committed
112

113
/* XXX We should include Errors.h here, but it has a name conflict
114 115 116
** with the python errors.h. */
#define fnfErr -43

117
/* Declared in macfsmodule.c: */
118
extern FSSpec *mfs_GetFSSpecFSSpec(PyObject *);
119
extern PyObject *newmfssobject(FSSpec *);
120

121 122
/* Interrupt code variables: */
static int interrupted;			/* Set to true when cmd-. seen */
123
static RETSIGTYPE intcatcher(int);
124

125
static int PyMac_Yield(void);
Jack Jansen's avatar
Jack Jansen committed
126

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
/*
** These are the real scheduling parameters that control what we check
** in the event loop, and how often we check. The values are initialized
** from pyMac_SchedParamStruct.
*/

struct real_sched_param_struct {
	int		check_interrupt;	/* if true check for command-dot */
	int		process_events;		/* if nonzero enable evt processing, this mask */
	int		besocial;		/* if nonzero be a little social with CPU */
	unsigned long	check_interval;		/* how often to check, in ticks */
	unsigned long	bg_yield;		/* yield so long when in background */
	/* these are computed from previous and clock and such */
	int		enabled;		/* check_interrupt OR process_event OR yield */
	unsigned long	next_check;		/* when to check/yield next, in ticks */
};

static struct real_sched_param_struct schedparams =
	{ 1, MAINLOOP_EVENTMASK, 1, 15, 15, 1, 0};

Jack Jansen's avatar
Jack Jansen committed
147 148 149 150 151
/*
** Workaround for sioux/gusi combo: set when we are exiting
*/
int PyMac_ConsoleIsDead;

152 153 154 155 156
/*
** Sioux menu bar, saved early so we can restore it
*/
static Handle sioux_mbar;

157 158 159 160 161 162 163
/*
** Some stuff for our GetDirectory and PromptGetFile routines
*/
struct hook_args {
	int selectcur_hit;		/* Set to true when "select current" selected */
	char *prompt;			/* The prompt */
};
164
#if TARGET_API_MAC_CARBON
165 166 167 168 169
/* The StandardFile hooks don't exist in Carbon. This breaks GetDirectory,
** but the macfsn code will replace it by a NavServices version anyway.
*/
#define myhook_upp NULL
#else
170 171
static DlgHookYDUPP myhook_upp;
static int upp_inited = 0;
172
#endif
173

174 175 176 177 178
/*
** The python-code event handler
*/
static PyObject *python_event_handler;

179 180 181 182 183
/*
** Set to true if we're appearance-compliant
*/
int PyMac_AppearanceCompliant;

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
/*
** Find out what the current script is.
** Donated by Fredrik Lund.
*/
char *PyMac_getscript()
{
   int font, script, lang;
    font = 0;
    font = GetSysFont();
    script = FontToScript(font);
    switch (script) {
    case smRoman:
        lang = GetScriptVariable(script, smScriptLang);
        if (lang == langIcelandic)
            return "mac-iceland";
        else if (lang == langTurkish)
            return "mac-turkish";
        else if (lang == langGreek)
            return "mac-greek";
        else
            return "mac-roman";
        break;
    case smJapanese:
        return "mac-japan";
    case smGreek:
        return "mac-greek";
    case smCyrillic:
        return "mac-cyrillic";
    default:
        return "mac-roman"; /* better than nothing */
    }
}


218
#ifdef USE_GUSI1
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
/*
** GUSI (1.6.0 and earlier, at the least) do not set the MacOS idea of
** the working directory. Hence, we call this routine after each call
** to chdir() to rectify things.
*/
void
PyMac_FixGUSIcd()
{
	WDPBRec pb;
	FSSpec curdirfss;
	
	if ( Path2FSSpec(":x", &curdirfss) != noErr ) 
		return;
	
	/* Set MacOS "working directory" */
	pb.ioNamePtr= "\p";
	pb.ioVRefNum= curdirfss.vRefNum;
	pb.ioWDDirID= curdirfss.parID;
237
	if (PBHSetVolSync(&pb) != noErr)
238 239
		return;
}
240
#endif
241

242
#ifdef USE_GUSI
243 244 245 246
/*
** SpinCursor (needed by GUSI) drags in heaps of stuff, so we
** provide a dummy here.
*/
Jack Jansen's avatar
Jack Jansen committed
247
void SpinCursor(short x) { /* Dummy */ }
Jack Jansen's avatar
Jack Jansen committed
248
void RotateCursor(short x) { /* Dummy */ }
Jack Jansen's avatar
Jack Jansen committed
249

Jack Jansen's avatar
Jack Jansen committed
250 251 252
/*
** Replacement GUSI Spin function
*/
253
#ifdef USE_GUSI1
Jack Jansen's avatar
Jack Jansen committed
254 255 256
static int
PyMac_GUSISpin(spin_msg msg, long arg)
{
257 258
	static Boolean	inForeground = true;
	int		maxsleep = 6;	/* 6 ticks is "normal" sleeptime */
Jack Jansen's avatar
Jack Jansen committed
259 260 261 262 263 264 265 266 267

	if (PyMac_ConsoleIsDead) return 0;
#if 0
	if (inForeground)
		SpinCursor(msg == SP_AUTO_SPIN ? short(arg) : 1);
#endif

	if (interrupted) return -1;

268 269 270 271
	if ( msg == SP_AUTO_SPIN )
		maxsleep = 0;
	if ( msg==SP_SLEEP||msg==SP_SELECT )
		maxsleep = arg;
Jack Jansen's avatar
Jack Jansen committed
272

273
	PyMac_DoYield(maxsleep, 0); /* XXXX or is it safe to call python here? */
Jack Jansen's avatar
Jack Jansen committed
274 275 276 277 278 279 280 281

	return 0;
}

void
PyMac_SetGUSISpin() {
	GUSISetHook(GUSI_SpinHook, (GUSIHook)PyMac_GUSISpin);
}
282
#endif
Jack Jansen's avatar
Jack Jansen committed
283

284 285 286 287 288 289 290 291 292 293
/* Called at exit() time thru atexit(), to stop event processing */
void
PyMac_StopGUSISpin() {
	PyMac_ConsoleIsDead = 1;
}

/*
** Replacement routines for the PLstr... functions so we don't need
** StdCLib. Moreover, that implementation is broken under cfm68k...
*/
294
pascal void
295
PLstrcpy(unsigned char *to, unsigned char *fr)
296 297 298 299
{
	memcpy(to, fr, fr[0]+1);
}

300
pascal int
301
PLstrcmp(unsigned char *s1, unsigned char *s2)
302 303 304 305 306 307 308 309
{
	int res;
	int l = s1[0] < s2[0] ? s1[0] : s2[0];
	
	res = memcmp(s1+1, s2+1, l);
	if ( res != 0 )
		return res;
	
310
	if ( s1[0] < s2[0] )
311
		return -1;
312
	else if ( s1[0] > s2[0] )
313 314 315 316 317
		return 1;
	else
		return 0;
}

318
pascal unsigned char *
319
PLstrrchr(unsigned char *str, unsigned char chr)
320 321 322 323 324 325 326 327 328 329 330
{
	unsigned char *ptr = 0;
	unsigned char *p;
	
	for(p=str+1; p<str+str[0]; p++)
		if ( *p == chr )
			ptr = p;
	return ptr;
}
	
#endif /* USE_GUSI */
331

332

333 334 335 336 337 338 339 340
/* Convert C to Pascal string. Returns pointer to static buffer. */
unsigned char *
Pstring(char *str)
{
	static Str255 buf;
	int len;

	len = strlen(str);
341 342
	if (len > 255)
		len = 255;
343 344 345 346 347
	buf[0] = (unsigned char)len;
	strncpy((char *)buf+1, str, len);
	return buf;
}

348 349
/* Like strerror() but for Mac OS error numbers */
char *PyMac_StrError(int err)
Jack Jansen's avatar
Jack Jansen committed
350 351 352 353 354 355 356 357 358 359
{
	static char buf[256];
	Handle h;
	char *str;
	
	h = GetResource('Estr', err);
	if ( h ) {
		HLock(h);
		str = (char *)*h;
		memcpy(buf, str+1, (unsigned char)str[0]);
360
		buf[(unsigned char)str[0]] = '\0';
Jack Jansen's avatar
Jack Jansen committed
361 362 363 364 365 366 367 368
		HUnlock(h);
		ReleaseResource(h);
	} else {
		sprintf(buf, "Mac OS error code %d", err);
	}
	return buf;
}

369 370 371 372 373 374 375 376 377 378 379 380
/* Exception object shared by all Mac specific modules for Mac OS errors */
PyObject *PyMac_OSErrException;

/* Initialize and return PyMac_OSErrException */
PyObject *
PyMac_GetOSErrException()
{
	if (PyMac_OSErrException == NULL)
		PyMac_OSErrException = PyString_FromString("Mac OS Error");
	return PyMac_OSErrException;
}

Jack Jansen's avatar
Jack Jansen committed
381 382
/* Set a MAC-specific error from errno, and return NULL; return None if no error */
PyObject * 
Guido van Rossum's avatar
Guido van Rossum committed
383
PyErr_Mac(PyObject *eobj, int err)
Jack Jansen's avatar
Jack Jansen committed
384 385 386 387
{
	char *msg;
	PyObject *v;
	
388
	if (err == 0 && !PyErr_Occurred()) {
Jack Jansen's avatar
Jack Jansen committed
389 390 391
		Py_INCREF(Py_None);
		return Py_None;
	}
392 393
	if (err == -1 && PyErr_Occurred())
		return NULL;
394
	msg = PyMac_StrError(err);
Jack Jansen's avatar
Jack Jansen committed
395 396 397 398 399 400
	v = Py_BuildValue("(is)", err, msg);
	PyErr_SetObject(eobj, v);
	Py_DECREF(v);
	return NULL;
}

401 402 403 404 405 406 407
/* Call PyErr_Mac with PyMac_OSErrException */
PyObject *
PyMac_Error(OSErr err)
{
	return PyErr_Mac(PyMac_GetOSErrException(), err);
}

408 409 410 411 412
#ifdef USE_STACKCHECK
/* Check for stack overflow */
int
PyOS_CheckStack()
{
413 414
	char here;
	static char *sentinel = 0;
415
	
416 417 418 419
	if ( sentinel == 0 ) {		
		sentinel = &here - StackSpace() + MINIMUM_STACK_SIZE;
	}
	if ( &here < sentinel )
420 421 422 423 424
		return -1;
	return 0;
}
#endif /* USE_STACKCHECK */

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
/* The catcher routine (which may not be used for all compilers) */
static RETSIGTYPE
intcatcher(sig)
	int sig;
{
	interrupted = 1;
	signal(SIGINT, intcatcher);
}

void
PyOS_InitInterrupts()
{
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, intcatcher);
}

441 442 443 444 445
void
PyOS_FiniInterrupts()
{
}

446 447 448 449 450 451 452 453 454 455 456
/*
** This routine scans the event queue looking for cmd-.
** This is the only way to get an interrupt under THINK (since it
** doesn't do SIGINT handling), but is also used under MW, when
** the full-fledged event loop is disabled. This way, we can at least
** interrupt a runaway python program.
*/
static void
scan_event_queue(flush)
	int flush;
{
457
#if TARGET_API_MAC_CARBON
458 459 460
	/* CARBONXXXX To be implemented */
	return;
#else
461 462
	register EvQElPtr q;
	
Jack Jansen's avatar
Jack Jansen committed
463
	q = (EvQElPtr) LMGetEventQueue()->qHead;
464 465 466 467 468 469 470 471 472 473 474
	
	for (; q; q = (EvQElPtr)q->qLink) {
		if (q->evtQWhat == keyDown &&
				(char)q->evtQMessage == '.' &&
				(q->evtQModifiers & cmdKey) != 0) {
			if ( flush )
				FlushEvents(keyDownMask, 0);
			interrupted = 1;
			break;
		}
	}
475
#endif
476 477 478
}

int
479
PyErr_CheckSignals()
480
{
481 482
	if (schedparams.enabled) {
		if ( (unsigned long)LMGetTicks() > schedparams.next_check ) {
483 484
			if ( PyMac_Yield() < 0)
				return -1;
485 486 487
			schedparams.next_check = (unsigned long)LMGetTicks()
					 + schedparams.check_interval;
			if (interrupted) {
488
				scan_event_queue(1);	/* Eat events up to cmd-. */
489
				interrupted = 0;
490 491
				PyErr_SetNone(PyExc_KeyboardInterrupt);
				return -1;
492 493
			}
		}
494 495 496 497
	}
	return 0;
}

498 499 500 501 502 503
int
PyOS_InterruptOccurred()
{
	scan_event_queue(1);
	return interrupted;
}
504
/* Check whether we are in the foreground */
505 506
static int
PyMac_InForeground(void)
507 508 509 510 511 512
{
	static ProcessSerialNumber ours;
	static inited;
	ProcessSerialNumber curfg;
	Boolean eq;
	
513
	if ( inited == 0 ) {
514
		(void)GetCurrentProcess(&ours);
515 516
		inited = 1;
	}
517 518 519 520 521 522 523 524
	if ( GetFrontProcess(&curfg) < 0 )
		eq = 1;
	else if ( SameProcess(&ours, &curfg, &eq) < 0 )
		eq = 1;
	return (int)eq;

}

525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
int
PyMac_SetEventHandler(PyObject *evh)
{
	if ( evh && python_event_handler ) {
		PyErr_SetString(PyExc_RuntimeError, "Python event handler already set");
		return 0;
	}
	if ( python_event_handler )
		Py_DECREF(python_event_handler);
	if ( evh )
		Py_INCREF(evh);
	python_event_handler = evh;
	return 1;
}

540 541 542 543 544
/*
** Handle an event, either one found in the mainloop eventhandler or
** one passed back from the python program.
*/
void
545
PyMac_HandleEventIntern(evp)
546 547
	EventRecord *evp;
{
548
#if !TARGET_API_MAC_CARBON
549 550 551 552 553 554 555 556
	if ( evp->what == mouseDown ) {
		WindowPtr wp;
		
		if ( FindWindow(evp->where, &wp) == inSysWindow ) {
			SystemClick(evp, wp);
			return;
		}
	}
557
#endif
558
#ifdef __MWERKS__
559 560 561 562 563 564 565 566
	{
		int siouxdidit;

		/* If SIOUX wants it we're done */
		siouxdidit = SIOUXHandleOneEvent(evp);
		if ( siouxdidit )
			return;
	}
567
#else
568
	/* Other compilers are just unlucky... */
569
#endif /* !__MWERKS__ */
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
}

/*
** Handle an event, either through HandleEvent or by passing it to the Python
** event handler.
*/
int
PyMac_HandleEvent(evp)
	EventRecord *evp;
{
	PyObject *rv;
	
	if ( python_event_handler ) {
		rv = PyObject_CallFunction(python_event_handler, "(O&)", 
			PyMac_BuildEventRecord, evp);
		if ( rv )
			Py_DECREF(rv);
		else
			return -1;	/* Propagate exception */
	} else {
		PyMac_HandleEventIntern(evp);
	}
	return 0;
593 594
}

595
/*
596
** Yield the CPU to other tasks without processing events.
597
*/
598
int
599
PyMac_DoYield(int maxsleep, int maycallpython)
Jack Jansen's avatar
Jack Jansen committed
600 601
{
	EventRecord ev;
602
	int gotone;
603
	long latest_time_ready;
604
	static int in_here = 0;
605
	
606
	in_here++;
607 608 609 610 611 612
	/*
	** First check for interrupts, if wanted.
	** This sets a flag that will be picked up at an appropriate
	** moment in the mainloop.
	*/
	if (schedparams.check_interrupt)
613
		scan_event_queue(0);
614 615
	
	/* XXXX Implementing an idle routine goes here */
Jack Jansen's avatar
Jack Jansen committed
616
		
617 618 619 620 621 622
	/*
	** Check which of the eventloop cases we have:
	** - process events
	** - don't process events but do yield
	** - do neither
	*/
623 624
	if( in_here > 1 || !schedparams.process_events || 
	    (python_event_handler && !maycallpython) ) {
625
#if !TARGET_API_MAC_CARBON
626
		if ( maxsleep >= 0 ) {
627
			SystemTask();
628
		}
629
#endif
630 631
	} else {
		latest_time_ready = LMGetTicks() + maxsleep;
632
		do {
633 634 635 636 637
			/* XXXX Hack by Jack.
			** In time.sleep() you can click to another application
			** once only. If you come back to Python you cannot get away
			** again.
			**/
638
			gotone = WaitNextEvent(schedparams.process_events, &ev, maxsleep, NULL);	
639 640 641
			/* Get out quickly if nothing interesting is happening */
			if ( !gotone || ev.what == nullEvent )
				break;
642 643 644 645
			if ( PyMac_HandleEvent(&ev) < 0 ) {
				in_here--;
				return -1;
			}
646
			maxsleep = latest_time_ready - LMGetTicks();
647
		} while ( maxsleep > 0 );
Jack Jansen's avatar
Jack Jansen committed
648
	}
649 650
	in_here--;
	return 0;
651 652 653
}

/*
654
** Process events and/or yield the CPU to other tasks if opportune
655
*/
656
int
657
PyMac_Yield() {
658
	unsigned long maxsleep;
659
	
660 661
	if( PyMac_InForeground() )
		maxsleep = 0;
662
	else
663 664
		maxsleep = schedparams.bg_yield;

665
	return PyMac_DoYield(maxsleep, 1);
666 667 668
}

/*
669
** Return current scheduler parameters
670
*/
671 672
void
PyMac_GetSchedParams(PyMacSchedParams *sp)
673
{
674 675 676 677 678
	sp->check_interrupt = schedparams.check_interrupt;
	sp->process_events = schedparams.process_events;
	sp->besocial = schedparams.besocial;
	sp->check_interval = schedparams.check_interval / 60.0;
	sp->bg_yield = schedparams.bg_yield / 60.0;
Jack Jansen's avatar
Jack Jansen committed
679
}
Jack Jansen's avatar
Jack Jansen committed
680

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
/*
** Set current scheduler parameters
*/
void
PyMac_SetSchedParams(PyMacSchedParams *sp)
{
	schedparams.check_interrupt = sp->check_interrupt;
	schedparams.process_events = sp->process_events;
	schedparams.besocial = sp->besocial;
	schedparams.check_interval = (unsigned long)(sp->check_interval*60);
	schedparams.bg_yield = (unsigned long)(sp->bg_yield*60);
	if ( schedparams.check_interrupt || schedparams.process_events ||
	     schedparams.besocial )
	     	schedparams.enabled = 1;
	else
		schedparams.enabled = 0;
	schedparams.next_check = 0;	/* Check immedeately */
}
699

700 701 702 703 704 705 706 707
/*
** Install our menu bar.
*/
void
PyMac_InitMenuBar()
{
	MenuHandle applemenu;
	
708 709 710 711 712 713
	if ( (sioux_mbar=GetMenuBar()) == NULL )  {
		/* Sioux menu not installed yet. Do so */
		SIOUXSetupMenus();
		if ( (sioux_mbar=GetMenuBar()) == NULL )
			return;
	}
714
	if ( (applemenu=GetMenuHandle(SIOUX_APPLEID)) == NULL ) return;
715 716 717
	SetMenuItemText(applemenu, 1, "\pAbout Python...");
}

718 719 720 721 722 723
/*
** Restore sioux menu bar
*/
void
PyMac_RestoreMenuBar()
{
724
	if ( sioux_mbar ) {
725
		SetMenuBar(sioux_mbar);
726
		DrawMenuBar();
Jack Jansen's avatar
Jack Jansen committed
727 728
	} else
		PyMac_InitMenuBar();
729 730 731
}


732 733 734
/*
** Our replacement about box
*/
735 736 737

#include "patchlevel.h"

738 739 740 741
void
SIOUXDoAboutBox(void)
{
	DialogPtr theDialog;
742
	WindowPtr theWindow;
743
	short item;
744
	short fontID;
745 746 747
	
	if( (theDialog = GetNewDialog(ABOUT_ID, NULL, (WindowPtr)-1)) == NULL )
		return;
748
	theWindow = GetDialogWindow(theDialog);
749 750 751 752 753 754 755
	SetPortWindowPort(theWindow);
	GetFNum("\pPython-Sans", &fontID);
	if (fontID == 0)
		fontID = kFontIDGeneva;
	TextFont(fontID);
	TextSize(9);
	ParamText(Pstring(PATCHLEVEL), "\p", "\p", "\p");
756
	ShowWindow(theWindow);
757 758 759 760
	ModalDialog(NULL, &item);
	DisposeDialog(theDialog);
}

761 762 763 764 765 766 767 768 769 770 771 772
#if 0
int
PyMac_FileExists(char *name)
{
	FSSpec fss;
	
	if ( FSMakeFSSpec(0, 0, Pstring(name), &fss) == noErr )
		return 1;
	return 0;
}
#endif

773 774 775
/*
** Helper routine for GetDirectory
*/
776
static pascal short
777
myhook_proc(short item, DialogPtr theDialog, struct hook_args *dataptr)
778
{
779 780 781 782 783 784 785 786 787
	if ( item == sfHookFirstCall && dataptr->prompt) {
		Handle prompth;
		short type;
		Rect rect;
		
		GetDialogItem(theDialog, PROMPT_ITEM, &type, &prompth, &rect);
		if ( prompth )
			SetDialogItemText(prompth, (unsigned char *)dataptr->prompt);
	} else
788 789
	if ( item == SELECTCUR_ITEM ) {
		item = sfItemCancelButton;
790
		dataptr->selectcur_hit = 1;
791 792 793
	}
	return item;
}	
794
#if !TARGET_API_MAC_CARBON
795 796 797 798 799
/*
** Ask the user for a directory. I still can't understand
** why Apple doesn't provide a standard solution for this...
*/
int
800
PyMac_GetDirectory(dirfss, prompt)
801
	FSSpec *dirfss;
802
	char *prompt;
803 804 805 806
{
	static SFTypeList list = {'fldr', 0, 0, 0};
	static Point where = {-1, -1};
	StandardFileReply reply;
807
	struct hook_args hook_args;
808 809 810 811 812
	
	if ( !upp_inited ) {
		myhook_upp = NewDlgHookYDProc(myhook_proc);
		upp_inited = 1;
	}
813 814 815 816 817
	if ( prompt && *prompt )
		hook_args.prompt = (char *)Pstring(prompt);
	else
		hook_args.prompt = NULL;
	hook_args.selectcur_hit = 0;
818
	CustomGetFile((FileFilterYDUPP)0, 1, list, &reply, GETDIR_ID, where, myhook_upp,
819
				NULL, NULL, NULL, (void *)&hook_args);
820 821 822 823
				
	reply.sfFile.name[0] = 0;
	if( FSMakeFSSpec(reply.sfFile.vRefNum, reply.sfFile.parID, reply.sfFile.name, dirfss) )
		return 0;
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
	return hook_args.selectcur_hit;
}

/*
** Slightly extended StandardGetFile: accepts a prompt */
void PyMac_PromptGetFile(short numTypes, ConstSFTypeListPtr typeList, 
		StandardFileReply *reply, char *prompt)
{
	static Point where = {-1, -1};
	struct hook_args hook_args;
	
	if ( !upp_inited ) {
		myhook_upp = NewDlgHookYDProc(myhook_proc);
		upp_inited = 1;
	}
	if ( prompt && *prompt )
		hook_args.prompt = (char *)Pstring(prompt);
	else
		hook_args.prompt = NULL;
	hook_args.selectcur_hit = 0;
	CustomGetFile((FileFilterYDUPP)0, numTypes, typeList, reply, GETFILEPROMPT_ID, where,
				myhook_upp, NULL, NULL, NULL, (void *)&hook_args);
846
}
847
#endif /* TARGET_API_MAC_CARBON */
848

849
/* Convert a 4-char string object argument to an OSType value */
850
int
851
PyMac_GetOSType(PyObject *v, OSType *pr)
852 853 854 855 856 857 858 859 860 861
{
	if (!PyString_Check(v) || PyString_Size(v) != 4) {
		PyErr_SetString(PyExc_TypeError,
			"OSType arg must be string of 4 chars");
		return 0;
	}
	memcpy((char *)pr, PyString_AsString(v), 4);
	return 1;
}

862 863 864 865 866 867 868
/* Convert an OSType value to a 4-char string object */
PyObject *
PyMac_BuildOSType(OSType t)
{
	return PyString_FromStringAndSize((char *)&t, 4);
}

869 870 871 872 873 874 875
/* Convert an NumVersion value to a 4-element tuple */
PyObject *
PyMac_BuildNumVersion(NumVersion t)
{
	return Py_BuildValue("(hhhh)", t.majorRev, t.minorAndBugRev, t.stage, t.nonRelRev);
}

876 877

/* Convert a Python string object to a Str255 */
878
int
879
PyMac_GetStr255(PyObject *v, Str255 pbuf)
880 881 882 883 884 885 886 887 888 889 890 891
{
	int len;
	if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
		PyErr_SetString(PyExc_TypeError,
			"Str255 arg must be string of at most 255 chars");
		return 0;
	}
	pbuf[0] = len;
	memcpy((char *)(pbuf+1), PyString_AsString(v), len);
	return 1;
}

892 893 894 895
/* Convert a Str255 to a Python string object */
PyObject *
PyMac_BuildStr255(Str255 s)
{
896 897 898 899 900 901 902 903 904 905 906 907 908 909
	if ( s == NULL ) {
		PyErr_SetString(PyExc_SystemError, "Str255 pointer is NULL");
		return NULL;
	}
	return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
}

PyObject *
PyMac_BuildOptStr255(Str255 s)
{
	if ( s == NULL ) {
		Py_INCREF(Py_None);
		return Py_None;
	}
910 911 912 913
	return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
}


914
/*
915 916 917
** Convert a Python object to an FSSpec.
** The object may either be a full pathname or a triple
** (vrefnum, dirid, path).
918 919 920 921 922 923
** NOTE: This routine will fail on pre-sys7 machines. 
** The caller is responsible for not calling this routine
** in those cases (which is fine, since everyone calling
** this is probably sys7 dependent anyway).
*/
int
924
PyMac_GetFSSpec(PyObject *v, FSSpec *fs)
925 926 927 928 929
{
	Str255 path;
	short refnum;
	long parid;
	OSErr err;
930
	FSSpec *fs2;
931

932 933 934
	/* first check whether it already is an FSSpec */
	fs2 = mfs_GetFSSpecFSSpec(v);
	if ( fs2 ) {
935
		(void)FSMakeFSSpec(fs2->vRefNum, fs2->parID, fs2->name, fs);
936 937
		return 1;
	}
938 939
	if ( PyString_Check(v) ) {
		/* It's a pathname */
940
		if( !PyArg_Parse(v, "O&", PyMac_GetStr255, &path) )
941
			return 0;
942
		refnum = 0; /* XXXX Should get CurWD here?? */
943 944
		parid = 0;
	} else {
945 946
		if( !PyArg_Parse(v, "(hlO&); FSSpec should be fullpath or (vrefnum,dirid,path)",
							&refnum, &parid, PyMac_GetStr255, &path)) {
947
			return 0;
948
		}
949 950 951
	}
	err = FSMakeFSSpec(refnum, parid, path, fs);
	if ( err && err != fnfErr ) {
952
		PyMac_Error(err);
953 954 955 956 957
		return 0;
	}
	return 1;
}

958 959 960 961 962
/* Convert FSSpec to PyObject */
PyObject *PyMac_BuildFSSpec(FSSpec *v)
{
	return newmfssobject(v);
}
963

964
/* Convert a Python object to a Rect.
965 966 967
   The object must be a (left, top, right, bottom) tuple.
   (This differs from the order in the struct but is consistent with
   the arguments to SetRect(), and also with STDWIN). */
968 969 970
int
PyMac_GetRect(PyObject *v, Rect *r)
{
971
	return PyArg_Parse(v, "(hhhh)", &r->left, &r->top, &r->right, &r->bottom);
972 973 974
}

/* Convert a Rect to a Python object */
975
PyObject *
976
PyMac_BuildRect(Rect *r)
977
{
978
	return Py_BuildValue("(hhhh)", r->left, r->top, r->right, r->bottom);
979 980 981 982
}


/* Convert a Python object to a Point.
983 984 985
   The object must be a (h, v) tuple.
   (This differs from the order in the struct but is consistent with
   the arguments to SetPoint(), and also with STDWIN). */
986 987 988
int
PyMac_GetPoint(PyObject *v, Point *p)
{
989
	return PyArg_Parse(v, "(hh)", &p->h, &p->v);
990
}
991

992
/* Convert a Point to a Python object */
993
PyObject *
994
PyMac_BuildPoint(Point p)
995
{
996
	return Py_BuildValue("(hh)", p.h, p.v);
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
}


/* Convert a Python object to an EventRecord.
   The object must be a (what, message, when, (v, h), modifiers) tuple. */
int
PyMac_GetEventRecord(PyObject *v, EventRecord *e)
{
	return PyArg_Parse(v, "(hll(hh)h)",
	                   &e->what,
	                   &e->message,
	                   &e->when,
	                   &e->where.h,
1010
	                   &e->where.v,                   
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
	                   &e->modifiers);
}

/* Convert a Rect to an EventRecord object */
PyObject *
PyMac_BuildEventRecord(EventRecord *e)
{
	return Py_BuildValue("(hll(hh)h)",
	                     e->what,
	                     e->message,
	                     e->when,
	                     e->where.h,
1023
	                     e->where.v,
1024
	                     e->modifiers);
1025
}
Jack Jansen's avatar
Jack Jansen committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

/* Convert Python object to Fixed */
int
PyMac_GetFixed(PyObject *v, Fixed *f)
{
	double d;
	
	if( !PyArg_Parse(v, "d", &d))
		return 0;
	*f = (Fixed)(d * 0x10000);
1036
	return 1;
Jack Jansen's avatar
Jack Jansen committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
}

/* Convert a Point to a Python object */
PyObject *
PyMac_BuildFixed(Fixed f)
{
	double d;
	
	d = f;
	d = d / 0x10000;
	return Py_BuildValue("d", d);
}

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
/* Convert wide to/from Python int or (hi, lo) tuple. XXXX Should use Python longs */
int
PyMac_Getwide(PyObject *v, wide *rv)
{
	if (PyInt_Check(v)) {
		rv->hi = 0;
		rv->lo = PyInt_AsLong(v);
		if( rv->lo & 0x80000000 )
			rv->hi = -1;
		return 1;
	}
	return PyArg_Parse(v, "(ll)", &rv->hi, &rv->lo);
}


PyObject *
1066
PyMac_Buildwide(wide *w)
1067
{
1068 1069 1070 1071
	if ( (w->hi == 0 && (w->lo & 0x80000000) == 0) ||
	     (w->hi == -1 && (w->lo & 0x80000000) ) )
		return PyInt_FromLong(w->lo);
	return Py_BuildValue("(ll)", w->hi, w->lo);
1072
}