#import "drawundo.h"

@implementation PerformTextGraphicsChange

static id editText = nil;
static id editWindow = nil;

- initGraphic:aGraph3iew:aGraphicView
{
    [super init];

    if (editText == nil) {
	editText = [[UndoText alloc] initFrame:(NXRect *)0];
	[editText setMonoFont:NO];
    }

    if (editWindow == nil) {
	editWindow = [[Window alloc] init];
    }

    graphic = aGraphic;
    graphicView = aGraphicView;
    textChange = nil;

    return self;
}

- free
{
    [textChange free];
    return [super free];
}

- (const char *)changeName
{
    return [textChange changeName];
}

- undoChange
{
    NXRect bounds;

    [self loadGraphic];
    [textChange undoChange];
    [self unloadGraphic];
    [graphic getBounds:&bounds];
    [graphicView cache:&bounds];
    [[graphicView window] flushWindow];

    return [super undoChange];
}

- redoChange
{
    NXRect bounds;

    [self loadGraphic];
    [textChange redoChange];
    [self unloadGraphic];
    [graphic getBounds:&bounds];
    [graphicView cache:&bounds];
    [[graphicView window] flushWindow];

    return [super redoChange];
}

- (BOOL)incorporateChange:aChange
{
    if (textChange == nil) {
	textChange = aChange;
	return YES;
    } else {
	return NO;
    }
}

- loadGraphic
{
    NXRect graphicBounds;

    stream = NXOpenMemory([graphic data], [graphic length], NX_READONLY);
    [editText readRichText:stream];
    NXCloseMemory(stream, NX_SAVEBUFFER);

    [graphic getBounds:&graphicBounds];
    [editText setFrame:&graphicBounds];

    [editWindow setNextResponder:graphicView]; /* so changes can find our */
                                               /* change manager          */
    [[editWindow contentView] addSubview:editText];

    [editText selectAll:self];

    return self;
}

- unloadGraphic
{
    int length, maxlen;
    char *buffer, *data;

    [editWindow setNextResponder:nil];
    [editText removeFromSuperview];
    [editText setSel:0 :0];
    [graphic setFont:[editText font]];

    stream = NXOpenMemory(NULL, 0, NX_WRITEONLY);
    [editText writeRichText:stream];
    NXGetMemoryBuffer(stream, &buffer, &length, &maxlen);
    NX_ZONEMALLOC([graphic zone], data, char, length);
    bcopy(buffer, data, length);
    NXCloseMemory(stream, NX_FREEBUFFER);

    [graphic setData:data];
    [graphic setLength:length];

    return self;
}

- editText
{
    return editText;
}

@end
