/* 
	AdjFontTextField class, written by Robert Vasvari
	
	this class displays a string of any length by
   	first: cutting down the size of the font
          until it reaches the specified minimum font
   	second: the text will be truncated until it fits
           into the textfield


	setup: [adjFontTextObject setFont:"SomeFontName"];
	       [adjFontTextObject setAttributes:minsize :maxsize
			align:NX_CENTERED
			lines:1];
    the numbers minsize and maxsize are indices in the array 
	containing the known font sizes: 8,9,10,12,14, etc...
	So, 0 stands for point size 8, 1 for 9 etc...
	
	AdjFontTextField will always try to use the maximum font size.
	AdjFontTextField will use the specified alignment, such
	as NX_LEFTALIGNED, NX_CENTERED, etc.
	
	textGray defaults to NX_BLACK,
	backgroundGraydefaults to NX_LTGRAY
*/

#import <stdio.h>
#import <stdlib.h>
#import "AdjFontTextField.h"

#define BUFSIZE 1024
#define ELLIPSIS ('\274')

@implementation AdjFontTextField

- initFrame:(const NXRect *)f
{
	[super initFrame:f];
	[self setSelectable:NO];
	[self setBordered:NO];
	[self setBackgroundGray:NX_LTGRAY];
	[self setTextGray:NX_BLACK];
	return self;
}

- setFontString:(const char *)aFont
{	fontString=aFont;
	font=[self font];
	return self;
}

- setAttributes:(int)min :(int)max
	align:(int)aMode
	lines:(int)numLines
{	minSize=min;
	maxSize=max;
	curSize=0;
	[cell setAlignment:aMode];
	lines=numLines;
	return self;
}

- setStringValue:(const char *)text
{
static float sizes[]={8.0,9.0,10.0,11.0,12.0,14.0,16.0,18.0,
                      24.0,36.0,48.0,64.0};
NXSize s;
NXRect r=frame;
	r.size.height=36.0;
	[super setStringValue:text];

	if(curSize!=maxSize)
	  { font=[Font newFont:fontString
	              size:sizes[maxSize]
	              matrix:NX_FLIPPEDMATRIX];
	   [self setFont:font];
	   curSize=maxSize;
	  }
	
	[cell calcCellSize:&s inRect:&r];
	
	while(curSize>0 && (int)(s.height/sizes[curSize])>lines)
	 { curSize--;
	   font=[Font newFont:fontString
	              size:sizes[curSize]
	              matrix:NX_FLIPPEDMATRIX];
	   [self setFont:font];
	   [cell calcCellSize:&s inRect:&r];
	 }
	
	if(!curSize)
	     { /* the text is still too large let's cut it down */
		   char *p, shortNameBuf[BUFSIZE+1]="";
		   strcpy(shortNameBuf,text);
		   p=strchr(shortNameBuf,'\0');
		   while((int)(s.height/sizes[curSize])>lines)
		      { p--;
				*p=ELLIPSIS; p[1]='\0';
				[super setStringValue:shortNameBuf];
				[cell calcCellSize:&s inRect:&r];
			  }
		   [cell calcCellSize:&s inRect:&r];	  
         }
	[self sizeTo:bounds.size.width :s.height];
	return self;
}


@end
