#import "draw.h"

@implementation GraphicView(Services)

/* Services menu methods */

/*
* Services in Draw are trivial to implement since we leverage heavily
* off of the copy/paste code. Note that write/readSelectionTo/FromPasteboard:
* do little more than call the copy/paste code.
*/

/*
* We are a valid requestor whenever any of the send or return types is
* PostScript, TIFF, or Draw (actually, any return type that NXImage can
* handle is okay with us).
*/

- validRequestorForSendType:(NXAtom)sendType andReturnType:(NXAtom)returnType
{

if ((!sendType || !*sendType ||
((sendType == NXPostScriptPboardType ||
sendType == NXTIFFPboardType ||
sendType == DrawPboardType) && [slist count])) &&
(!returnType || !*returnType ||
IncludesType([NXImage imagePasteboardTypes], returnType) ||
returnType == DrawPboardType)) {
return self;
}

return [super validRequestorForSendType:sendType andReturnType:returnType];
}

/*
* If one of the requested types is one of the ones we handle,
* then we put our selection in the Pasteboard. The serviceActsOnSelection
* flag is so that we can effectively undo a Service request.
*/

- (BOOL)writeSelectionToPasteboard:(Pasteboard *)pboard types:(NXAtom *)types
{
while (types && *types) {
if (*types == NXPostScriptPboardType || *types == NXTIFFPboardType || *types == DrawPboardType) break;
types++;
}

if (types && *types && [self copyToPasteboard:pboard types:types]) {
gvFlags.serviceActsOnSelection = YES;
return YES;
} else {
return NO;
}
}

#define SERVICE_CALL_OPERATION NXLocalStringFromTable("Operations", "Service Call", NULL, "The user action of selecting an item in the Services menu.")

/*
* When a result comes back from the Services menu request,
* we replace the selection with the return value.
* If the user really wants the return value in addition to
* the current selection, she can simply copy, then paste
* twice to get two copies, then choose the Services menu item.
*/

- readSelectionFromPasteboard:(Pasteboard *)pboard
{
id change;
NXRect sbbox;
NXPoint *position = &sbbox.origin;

change = [[MultipleChange alloc] initChangeName:SERVICE_CALL_OPERATION];
[change startChange];
if (gvFlags.serviceActsOnSelection) {
[self getBBox:&sbbox of:slist extended:NO];
sbbox.origin.x += floor(sbbox.size.width / 2.0 + 0.5);
sbbox.origin.y += floor(sbbox.size.height / 2.0 + 0.5);
[self delete:self];
gvFlags.serviceActsOnSelection = NO;
} else {
position = NULL;
}
[self pasteFromPasteboard:pboard andLink:DontLink at:position];
[change endChange];

return self;
}

@end