macgetpath.c 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/***********************************************************
Copyright 1991-1997 by Stichting Mathematisch Centrum, Amsterdam,
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 or Corporation for National Research Initiatives or
CNRI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address ftp://ftp.python.org.

STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI 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.

******************************************************************/

32 33
#include "Python.h"
#include "osdefs.h"
34
#include "macglue.h"
35
#include "macdefs.h"
36
#include "pythonresources.h"
37 38 39
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
40

41
#define PATHNAMELEN 256
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

/* Return the initial python search path.  This is called once from
** initsys() to initialize sys.path.
**
** If USE_BUILTIN_PATH is defined the path defined here is used
** (after prepending the python home dir to each item).
** If it is not defined the path is gotten from a resource in the
** Preferences file.
**
** XXXX This code needs cleaning up. The routines here have moved
** around quite a bit, and they're pretty messy for that reason.
*/

#include <Files.h>
#include <Aliases.h>
#include <Folders.h>
#include <Resources.h>
#include <TextUtils.h>
60
#include <Dialogs.h>
61

62
#ifndef USE_BUILTIN_PATH
63
static char *PyMac_GetPythonPath();
64 65
#endif

66 67 68 69 70 71 72
#define PYTHONPATH "\
:\n\
:Lib\n\
:Lib:stdwin\n\
:Lib:test\n\
:Lib:mac"

73
static int
74 75 76
getpreffilefss(FSSpec *fssp)
{
	static int diditbefore=0;
77
	static int rv = 1;
78
	static FSSpec fss;
79 80
	short prefdirRefNum;
	long prefdirDirID;
81
	long pyprefdirDirID;
82
	Handle namehandle;
83
	OSErr err;
84 85 86 87 88 89 90 91 92 93 94 95
	
	if ( !diditbefore ) {
		if ( (namehandle=GetNamedResource('STR ', PREFFILENAME_NAME)) == NULL ) {
			(void)StopAlert(NOPREFNAME_ID, NULL);
			exit(1);
		}
		
		if ( **namehandle == '\0' ) {
			/* Empty string means don't use preferences file */
			rv = 0;
		} else {
			/* There is a filename, construct the fsspec */
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
			if ( FindFolder(kOnSystemDisk, 'pref', kDontCreateFolder, &prefdirRefNum,
							&prefdirDirID) != noErr ) {
				/* Something wrong with preferences folder */
				(void)StopAlert(NOPREFDIR_ID, NULL);
				exit(1);
			}
			/* make fsspec for the "Python" folder inside the prefs folder */
			err = FSMakeFSSpec(prefdirRefNum, prefdirDirID, "\pPython", &fss);
			if (err == fnfErr) {
				/* it doesn't exist: create it */
				err = FSpDirCreate(&fss, smSystemScript, &pyprefdirDirID);
			} else {
				/* it does exist, now find out the dirID of the Python prefs folder, brrr. */
				CInfoPBRec info;
				info.dirInfo.ioVRefNum 		= fss.vRefNum;
				info.dirInfo.ioDrDirID 		= fss.parID;
				info.dirInfo.ioNamePtr 		= fss.name;
				info.dirInfo.ioFDirIndex 	= 0;
				info.dirInfo.ioACUser 		= 0;
				err = PBGetCatInfo(&info, 0);
				if (err == noErr) {
					pyprefdirDirID = info.dirInfo.ioDrDirID;
				}
			}
			if (err != noErr) {
				(void)StopAlert(NOPREFDIR_ID, NULL);
				exit(1);
			}
			HLock(namehandle);
			err = FSMakeFSSpec(fss.vRefNum, pyprefdirDirID, (unsigned char *)*namehandle, &fss);
			HUnlock(namehandle);
			if (err != noErr && err != fnfErr) {
				(void)StopAlert(NOPREFDIR_ID, NULL);
				exit(1);
			}
131
		}
132 133 134 135
		ReleaseResource(namehandle);
		diditbefore = 1;
	}
	*fssp = fss;
136
	return rv;
137
}
138 139

