Debian Codegraph @

pTk/mTk/unix/tkUnixSelect.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * tkUnixSelect.c --
3 *
4 * This file contains X specific routines for manipulating
5 * selections.
6 *
7 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
8 *
9 * See the file "license.terms" for information on usage and redistribution
10 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 *
12 * RCS: @(#) $Id: tkUnixSelect.c,v 1.11 2002/10/01 08:48:08 dkf Exp $
13 */
14
15 #include "tkInt.h"
16 #include "tkSelect.h"
17
18 typedef struct ConvertInfo {
19 int offset; /* The starting byte offset into the selection
20 * for the next chunk; -1 means all data has
21 * been transferred for this conversion. -2
22 * means only the final zero-length transfer
23 * still has to be done. Otherwise it is the
24 * offset of the next chunk of data to
25 * transfer. */
26 Tcl_EncodingState state; /* The encoding state needed across chunks. */
27 char buffer[TCL_UTF_MAX]; /* A buffer to hold part of a UTF character
28 * that is split across chunks.*/
29 } ConvertInfo;
30
31 /*
32 * When handling INCR-style selection retrievals, the selection owner
33 * uses the following data structure to communicate between the
34 * ConvertSelection procedure and TkSelPropProc.
35 */
36
37 typedef struct IncrInfo {
38 TkWindow *winPtr; /* Window that owns selection. */
39 Atom selection; /* Selection that is being retrieved. */
40 Atom *multAtoms; /* Information about conversions to
41 * perform: one or more pairs of
42 * (target, property). This either
43 * points to a retrieved property (for
44 * MULTIPLE retrievals) or to a static
45 * array. */
46 unsigned long numConversions;
47 /* Number of entries in converts (same as
48 * # of pairs in multAtoms). */
49 ConvertInfo *converts; /* One entry for each pair in multAtoms.
50 * This array is malloc-ed. */
51 char **tempBufs; /* One pointer for each pair in multAtoms;
52 * each pointer is either NULL, or it points
53 * to a small bit of character data that was
54 * left over from the previous chunk. */
55 Tcl_EncodingState *state; /* One state info per pair in multAtoms:
56 * State info for encoding conversions
57 * that span multiple buffers. */
58 int *flags; /* One state flag per pair in multAtoms:
59 * Encoding flags, set to TCL_ENCODING_START
60 * at the beginning of an INCR transfer. */
61 int numIncrs; /* Number of entries in converts that
62 * aren't -1 (i.e. # of INCR-mode transfers
63 * not yet completed). */
64 Tcl_TimerToken timeout; /* Token for timer procedure. */
65 int idleTime; /* Number of seconds since we heard
66 * anything from the selection
67 * requestor. */
68 Window reqWindow; /* Requestor's window id. */
69 Time time; /* Timestamp corresponding to
70 * selection at beginning of request;
71 * used to abort transfer if selection
72 * changes. */
73 struct IncrInfo *nextPtr; /* Next in list of all INCR-style
74 * retrievals currently pending. */
75 } IncrInfo;
76
77
78 typedef struct ThreadSpecificData {
79 IncrInfo *pendingIncrs; /* List of all incr structures
80 * currently active. */
81 } ThreadSpecificData;
82 static Tcl_ThreadDataKey dataKey;
83
84 /*
85 * Largest property that we'll accept when sending or receiving the
86 * selection:
87 */
88
89 #define MAX_PROP_WORDS 100000
90
91 static TkSelRetrievalInfo *pendingRetrievals = NULL;
92 /* List of all retrievals currently
93 * being waited for. */
94
95 /*
96 * Forward declarations for procedures defined in this file:
97 */
98
99 static void ConvertSelection _ANSI_ARGS_((TkWindow *winPtr,
100 XSelectionRequestEvent *eventPtr));
101 static void IncrTimeoutProc _ANSI_ARGS_((ClientData clientData));
102 static int SelectionSize _ANSI_ARGS_((TkSelHandler *selPtr, Atom type, Tk_Window tkwin));
103 static int SelGetProc _ANSI_ARGS_((ClientData clientData,
104 Tcl_Interp *interp, char *portion));
105 static void SelRcvIncrProc _ANSI_ARGS_((ClientData clientData,
106 XEvent *eventPtr));
107 static void SelTimeoutProc _ANSI_ARGS_((ClientData clientData));
108
109 static void FreeHandler _ANSI_ARGS_((ClientData clientData));
110 static int HandleCompat _ANSI_ARGS_((ClientData clientData,
111 int offset, long *buffer, int maxBytes,
112 Atom type, Tk_Window tkwin));
113
114 /*
115 *----------------------------------------------------------------------
116 *
117 * TkSelGetSelection --
118 *
119 * Retrieve the specified selection from another process.
120 *
121 * Results:
122 * The return value is a standard Tcl return value.
123 * If an error occurs (such as no selection exists)
124 * then an error message is left in the interp's result.
125 *
126 * Side effects:
127 * None.
128 *
129 *----------------------------------------------------------------------
130 */
131
132 int
133 TkSelGetSelection(interp, tkwin, selection, target, proc, clientData)
134 Tcl_Interp *interp; /* Interpreter to use for reporting
135 * errors. */
136 Tk_Window tkwin; /* Window on whose behalf to retrieve
137 * the selection (determines display
138 * from which to retrieve). */
139 Atom selection; /* Selection to retrieve. */
140 Atom target; /* Desired form in which selection
141 * is to be returned. */
142 Tk_GetXSelProc *proc; /* Procedure to call to process the
143 * selection, once it has been retrieved. */
144 ClientData clientData; /* Arbitrary value to pass to proc. */
145 {
146 TkSelRetrievalInfo retr;
147 TkWindow *winPtr = (TkWindow *) tkwin;
148 TkDisplay *dispPtr = winPtr->dispPtr;
149
150 /*
151 * The selection is owned by some other process. To
152 * retrieve it, first record information about the retrieval
153 * in progress. Use an internal window as the requestor.
154 */
155
156 retr.interp = interp;
157 if (dispPtr->clipWindow == NULL) {
158 int result;
159
160 result = TkClipInit(interp, dispPtr);
161 if (result != TCL_OK) {
162 return result;
163 }
164 }
165 retr.winPtr = (TkWindow *) dispPtr->clipWindow;
166 retr.selection = selection;
167 retr.property = selection;
168 retr.target = target;
169 retr.proc = proc;
170 retr.clientData = clientData;
171 retr.result = -1;
172 retr.idleTime = 0;
173 retr.encFlags = TCL_ENCODING_START;
174 retr.nextPtr = pendingRetrievals;
175 Tcl_DStringInit(&retr.buf);
176 pendingRetrievals = &retr;
177
178 /*
179 * Tcl/Tk says:
180 * Initiate the request for the selection. Note: can't use
181 * TkCurrentTime for the time. If we do, and this application hasn't
182 * received any X events in a long time, the current time will be way
183 * in the past and could even predate the time when the selection was
184 * made; if this happens, the request will be rejected.
185 *
186 * NI-S Believes that X ICCCM rules say we must use an event time
187 * and such a rejection is valid - try it and see.
188 */
189
190 XConvertSelection(winPtr->display, retr.selection, retr.target,
191 retr.property, retr.winPtr->window, TkCurrentTime(dispPtr,1));
192
193 /*
194 * Enter a loop processing X events until the selection
195 * has been retrieved and processed. If no response is
196 * received within a few seconds, then timeout.
197 */
198
199 retr.timeout = Tcl_CreateTimerHandler(1000, SelTimeoutProc,
200 (ClientData) &retr);
201 while (retr.result == -1) {
202 Tcl_DoOneEvent(0);
203 }
204 Tcl_DeleteTimerHandler(retr.timeout);
205
206 /*
207 * Unregister the information about the selection retrieval
208 * in progress.
209 */
210
211 if (pendingRetrievals == &retr) {
212 pendingRetrievals = retr.nextPtr;
213 } else {
214 TkSelRetrievalInfo *retrPtr;
215
216 for (retrPtr = pendingRetrievals; retrPtr != NULL;
217 retrPtr = retrPtr->nextPtr) {
218 if (retrPtr->nextPtr == &retr) {
219 retrPtr->nextPtr = retr.nextPtr;
220 break;
221 }
222 }
223 }
224 Tcl_DStringFree(&retr.buf);
225 return retr.result;
226 }
227
228 /*
229 *----------------------------------------------------------------------
230 *
231 * TkSelPropProc --
232 *
233 * This procedure is invoked when property-change events
234 * occur on windows not known to the toolkit. Its function
235 * is to implement the sending side of the INCR selection
236 * retrieval protocol when the selection requestor deletes
237 * the property containing a part of the selection.
238 *
239 * Results:
240 * None.
241 *
242 * Side effects:
243 * If the property that is receiving the selection was just
244 * deleted, then a new piece of the selection is fetched and
245 * placed in the property, until eventually there's no more
246 * selection to fetch.
247 *
248 *----------------------------------------------------------------------
249 */
250 void
251 TkSelPropProc(eventPtr)
252 register XEvent *eventPtr; /* X PropertyChange event. */
253 {
254 register IncrInfo *incrPtr;
255 register TkSelHandler *selPtr;
256 unsigned i;
257 int length, numItems;
258 Atom target, formatType = None;
259 long buffer[TK_SEL_WORDS_AT_ONCE];
260 TkDisplay *dispPtr = TkGetDisplay(eventPtr->xany.display);
261 Tk_ErrorHandler errorHandler;
262 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
263 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
264
265 /*
266 * See if this event announces the deletion of a property being
267 * used for an INCR transfer. If so, then add the next chunk of
268 * data to the property.
269 */
270
271 if (eventPtr->xproperty.state != PropertyDelete) {
272 return;
273 }
274 for (incrPtr = tsdPtr->pendingIncrs; incrPtr != NULL;
275 incrPtr = incrPtr->nextPtr) {
276 if (incrPtr->reqWindow != eventPtr->xproperty.window) {
277 continue;
278 }
279
280 /*
281 * For each conversion that has been requested, handle any
282 * chunks that haven't been transmitted yet.
283 */
284
285 for (i = 0; i < incrPtr->numConversions; i++) {
286 if ((eventPtr->xproperty.atom != incrPtr->multAtoms[2*i + 1])
287 || (incrPtr->converts[i].offset == -1)) {
288 continue;
289 }
290 target = incrPtr->multAtoms[2*i];
291 incrPtr->idleTime = 0;
292
293 /*
294 * Look for a matching selection handler.
295 */
296
297 for (selPtr = incrPtr->winPtr->selHandlerList; ;
298 selPtr = selPtr->nextPtr) {
299 if (selPtr == NULL) {
300 /*
301 * No handlers match, so mark the conversion as done.
302 */
303
304 incrPtr->multAtoms[2*i + 1] = None;
305 incrPtr->converts[i].offset = -1;
306 incrPtr->numIncrs --;
307 return;
308 }
309 if ((selPtr->target == target)
310 && (selPtr->selection == incrPtr->selection)) {
311 break;
312 }
313 }
314
315 /*
316 * We found a handler, so get the next chunk from it.
317 */
318
319 LangSelectHook("INCRRequest",(Tk_Window) incrPtr->winPtr,
320 selPtr->selection, selPtr->target, selPtr->format);
321
322 formatType = selPtr->format;
323 if (incrPtr->converts[i].offset == -2) {
324 /*
325 * We already got the last chunk, so send a null chunk
326 * to indicate that we are finished.
327 */
328
329 numItems = 0;
330 length = 0;
331 } else {
332 TkSelInProgress ip;
333 ip.selPtr = selPtr;
334 ip.nextPtr = TkSelGetInProgress();
335 TkSelSetInProgress(&ip);
336
337 /*
338 * Copy any bytes left over from a partial character at the end
339 * of the previous chunk into the beginning of the buffer.
340 * Pass the rest of the buffer space into the selection
341 * handler.
342 */
343
344 length = strlen(incrPtr->converts[i].buffer);
345 strcpy((char *)buffer, incrPtr->converts[i].buffer);
346
347 numItems = (*selPtr->proc)(selPtr->clientData,
348 incrPtr->converts[i].offset,
349 (long *)(((char *) buffer) + length),
350 TK_SEL_BYTES_AT_ONCE - length, formatType, (Tk_Window) incrPtr->winPtr);
351 TkSelSetInProgress(ip.nextPtr);
352 if (ip.selPtr == NULL) {
353 /*
354 * The selection handler deleted itself.
355 */
356
357 return;
358 }
359 if (numItems < 0) {
360 numItems = 0;
361 }
362 numItems += length;
363 if (numItems > TK_SEL_BYTES_AT_ONCE) {
364 panic("selection handler returned too many bytes");
365 }
366 }
367 ((char *) buffer)[numItems] = 0;
368
369 errorHandler = Tk_CreateErrorHandler(eventPtr->xproperty.display,
•370 -1, -1, -1, (int (*)(void *, XErrorEvent *)) NULL, (ClientData) NULL);
371 /*
372 * Encode the data using the proper format for each type.
373 */
374
375 if ((formatType == XA_STRING)
376 || (dispPtr && formatType==dispPtr->utf8Atom)
377 || (dispPtr && formatType==dispPtr->compoundTextAtom)) {
378 char *space = NULL;
379 int spaceAlloc = 0;
380 int spaceUsed = 0;
381 int encodingCvtFlags;
382 int srcLen, dstLen, result, srcRead, dstWrote, soFar;
383 char *src, *dst;
384 Tcl_Encoding encoding;
385
386 /*
387 * Set up the encoding state based on the format and whether
388 * this is the first and/or last chunk.
389 */
390
391 encodingCvtFlags = 0;
392 if (incrPtr->converts[i].offset == 0) {
393 encodingCvtFlags |= TCL_ENCODING_START;
394 }
395 if (numItems < TK_SEL_BYTES_AT_ONCE) {
396 encodingCvtFlags |= TCL_ENCODING_END;
397 }
398 if (formatType == XA_STRING) {
399 encoding = Tcl_GetEncoding(NULL, "iso8859-1");
400 } else if (dispPtr && formatType==dispPtr->utf8Atom) {
401 encoding = Tcl_GetEncoding(NULL, "utf-8");
402 } else {
403 encoding = Tcl_GetEncoding(NULL, "iso2022");
404 }
405
406 /*
407 * Now convert the data.
408 */
409
410 src = (char *)buffer;
411 srcLen = numItems;
412
413 dstLen = 2*numItems;
414 if (dstLen < 16) {
415 dstLen = 16;
416 }
417 space = ckalloc(dstLen+1);
418 if (space) {
419 spaceAlloc = dstLen;
420 }
421 dst = space;
422 dstLen = spaceAlloc;
423
424 /*
425 * Now convert the data, growing the destination buffer
426 * as needed.
427 */
428
429 while (1) {
430 result = Tcl_UtfToExternal(NULL, encoding,
431 src, srcLen, encodingCvtFlags,
432 &incrPtr->converts[i].state,
433 dst, dstLen, &srcRead, &dstWrote, NULL);
434 soFar = dst + dstWrote - space;
435 encodingCvtFlags &= ~TCL_ENCODING_START;
436 src += srcRead;
437 srcLen -= srcRead;
438 spaceUsed = soFar;
439 if (result != TCL_CONVERT_NOSPACE) {
440 break;
441 }
442 /* use dst/dstLen as scratch for realloc */
443 dstLen = 2*spaceUsed;
444 if (!dstLen) {
445 dstLen = numItems;
446 }
447 if ((dst = ckrealloc(space,dstLen+1))) {
448 space = dst;
449 spaceAlloc = dstLen;
450 }
451 else {
452 /* Could not get that much */
453 panic("Could not get %d bytes for conversion",dstLen+1);
454 break;
455 }
456 /* reset dst/dstLen for avail region */
457 dst = space + soFar;
458 dstLen = spaceAlloc - (soFar);
459 }
460 spaceUsed = soFar;
461 space[spaceUsed] = '\0';
462
463 if (encoding) {
464 Tcl_FreeEncoding(encoding);
465 }
466
467 /*
468 * Set the property to the encoded string value.
469 */
470
471 XChangeProperty(eventPtr->xproperty.display,
472 eventPtr->xproperty.window, eventPtr->xproperty.atom,
473 formatType, 8, PropModeReplace,
474 (unsigned char *) space, spaceUsed);
475
476 /*
477 * Preserve any left-over bytes.
478 */
479
480 if (srcLen > TCL_UTF_MAX) {
481 panic("selection conversion left too many bytes unconverted");
482 }
483 memcpy(incrPtr->converts[i].buffer, src, (size_t) srcLen+1);
484 ckfree(space);
485 } else {
486 #ifdef _LANG
487 /*
488 * Set the property to something other than a string
489 */
490
491 long *propPtr = (long *) ckalloc(TK_SEL_BYTES_AT_ONCE);
492 numItems = TkSelCvtToX(propPtr, (char *) buffer,
493 formatType, (Tk_Window) incrPtr->winPtr,
494 TK_SEL_BYTES_AT_ONCE);
495
496 XChangeProperty(eventPtr->xproperty.display,
497 eventPtr->xproperty.window,
498 eventPtr->xproperty.atom, formatType, 32,
499 PropModeReplace,
500 (unsigned char *) propPtr, numItems);
501
502 ckfree((char *)propPtr);
503 #else
504 /*
505 * Set the property to the encoded string value.
506 */
507
508 char *propPtr = (char *) SelCvtToX((char *) buffer,
509 formatType, (Tk_Window) incrPtr->winPtr,
510 &numItems);
511
512 XChangeProperty(eventPtr->xproperty.display,
513 eventPtr->xproperty.window,
514 eventPtr->xproperty.atom, formatType, 8,
515 PropModeReplace,
516 (unsigned char *) Tcl_DStringValue(&ds), numItems);
517
518 ckfree(propPtr);
519 #endif
520 }
521 Tk_DeleteErrorHandler(errorHandler);
522
523 /*
524 * Compute the next offset value. If this was the last chunk,
525 * then set the offset to -2. If this was an empty chunk,
526 * then set the offset to -1 to indicate we are done.
527 */
528
529 if (numItems < TK_SEL_BYTES_AT_ONCE) {
530 if (numItems <= 0) {
531 incrPtr->converts[i].offset = -1;
532 incrPtr->numIncrs--;
533 } else {
534 incrPtr->converts[i].offset = -2;
535 }
536 } else {
537 /*
538 * Advance over the selection data that was consumed
539 * this time.
540 */
541
542 incrPtr->converts[i].offset += numItems - length;
543 }
544 return;
545 }
546 }
547 }
548
549 /*
550 *--------------------------------------------------------------
551 *
552 * TkSelEventProc --
553 *
554 * This procedure is invoked whenever a selection-related
555 * event occurs. It does the lion's share of the work
556 * in implementing the selection protocol.
557 *
558 * Results:
559 * None.
560 *
561 * Side effects:
562 * Lots: depends on the type of event.
563 *
564 *--------------------------------------------------------------
565 */
566
567 void
568 TkSelEventProc(tkwin, eventPtr)
569 Tk_Window tkwin; /* Window for which event was
570 * targeted. */
571 register XEvent *eventPtr; /* X event: either SelectionClear,
572 * SelectionRequest, or
573 * SelectionNotify. */
574 {
575 register TkWindow *winPtr = (TkWindow *) tkwin;
576 TkDisplay *dispPtr = winPtr->dispPtr;
577 Tcl_Interp *interp;
578
579 /*
580 * Case #1: SelectionClear events.
581 */
582
583 if (eventPtr->type == SelectionClear) {
584 TkSelClearSelection(tkwin, eventPtr);
585 }
586
587 /*
588 * Case #2: SelectionNotify events. Call the relevant procedure
589 * to handle the incoming selection.
590 */
591
592 if (eventPtr->type == SelectionNotify) {
593 register TkSelRetrievalInfo *retrPtr;
594 long *propInfo;
595 Atom type;
596 int format, result;
597 unsigned long numItems, bytesAfter;
598 Tcl_DString ds;
599 Tcl_Encoding encoding;
600
601 for (retrPtr = pendingRetrievals; ; retrPtr = retrPtr->nextPtr) {
602 if (retrPtr == NULL) {
603 return;
604 }
605 if ((retrPtr->winPtr == winPtr)
606 && (retrPtr->selection == eventPtr->xselection.selection)
607 && (retrPtr->target == eventPtr->xselection.target)
608 && (retrPtr->result == -1)) {
609 if (retrPtr->property == eventPtr->xselection.property) {
610 break;
611 }
612 if (eventPtr->xselection.property == None) {
613 Tcl_SetResult(retrPtr->interp, (char *) NULL, TCL_STATIC);
614 Tcl_AppendResult(retrPtr->interp,
615 Tk_GetAtomName(tkwin, retrPtr->selection),
616 " selection doesn't exist or form \"",
617 Tk_GetAtomName(tkwin, retrPtr->target),
618 "\" not defined", (char *) NULL);
619 retrPtr->result = TCL_ERROR;
620 return;
621 }
622 }
623 }
624
625 propInfo = NULL;
626 result = XGetWindowProperty(eventPtr->xselection.display,
627 eventPtr->xselection.requestor, retrPtr->property,
628 0, MAX_PROP_WORDS, False, (Atom) AnyPropertyType,
629 &type, &format, &numItems, &bytesAfter,
630 (unsigned char **) &propInfo);
631 if ((result != Success) || (type == None)) {
632 return;
633 }
634 if (bytesAfter != 0) {
635 Tcl_SetResult(retrPtr->interp, "selection property too large",
636 TCL_STATIC);
637 retrPtr->result = TCL_ERROR;
638 XFree((char *) propInfo);
639 return;
640 }
641
642 LangSelectHook("Notify",(Tk_Window) winPtr, retrPtr->selection, retrPtr->target, type);
643
644 if (type == dispPtr->utf8Atom) {
645 /*
646 * The X selection data is in UTF-8 format already.
647 * We can't guarantee that propInfo is NULL-terminated,
648 * so we might have to copy the string.
649 */
650 char *propData = (char *) propInfo;
651
652 if (format != 8) {
653 char buf[64 + TCL_INTEGER_SPACE];
654
655 sprintf(buf,
656 "bad format for UTF-8 string selection: wanted \"8\", got \"%d\"",
657 format);
658 Tcl_SetResult(retrPtr->interp, buf, TCL_VOLATILE);
659 retrPtr->result = TCL_ERROR;
660 return;
661 }
662
663 if (numItems >= sizeof(long)*MAX_PROP_WORDS || propData[numItems] != '\0') {
664 propData = ckalloc((size_t) numItems + 1);
665 strncpy(propData, (char *) propInfo, numItems);
666 propData[numItems] = '\0';
667 }
668 retrPtr->result = (*retrPtr->proc)(retrPtr->clientData, retrPtr->interp, (long *) propData,
669 numItems, format, type, (Tk_Window) winPtr);
670 if (propData != (char *) propInfo) {
671 ckfree((char *) propData);
672 }
673 } else if (type == dispPtr->incrAtom) {
674
675 /*
676 * It's a !?#@!?!! INCR-style reception. Arrange to receive
677 * the selection in pieces, using the ICCCM protocol, then
678 * hang around until either the selection is all here or a
679 * timeout occurs.
680 */
681
682 retrPtr->idleTime = 0;
683 Tk_CreateEventHandler(tkwin, PropertyChangeMask, SelRcvIncrProc,
684 (ClientData) retrPtr);
685 XDeleteProperty(Tk_Display(tkwin), Tk_WindowId(tkwin),
686 retrPtr->property);
687 while (retrPtr->result == -1) {
688 Tcl_DoOneEvent(0);
689 }
690 Tk_DeleteEventHandler(tkwin, PropertyChangeMask, SelRcvIncrProc,
691 (ClientData) retrPtr);
692 } else if ((type == XA_STRING) || (type == dispPtr->textAtom)
693 || (type == dispPtr->compoundTextAtom)) {
694 if (format != 8) {
695 char buf[64 + TCL_INTEGER_SPACE];
696
697 sprintf(buf,
698 "bad format for string selection: wanted \"8\", got \"%d\"",
699 format);
700 Tcl_SetResult(retrPtr->interp, buf, TCL_VOLATILE);
701 retrPtr->result = TCL_ERROR;
702 return;
703 }
704 interp = retrPtr->interp;
705 Tcl_Preserve((ClientData) interp);
706
707 /*
708 * Convert the X selection data into UTF before passing it
709 * to the selection callback. Note that the COMPOUND_TEXT
710 * uses a modified iso2022 encoding, not the current system
711 * encoding. For now we'll just blindly apply the iso2022
712 * encoding. This is probably wrong, but it's a placeholder
713 * until we figure out what we're really supposed to do. For
714 * STRING, we need to use Latin-1 instead. Again, it's not
715 * really the full iso8859-1 space, but this is close enough.
716 */
717
718 if (type == dispPtr->compoundTextAtom) {
719 encoding = Tcl_GetEncoding(NULL, "iso2022");
720 } else {
721 encoding = Tcl_GetEncoding(NULL, "iso8859-1");
722 }
723 Tcl_ExternalToUtfDString(encoding, (char *) propInfo, (int)numItems, &ds);
724 if (encoding) {
725 Tcl_FreeEncoding(encoding);
726 }
727 /*
728 * Assuming we know about UTF8_STRING then use that as the type
729 * when calling the handler
730 */
731 if (dispPtr->utf8Atom) {
732 type = dispPtr->utf8Atom;
733 }
734 retrPtr->result = (*retrPtr->proc)(retrPtr->clientData,
735 interp, (long *) Tcl_DStringValue(&ds), Tcl_DStringLength(&ds),
736 format, type, (Tk_Window) winPtr);
737 Tcl_DStringFree(&ds);
738 Tcl_Release((ClientData) interp);
739 } else {
740 #ifndef _LANG
741 char *string;
742 if (format != 32) {
743 char buf[64 + TCL_INTEGER_SPACE];
744
745 sprintf(buf,
746 "bad format for selection: wanted \"32\", got \"%d\"",
747 format);
748 Tcl_SetResult(retrPtr->interp, buf, TCL_VOLATILE);
749 retrPtr->result = TCL_ERROR;
750 XFree((char *) propInfo);
751 return;
752 }
753 string = TkSelCvtFromX((long *) propInfo, (int) numItems, type,
754 (Tk_Window) winPtr);
755 #endif
756 interp = retrPtr->interp;
757 Tcl_Preserve((ClientData) interp);
758 retrPtr->result = (*retrPtr->proc)(retrPtr->clientData,
759 interp, propInfo, (int) numItems, format, type, (Tk_Window) winPtr);
760 Tcl_Release((ClientData) interp);
761 }
762 XFree((char *) propInfo);
763 return;
764 }
765
766 /*
767 * Case #3: SelectionRequest events. Call ConvertSelection to
768 * do the dirty work.
769 */
770
771 if (eventPtr->type == SelectionRequest) {
772 ConvertSelection(winPtr, &eventPtr->xselectionrequest);
773 return;
774 }
775 }
776
777 /*
778 *----------------------------------------------------------------------
779 *
780 * SelTimeoutProc --
781 *
782 * This procedure is invoked once every second while waiting for
783 * the selection to be returned. After a while it gives up and
784 * aborts the selection retrieval.
785 *
786 * Results:
787 * None.
788 *
789 * Side effects:
790 * A new timer callback is created to call us again in another
791 * second, unless time has expired, in which case an error is
792 * recorded for the retrieval.
793 *
794 *----------------------------------------------------------------------
795 */
796
797 static void
798 SelTimeoutProc(clientData)
799 ClientData clientData; /* Information about retrieval
800 * in progress. */
801 {
802 register TkSelRetrievalInfo *retrPtr = (TkSelRetrievalInfo *) clientData;
803
804 /*
805 * Make sure that the retrieval is still in progress. Then
806 * see how long it's been since any sort of response was received
807 * from the other side.
808 */
809
810 if (retrPtr->result != -1) {
811 return;
812 }
813 retrPtr->idleTime++;
814 if (retrPtr->idleTime >= 5) {
815
816 /*
817 * Use a careful procedure to store the error message, because
818 * the result could already be partially filled in with a partial
819 * selection return.
820 */
821
822 Tcl_SetResult(retrPtr->interp, "selection owner didn't respond",
823 TCL_STATIC);
824 retrPtr->result = TCL_ERROR;
825 } else {
826 retrPtr->timeout = Tcl_CreateTimerHandler(1000, SelTimeoutProc,
827 (ClientData) retrPtr);
828 }
829 }
830
831 /*
832 *----------------------------------------------------------------------
833 *
834 * ConvertSelection --
835 *
836 * This procedure is invoked to handle SelectionRequest events.
837 * It responds to the requests, obeying the ICCCM protocols.
838 *
839 * Results:
840 * None.
841 *
842 * Side effects:
843 * Properties are created for the selection requestor, and a
844 * SelectionNotify event is generated for the selection
845 * requestor. In the event of long selections, this procedure
846 * implements INCR-mode transfers, using the ICCCM protocol.
847 *
848 *----------------------------------------------------------------------
849 */
850
851 static void
852 ConvertSelection(winPtr, eventPtr)
853 TkWindow *winPtr; /* Window that received the
854 * conversion request; may not be
855 * selection's current owner, be we
856 * set it to the current owner. */
857 register XSelectionRequestEvent *eventPtr;
858 /* Event describing request. */
859 {
860 XSelectionEvent reply; /* Used to notify requestor that
861 * selection info is ready. */
862 int multiple; /* Non-zero means a MULTIPLE request
863 * is being handled. */
864 IncrInfo incr; /* State of selection conversion. */
865 Atom singleInfo[2]; /* incr.multAtoms points here except
866 * for multiple conversions. */
867 unsigned i;
868 Tk_ErrorHandler errorHandler;
869 TkSelectionInfo *infoPtr;
870 TkSelInProgress ip;
871 ThreadSpecificData *tsdPtr = (ThreadSpecificData *)
872 Tcl_GetThreadData(&dataKey, sizeof(ThreadSpecificData));
873
874 errorHandler = Tk_CreateErrorHandler(eventPtr->display, -1, -1,-1,
•875 (int (*)(void *, XErrorEvent *)) NULL, (ClientData) NULL);
876
877 /*
878 * Initialize the reply event.
879 */
880
881 reply.type = SelectionNotify;
882 reply.serial = 0;
883 reply.send_event = True;
884 reply.display = eventPtr->display;
885 reply.requestor = eventPtr->requestor;
886 reply.selection = eventPtr->selection;
887 reply.target = eventPtr->target;
888 reply.property = eventPtr->property;
889 if (reply.property == None) {
890 reply.property = reply.target;
891 }
892 reply.time = eventPtr->time;
893
894 for (infoPtr = winPtr->dispPtr->selectionInfoPtr; infoPtr != NULL;
895 infoPtr = infoPtr->nextPtr) {
896 if (infoPtr->selection == eventPtr->selection)
897 break;
898 }
899 if (infoPtr == NULL) {
900 goto refuse;
901 }
902 winPtr = (TkWindow *) infoPtr->owner;
903
904 /*
905 * Figure out which kind(s) of conversion to perform. If handling
906 * a MULTIPLE conversion, then read the property describing which
907 * conversions to perform.
908 */
909
910 incr.winPtr = winPtr;
911 incr.selection = eventPtr->selection;
912 if (eventPtr->target != winPtr->dispPtr->multipleAtom) {
913 multiple = 0;
914 singleInfo[0] = reply.target;
915 singleInfo[1] = reply.property;
916 incr.multAtoms = singleInfo;
917 incr.numConversions = 1;
918 } else {
919 Atom type;
920 int format, result;
921 unsigned long bytesAfter;
922
923 multiple = 1;
924 incr.multAtoms = NULL;
925 if (eventPtr->property == None) {
926 goto refuse;
927 }
928 result = XGetWindowProperty(eventPtr->display,
929 eventPtr->requestor, eventPtr->property,
930 0, MAX_PROP_WORDS, False, XA_ATOM,
931 &type, &format, &incr.numConversions, &bytesAfter,
932 (unsigned char **) &incr.multAtoms);
933 if (result == Success && incr.numConversions == 0 && format == 32 &&
934 type != XA_ATOM && type != None) {
935 result = XGetWindowProperty(eventPtr->display,
936 eventPtr->requestor, eventPtr->property,
937 0, MAX_PROP_WORDS, False, type,
938 &type, &format, &incr.numConversions, &bytesAfter,
939 (unsigned char **) &incr.multAtoms);
940 }
941 if ((result != Success) || (bytesAfter != 0) || (format != 32)
942 || (type == None)) {
943 if (incr.multAtoms != NULL) {
944 XFree((char *) incr.multAtoms);
945 }
946 goto refuse;
947 }
948 incr.numConversions /= 2; /* Two atoms per conversion. */
949 }
950
951 /*
952 * Loop through all of the requested conversions, and either return
953 * the entire converted selection, if it can be returned in a single
954 * bunch, or return INCR information only (the actual selection will
955 * be returned below).
956 */
957
958 incr.converts = (ConvertInfo *) ckalloc((unsigned)
959 (incr.numConversions*sizeof(ConvertInfo)));
960 incr.numIncrs = 0;
961 for (i = 0; i < incr.numConversions; i++) {
962 Atom target, property, type = XA_STRING;
963 long buffer[TK_SEL_WORDS_AT_ONCE];
964 register TkSelHandler *selPtr;
965 int numItems, format = 8;
966 char *propPtr = (char *) buffer;
967
968 target = incr.multAtoms[2*i];
969 property = incr.multAtoms[2*i + 1];
970 incr.converts[i].offset = -1;
971 incr.converts[i].buffer[0] = '\0';
972
973 /* If we get asked for compound text look for string/utf8_string ?
974 otherwise cannot see how it would ever get handled
975 despite the encoding call below.
976 Also presumably TEXT could do the same and convert
977 to locale encoding?
978 */
979
980 for (selPtr = winPtr->selHandlerList; selPtr != NULL;
981 selPtr = selPtr->nextPtr) {
982 if ((selPtr->target == target)
983 && (selPtr->selection == eventPtr->selection)) {
984 break;
985 }
986 }
987
988 if (selPtr == NULL) {
989 /*
990 * Nobody seems to know about this kind of request. If
991 * it's of a sort that we can handle without any help, do
992 * it. Otherwise mark the request as an errror.
993 */
994
995 numItems = TkSelDefaultSelection(infoPtr, target, buffer,
996 TK_SEL_BYTES_AT_ONCE, &type, &format);
997 if (numItems < 0) {
998 incr.multAtoms[2*i + 1] = None;
999 LangSelectHook("Request",(Tk_Window) winPtr, infoPtr->selection, target, None);
1000 continue;
1001 }
1002 } else {
1003 ip.selPtr = selPtr;
1004 ip.nextPtr = TkSelGetInProgress();
1005 TkSelSetInProgress(&ip);
1006 type = selPtr->format;
1007 if ((type == XA_STRING)
1008 || (type==winPtr->dispPtr->utf8Atom)
1009 || (type==winPtr->dispPtr->textAtom)
1010 || (type==winPtr->dispPtr->compoundTextAtom)) {
1011 format = 8;
1012 } else {
1013 format = 32;
1014 }
1015 numItems = (*selPtr->proc)(selPtr->clientData, 0,
1016 buffer, TK_SEL_BYTES_AT_ONCE, type, (Tk_Window) winPtr);
1017 TkSelSetInProgress(ip.nextPtr);
1018 if ((ip.selPtr == NULL) || (numItems < 0)) {
1019 incr.multAtoms[2*i + 1] = None;
1020 continue;
1021 }
1022 if (numItems > TK_SEL_BYTES_AT_ONCE) {
1023 panic("selection handler returned too many bytes");
1024 }
1025 ((char *) buffer)[numItems] = '\0';
1026 }
1027
1028 /*
1029 * Got the selection; store it back on the requestor's property.
1030 */
1031
1032 if (numItems == TK_SEL_BYTES_AT_ONCE) {
1033 /*
1034 * Selection is too big to send at once; start an
1035 * INCR-mode transfer.
1036 */
1037
1038 incr.numIncrs++;
1039 type = winPtr->dispPtr->incrAtom;
1040 buffer[0] = SelectionSize(selPtr, type, (Tk_Window) winPtr);
1041 /* What units is the value we are returning here ?
1042 SelctionSize counts numItems things which are
1043 expected to be bytes for Tcl world.
1044 Size is also size before encoding ...
1045 */
1046 if (buffer[0] == 0) {
1047 incr.multAtoms[2*i + 1] = None;
1048 continue;
1049 }
1050 numItems = 1;
1051 propPtr = (char *) buffer;
1052 format = 32;
1053 incr.converts[i].offset = 0;
1054 XChangeProperty(reply.display, reply.requestor,
1055 property, type, format, PropModeReplace,
1056 (unsigned char *) propPtr, numItems);
1057 } else if (type == winPtr->dispPtr->utf8Atom) {
1058 /*
1059 * This matches selection requests of type UTF8_STRING,
1060 * which allows us to pass our utf-8 information untouched.
1061 */
1062
1063 XChangeProperty(reply.display, reply.requestor,
1064 property, type, 8, PropModeReplace,
1065 (unsigned char *) buffer, numItems);
1066 } else if ((type == XA_STRING)
1067 || (type == winPtr->dispPtr->compoundTextAtom)) {
1068 Tcl_DString ds;
1069 Tcl_Encoding encoding;
1070
1071 /*
1072 * STRING is Latin-1, COMPOUND_TEXT is an iso2022 variant.
1073 * We need to convert the selection text into these external
1074 * forms before modifying the property.
1075 */
1076
1077
1078 if (type == XA_STRING) {
1079 encoding = Tcl_GetEncoding(NULL, "iso8859-1");
1080 } else {
1081 encoding = Tcl_GetEncoding(NULL, "iso2022");
1082 }
1083 /* What does this do if it cannot encode ?
1084 we "should" fail in that case
1085 */
1086 Tcl_UtfToExternalDString(encoding, (char*)buffer, numItems, &ds);
1087 XChangeProperty(reply.display, reply.requestor,
1088 property, type, 8, PropModeReplace,
1089 (unsigned char *) Tcl_DStringValue(&ds),
1090 Tcl_DStringLength(&ds));
1091 if (encoding) {
1092 Tcl_FreeEncoding(encoding);
1093 }
1094 Tcl_DStringFree(&ds);
1095 } else {
1096 /* Put value in format/type provided */
1097 XChangeProperty(reply.display, reply.requestor,
1098 property, type, format, PropModeReplace,
1099 (unsigned char *) buffer, numItems);
1100 }
1101 }
1102
1103 /*
1104 * Send an event back to the requestor to indicate that the
1105 * first stage of conversion is complete (everything is done
1106 * except for long conversions that have to be done in INCR
1107 * mode).
1108 */
1109
1110 if (incr.numIncrs > 0) {
1111 XSelectInput(reply.display, reply.requestor, PropertyChangeMask);
1112 incr.timeout = Tcl_CreateTimerHandler(1000, IncrTimeoutProc,
1113 (ClientData) &incr);
1114 incr.idleTime = 0;
1115 incr.reqWindow = reply.requestor;
1116 incr.time = infoPtr->time;
1117 incr.nextPtr = tsdPtr->pendingIncrs;
1118 tsdPtr->pendingIncrs = &incr;
1119 }
1120 if (multiple) {
1121 XChangeProperty(reply.display, reply.requestor, reply.property,
1122 XA_ATOM, 32, PropModeReplace,
1123 (unsigned char *) incr.multAtoms,
1124 (int) incr.numConversions*2);
1125 } else {
1126
1127 /*
1128 * Not a MULTIPLE request. The first property in "multAtoms"
1129 * got set to None if there was an error in conversion.
1130 */
1131
1132 reply.property = incr.multAtoms[1];
1133 }
1134 XSendEvent(reply.display, reply.requestor, False, 0, (XEvent *) &reply);
1135 Tk_DeleteErrorHandler(errorHandler);
1136
1137 /*
1138 * Handle any remaining INCR-mode transfers. This all happens
1139 * in callbacks to TkSelPropProc, so just wait until the number
1140 * of uncompleted INCR transfers drops to zero.
1141 */
1142
1143 if (incr.numIncrs > 0) {
1144 IncrInfo *incrPtr2;
1145
1146 while (incr.numIncrs > 0) {
1147 Tcl_DoOneEvent(0);
1148 }
1149 Tcl_DeleteTimerHandler(incr.timeout);
1150 /* winPtr may have been destroyed now */
1151 errorHandler = Tk_CreateErrorHandler(reply.display,
•1152 -1, -1,-1, (int (*)(void *, XErrorEvent *)) NULL, (ClientData) NULL);
1153 XSelectInput(reply.display, reply.requestor, 0L);
1154 Tk_DeleteErrorHandler(errorHandler);
1155 if (tsdPtr->pendingIncrs == &incr) {
1156 tsdPtr->pendingIncrs = incr.nextPtr;
1157 } else {
1158 for (incrPtr2 = tsdPtr->pendingIncrs; incrPtr2 != NULL;
1159 incrPtr2 = incrPtr2->nextPtr) {
1160 if (incrPtr2->nextPtr == &incr) {
1161 incrPtr2->nextPtr = incr.nextPtr;
1162 break;
1163 }
1164 }
1165 }
1166 }
1167
1168 /*
1169 * All done. Cleanup and return.
1170 */
1171
1172 ckfree((char *) incr.converts);
1173 if (multiple) {
1174 XFree((char *) incr.multAtoms);
1175 }
1176 return;
1177
1178 /*
1179 * An error occurred. Send back a refusal message.
1180 */
1181
1182 refuse:
1183 reply.property = None;
1184 XSendEvent(reply.display, reply.requestor, False, 0, (XEvent *) &reply);
1185 Tk_DeleteErrorHandler(errorHandler);
1186 return;
1187 }
1188
1189 /*
1190 *----------------------------------------------------------------------
1191 *
1192 * SelRcvIncrProc --
1193 *
1194 * This procedure handles the INCR protocol on the receiving
1195 * side. It is invoked in response to property changes on
1196 * the requestor's window (which hopefully are because a new
1197 * chunk of the selection arrived).
1198 *
1199 * Results:
1200 * None.
1201 *
1202 * Side effects:
1203 * If a new piece of selection has arrived, a procedure is
1204 * invoked to deal with that piece. When the whole selection
1205 * is here, a flag is left for the higher-level procedure that
1206 * initiated the selection retrieval.
1207 *
1208 *----------------------------------------------------------------------
1209 */
1210
1211 static void
1212 SelRcvIncrProc(clientData, eventPtr)
1213 ClientData clientData; /* Information about retrieval. */
1214 register XEvent *eventPtr; /* X PropertyChange event. */
1215 {
1216 register TkSelRetrievalInfo *retrPtr = (TkSelRetrievalInfo *) clientData;
1217 char *propInfo;
1218 Atom type;
1219 int format, result;
1220 unsigned long numItems, bytesAfter;
1221 Tcl_Interp *interp;
1222
1223 if ((eventPtr->xproperty.atom != retrPtr->property)
1224 || (eventPtr->xproperty.state != PropertyNewValue)
1225 || (retrPtr->result != -1)) {
1226 return;
1227 }
1228 propInfo = NULL;
1229 result = XGetWindowProperty(eventPtr->xproperty.display,
1230 eventPtr->xproperty.window, retrPtr->property, 0, MAX_PROP_WORDS,
1231 True, (Atom) AnyPropertyType, &type, &format, &numItems,
1232 &bytesAfter, (unsigned char **) &propInfo);
1233 if ((result != Success) || (type == None)) {
1234 return;
1235 }
1236 if (bytesAfter != 0) {
1237 Tcl_SetResult(retrPtr->interp, "selection property too large",
1238 TCL_STATIC);
1239 retrPtr->result = TCL_ERROR;
1240 goto done;
1241 }
1242
1243 LangSelectHook("INCRNotify",(Tk_Window) retrPtr->winPtr,
1244 retrPtr->selection, retrPtr->target, type);
1245
1246 if ((type == XA_STRING)
1247 || (type == retrPtr->winPtr->dispPtr->textAtom)
1248 || (type == retrPtr->winPtr->dispPtr->utf8Atom)
1249 || (type == retrPtr->winPtr->dispPtr->compoundTextAtom)) {
1250 char *dst, *src;
1251 int srcLen, dstLen, srcRead, dstWrote, soFar;
1252 Tcl_Encoding encoding;
1253 Tcl_DString *dstPtr, temp;
1254
1255 if (format != 8) {
1256 char buf[64 + TCL_INTEGER_SPACE];
1257
1258 sprintf(buf,
1259 "bad format for string selection: wanted \"8\", got \"%d\"",
1260 format);
1261 Tcl_SetResult(retrPtr->interp, buf, TCL_VOLATILE);
1262 retrPtr->result = TCL_ERROR;
1263 goto done;
1264 }
1265 interp = retrPtr->interp;
1266 Tcl_Preserve((ClientData) interp);
1267
1268 if (type == retrPtr->winPtr->dispPtr->compoundTextAtom) {
1269 encoding = Tcl_GetEncoding(NULL, "iso2022");
1270 } else if (type == retrPtr->winPtr->dispPtr->utf8Atom) {
1271 /* We use encoding even though we have data as UTF-8 as code
1272 below handles partial characters at buffer boundaries
1273 */
1274 encoding = Tcl_GetEncoding(NULL, "utf-8");
1275 } else {
1276 encoding = Tcl_GetEncoding(NULL, "iso8859-1");
1277 }
1278
1279 /*
1280 * Check to see if there is any data left over from the previous
1281 * chunk. If there is, copy the old data and the new data into
1282 * a new buffer.
1283 */
1284
1285 Tcl_DStringInit(&temp);
1286 if (Tcl_DStringLength(&retrPtr->buf) > 0) {
1287 Tcl_DStringAppend(&temp, Tcl_DStringValue(&retrPtr->buf),
1288 Tcl_DStringLength(&retrPtr->buf));
1289 if (numItems > 0) {
1290 Tcl_DStringAppend(&temp, propInfo, (int)numItems);
1291 }
1292 src = Tcl_DStringValue(&temp);
1293 srcLen = Tcl_DStringLength(&temp);
1294 } else if (numItems == 0) {
1295 /*
1296 * There is no new data, so we're done.
1297 */
1298
1299 retrPtr->result = TCL_OK;
1300 Tcl_Release((ClientData) interp);
1301 goto done;
1302 } else {
1303 src = propInfo;
1304 srcLen = numItems;
1305 }
1306
1307 /*
1308 * Set up the destination buffer so we can use as much space as
1309 * is available.
1310 */
1311
1312 dstPtr = &retrPtr->buf;
1313 Tcl_DStringSetLength(dstPtr,2*numItems);
1314 Tcl_DStringSetLength(dstPtr,0);
1315 dst = Tcl_DStringValue(dstPtr);
1316 dstLen = 2*numItems;
1317
1318 /*
1319 * Now convert the data, growing the destination buffer as needed.
1320 */
1321
1322 while (1) {
1323 result = Tcl_ExternalToUtf(NULL, encoding, src, srcLen,
1324 retrPtr->encFlags, &retrPtr->encState,
1325 dst, dstLen, &srcRead, &dstWrote, NULL);
1326 soFar = dst + dstWrote - Tcl_DStringValue(dstPtr);
1327 retrPtr->encFlags &= ~TCL_ENCODING_START;
1328 src += srcRead;
1329 srcLen -= srcRead;
1330 if (result != TCL_CONVERT_NOSPACE) {
1331 Tcl_DStringSetLength(dstPtr, soFar);
1332 break;
1333 }
1334 if (Tcl_DStringLength(dstPtr) == 0) {
1335 Tcl_DStringSetLength(dstPtr, dstLen);
1336 }
1337 Tcl_DStringSetLength(dstPtr, 2 * Tcl_DStringLength(dstPtr) + 1);
1338 dst = Tcl_DStringValue(dstPtr) + soFar;
1339 dstLen = Tcl_DStringLength(dstPtr) - soFar - 1;
1340 }
1341 Tcl_DStringSetLength(dstPtr, soFar);
1342
1343 if (retrPtr->winPtr->dispPtr->utf8Atom) {
1344 type = retrPtr->winPtr->dispPtr->utf8Atom;
1345 }
1346
1347 result = (*retrPtr->proc)(retrPtr->clientData, interp,
1348 (long *) Tcl_DStringValue(dstPtr), Tcl_DStringLength(dstPtr),
1349 format, type, (Tk_Window) retrPtr->winPtr);
1350 Tcl_Release((ClientData) interp);
1351
1352 /*
1353 * Copy any unused data into the destination buffer so we can
1354 * pick it up next time around.
1355 */
1356
1357 Tcl_DStringSetLength(dstPtr, 0);
1358 Tcl_DStringAppend(dstPtr, src, srcLen);
1359
1360 Tcl_DStringFree(&temp);
1361 if (encoding) {
1362 Tcl_FreeEncoding(encoding);
1363 }
1364 if (result != TCL_OK) {
1365 retrPtr->result = result;
1366 }
1367 } else if (numItems == 0) {
1368 retrPtr->result = TCL_OK;
1369 } else {
1370 #ifndef _LANG
1371 char *string;
1372
1373 if (format != 32) {
1374 char buf[64 + TCL_INTEGER_SPACE];
1375
1376 sprintf(buf,
1377 "bad format for selection: wanted \"32\", got \"%d\"",
1378 format);
1379 Tcl_SetResult(retrPtr->interp, buf, TCL_VOLATILE);
1380 retrPtr->result = TCL_ERROR;
1381 goto done;
1382 }
1383 string = TkSelCvtFromX((long *) propInfo, (int) numItems, type,
1384 (Tk_Window) retrPtr->winPtr);
1385 #endif
1386 interp = retrPtr->interp;
1387 Tcl_Preserve((ClientData) interp);
1388 result = (*retrPtr->proc)(retrPtr->clientData, interp,
1389 (long *) propInfo, (int) numItems, format, type, (Tk_Window) retrPtr->winPtr);
1390 Tcl_Release((ClientData) interp);
1391 if (result != TCL_OK) {
1392 retrPtr->result = result;
1393 }
1394 }
1395
1396 done:
1397 XFree((char *) propInfo);
1398 retrPtr->idleTime = 0;
1399 }
1400
1401 /*
1402 *----------------------------------------------------------------------
1403 *
1404 * SelectionSize --
1405 *
1406 * This procedure is called when the selection is too large to
1407 * send in a single buffer; it computes the total length of
1408 * the selection in bytes.
1409 *
1410 * Results:
1411 * The return value is the number of bytes in the selection
1412 * given by selPtr.
1413 *
1414 * Side effects:
1415 * The selection is retrieved from its current owner (this is
1416 * the only way to compute its size).
1417 *
1418 *----------------------------------------------------------------------
1419 */
1420
1421 static int
1422 SelectionSize(selPtr, type, tkwin)
1423 TkSelHandler *selPtr; /* Information about how to retrieve
1424 * the selection whose size is wanted. */
1425 Atom type;
1426 Tk_Window tkwin;
1427 {
1428 long buffer[TK_SEL_WORDS_AT_ONCE];
1429 int size, chunkSize;
1430 TkSelInProgress ip;
1431
1432 size = TK_SEL_BYTES_AT_ONCE;
1433 ip.selPtr = selPtr;
1434 ip.nextPtr = TkSelGetInProgress();
1435 TkSelSetInProgress(&ip);
1436 do {
1437 chunkSize = (*selPtr->proc)(selPtr->clientData, size,
1438 buffer, TK_SEL_BYTES_AT_ONCE, type, tkwin);
1439 if (ip.selPtr == NULL) {
1440 size = 0;
1441 break;
1442 }
1443 size += chunkSize;
1444 } while (chunkSize == TK_SEL_BYTES_AT_ONCE);
1445 TkSelSetInProgress(ip.nextPtr);
1446 return size;
1447 }
1448
1449 /*
1450 *----------------------------------------------------------------------
1451 *
1452 * IncrTimeoutProc --
1453 *
1454 * This procedure is invoked once a second while sending the
1455 * selection to a requestor in INCR mode. After a while it
1456 * gives up and aborts the selection operation.
1457 *
1458 * Results:
1459 * None.
1460 *
1461 * Side effects:
1462 * A new timeout gets registered so that this procedure gets
1463 * called again in another second, unless too many seconds
1464 * have elapsed, in which case incrPtr is marked as "all done".
1465 *
1466 *----------------------------------------------------------------------
1467 */
1468
1469 static void
1470 IncrTimeoutProc(clientData)
1471 ClientData clientData; /* Information about INCR-mode
1472 * selection retrieval for which
1473 * we are selection owner. */
1474 {
1475 register IncrInfo *incrPtr = (IncrInfo *) clientData;
1476
1477 incrPtr->idleTime++;
1478 if (incrPtr->idleTime >= 5) {
1479 incrPtr->numIncrs = 0;
1480 } else {
1481 incrPtr->timeout = Tcl_CreateTimerHandler(1000, IncrTimeoutProc,
1482 (ClientData) incrPtr);
1483 }
1484 }
1485
1486 /*
1487 *----------------------------------------------------------------------
1488 *
1489 * SelCvtToX --
1490 *
1491 * Given a selection represented as a string (the normal Tcl form),
1492 * convert it to the ICCCM-mandated format for X, depending on
1493 * the type argument. This procedure and SelCvtFromX are inverses.
1494 *
1495 * Results:
1496 * The return value is a malloc'ed buffer holding a value
1497 * equivalent to "string", but formatted as for "type". It is
1498 * the caller's responsibility to free the string when done with
1499 * it. The word at *numLongsPtr is filled in with the number of
1500 * 32-bit words returned in the result.
1501 *
1502 * Side effects:
1503 * None.
1504 *
1505 *----------------------------------------------------------------------
1506 */
1507
1508 int
1509 TkSelCvtToX(propPtr, string, type, tkwin, maxBytes)
1510 long *propPtr;
1511 char *string; /* String representation of selection. */
1512 Atom type; /* Atom specifying the X format that is
1513 * desired for the selection. Should not
1514 * be XA_STRING (if so, don't bother calling
1515 * this procedure at all). */
1516 Tk_Window tkwin; /* Window that governs atom conversion. */
1517 int maxBytes; /* Number of 32-bit words contained in the
1518 * result. */
1519 {
1520 register char *p;
1521 char *field;
1522 int numFields;
1523 int bytes;
1524 long *longPtr;
1525 #define MAX_ATOM_NAME_LENGTH 100
1526 char atomName[MAX_ATOM_NAME_LENGTH+1];
1527
1528 /*
1529 * The string is assumed to consist of fields separated by spaces.
1530 * The property gets generated by converting each field to an
1531 * integer number, in one of two ways:
1532 * 1. If type is XA_ATOM, convert each field to its corresponding
1533 * atom.
1534 * 2. If type is anything else, convert each field from an ASCII number
1535 * to a 32-bit binary number.
1536 */
1537
1538 numFields = 1;
1539 for (p = string; *p != 0; p++) {
1540 if (isspace(UCHAR(*p))) {
1541 numFields++;
1542 }
1543 }
1544
1545 /*
1546 * Convert the fields one-by-one.
1547 */
1548
1549 for (longPtr = propPtr, bytes = 0, p = string; bytes < maxBytes
1550 ; bytes += sizeof(long), longPtr++) {
1551 while (isspace(UCHAR(*p))) {
1552 p++;
1553 }
1554 if (*p == 0) {
1555 break;
1556 }
1557 field = p;
1558 while ((*p != 0) && !isspace(UCHAR(*p))) {
1559 p++;
1560 }
1561 if (type == XA_ATOM) {
1562 int length;
1563
1564 length = p - field;
1565 if (length > MAX_ATOM_NAME_LENGTH) {
1566 length = MAX_ATOM_NAME_LENGTH;
1567 }
1568 strncpy(atomName, field, (unsigned) length);
1569 atomName[length] = 0;
1570 *longPtr = (long) Tk_InternAtom(tkwin, atomName);
1571 } else {
1572 char *dummy;
1573
1574 *longPtr = strtol(field, &dummy, 0);
1575 }
1576 }
1577 return bytes / sizeof(long);
1578 }
1579
1580 /*
1581 *----------------------------------------------------------------------
1582 *
1583 * SelCvtFromX --
1584 *
1585 * Given an X property value, formatted as a collection of 32-bit
1586 * values according to "type" and the ICCCM conventions, convert
1587 * the value to a string suitable for manipulation by Tcl. This
1588 * procedure is the inverse of SelCvtToX.
1589 *
1590 * Results:
1591 * The return value is the string equivalent of "property". It is
1592 * malloc-ed and should be freed by the caller when no longer
1593 * needed.
1594 *
1595 * Side effects:
1596 * None.
1597 *
1598 *----------------------------------------------------------------------
1599 */
1600
1601 char *
1602 TkSelCvtFromX(propPtr, numValues, type, tkwin)
1603 register long *propPtr; /* Property value from X. */
1604 int numValues; /* Number of 32-bit values in property. */
1605 Atom type; /* Type of property Should not be
1606 * XA_STRING (if so, don't bother calling
1607 * this procedure at all). */
1608 Tk_Window tkwin; /* Window to use for atom conversion. */
1609 {
1610 char *result;
1611 int resultSpace, curSize, fieldSize;
1612 CONST char *atomName;
1613
1614 /*
1615 * Convert each long in the property to a string value, which is
1616 * either the name of an atom (if type is XA_ATOM) or a hexadecimal
1617 * string. Make an initial guess about the size of the result, but
1618 * be prepared to enlarge the result if necessary.
1619 */
1620
1621 resultSpace = 12*numValues+1;
1622 curSize = 0;
1623 atomName = ""; /* Not needed, but eliminates compiler warning. */
1624 result = (char *) ckalloc((unsigned) resultSpace);
1625 *result = '\0';
1626 for ( ; numValues > 0; propPtr++, numValues--) {
1627 if (type == XA_ATOM) {
1628 atomName = Tk_GetAtomName(tkwin, (Atom) *propPtr);
1629 fieldSize = strlen(atomName) + 1;
1630 } else {
1631 fieldSize = 12;
1632 }
1633 if (curSize+fieldSize >= resultSpace) {
1634 char *newResult;
1635
1636 resultSpace *= 2;
1637 if (curSize+fieldSize >= resultSpace) {
1638 resultSpace = curSize + fieldSize + 1;
1639 }
1640 newResult = (char *) ckalloc((unsigned) resultSpace);
1641 strncpy(newResult, result, (unsigned) curSize);
1642 ckfree(result);
1643 result = newResult;
1644 }
1645 if (curSize != 0) {
1646 result[curSize] = ' ';
1647 curSize++;
1648 }
1649 if (type == XA_ATOM) {
1650 strcpy(result+curSize, atomName);
1651 } else {
1652 sprintf(result+curSize, "0x%x", (unsigned int) *propPtr);
1653 }
1654 curSize += strlen(result+curSize);
1655 }
1656 return result;
1657 }
1658
1659
1660