/*  GadTools layout toolkit
**
**  Copyright © 1993-1994 by Olaf `Olsen' Barthel
**  Freely distributable.
*/

#include "gtlayout_global.h"

BOOLEAN __regargs
LTP_GlyphSetup(struct LayoutHandle *Handle,struct TextAttr *TextAttr)
{
	struct TextFont *Font;

	if(TextAttr)
	{
		Handle -> TextAttr = TextAttr;

		if(!(Font = OpenFont(Handle -> TextAttr)))
		{
			if(SysBase -> ThisTask -> tc_Node . ln_Type != NT_TASK)
			{
				struct Library *DiskfontBase;

				if(DiskfontBase = OpenLibrary("diskfont.library",0))
				{
					Font = OpenDiskFont(Handle -> TextAttr);

					CloseLibrary(DiskfontBase);
				}
			}
		}

		if(Font)
		{
			if(Handle -> CloseFont)
				CloseFont(Handle -> RPort . Font);
			else
				Handle -> CloseFont = TRUE;
		}
	}
	else
	{
		Handle -> TextAttr = Handle -> Screen -> Font;

		Font = Handle -> DrawInfo -> dri_Font;

		if(Handle -> CloseFont)
		{
			CloseFont(Handle -> RPort . Font);

			Handle -> CloseFont = FALSE;
		}
	}

	if(Font)
	{
		LONG	Count = 0;
		LONG	Total = 0;
		UBYTE	Glyph;
		UWORD	i;

		LTP_SetFont(Handle,Font);

			// Ok, first cover the standard ASCII character set

		for(i = 32 ; i < 127 ; i++,Count++)
		{
			Glyph = i;

			Total += TextLength(&Handle -> RPort,&Glyph,1);
		}

			// Now for the ISO part...

		for(i = 160 ; i < 256 ; i++,Count++)
		{
			Glyph = i;

			Total += TextLength(&Handle -> RPort,&Glyph,1);
		}

		Handle -> GlyphWidth = Total / Count;

			// Now for the numeric characters

		for(Total = 0, i = '0' ; i <= '9' ; i++)
		{
			Glyph = i;

			Total += TextLength(&Handle -> RPort,&Glyph,1);
		}

			// Actually, the numeric character should be
			// just as wide as the space character. Let's
			// hope for the best.

		Total += TextLength(&Handle -> RPort," ",1);

		Total /= 11;

		if(Total > Handle -> GlyphWidth)
			Handle -> GlyphWidth = Total;

		if(Handle -> GlyphWidth <= 8)
			Handle -> InterWidth = 4;
		else
			Handle -> InterWidth = Handle -> GlyphWidth / 2;

		if(Handle -> RPort . TxHeight <= 8)
			Handle -> InterHeight = 2;
		else
			Handle -> InterHeight = Handle -> RPort . TxHeight / 4;

		return(TRUE);
	}
	else
		return(FALSE);
}