char *
140
Py_GetPath()
141 142 143 144 145 146 147 148 149
{
	/* Modified by Jack to do something a bit more sensible:
	** - Prepend the python home-directory (which is obtained from a Preferences
	**   resource)
	** - Add :
	*/
	static char *pythonpath;
	char *p, *endp;
	int newlen;
150
	char *curwd;
151 152 153
	
	if ( pythonpath ) return pythonpath;
#ifndef USE_BUILTIN_PATH
154
	if ( pythonpath = PyMac_GetPythonPath() )
155 156 157
		return pythonpath;
	printf("Warning: No pythonpath resource found, using builtin default\n");
#endif
158
	curwd = PyMac_GetPythonDir();
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	p = PYTHONPATH;
	endp = p;
	pythonpath = malloc(2);
	if ( pythonpath == NULL ) return PYTHONPATH;
	strcpy(pythonpath, ":");
	while (*endp) {
		endp = strchr(p, '\n');
		if ( endp == NULL )
			endp = p + strlen(p);
		newlen = strlen(pythonpath) + 1 + strlen(curwd) + (endp-p);
		pythonpath = realloc(pythonpath, newlen+1);
		if ( pythonpath == NULL ) return PYTHONPATH;
		strcat(pythonpath, "\n");
		if ( *p == ':' ) {
			p++;
			strcat(pythonpath, curwd);
			strncat(pythonpath, p, (endp-p));
			newlen--;   /* Ok, ok, we've allocated one byte too much */
		} else {
			/* We've allocated too much in this case */
			newlen -= strlen(curwd);
			pythonpath = realloc(pythonpath, newlen+1);
			if ( pythonpath == NULL ) return PYTHONPATH;
			strncat(pythonpath, p, (endp-p));
		}
		pythonpath[newlen] = '\0';
		p = endp + 1;
	}
	return pythonpath;
}

190

191 192 193
/*
** Open/create the Python Preferences file, return the handle
*/
194
short
195 196
PyMac_OpenPrefFile()
{
197 198 199 200
	AliasHandle handle;
	FSSpec dirspec;
	short prefrh;
	OSErr err;
201

202 203
	if ( !getpreffilefss(&dirspec))
		return -1;
204 205
	prefrh = FSpOpenResFile(&dirspec, fsRdWrShPerm);
	if ( prefrh < 0 ) {
206
		FSpCreateResFile(&dirspec, 'Pyth', 'pref', 0);
207 208 209
		prefrh = FSpOpenResFile(&dirspec, fsRdWrShPerm);
		if ( prefrh == -1 ) {
			/* This "cannot happen":-) */
210
			printf("Cannot create preferences file, error %d\n", ResError());
211 212
			exit(1);
		}
213 214
		if ( (err=PyMac_init_process_location()) != 0 ) {
			printf("Cannot get application location, error %d\n", err);
215 216
			exit(1);
		}
217
		dirspec = PyMac_ApplicationFSSpec;
218
		dirspec.name[0] = 0;
219 220
		if ((err=NewAlias(NULL, &dirspec, &handle)) != 0 ) {
			printf("Cannot make alias to application directory, error %d\n", err);
221 222
			exit(1);
		}
223 224
		AddResource((Handle)handle, 'alis', PYTHONHOME_ID, "\p");
		UpdateResFile(prefrh);
225 226 227 228 229 230

	} else {
		UseResFile(prefrh);
	}
	return prefrh;
}
231 232 233 234

