#import "textundo.h"

@implementation TextSelection

/*
 * The TextSelection class takes a snapshot of the current selection of
 * a Text object. It remembers the position of the selection and records
 * the characters in the selection with an RTF stream.
 */

- initText:aView
{
    NXSelPt selStart, selEnd;

    [aView getSel:&selStart :&selEnd];
    return [self initText:aView start:selStart.cp end:selEnd.cp];
}

- initText:aView start:(int)startPos end:(int)endPos
{
    [super init];

    text = aView;
    start = startPos;
    end = endPos;

    selectionChars = (NXStream *) 0;

    if (start == 0 && end == [text textLength]) {
	allText = YES;
    } else {
	allText = NO;
2b}

    [text getFrame:&frame];

    return self;
}

- free
{
    if (selectionChars) {
	NXCloseMemory(selectionChars, NX_FREEBUFFER);
    }

    return [super free];
}

- (int)clickCount
{
    return clickCount;
}

- setClickCount:(int)value
{
    clickCount = value;
    return self;
}

/*
 * The Text object doesn't save everything out in writeRichText:from:to: even
 * if the bounds specify the entire contents of the object. Things like tab
 * stops and margins are missing. However, writeRichText: does a better job,
 * although not perfect.
 */

- capture
{
    clickCount = [text clickCount];

    if (start < end || allText) {
	selectionChars = NXOpenMemory(NULL, 0, NX_READWRITE);
	if (allText) {
	    [text writeRichText:selectionChars];
	} else {
	    [text writeRichText:selectionChars from:start to:end];
	}
    }

    return self;
}

- install
{
    [text setSel:start :start];
    [text setFrame:&frame];

    if (selectionChars) {
	NXSeek(selectionChars, 0, NX_FROMSTART);

	if (allText) {
	    [text readRichText:selectionChars];
	    [text display];
	} else {
	    [text replaceSelWithRichText:selectionChars];
	}

	[text setSel:start :end];

    }

    return self;
}

- remove
{
    [text setSel:start :end];
    [text setClickCount:clickCount];
    [text eraseSelection];

    return self;
}

@end
