#include "utils.h"
#include "defines.h"
#include <ctype.h>
#include <string.h>

short RectWidth(Rect *r)
{
	return r->right - r->left;
}

short RectHeight(Rect *r)
{
	return r->bottom - r->top;
}

void CenterWindow(WindowPtr win)
{
	short barHeight = GetMBarHeight() * 2; // menu + title bar
	short screenWidth = RectWidth(&qd.screenBits.bounds);
	short screenHeight = RectHeight(&qd.screenBits.bounds) - barHeight;
	short winWidth = RectWidth(&win->portRect);
	short winHeight = RectHeight(&win->portRect);

	MoveWindow(win, (screenWidth - winWidth) / 2, barHeight + (screenHeight - winHeight) / 2, false);
}

void GcDie(const char *error)
{
	paramtext(error, nil, nil, nil);
	StopAlert(kBaseRes, nil);
	ExitToShell();
}

void GcWarn(const char *warn)
{
	paramtext(warn, nil, nil, nil);
	CautionAlert(kBaseRes, nil);
}

void GcInfo(const char *info)
{
	paramtext(info, nil, nil, nil);
	NoteAlert(kBaseRes, nil);
}

void str2cpy(char *dst, const char *src, size_t len)
{
	if (len == 0)
		return;

	while (--len && *src)
	{
		*dst++ = *src++;
	}
	*dst = 0;
}

void GcStripTrailingWhitespace(char *str)
{
	size_t len = strlen(str);
	for (int i = len - 1; i >= 0; i--)
	{
		if (isspace(str[i]))
		{
			str[i] = 0;
		}
		else
		{
			break;
		}
	}
}

OSStatus GcIsAppearancePresent(Boolean *haveAppearance)
{
	OSStatus err = noErr;

	long response;

	// Attempt to call Gestalt; if we succeed, test for presence of Appearance Mgr
	if (!(err = Gestalt(gestaltAppearanceAttr, &response)))
		*haveAppearance = response & (1 << gestaltAppearanceExists) ? true : false;
	// If the Appearance Mgr selector is undefined, the Appearance Mgr is not present
	else if (err == gestaltUndefSelectorErr)
	{
		*haveAppearance = false;
		err = noErr;
	}

	return err;
}