/*
** Return the name of the Python directory
*/
235
char *
236 237
PyMac_GetPythonDir()
{
238
	static int diditbefore = 0;
239
	static char name[PATHNAMELEN] = {':', '\0'};
240 241 242 243 244 245 246 247 248
	AliasHandle handle;
	FSSpec dirspec;
	Boolean modified = 0;
	short oldrh, prefrh = -1, homerh;
	
	if ( diditbefore )
		return name;
		
	oldrh = CurResFile();
249

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
	/* First look for an override in the application file */
	UseResFile(PyMac_AppRefNum);
	handle = (AliasHandle)Get1Resource('alis', PYTHONHOMEOVERRIDE_ID);
	UseResFile(oldrh);
	if ( handle != NULL ) {
		homerh = PyMac_AppRefNum;
	} else {   
		/* Try to open preferences file in the preferences folder. */
		prefrh = PyMac_OpenPrefFile();
		handle = (AliasHandle)Get1Resource('alis', PYTHONHOME_ID);
		if ( handle == NULL ) {
			/* (void)StopAlert(BADPREFFILE_ID, NULL); */
			diditbefore=1;
			return ":";
		}
		homerh = prefrh;
	}
	/* It exists. Resolve it (possibly updating it) */
	if ( ResolveAlias(NULL, handle, &dirspec, &modified) != noErr ) {
		(void)StopAlert(BADPREFFILE_ID, NULL);
		diditbefore=1;
		return ":";
	}
	if ( modified ) {
274
   		ChangedResource((Handle)handle);
275 276 277 278
		UpdateResFile(homerh);
	}
	if ( prefrh != -1 ) CloseResFile(prefrh);
	UseResFile(oldrh);
279

280
   	if ( PyMac_GetFullPathname(&dirspec, name, PATHNAMELEN) == 0 ) {
281
   		strcat(name, ":");
282
	} else {
283 284
 		/* If all fails, we return the current directory */
   		printf("Python home dir exists but I cannot find the pathname!!\n");
285
		name[0] = 0;
286
		(void)getcwd(name, sizeof(name));
287
	}
288
	diditbefore = 1;
289 290 291 292
	return name;
}

