/* CompletionView.m
 * CompletionView is a simple "gas gauge" display to display the proress
 * of some calclation.  As you call [compltionView setDoubleValue:value]
 * with values of 0.0 to 1.0, the completion view go from empty to full.
 *
 * You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 *
 * Written by: Robert Poor
 * Created: Sep/92
 *
 *  Below is the body of the .m file with detailed comments as appropriate.
 */

#import "CompletionView.h"
#import <appkit/Cell.h>
#import <appkit/graphics.h>
#import <dpsclient/psops.h>

@interface CompletionView(CompletionViewPrivate)
- _setInstanceValue:(double *)instanceValue from:(double)newValue;
@end

@implementation CompletionView:View

- initFrame:(const NXRect *)frameRect
{
  [super initFrame:frameRect];
  backgroundColor = NX_LTGRAY;
  completionColor = NX_DKGRAY;
  updateTextField = NO;
  /* set value and pctValue to out-of-range values ... */
  value = -1.0;
  pctValue = -1;
  /* ... to force an update here */
  [self setDoubleValue:0.0];
  return self;
}

- (double)value { return value; }
- setDoubleValue:(double)newValue
{
  /* limit newValue to fall within 0 and 1 (inclusive) */ 
  if (newValue < 0.0) newValue = 0.0;
  else if (newValue > 1.0) newValue = 1.0;

  if (newValue != value) {
    value = newValue;
    [self display];
    if (updateTextField) {
      /* update the associated TextField, if any... */
      int newPctValue = newValue * 100;
      if (newPctValue != pctValue) {
	char buf[5];
	pctValue = newPctValue;
	sprintf(buf,"%3d%%",pctValue);
	[textField setStringValue:buf];
      }
    }
  }
  return self;
}

- (float)backgroundColor { return backgroundColor; }
- setBackgroundColor:(float)color { backgroundColor = color; return self; }
- (float)completionColor { return completionColor; }
- setCompletionColor:(float)color { completionColor = color; return self; }

- textField { return textField; }
- setTextField:aTextField
{
  if (aTextField && [aTextField respondsTo:@selector(setStringValue:)]) {
    textField = aTextField;
    updateTextField = YES;
    return self;
  } else {
    return nil;
  }
}

- drawSelf:(NXRect *)rects :(int)rectCount
{
  NXRect completionRect = bounds;

  /* erase the background */
  PSsetgray (backgroundColor);
  NXRectFill(&bounds);

  if (bounds.size.width > bounds.size.height) {
    /* grow horizontally */
    completionRect.size.width = bounds.size.width * value;
  } else {
    /* grow vertically */
    completionRect.size.height = bounds.size.height * value;
  }
  PSsetgray (NX_DKGRAY);
  NXRectFill(&completionRect);

  return self;
}

@end
