/* CustomView.m created by tsukasak on Mon 17-Aug-1998 */

#import "MyView.h"

NSRect makeRectFromPoint( NSPoint pos, float w);

@implementation MyView

-(void)awakeFromNib
{
    NSCustomImageRep *imgRep;

    penSize=[ptsPenSize floatValue];
    penColor=[ptsPenColor color];
    bgColor=[ptsBGColor color];

    rect=[self bounds];
    size=rect.size;
    image=[[NSImage allocWithZone:[self zone]] initWithSize:size];
    imgRep=[[[NSCustomImageRep alloc]
        initWithDrawSelector:@selector(drawImage:) delegate:self] autorelease];
    [image addRepresentation:imgRep];
    [image setBackgroundColor:bgColor];
}


-(BOOL)acceptsFirstResponder
{
    return YES;
}


// action methods

-(void)clear:(id)sender
{
    [image lockFocus];
    [bgColor set];
    NSRectFill( rect);
    [image unlockFocus];
    [self setNeedsDisplay:YES];
}

-(void)changePenSize:(id)sender
{
    penSize=[ptsPenSize floatValue];
}

-(void)changePenColor:(id)sender
{
    penColor=[ptsPenColor color];
}

-(void)changeBGColor:(id)sender
{
    bgColor=[ptsBGColor color];
}


// event mothods

-(void)mouseDown:(NSEvent*)ev
{
    NSPoint winPos=[ev locationInWindow];
    curPos=[self convertPoint:winPos fromView:nil];
    curRect=makeRectFromPoint( curPos, penSize);
    prevPos=curPos;
    prevRect=curRect;
    [self draw];
}

-(void)mouseDragged:(NSEvent*)ev
{
    NSPoint winPos=[ev locationInWindow];
    curPos=[self convertPoint:winPos fromView:nil];
    curRect=makeRectFromPoint( curPos, penSize);
    [self draw];
    prevPos=curPos;
    prevRect=curRect;
}


// drawing

-(void)draw
{
    [image lockFocus];
    [penColor set];
    PSmoveto( prevPos.x, prevPos.y);
    PSlineto( curPos.x, curPos.y);
    PSsetlinewidth( penSize);
    PSsetlinecap( 1);
    PSstroke();
    [image unlockFocus];
    [self setNeedsDisplayInRect:NSUnionRect( curRect, prevRect)];
}

-(void)drawImage:(NSCustomImageRep*)rep
{
}

- (void)drawRect:(NSRect)_rect
{
    [image compositeToPoint:_rect.origin
                  fromRect:_rect operation:NSCompositeCopy];
}

@end

NSRect makeRectFromPoint( NSPoint pos, float w)
{
    return NSMakeRect( pos.x-w/2, pos.y-w/2, w, w);
}