#ifndef USE_BUILTIN_PATH
293
char *
294
PyMac_GetPythonPath(void)
295
{
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
	short oldrh, prefrh = -1;
	char *rv;
	int i, newlen;
	Str255 pathitem;
	int resource_id;
	OSErr err;
	Handle h;
	
	oldrh = CurResFile();
	/*
	** This is a bit tricky. We check here whether the application file
	** contains an override. This is to forestall us finding another STR# resource
	** with "our" id and using that for path initialization
	*/
	UseResFile(PyMac_AppRefNum);
	SetResLoad(0);
	if ( (h=Get1Resource('STR#', PYTHONPATHOVERRIDE_ID)) ) {
		ReleaseResource(h);
		resource_id = PYTHONPATHOVERRIDE_ID;
	} else {
		resource_id = PYTHONPATH_ID;
	}
	SetResLoad(1);
	UseResFile(oldrh);
	
	/* Open the preferences file only if there is no override */
	if ( resource_id != PYTHONPATHOVERRIDE_ID )
		prefrh = PyMac_OpenPrefFile();
	/* At this point, we may or may not have the preferences file open, and it
	** may or may not contain a sys.path STR# resource. We don't care, if it doesn't
	** exist we use the one from the application (the default).
	** We put an initial '\n' in front of the path that we don't return to the caller
	*/
	if( (rv = malloc(2)) == NULL )
		goto out;
	strcpy(rv, "\n");
332

333 334 335 336 337 338 339 340 341 342 343 344 345 346
	for(i=1; ; i++) {
		GetIndString(pathitem, resource_id, i);
		if( pathitem[0] == 0 )
			break;
		if ( pathitem[0] >= 9 && strncmp((char *)pathitem+1, "$(PYTHON)", 9) == 0 ) {
			/* We have to put the directory in place */
			char *dir = PyMac_GetPythonDir();
			
			newlen = strlen(rv) + strlen(dir) + (pathitem[0]-9) + 2;
			if( (rv=realloc(rv, newlen)) == NULL)
				goto out;
			strcat(rv, dir);
			/* Skip a colon at the beginning of the item */
			if ( pathitem[0] > 9 && pathitem[1+9] == ':' ) {
347 348 349 350 351
				memcpy(rv+strlen(rv), pathitem+1+10, pathitem[0]-10);
				newlen--;
			} else {
				memcpy(rv+strlen(rv), pathitem+1+9, pathitem[0]-9);
			}
352 353 354 355
			rv[newlen-2] = '\n';
			rv[newlen-1] = 0;
		} else if ( pathitem[0] >= 14 && strncmp((char *)pathitem+1, "$(APPLICATION)", 14) == 0 ) {
			/* This is the application itself */
356
			
357
			if ( (err=PyMac_init_process_location()) != 0 ) {
358
				printf("Cannot get  application location, error %d\n", err);
359 360
				exit(1);
			}
361 362

			newlen = strlen(rv) + strlen(PyMac_ApplicationPath) + 2;
363 364 365 366 367
			if( (rv=realloc(rv, newlen)) == NULL)
				goto out;
			strcpy(rv+strlen(rv), PyMac_ApplicationPath);
			rv[newlen-2] = '\n';
			rv[newlen-1] = 0;
368

369 370 371 372 373 374 375 376 377
		} else {
			/* Use as-is */
			newlen = strlen(rv) + (pathitem[0]) + 2;
			if( (rv=realloc(rv, newlen)) == NULL)
				goto out;
			memcpy(rv+strlen(rv), pathitem+1, pathitem[0]);
			rv[newlen-2] = '\n';
			rv[newlen-1] = 0;
		}
378 379 380 381 382 383 384 385 386 387
	}
	if( strlen(rv) == 1) {
		free(rv);
		rv = NULL;
	}
	if ( rv ) {
		rv[strlen(rv)-1] = 0;
		rv++;
	}
out:
388 389
	if ( prefrh != -1) CloseResFile(prefrh);
	UseResFile(oldrh);
390 391 392 393
	return rv;
}
#endif /* !USE_BUILTIN_PATH */

394
void
395
PyMac_PreferenceOptions(PyMac_PrefRecord *pr)
396
{
397
	short oldrh, prefrh = -1;
398 399
	Handle handle;
	int size;
400 401
	PyMac_PrefRecord *p;
	int action;
402 403
	
	
404 405 406 407 408 409 410 411 412 413 414
	oldrh = CurResFile();
	
	/* Attempt to load overrides from application */
	UseResFile(PyMac_AppRefNum);
	handle = Get1Resource('Popt', PYTHONOPTIONSOVERRIDE_ID);
	UseResFile(oldrh);
	
	/* Otherwise get options from prefs file or any other open resource file */
	if ( handle == NULL ) {
		prefrh = PyMac_OpenPrefFile();
		handle = GetResource('Popt', PYTHONOPTIONS_ID);
415
	}
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
	if ( handle == NULL ) {
		return;
	}
	HLock(handle);
	size = GetHandleSize(handle);
	p = (PyMac_PrefRecord *)*handle;
	if ( p->version == POPT_VERSION_CURRENT && size == sizeof(PyMac_PrefRecord) ) {
		*pr = *p;
	} else {
		action = CautionAlert(BADPREFERENCES_ID, NULL);
		if ( action == BADPREF_DELETE ) {
			OSErr err;
			
			RemoveResource(handle);
			if ( (err=ResError()) ) printf("RemoveResource: %d\n", err);
			if ( prefrh != -1 ) {
				UpdateResFile(prefrh);
				if ( (err=ResError()) ) printf("UpdateResFile: %d\n", err);
			}
		} else if ( action == BADPREF_QUIT )
			exit(1);
	}
	HUnlock(handle);
439

440
   	if ( prefrh != -1) CloseResFile(prefrh);
441
	UseResFile(oldrh);
442
}