/*
 * LaunchApp.c
 */
 /*
 * Copyright (C) 1985-1992  New York University
 * Copyright (C) 1994 George Washington University
 * 
 * This file is part of the GWAdaEd system, an extension of the Ada/Ed-C
 * system.  See the Ada/Ed README file for warranty (none) and distribution
 * info and also the GNU General Public License for more details.
 */


#include "LaunchApp.h"
#include <AppleEvents.h>

OSErr LaunchAnApplication(FSSpec sfFile, Boolean front, ProcessSerialNumber *psn)
{
LaunchParamBlockRec myLaunchParam;
ProcessSerialNumber launchedProcessSN;
OSErr launchErr;
long prefSize;
long minSize;
long availSize;

	myLaunchParam.launchBlockID = extendedBlock;
	myLaunchParam.launchEPBLength = extendedBlockLen;
	myLaunchParam.launchFileFlags = 0;
	if (front)
		myLaunchParam.launchControlFlags = launchContinue + launchNoFileFlags;
	else
		myLaunchParam.launchControlFlags = launchContinue + launchNoFileFlags
										+ launchDontSwitch;
	myLaunchParam.launchAppSpec = &sfFile;
	myLaunchParam.launchAppParameters = NULL;
	
	launchErr = LaunchApplication(&myLaunchParam);
	
	prefSize = myLaunchParam.launchPreferredSize;
	minSize = myLaunchParam.launchMinimumSize;
	if (launchErr == noErr) {
		launchedProcessSN = myLaunchParam.launchProcessSN;
	}
	else if (launchErr == memFullErr) {
		availSize = myLaunchParam.launchAvailableSize;
	}
	/* else do_error() */

	*psn = launchedProcessSN;
	return launchErr;
}

Boolean StillGoing(ProcessSerialNumber psn)
{
ProcessInfoRec info;
OSErr err;

	info.processName = NULL;
	info.processAppSpec = NULL;
	info.processInfoLength = sizeof(ProcessInfoRec);
	err = GetProcessInformation(&psn, &info);
	return (err == noErr);
}

Boolean TerminateAnApplication(ProcessSerialNumber psn)
{
AEAddressDesc theDoomed;	/* PSN descriptor of process to be terminated */
AppleEvent quitEvent;		/* 'quit' AppleEvent */
AppleEvent reply;			/* Reply from receiving application; ignored */
OSErr error;

	theDoomed.dataHandle = NULL;
	quitEvent.dataHandle = NULL;
	reply.dataHandle = NULL;
	
	/* Create the Process Serial Number event descriptor */
	error = AECreateDesc(typeProcessSerialNumber, (Ptr)&psn, sizeof(psn), &theDoomed);
	if (error != noErr)
		return false;
	
	/* Create 'quit' event with the specified process serial number */
	error = AECreateAppleEvent(kCoreEventClass, kAEQuitApplication, &theDoomed,
		 kAutoGenerateReturnID, kAnyTransactionID, &quitEvent);
	if (error != noErr)
		return false;
	
	/* Send the 'quit' event */
	error = AESend(&quitEvent, &reply, kAENoReply, kAENormalPriority,
		kNoTimeOut, NULL, NULL);
	if (error != noErr)
		return false;
	
	/* PSN in the AppleEvent, so can dispose of PSN descriptor */
	error = AEDisposeDesc(&theDoomed);
	
	/* Dispose of the 'quit' AppleEvent */
	error = AEDisposeDesc(&quitEvent);

	return true;
}

