/*1* tkClipboard.c --2*3* This file manages the clipboard for the Tk toolkit,4* maintaining a collection of data buffers that will be5* supplied on demand to requesting applications.6*7* Copyright (c) 1994 The Regents of the University of California.8* Copyright (c) 1994-1995 Sun Microsystems, Inc.9*10* See the file "license.terms" for information on usage and redistribution11* of this file, and for a DISCLAIMER OF ALL WARRANTIES.12*13* SCCS: @(#) tkClipboard.c 1.14 96/02/15 18:52:3714*/1516#include "tkInt.h"17#include "tkSelect.h"1819/*20* Prototypes for procedures used only in this file:21*/2223static int ClipboardAppHandler _ANSI_ARGS_((ClientData clientData,24int offset, char *buffer, int maxBytes));25static int ClipboardHandler _ANSI_ARGS_((ClientData clientData,26int offset, char *buffer, int maxBytes));27static int ClipboardWindowHandler _ANSI_ARGS_((28ClientData clientData, int offset, char *buffer,29int maxBytes));30static void ClipboardLostSel _ANSI_ARGS_((ClientData clientData));3132/*33*----------------------------------------------------------------------34*35* ClipboardHandler --36*37* This procedure acts as selection handler for the38* clipboard manager. It extracts the required chunk of39* data from the buffer chain for a given selection target.40*41* Results:42* The return value is a count of the number of bytes43* actually stored at buffer.44*45* Side effects:46* None.47*48*----------------------------------------------------------------------49*/5051static int52ClipboardHandler(clientData, offset, buffer, maxBytes)53ClientData clientData; /* Information about data to fetch. */54int offset; /* Return selection bytes starting at this55* offset. */56char *buffer; /* Place to store converted selection. */57int maxBytes; /* Maximum # of bytes to store at buffer. */58{59TkClipboardTarget *targetPtr = (TkClipboardTarget*) clientData;60TkClipboardBuffer *cbPtr;61char *srcPtr, *destPtr;62int count = 0;63int scanned = 0;64size_t length, freeCount;6566/*67* Skip to buffer containing offset byte68*/6970for (cbPtr = targetPtr->firstBufferPtr; ; cbPtr = cbPtr->nextPtr) {71if (cbPtr == NULL) {72return 0;73}74if (scanned + cbPtr->length > offset) {75break;76}77scanned += cbPtr->length;78}7980/*81* Copy up to maxBytes or end of list, switching buffers as needed.82*/8384freeCount = maxBytes;85srcPtr = cbPtr->buffer + (offset - scanned);86destPtr = buffer;87length = cbPtr->length - (offset - scanned);88while (1) {89if (length > freeCount) {90strncpy(destPtr, srcPtr, freeCount);91return maxBytes;92} else {93strncpy(destPtr, srcPtr, length);94destPtr += length;95count += length;96freeCount -= length;97}98cbPtr = cbPtr->nextPtr;99if (cbPtr == NULL) {100break;101}102srcPtr = cbPtr->buffer;103length = cbPtr->length;104}105return count;106}107108/*109*----------------------------------------------------------------------110*111* ClipboardAppHandler --112*113* This procedure acts as selection handler for retrievals of type114* TK_APPLICATION. It returns the name of the application that115* owns the clipboard. Note: we can't use the default Tk116* selection handler for this selection type, because the clipboard117* window isn't a "real" window and doesn't have the necessary118* information.119*120* Results:121* The return value is a count of the number of bytes122* actually stored at buffer.123*124* Side effects:125* None.126*127*----------------------------------------------------------------------128*/129130static int131ClipboardAppHandler(clientData, offset, buffer, maxBytes)132ClientData clientData; /* Pointer to TkDisplay structure. */133int offset; /* Return selection bytes starting at this134* offset. */135char *buffer; /* Place to store converted selection. */136int maxBytes; /* Maximum # of bytes to store at buffer. */137{138TkDisplay *dispPtr = (TkDisplay *) clientData;139size_t length;140char *p;141142p = dispPtr->clipboardAppPtr->winPtr->nameUid;143length = strlen(p);144length -= offset;145if (length <= 0) {146return 0;147}148if (length > maxBytes) {149length = maxBytes;150}151strncpy(buffer, p, length);152return length;153}154155/*156*----------------------------------------------------------------------157*158* ClipboardWindowHandler --159*160* This procedure acts as selection handler for retrievals of161* type TK_WINDOW. Since the clipboard doesn't correspond to162* any particular window, we just return ".". We can't use Tk's163* default handler for this selection type, because the clipboard164* window isn't a valid window.165*166* Results:167* The return value is 1, the number of non-null bytes stored168* at buffer.169*170* Side effects:171* None.172*173*----------------------------------------------------------------------174*/175176static int177ClipboardWindowHandler(clientData, offset, buffer, maxBytes)178ClientData clientData; /* Not used. */179int offset; /* Return selection bytes starting at this180* offset. */181char *buffer; /* Place to store converted selection. */182int maxBytes; /* Maximum # of bytes to store at buffer. */183{184buffer[0] = '.';185buffer[1] = 0;186return 1;187}188189/*190*----------------------------------------------------------------------191*192* ClipboardLostSel --193*194* This procedure is invoked whenever clipboard ownership is195* claimed by another window. It just sets a flag so that we196* know the clipboard was taken away.197*198* Results:199* None.200*201* Side effects:202* The clipboard is marked as inactive.203*204*----------------------------------------------------------------------205*/206207static void208ClipboardLostSel(clientData)209ClientData clientData; /* Pointer to TkDisplay structure. */210{211TkDisplay *dispPtr = (TkDisplay*) clientData;212213dispPtr->clipboardActive = 0;214}215216/*217*----------------------------------------------------------------------218*219* Tk_ClipboardClear --220*221* Take control of the clipboard and clear out the previous222* contents. This procedure must be invoked before any223* calls to Tk_AppendToClipboard.224*225* Results:226* A standard Tcl result. If an error occurs, an error message is227* left in interp->result.228*229* Side effects:230* From now on, requests for the CLIPBOARD selection will be231* directed to the clipboard manager routines associated with232* clipWindow for the display of tkwin. In order to guarantee233* atomicity, no event handling should occur between234* Tk_ClipboardClear and the following Tk_AppendToClipboard235* calls. This procedure may cause a user-defined LostSel command236* to be invoked when the CLIPBOARD is claimed, so any calling237* function should be reentrant at the point Tk_ClipboardClear is238* invoked.239*240*----------------------------------------------------------------------241*/242243int244Tk_ClipboardClear(interp, tkwin)245Tcl_Interp *interp; /* Interpreter to use for error reporting. */246Tk_Window tkwin; /* Window in application that is clearing247* clipboard; identifies application and248* display. */249{250TkWindow *winPtr = (TkWindow *) tkwin;251TkDisplay *dispPtr = winPtr->dispPtr;252TkClipboardTarget *targetPtr, *nextTargetPtr;253TkClipboardBuffer *cbPtr, *nextCbPtr;254255if (dispPtr->clipWindow == NULL) {256int result;257258result = TkClipInit(interp, dispPtr);259if (result != TCL_OK) {260return result;261}262}263264/*265* Discard any existing clipboard data and delete the selection266* handler(s) associated with that data.267*/268269for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL;270targetPtr = nextTargetPtr) {271for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL;272cbPtr = nextCbPtr) {273ckfree(cbPtr->buffer);274nextCbPtr = cbPtr->nextPtr;275ckfree((char *) cbPtr);276}277nextTargetPtr = targetPtr->nextPtr;278Tk_DeleteSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom,279targetPtr->type);280ckfree((char *) targetPtr);281}282dispPtr->clipTargetPtr = NULL;283284/*285* Reclaim the clipboard selection if we lost it.286*/287288if (!dispPtr->clipboardActive) {289Tk_OwnSelection(dispPtr->clipWindow, dispPtr->clipboardAtom,290ClipboardLostSel, (ClientData) dispPtr);291dispPtr->clipboardActive = 1;292}293dispPtr->clipboardAppPtr = winPtr->mainPtr;294return TCL_OK;295}296297/*298*----------------------------------------------------------------------299*300* Tk_ClipboardAppend --301*302* Append a buffer of data to the clipboard. The first buffer of303* a given type determines the format for that type. Any successive304* appends to that type must have the same format or an error will305* be returned. Tk_ClipboardClear must be called before a sequence306* of Tk_ClipboardAppend calls can be issued. In order to guarantee307* atomicity, no event handling should occur between Tk_ClipboardClear308* and the following Tk_AppendToClipboard calls.309*310* Results:311* A standard Tcl result. If an error is returned, an error message312* is left in interp->result.313*314* Side effects:315* The specified buffer will be copied onto the end of the clipboard.316* The clipboard maintains a list of buffers which will be used to317* supply the data for a selection get request. The first time a given318* type is appended, Tk_ClipboardAppend will register a selection319* handler of the appropriate type.320*321*----------------------------------------------------------------------322*/323324int325Tk_ClipboardAppend(interp, tkwin, type, format, buffer)326Tcl_Interp *interp; /* Used for error reporting. */327Tk_Window tkwin; /* Window that selects a display. */328Atom type; /* The desired conversion type for this329* clipboard item, e.g. STRING or LENGTH. */330Atom format; /* Format in which the selection331* information should be returned to332* the requestor. */333char* buffer; /* NULL terminated string containing the data334* to be added to the clipboard. */335{336TkWindow *winPtr = (TkWindow *) tkwin;337TkDisplay *dispPtr = winPtr->dispPtr;338TkClipboardTarget *targetPtr;339TkClipboardBuffer *cbPtr;340341/*342* If this application doesn't already own the clipboard, clear343* the clipboard. If we don't own the clipboard selection, claim it.344*/345346if (dispPtr->clipboardAppPtr != winPtr->mainPtr) {347Tk_ClipboardClear(interp, tkwin);348} else if (!dispPtr->clipboardActive) {349Tk_OwnSelection(dispPtr->clipWindow, dispPtr->clipboardAtom,350ClipboardLostSel, (ClientData) dispPtr);351dispPtr->clipboardActive = 1;352}353354/*355* Check to see if the specified target is already present on the356* clipboard. If it isn't, we need to create a new target; otherwise,357* we just append the new buffer to the clipboard list.358*/359360for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL;361targetPtr = targetPtr->nextPtr) {362if (targetPtr->type == type)363break;364}365if (targetPtr == NULL) {366targetPtr = (TkClipboardTarget*) ckalloc(sizeof(TkClipboardTarget));367targetPtr->type = type;368targetPtr->format = format;369targetPtr->firstBufferPtr = targetPtr->lastBufferPtr = NULL;370targetPtr->nextPtr = dispPtr->clipTargetPtr;371dispPtr->clipTargetPtr = targetPtr;372Tk_CreateSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom,373type, ClipboardHandler, (ClientData) targetPtr, format);374} else if (targetPtr->format != format) {375Tcl_AppendResult(interp, "format \"", Tk_GetAtomName(tkwin, format),376"\" does not match current format \"",377Tk_GetAtomName(tkwin, targetPtr->format),"\" for ",378Tk_GetAtomName(tkwin, type), (char *) NULL);379return TCL_ERROR;380}381382/*383* Append a new buffer to the buffer chain.384*/385386cbPtr = (TkClipboardBuffer*) ckalloc(sizeof(TkClipboardBuffer));387cbPtr->nextPtr = NULL;388if (targetPtr->lastBufferPtr != NULL) {389targetPtr->lastBufferPtr->nextPtr = cbPtr;390} else {391targetPtr->firstBufferPtr = cbPtr;392}393targetPtr->lastBufferPtr = cbPtr;394395cbPtr->length = strlen(buffer);396cbPtr->buffer = (char *) ckalloc((unsigned) (cbPtr->length + 1));397strcpy(cbPtr->buffer, buffer);398399TkSelUpdateClipboard((TkWindow*)(dispPtr->clipWindow), targetPtr);400401return TCL_OK;402}403404/*405*----------------------------------------------------------------------406*407* Tk_ClipboardCmd --408*409* This procedure is invoked to process the "clipboard" Tcl410* command. See the user documentation for details on what411* it does.412*413* Results:414* A standard Tcl result.415*416* Side effects:417* See the user documentation.418*419*----------------------------------------------------------------------420*/421422int423Tk_ClipboardCmd(clientData, interp, argc, argv)424ClientData clientData; /* Main window associated with425* interpreter. */426Tcl_Interp *interp; /* Current interpreter. */427int argc; /* Number of arguments. */428char **argv; /* Argument strings. */429{430Tk_Window tkwin = (Tk_Window) clientData;431char *path = NULL;432size_t length;433int count;434char c;435char **args;436437if (argc < 2) {438Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],439" option ?arg arg ...?\"", (char *) NULL);440return TCL_ERROR;441}442c = argv[1][0];443length = strlen(argv[1]);444if ((c == 'a') && (strncmp(argv[1], "append", length) == 0)) {445Atom target, format;446char *targetName = NULL;447char *formatName = NULL;448449for (count = argc-2, args = argv+2; count > 1; count -= 2, args += 2) {450if (args[0][0] != '-') {451break;452}453c = args[0][1];454length = strlen(args[0]);455if ((c == '-') && (length == 2)) {456args++;457count--;458break;459}460if ((c == 'd') && (strncmp(args[0], "-displayof", length) == 0)) {461path = args[1];462} else if ((c == 'f')463&& (strncmp(args[0], "-format", length) == 0)) {464formatName = args[1];465} else if ((c == 't')466&& (strncmp(args[0], "-type", length) == 0)) {467targetName = args[1];468} else {469Tcl_AppendResult(interp, "unknown option \"", args[0],470"\"", (char *) NULL);471return TCL_ERROR;472}473}474if (count != 1) {475Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],476" append ?options? data\"", (char *) NULL);477return TCL_ERROR;478}479if (path != NULL) {480tkwin = Tk_NameToWindow(interp, path, tkwin);481}482if (tkwin == NULL) {483return TCL_ERROR;484}485if (targetName != NULL) {486target = Tk_InternAtom(tkwin, targetName);487} else {488target = XA_STRING;489}490if (formatName != NULL) {491format = Tk_InternAtom(tkwin, formatName);492} else {493format = XA_STRING;494}495return Tk_ClipboardAppend(interp, tkwin, target, format, args[0]);496} else if ((c == 'c') && (strncmp(argv[1], "clear", length) == 0)) {497for (count = argc-2, args = argv+2; count > 0; count -= 2, args += 2) {498if (args[0][0] != '-') {499break;500}501if (count < 2) {502Tcl_AppendResult(interp, "value for \"", *args,503"\" missing", (char *) NULL);504return TCL_ERROR;505}506c = args[0][1];507length = strlen(args[0]);508if ((c == 'd') && (strncmp(args[0], "-displayof", length) == 0)) {509path = args[1];510} else {511Tcl_AppendResult(interp, "unknown option \"", args[0],512"\"", (char *) NULL);513return TCL_ERROR;514}515}516if (count > 0) {517Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],518" clear ?options?\"", (char *) NULL);519return TCL_ERROR;520}521if (path != NULL) {522tkwin = Tk_NameToWindow(interp, path, tkwin);523}524if (tkwin == NULL) {525return TCL_ERROR;526}527return Tk_ClipboardClear(interp, tkwin);528} else {529sprintf(interp->result,530"bad option \"%.50s\": must be clear or append",531argv[1]);532return TCL_ERROR;533}534}535536/*537*----------------------------------------------------------------------538*539* TkClipInit --540*541* This procedure is called to initialize the window for claiming542* clipboard ownership and for receiving selection get results. This543* function is called from tkSelect.c as well as tkClipboard.c.544*545* Results:546* The result is a standard Tcl return value, which is normally TCL_OK.547* If an error occurs then an error message is left in interp->result548* and TCL_ERROR is returned.549*550* Side effects:551* Sets up the clipWindow and related data structures.552*553*----------------------------------------------------------------------554*/555556int557TkClipInit(interp, dispPtr)558Tcl_Interp *interp; /* Interpreter to use for error559* reporting. */560register TkDisplay *dispPtr;/* Display to initialize. */561{562XSetWindowAttributes atts;563564dispPtr->clipTargetPtr = NULL;565dispPtr->clipboardActive = 0;566dispPtr->clipboardAppPtr = NULL;567568/*569* Create the window used for clipboard ownership and selection retrieval,570* and set up an event handler for it.571*/572573dispPtr->clipWindow = Tk_CreateWindow(interp, (Tk_Window) NULL,574"_clip", DisplayString(dispPtr->display));575if (dispPtr->clipWindow == NULL) {576return TCL_ERROR;577}578atts.override_redirect = True;579Tk_ChangeWindowAttributes(dispPtr->clipWindow, CWOverrideRedirect, &atts);580Tk_MakeWindowExist(dispPtr->clipWindow);581582if (dispPtr->multipleAtom == None) {583/*584* Need to invoke selection initialization to make sure that585* atoms we depend on below are defined.586*/587588TkSelInit(dispPtr->clipWindow);589}590591/*592* Create selection handlers for types TK_APPLICATION and TK_WINDOW593* on this window. Can't use the default handlers for these types594* because this isn't a full-fledged window.595*/596597Tk_CreateSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom,598dispPtr->applicationAtom, ClipboardAppHandler,599(ClientData) dispPtr, XA_STRING);600Tk_CreateSelHandler(dispPtr->clipWindow, dispPtr->clipboardAtom,601dispPtr->windowAtom, ClipboardWindowHandler,602(ClientData) dispPtr, XA_STRING);603return TCL_OK;604}605606607