Merge from trunk.
[bpt/emacs.git] / src / xselect.c
1 /* X Selection processing for Emacs.
2 Copyright (C) 1993-1997, 2000-2011 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
18
19
20 /* Rewritten by jwz */
21
22 #include <config.h>
23 #include <limits.h>
24 #include <stdio.h> /* termhooks.h needs this */
25 #include <setjmp.h>
26
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30
31 #include <unistd.h>
32
33 #include "lisp.h"
34 #include "xterm.h" /* for all of the X includes */
35 #include "dispextern.h" /* frame.h seems to want this */
36 #include "frame.h" /* Need this to get the X window of selected_frame */
37 #include "blockinput.h"
38 #include "buffer.h"
39 #include "process.h"
40 #include "termhooks.h"
41 #include "keyboard.h"
42 #include "character.h"
43
44 #include <X11/Xproto.h>
45
46 struct prop_location;
47 struct selection_data;
48
49 static Lisp_Object x_atom_to_symbol (Display *dpy, Atom atom);
50 static Atom symbol_to_x_atom (struct x_display_info *, Lisp_Object);
51 static void x_own_selection (Lisp_Object, Lisp_Object, Lisp_Object);
52 static Lisp_Object x_get_local_selection (Lisp_Object, Lisp_Object, int,
53 struct x_display_info *);
54 static void x_decline_selection_request (struct input_event *);
55 static Lisp_Object x_selection_request_lisp_error (Lisp_Object);
56 static Lisp_Object queue_selection_requests_unwind (Lisp_Object);
57 static Lisp_Object x_catch_errors_unwind (Lisp_Object);
58 static void x_reply_selection_request (struct input_event *, struct x_display_info *);
59 static int x_convert_selection (struct input_event *, Lisp_Object, Lisp_Object,
60 Atom, int, struct x_display_info *);
61 static int waiting_for_other_props_on_window (Display *, Window);
62 static struct prop_location *expect_property_change (Display *, Window,
63 Atom, int);
64 static void unexpect_property_change (struct prop_location *);
65 static Lisp_Object wait_for_property_change_unwind (Lisp_Object);
66 static void wait_for_property_change (struct prop_location *);
67 static Lisp_Object x_get_foreign_selection (Lisp_Object, Lisp_Object,
68 Lisp_Object, Lisp_Object);
69 static void x_get_window_property (Display *, Window, Atom,
70 unsigned char **, int *,
71 Atom *, int *, unsigned long *, int);
72 static void receive_incremental_selection (Display *, Window, Atom,
73 Lisp_Object, unsigned,
74 unsigned char **, int *,
75 Atom *, int *, unsigned long *);
76 static Lisp_Object x_get_window_property_as_lisp_data (Display *,
77 Window, Atom,
78 Lisp_Object, Atom);
79 static Lisp_Object selection_data_to_lisp_data (Display *,
80 const unsigned char *,
81 int, Atom, int);
82 static void lisp_data_to_selection_data (Display *, Lisp_Object,
83 unsigned char **, Atom *,
84 unsigned *, int *, int *);
85 static Lisp_Object clean_local_selection_data (Lisp_Object);
86
87 /* Printing traces to stderr. */
88
89 #ifdef TRACE_SELECTION
90 #define TRACE0(fmt) \
91 fprintf (stderr, "%d: " fmt "\n", getpid ())
92 #define TRACE1(fmt, a0) \
93 fprintf (stderr, "%d: " fmt "\n", getpid (), a0)
94 #define TRACE2(fmt, a0, a1) \
95 fprintf (stderr, "%d: " fmt "\n", getpid (), a0, a1)
96 #define TRACE3(fmt, a0, a1, a2) \
97 fprintf (stderr, "%d: " fmt "\n", getpid (), a0, a1, a2)
98 #else
99 #define TRACE0(fmt) (void) 0
100 #define TRACE1(fmt, a0) (void) 0
101 #define TRACE2(fmt, a0, a1) (void) 0
102 #endif
103
104
105 static Lisp_Object QSECONDARY, QSTRING, QINTEGER, QCLIPBOARD, QTIMESTAMP,
106 QTEXT, QDELETE, QMULTIPLE, QINCR, QEMACS_TMP, QTARGETS, QATOM, QNULL,
107 QATOM_PAIR, QCLIPBOARD_MANAGER, QSAVE_TARGETS;
108
109 static Lisp_Object QCOMPOUND_TEXT; /* This is a type of selection. */
110 static Lisp_Object QUTF8_STRING; /* This is a type of selection. */
111
112 static Lisp_Object Qcompound_text_with_extensions;
113
114 static Lisp_Object Qforeign_selection;
115
116 /* If this is a smaller number than the max-request-size of the display,
117 emacs will use INCR selection transfer when the selection is larger
118 than this. The max-request-size is usually around 64k, so if you want
119 emacs to use incremental selection transfers when the selection is
120 smaller than that, set this. I added this mostly for debugging the
121 incremental transfer stuff, but it might improve server performance. */
122 #define MAX_SELECTION_QUANTUM 0xFFFFFF
123
124 #define SELECTION_QUANTUM(dpy) ((XMaxRequestSize(dpy) << 2) - 100)
125
126 #define LOCAL_SELECTION(selection_symbol,dpyinfo) \
127 assq_no_quit (selection_symbol, dpyinfo->terminal->Vselection_alist)
128
129 \f
130 /* Define a queue to save up SELECTION_REQUEST_EVENT events for later
131 handling. */
132
133 struct selection_event_queue
134 {
135 struct input_event event;
136 struct selection_event_queue *next;
137 };
138
139 static struct selection_event_queue *selection_queue;
140
141 /* Nonzero means queue up SELECTION_REQUEST_EVENT events. */
142
143 static int x_queue_selection_requests;
144
145 /* Queue up an SELECTION_REQUEST_EVENT *EVENT, to be processed later. */
146
147 static void
148 x_queue_event (struct input_event *event)
149 {
150 struct selection_event_queue *queue_tmp;
151
152 /* Don't queue repeated requests.
153 This only happens for large requests which uses the incremental protocol. */
154 for (queue_tmp = selection_queue; queue_tmp; queue_tmp = queue_tmp->next)
155 {
156 if (!memcmp (&queue_tmp->event, event, sizeof (*event)))
157 {
158 TRACE1 ("DECLINE DUP SELECTION EVENT %p", queue_tmp);
159 x_decline_selection_request (event);
160 return;
161 }
162 }
163
164 queue_tmp
165 = (struct selection_event_queue *) xmalloc (sizeof (struct selection_event_queue));
166
167 if (queue_tmp != NULL)
168 {
169 TRACE1 ("QUEUE SELECTION EVENT %p", queue_tmp);
170 queue_tmp->event = *event;
171 queue_tmp->next = selection_queue;
172 selection_queue = queue_tmp;
173 }
174 }
175
176 /* Start queuing SELECTION_REQUEST_EVENT events. */
177
178 static void
179 x_start_queuing_selection_requests (void)
180 {
181 if (x_queue_selection_requests)
182 abort ();
183
184 x_queue_selection_requests++;
185 TRACE1 ("x_start_queuing_selection_requests %d", x_queue_selection_requests);
186 }
187
188 /* Stop queuing SELECTION_REQUEST_EVENT events. */
189
190 static void
191 x_stop_queuing_selection_requests (void)
192 {
193 TRACE1 ("x_stop_queuing_selection_requests %d", x_queue_selection_requests);
194 --x_queue_selection_requests;
195
196 /* Take all the queued events and put them back
197 so that they get processed afresh. */
198
199 while (selection_queue != NULL)
200 {
201 struct selection_event_queue *queue_tmp = selection_queue;
202 TRACE1 ("RESTORE SELECTION EVENT %p", queue_tmp);
203 kbd_buffer_unget_event (&queue_tmp->event);
204 selection_queue = queue_tmp->next;
205 xfree ((char *)queue_tmp);
206 }
207 }
208 \f
209
210 /* This converts a Lisp symbol to a server Atom, avoiding a server
211 roundtrip whenever possible. */
212
213 static Atom
214 symbol_to_x_atom (struct x_display_info *dpyinfo, Lisp_Object sym)
215 {
216 Atom val;
217 if (NILP (sym)) return 0;
218 if (EQ (sym, QPRIMARY)) return XA_PRIMARY;
219 if (EQ (sym, QSECONDARY)) return XA_SECONDARY;
220 if (EQ (sym, QSTRING)) return XA_STRING;
221 if (EQ (sym, QINTEGER)) return XA_INTEGER;
222 if (EQ (sym, QATOM)) return XA_ATOM;
223 if (EQ (sym, QCLIPBOARD)) return dpyinfo->Xatom_CLIPBOARD;
224 if (EQ (sym, QTIMESTAMP)) return dpyinfo->Xatom_TIMESTAMP;
225 if (EQ (sym, QTEXT)) return dpyinfo->Xatom_TEXT;
226 if (EQ (sym, QCOMPOUND_TEXT)) return dpyinfo->Xatom_COMPOUND_TEXT;
227 if (EQ (sym, QUTF8_STRING)) return dpyinfo->Xatom_UTF8_STRING;
228 if (EQ (sym, QDELETE)) return dpyinfo->Xatom_DELETE;
229 if (EQ (sym, QMULTIPLE)) return dpyinfo->Xatom_MULTIPLE;
230 if (EQ (sym, QINCR)) return dpyinfo->Xatom_INCR;
231 if (EQ (sym, QEMACS_TMP)) return dpyinfo->Xatom_EMACS_TMP;
232 if (EQ (sym, QTARGETS)) return dpyinfo->Xatom_TARGETS;
233 if (EQ (sym, QNULL)) return dpyinfo->Xatom_NULL;
234 if (!SYMBOLP (sym)) abort ();
235
236 TRACE1 (" XInternAtom %s", SSDATA (SYMBOL_NAME (sym)));
237 BLOCK_INPUT;
238 val = XInternAtom (dpyinfo->display, SSDATA (SYMBOL_NAME (sym)), False);
239 UNBLOCK_INPUT;
240 return val;
241 }
242
243
244 /* This converts a server Atom to a Lisp symbol, avoiding server roundtrips
245 and calls to intern whenever possible. */
246
247 static Lisp_Object
248 x_atom_to_symbol (Display *dpy, Atom atom)
249 {
250 struct x_display_info *dpyinfo;
251 char *str;
252 Lisp_Object val;
253
254 if (! atom)
255 return Qnil;
256
257 switch (atom)
258 {
259 case XA_PRIMARY:
260 return QPRIMARY;
261 case XA_SECONDARY:
262 return QSECONDARY;
263 case XA_STRING:
264 return QSTRING;
265 case XA_INTEGER:
266 return QINTEGER;
267 case XA_ATOM:
268 return QATOM;
269 }
270
271 dpyinfo = x_display_info_for_display (dpy);
272 if (dpyinfo == NULL)
273 return Qnil;
274 if (atom == dpyinfo->Xatom_CLIPBOARD)
275 return QCLIPBOARD;
276 if (atom == dpyinfo->Xatom_TIMESTAMP)
277 return QTIMESTAMP;
278 if (atom == dpyinfo->Xatom_TEXT)
279 return QTEXT;
280 if (atom == dpyinfo->Xatom_COMPOUND_TEXT)
281 return QCOMPOUND_TEXT;
282 if (atom == dpyinfo->Xatom_UTF8_STRING)
283 return QUTF8_STRING;
284 if (atom == dpyinfo->Xatom_DELETE)
285 return QDELETE;
286 if (atom == dpyinfo->Xatom_MULTIPLE)
287 return QMULTIPLE;
288 if (atom == dpyinfo->Xatom_INCR)
289 return QINCR;
290 if (atom == dpyinfo->Xatom_EMACS_TMP)
291 return QEMACS_TMP;
292 if (atom == dpyinfo->Xatom_TARGETS)
293 return QTARGETS;
294 if (atom == dpyinfo->Xatom_NULL)
295 return QNULL;
296
297 BLOCK_INPUT;
298 str = XGetAtomName (dpy, atom);
299 UNBLOCK_INPUT;
300 TRACE1 ("XGetAtomName --> %s", str);
301 if (! str) return Qnil;
302 val = intern (str);
303 BLOCK_INPUT;
304 /* This was allocated by Xlib, so use XFree. */
305 XFree (str);
306 UNBLOCK_INPUT;
307 return val;
308 }
309 \f
310 /* Do protocol to assert ourself as a selection owner.
311 FRAME shall be the owner; it must be a valid X frame.
312 Update the Vselection_alist so that we can reply to later requests for
313 our selection. */
314
315 static void
316 x_own_selection (Lisp_Object selection_name, Lisp_Object selection_value,
317 Lisp_Object frame)
318 {
319 struct frame *f = XFRAME (frame);
320 Window selecting_window = FRAME_X_WINDOW (f);
321 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
322 Display *display = dpyinfo->display;
323 Time timestamp = last_event_timestamp;
324 Atom selection_atom = symbol_to_x_atom (dpyinfo, selection_name);
325
326 BLOCK_INPUT;
327 x_catch_errors (display);
328 XSetSelectionOwner (display, selection_atom, selecting_window, timestamp);
329 x_check_errors (display, "Can't set selection: %s");
330 x_uncatch_errors ();
331 UNBLOCK_INPUT;
332
333 /* Now update the local cache */
334 {
335 Lisp_Object selection_data;
336 Lisp_Object prev_value;
337
338 selection_data = list4 (selection_name, selection_value,
339 INTEGER_TO_CONS (timestamp), frame);
340 prev_value = LOCAL_SELECTION (selection_name, dpyinfo);
341
342 dpyinfo->terminal->Vselection_alist
343 = Fcons (selection_data, dpyinfo->terminal->Vselection_alist);
344
345 /* If we already owned the selection, remove the old selection
346 data. Don't use Fdelq as that may QUIT. */
347 if (!NILP (prev_value))
348 {
349 /* We know it's not the CAR, so it's easy. */
350 Lisp_Object rest = dpyinfo->terminal->Vselection_alist;
351 for (; CONSP (rest); rest = XCDR (rest))
352 if (EQ (prev_value, Fcar (XCDR (rest))))
353 {
354 XSETCDR (rest, XCDR (XCDR (rest)));
355 break;
356 }
357 }
358 }
359 }
360 \f
361 /* Given a selection-name and desired type, look up our local copy of
362 the selection value and convert it to the type.
363 The value is nil or a string.
364 This function is used both for remote requests (LOCAL_REQUEST is zero)
365 and for local x-get-selection-internal (LOCAL_REQUEST is nonzero).
366
367 This calls random Lisp code, and may signal or gc. */
368
369 static Lisp_Object
370 x_get_local_selection (Lisp_Object selection_symbol, Lisp_Object target_type,
371 int local_request, struct x_display_info *dpyinfo)
372 {
373 Lisp_Object local_value;
374 Lisp_Object handler_fn, value, check;
375 int count;
376
377 local_value = LOCAL_SELECTION (selection_symbol, dpyinfo);
378
379 if (NILP (local_value)) return Qnil;
380
381 /* TIMESTAMP is a special case. */
382 if (EQ (target_type, QTIMESTAMP))
383 {
384 handler_fn = Qnil;
385 value = XCAR (XCDR (XCDR (local_value)));
386 }
387 else
388 {
389 /* Don't allow a quit within the converter.
390 When the user types C-g, he would be surprised
391 if by luck it came during a converter. */
392 count = SPECPDL_INDEX ();
393 specbind (Qinhibit_quit, Qt);
394
395 CHECK_SYMBOL (target_type);
396 handler_fn = Fcdr (Fassq (target_type, Vselection_converter_alist));
397 /* gcpro is not needed here since nothing but HANDLER_FN
398 is live, and that ought to be a symbol. */
399
400 if (!NILP (handler_fn))
401 value = call3 (handler_fn,
402 selection_symbol, (local_request ? Qnil : target_type),
403 XCAR (XCDR (local_value)));
404 else
405 value = Qnil;
406 unbind_to (count, Qnil);
407 }
408
409 /* Make sure this value is of a type that we could transmit
410 to another X client. */
411
412 check = value;
413 if (CONSP (value)
414 && SYMBOLP (XCAR (value)))
415 check = XCDR (value);
416
417 if (STRINGP (check)
418 || VECTORP (check)
419 || SYMBOLP (check)
420 || INTEGERP (check)
421 || NILP (value))
422 return value;
423 /* Check for a value that CONS_TO_INTEGER could handle. */
424 else if (CONSP (check)
425 && INTEGERP (XCAR (check))
426 && (INTEGERP (XCDR (check))
427 ||
428 (CONSP (XCDR (check))
429 && INTEGERP (XCAR (XCDR (check)))
430 && NILP (XCDR (XCDR (check))))))
431 return value;
432
433 signal_error ("Invalid data returned by selection-conversion function",
434 list2 (handler_fn, value));
435 }
436 \f
437 /* Subroutines of x_reply_selection_request. */
438
439 /* Send a SelectionNotify event to the requestor with property=None,
440 meaning we were unable to do what they wanted. */
441
442 static void
443 x_decline_selection_request (struct input_event *event)
444 {
445 XEvent reply_base;
446 XSelectionEvent *reply = &(reply_base.xselection);
447
448 reply->type = SelectionNotify;
449 reply->display = SELECTION_EVENT_DISPLAY (event);
450 reply->requestor = SELECTION_EVENT_REQUESTOR (event);
451 reply->selection = SELECTION_EVENT_SELECTION (event);
452 reply->time = SELECTION_EVENT_TIME (event);
453 reply->target = SELECTION_EVENT_TARGET (event);
454 reply->property = None;
455
456 /* The reason for the error may be that the receiver has
457 died in the meantime. Handle that case. */
458 BLOCK_INPUT;
459 x_catch_errors (reply->display);
460 XSendEvent (reply->display, reply->requestor, False, 0L, &reply_base);
461 XFlush (reply->display);
462 x_uncatch_errors ();
463 UNBLOCK_INPUT;
464 }
465
466 /* This is the selection request currently being processed.
467 It is set to zero when the request is fully processed. */
468 static struct input_event *x_selection_current_request;
469
470 /* Display info in x_selection_request. */
471
472 static struct x_display_info *selection_request_dpyinfo;
473
474 /* Raw selection data, for sending to a requestor window. */
475
476 struct selection_data
477 {
478 unsigned char *data;
479 unsigned int size;
480 int format;
481 Atom type;
482 int nofree;
483 Atom property;
484 /* This can be set to non-NULL during x_reply_selection_request, if
485 the selection is waiting for an INCR transfer to complete. Don't
486 free these; that's done by unexpect_property_change. */
487 struct prop_location *wait_object;
488 struct selection_data *next;
489 };
490
491 /* Linked list of the above (in support of MULTIPLE targets). */
492
493 static struct selection_data *converted_selections;
494
495 /* "Data" to send a requestor for a failed MULTIPLE subtarget. */
496 static Atom conversion_fail_tag;
497
498 /* Used as an unwind-protect clause so that, if a selection-converter signals
499 an error, we tell the requester that we were unable to do what they wanted
500 before we throw to top-level or go into the debugger or whatever. */
501
502 static Lisp_Object
503 x_selection_request_lisp_error (Lisp_Object ignore)
504 {
505 struct selection_data *cs, *next;
506
507 for (cs = converted_selections; cs; cs = next)
508 {
509 next = cs->next;
510 if (cs->nofree == 0 && cs->data)
511 xfree (cs->data);
512 xfree (cs);
513 }
514 converted_selections = NULL;
515
516 if (x_selection_current_request != 0
517 && selection_request_dpyinfo->display)
518 x_decline_selection_request (x_selection_current_request);
519 return Qnil;
520 }
521
522 static Lisp_Object
523 x_catch_errors_unwind (Lisp_Object dummy)
524 {
525 BLOCK_INPUT;
526 x_uncatch_errors ();
527 UNBLOCK_INPUT;
528 return Qnil;
529 }
530 \f
531
532 /* This stuff is so that INCR selections are reentrant (that is, so we can
533 be servicing multiple INCR selection requests simultaneously.) I haven't
534 actually tested that yet. */
535
536 /* Keep a list of the property changes that are awaited. */
537
538 struct prop_location
539 {
540 int identifier;
541 Display *display;
542 Window window;
543 Atom property;
544 int desired_state;
545 int arrived;
546 struct prop_location *next;
547 };
548
549 static struct prop_location *expect_property_change (Display *display, Window window, Atom property, int state);
550 static void wait_for_property_change (struct prop_location *location);
551 static void unexpect_property_change (struct prop_location *location);
552 static int waiting_for_other_props_on_window (Display *display, Window window);
553
554 static int prop_location_identifier;
555
556 static Lisp_Object property_change_reply;
557
558 static struct prop_location *property_change_reply_object;
559
560 static struct prop_location *property_change_wait_list;
561
562 static Lisp_Object
563 queue_selection_requests_unwind (Lisp_Object tem)
564 {
565 x_stop_queuing_selection_requests ();
566 return Qnil;
567 }
568
569 \f
570 /* Send the reply to a selection request event EVENT. */
571
572 #ifdef TRACE_SELECTION
573 static int x_reply_selection_request_cnt;
574 #endif /* TRACE_SELECTION */
575
576 static void
577 x_reply_selection_request (struct input_event *event, struct x_display_info *dpyinfo)
578 {
579 XEvent reply_base;
580 XSelectionEvent *reply = &(reply_base.xselection);
581 Display *display = SELECTION_EVENT_DISPLAY (event);
582 Window window = SELECTION_EVENT_REQUESTOR (event);
583 int bytes_remaining;
584 int max_bytes = SELECTION_QUANTUM (display);
585 int count = SPECPDL_INDEX ();
586 struct selection_data *cs;
587
588 if (max_bytes > MAX_SELECTION_QUANTUM)
589 max_bytes = MAX_SELECTION_QUANTUM;
590
591 reply->type = SelectionNotify;
592 reply->display = display;
593 reply->requestor = window;
594 reply->selection = SELECTION_EVENT_SELECTION (event);
595 reply->time = SELECTION_EVENT_TIME (event);
596 reply->target = SELECTION_EVENT_TARGET (event);
597 reply->property = SELECTION_EVENT_PROPERTY (event);
598 if (reply->property == None)
599 reply->property = reply->target;
600
601 BLOCK_INPUT;
602 /* The protected block contains wait_for_property_change, which can
603 run random lisp code (process handlers) or signal. Therefore, we
604 put the x_uncatch_errors call in an unwind. */
605 record_unwind_protect (x_catch_errors_unwind, Qnil);
606 x_catch_errors (display);
607
608 /* Loop over converted selections, storing them in the requested
609 properties. If data is large, only store the first N bytes
610 (section 2.7.2 of ICCCM). Note that we store the data for a
611 MULTIPLE request in the opposite order; the ICCM says only that
612 the conversion itself must be done in the same order. */
613 for (cs = converted_selections; cs; cs = cs->next)
614 {
615 if (cs->property == None)
616 continue;
617
618 bytes_remaining = cs->size * (cs->format / 8);
619 if (bytes_remaining <= max_bytes)
620 {
621 /* Send all the data at once, with minimal handshaking. */
622 TRACE1 ("Sending all %d bytes", bytes_remaining);
623 XChangeProperty (display, window, cs->property,
624 cs->type, cs->format, PropModeReplace,
625 cs->data, cs->size);
626 }
627 else
628 {
629 /* Send an INCR tag to initiate incremental transfer. */
630 long value[1];
631
632 TRACE2 ("Start sending %d bytes incrementally (%s)",
633 bytes_remaining, XGetAtomName (display, cs->property));
634 cs->wait_object
635 = expect_property_change (display, window, cs->property,
636 PropertyDelete);
637
638 /* XChangeProperty expects an array of long even if long is
639 more than 32 bits. */
640 value[0] = bytes_remaining;
641 XChangeProperty (display, window, cs->property,
642 dpyinfo->Xatom_INCR, 32, PropModeReplace,
643 (unsigned char *) value, 1);
644 XSelectInput (display, window, PropertyChangeMask);
645 }
646 }
647
648 /* Now issue the SelectionNotify event. */
649 XSendEvent (display, window, False, 0L, &reply_base);
650 XFlush (display);
651
652 #ifdef TRACE_SELECTION
653 {
654 char *sel = XGetAtomName (display, reply->selection);
655 char *tgt = XGetAtomName (display, reply->target);
656 TRACE3 ("Sent SelectionNotify: %s, target %s (%d)",
657 sel, tgt, ++x_reply_selection_request_cnt);
658 if (sel) XFree (sel);
659 if (tgt) XFree (tgt);
660 }
661 #endif /* TRACE_SELECTION */
662
663 /* Finish sending the rest of each of the INCR values. This should
664 be improved; there's a chance of deadlock if more than one
665 subtarget in a MULTIPLE selection requires an INCR transfer, and
666 the requestor and Emacs loop waiting on different transfers. */
667 for (cs = converted_selections; cs; cs = cs->next)
668 if (cs->wait_object)
669 {
670 int format_bytes = cs->format / 8;
671 int had_errors = x_had_errors_p (display);
672 UNBLOCK_INPUT;
673
674 bytes_remaining = cs->size * format_bytes;
675
676 /* Wait for the requester to ack by deleting the property.
677 This can run Lisp code (process handlers) or signal. */
678 if (! had_errors)
679 {
680 TRACE1 ("Waiting for ACK (deletion of %s)",
681 XGetAtomName (display, cs->property));
682 wait_for_property_change (cs->wait_object);
683 }
684 else
685 unexpect_property_change (cs->wait_object);
686
687 while (bytes_remaining)
688 {
689 int i = ((bytes_remaining < max_bytes)
690 ? bytes_remaining
691 : max_bytes) / format_bytes;
692 BLOCK_INPUT;
693
694 cs->wait_object
695 = expect_property_change (display, window, cs->property,
696 PropertyDelete);
697
698 TRACE1 ("Sending increment of %d elements", i);
699 TRACE1 ("Set %s to increment data",
700 XGetAtomName (display, cs->property));
701
702 /* Append the next chunk of data to the property. */
703 XChangeProperty (display, window, cs->property,
704 cs->type, cs->format, PropModeAppend,
705 cs->data, i);
706 bytes_remaining -= i * format_bytes;
707 cs->data += i * ((cs->format == 32) ? sizeof (long)
708 : format_bytes);
709 XFlush (display);
710 had_errors = x_had_errors_p (display);
711 UNBLOCK_INPUT;
712
713 if (had_errors) break;
714
715 /* Wait for the requester to ack this chunk by deleting
716 the property. This can run Lisp code or signal. */
717 TRACE1 ("Waiting for increment ACK (deletion of %s)",
718 XGetAtomName (display, cs->property));
719 wait_for_property_change (cs->wait_object);
720 }
721
722 /* Now write a zero-length chunk to the property to tell the
723 requester that we're done. */
724 BLOCK_INPUT;
725 if (! waiting_for_other_props_on_window (display, window))
726 XSelectInput (display, window, 0L);
727
728 TRACE1 ("Set %s to a 0-length chunk to indicate EOF",
729 XGetAtomName (display, cs->property));
730 XChangeProperty (display, window, cs->property,
731 cs->type, cs->format, PropModeReplace,
732 cs->data, 0);
733 TRACE0 ("Done sending incrementally");
734 }
735
736 /* rms, 2003-01-03: I think I have fixed this bug. */
737 /* The window we're communicating with may have been deleted
738 in the meantime (that's a real situation from a bug report).
739 In this case, there may be events in the event queue still
740 refering to the deleted window, and we'll get a BadWindow error
741 in XTread_socket when processing the events. I don't have
742 an idea how to fix that. gerd, 2001-01-98. */
743 /* 2004-09-10: XSync and UNBLOCK so that possible protocol errors are
744 delivered before uncatch errors. */
745 XSync (display, False);
746 UNBLOCK_INPUT;
747
748 /* GTK queues events in addition to the queue in Xlib. So we
749 UNBLOCK to enter the event loop and get possible errors delivered,
750 and then BLOCK again because x_uncatch_errors requires it. */
751 BLOCK_INPUT;
752 /* This calls x_uncatch_errors. */
753 unbind_to (count, Qnil);
754 UNBLOCK_INPUT;
755 }
756 \f
757 /* Handle a SelectionRequest event EVENT.
758 This is called from keyboard.c when such an event is found in the queue. */
759
760 static void
761 x_handle_selection_request (struct input_event *event)
762 {
763 struct gcpro gcpro1, gcpro2;
764 Time local_selection_time;
765
766 Display *display = SELECTION_EVENT_DISPLAY (event);
767 struct x_display_info *dpyinfo = x_display_info_for_display (display);
768 Atom selection = SELECTION_EVENT_SELECTION (event);
769 Lisp_Object selection_symbol = x_atom_to_symbol (display, selection);
770 Atom target = SELECTION_EVENT_TARGET (event);
771 Lisp_Object target_symbol = x_atom_to_symbol (display, target);
772 Atom property = SELECTION_EVENT_PROPERTY (event);
773 Lisp_Object local_selection_data;
774 int success = 0;
775 int count = SPECPDL_INDEX ();
776 GCPRO2 (local_selection_data, target_symbol);
777
778 if (!dpyinfo) goto DONE;
779
780 local_selection_data = LOCAL_SELECTION (selection_symbol, dpyinfo);
781
782 /* Decline if we don't own any selections. */
783 if (NILP (local_selection_data)) goto DONE;
784
785 /* Decline requests issued prior to our acquiring the selection. */
786 CONS_TO_INTEGER (XCAR (XCDR (XCDR (local_selection_data))),
787 Time, local_selection_time);
788 if (SELECTION_EVENT_TIME (event) != CurrentTime
789 && local_selection_time > SELECTION_EVENT_TIME (event))
790 goto DONE;
791
792 x_selection_current_request = event;
793 selection_request_dpyinfo = dpyinfo;
794 record_unwind_protect (x_selection_request_lisp_error, Qnil);
795
796 /* We might be able to handle nested x_handle_selection_requests,
797 but this is difficult to test, and seems unimportant. */
798 x_start_queuing_selection_requests ();
799 record_unwind_protect (queue_selection_requests_unwind, Qnil);
800
801 TRACE2 ("x_handle_selection_request: selection=%s, target=%s",
802 SDATA (SYMBOL_NAME (selection_symbol)),
803 SDATA (SYMBOL_NAME (target_symbol)));
804
805 if (EQ (target_symbol, QMULTIPLE))
806 {
807 /* For MULTIPLE targets, the event property names a list of atom
808 pairs; the first atom names a target and the second names a
809 non-None property. */
810 Window requestor = SELECTION_EVENT_REQUESTOR (event);
811 Lisp_Object multprop;
812 int j, nselections;
813
814 if (property == None) goto DONE;
815 multprop
816 = x_get_window_property_as_lisp_data (display, requestor, property,
817 QMULTIPLE, selection);
818
819 if (!VECTORP (multprop) || ASIZE (multprop) % 2)
820 goto DONE;
821
822 nselections = ASIZE (multprop) / 2;
823 /* Perform conversions. This can signal. */
824 for (j = 0; j < nselections; j++)
825 {
826 Lisp_Object subtarget = AREF (multprop, 2*j);
827 Atom subproperty = symbol_to_x_atom (dpyinfo,
828 AREF (multprop, 2*j+1));
829
830 if (subproperty != None)
831 x_convert_selection (event, selection_symbol, subtarget,
832 subproperty, 1, dpyinfo);
833 }
834 success = 1;
835 }
836 else
837 {
838 if (property == None)
839 property = SELECTION_EVENT_TARGET (event);
840 success = x_convert_selection (event, selection_symbol,
841 target_symbol, property,
842 0, dpyinfo);
843 }
844
845 DONE:
846
847 if (success)
848 x_reply_selection_request (event, dpyinfo);
849 else
850 x_decline_selection_request (event);
851 x_selection_current_request = 0;
852
853 /* Run the `x-sent-selection-functions' abnormal hook. */
854 if (!NILP (Vx_sent_selection_functions)
855 && !EQ (Vx_sent_selection_functions, Qunbound))
856 {
857 Lisp_Object args[4];
858 args[0] = Vx_sent_selection_functions;
859 args[1] = selection_symbol;
860 args[2] = target_symbol;
861 args[3] = success ? Qt : Qnil;
862 Frun_hook_with_args (4, args);
863 }
864
865 unbind_to (count, Qnil);
866 UNGCPRO;
867 }
868
869 /* Perform the requested selection conversion, and write the data to
870 the converted_selections linked list, where it can be accessed by
871 x_reply_selection_request. If FOR_MULTIPLE is non-zero, write out
872 the data even if conversion fails, using conversion_fail_tag.
873
874 Return 0 if the selection failed to convert, 1 otherwise. */
875
876 static int
877 x_convert_selection (struct input_event *event, Lisp_Object selection_symbol,
878 Lisp_Object target_symbol, Atom property,
879 int for_multiple, struct x_display_info *dpyinfo)
880 {
881 struct gcpro gcpro1;
882 Lisp_Object lisp_selection;
883 struct selection_data *cs;
884 GCPRO1 (lisp_selection);
885
886 lisp_selection
887 = x_get_local_selection (selection_symbol, target_symbol,
888 0, dpyinfo);
889
890 /* A nil return value means we can't perform the conversion. */
891 if (NILP (lisp_selection)
892 || (CONSP (lisp_selection) && NILP (XCDR (lisp_selection))))
893 {
894 if (for_multiple)
895 {
896 cs = xmalloc (sizeof (struct selection_data));
897 cs->data = (unsigned char *) &conversion_fail_tag;
898 cs->size = 1;
899 cs->format = 32;
900 cs->type = XA_ATOM;
901 cs->nofree = 1;
902 cs->property = property;
903 cs->wait_object = NULL;
904 cs->next = converted_selections;
905 converted_selections = cs;
906 }
907
908 UNGCPRO;
909 return 0;
910 }
911
912 /* Otherwise, record the converted selection to binary. */
913 cs = xmalloc (sizeof (struct selection_data));
914 cs->nofree = 1;
915 cs->property = property;
916 cs->wait_object = NULL;
917 cs->next = converted_selections;
918 converted_selections = cs;
919 lisp_data_to_selection_data (SELECTION_EVENT_DISPLAY (event),
920 lisp_selection,
921 &(cs->data), &(cs->type),
922 &(cs->size), &(cs->format),
923 &(cs->nofree));
924 UNGCPRO;
925 return 1;
926 }
927 \f
928 /* Handle a SelectionClear event EVENT, which indicates that some
929 client cleared out our previously asserted selection.
930 This is called from keyboard.c when such an event is found in the queue. */
931
932 static void
933 x_handle_selection_clear (struct input_event *event)
934 {
935 Display *display = SELECTION_EVENT_DISPLAY (event);
936 Atom selection = SELECTION_EVENT_SELECTION (event);
937 Time changed_owner_time = SELECTION_EVENT_TIME (event);
938
939 Lisp_Object selection_symbol, local_selection_data;
940 Time local_selection_time;
941 struct x_display_info *dpyinfo = x_display_info_for_display (display);
942 Lisp_Object Vselection_alist;
943
944 TRACE0 ("x_handle_selection_clear");
945
946 if (!dpyinfo) return;
947
948 selection_symbol = x_atom_to_symbol (display, selection);
949 local_selection_data = LOCAL_SELECTION (selection_symbol, dpyinfo);
950
951 /* Well, we already believe that we don't own it, so that's just fine. */
952 if (NILP (local_selection_data)) return;
953
954 CONS_TO_INTEGER (XCAR (XCDR (XCDR (local_selection_data))),
955 Time, local_selection_time);
956
957 /* We have reasserted the selection since this SelectionClear was
958 generated, so we can disregard it. */
959 if (changed_owner_time != CurrentTime
960 && local_selection_time > changed_owner_time)
961 return;
962
963 /* Otherwise, really clear. Don't use Fdelq as that may QUIT;. */
964 Vselection_alist = dpyinfo->terminal->Vselection_alist;
965 if (EQ (local_selection_data, CAR (Vselection_alist)))
966 Vselection_alist = XCDR (Vselection_alist);
967 else
968 {
969 Lisp_Object rest;
970 for (rest = Vselection_alist; CONSP (rest); rest = XCDR (rest))
971 if (EQ (local_selection_data, CAR (XCDR (rest))))
972 {
973 XSETCDR (rest, XCDR (XCDR (rest)));
974 break;
975 }
976 }
977 dpyinfo->terminal->Vselection_alist = Vselection_alist;
978
979 /* Run the `x-lost-selection-functions' abnormal hook. */
980 {
981 Lisp_Object args[2];
982 args[0] = Vx_lost_selection_functions;
983 args[1] = selection_symbol;
984 Frun_hook_with_args (2, args);
985 }
986
987 prepare_menu_bars ();
988 redisplay_preserve_echo_area (20);
989 }
990
991 void
992 x_handle_selection_event (struct input_event *event)
993 {
994 TRACE0 ("x_handle_selection_event");
995 if (event->kind != SELECTION_REQUEST_EVENT)
996 x_handle_selection_clear (event);
997 else if (x_queue_selection_requests)
998 x_queue_event (event);
999 else
1000 x_handle_selection_request (event);
1001 }
1002
1003
1004 /* Clear all selections that were made from frame F.
1005 We do this when about to delete a frame. */
1006
1007 void
1008 x_clear_frame_selections (FRAME_PTR f)
1009 {
1010 Lisp_Object frame;
1011 Lisp_Object rest;
1012 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1013 struct terminal *t = dpyinfo->terminal;
1014
1015 XSETFRAME (frame, f);
1016
1017 /* Delete elements from the beginning of Vselection_alist. */
1018 while (CONSP (t->Vselection_alist)
1019 && EQ (frame, XCAR (XCDR (XCDR (XCDR (XCAR (t->Vselection_alist)))))))
1020 {
1021 /* Run the `x-lost-selection-functions' abnormal hook. */
1022 Lisp_Object args[2];
1023 args[0] = Vx_lost_selection_functions;
1024 args[1] = Fcar (Fcar (t->Vselection_alist));
1025 Frun_hook_with_args (2, args);
1026
1027 t->Vselection_alist = XCDR (t->Vselection_alist);
1028 }
1029
1030 /* Delete elements after the beginning of Vselection_alist. */
1031 for (rest = t->Vselection_alist; CONSP (rest); rest = XCDR (rest))
1032 if (CONSP (XCDR (rest))
1033 && EQ (frame, XCAR (XCDR (XCDR (XCDR (XCAR (XCDR (rest))))))))
1034 {
1035 Lisp_Object args[2];
1036 args[0] = Vx_lost_selection_functions;
1037 args[1] = XCAR (XCAR (XCDR (rest)));
1038 Frun_hook_with_args (2, args);
1039 XSETCDR (rest, XCDR (XCDR (rest)));
1040 break;
1041 }
1042 }
1043 \f
1044 /* Nonzero if any properties for DISPLAY and WINDOW
1045 are on the list of what we are waiting for. */
1046
1047 static int
1048 waiting_for_other_props_on_window (Display *display, Window window)
1049 {
1050 struct prop_location *rest = property_change_wait_list;
1051 while (rest)
1052 if (rest->display == display && rest->window == window)
1053 return 1;
1054 else
1055 rest = rest->next;
1056 return 0;
1057 }
1058
1059 /* Add an entry to the list of property changes we are waiting for.
1060 DISPLAY, WINDOW, PROPERTY, STATE describe what we will wait for.
1061 The return value is a number that uniquely identifies
1062 this awaited property change. */
1063
1064 static struct prop_location *
1065 expect_property_change (Display *display, Window window, Atom property, int state)
1066 {
1067 struct prop_location *pl = (struct prop_location *) xmalloc (sizeof *pl);
1068 pl->identifier = ++prop_location_identifier;
1069 pl->display = display;
1070 pl->window = window;
1071 pl->property = property;
1072 pl->desired_state = state;
1073 pl->next = property_change_wait_list;
1074 pl->arrived = 0;
1075 property_change_wait_list = pl;
1076 return pl;
1077 }
1078
1079 /* Delete an entry from the list of property changes we are waiting for.
1080 IDENTIFIER is the number that uniquely identifies the entry. */
1081
1082 static void
1083 unexpect_property_change (struct prop_location *location)
1084 {
1085 struct prop_location *prev = 0, *rest = property_change_wait_list;
1086 while (rest)
1087 {
1088 if (rest == location)
1089 {
1090 if (prev)
1091 prev->next = rest->next;
1092 else
1093 property_change_wait_list = rest->next;
1094 xfree (rest);
1095 return;
1096 }
1097 prev = rest;
1098 rest = rest->next;
1099 }
1100 }
1101
1102 /* Remove the property change expectation element for IDENTIFIER. */
1103
1104 static Lisp_Object
1105 wait_for_property_change_unwind (Lisp_Object loc)
1106 {
1107 struct prop_location *location = XSAVE_VALUE (loc)->pointer;
1108
1109 unexpect_property_change (location);
1110 if (location == property_change_reply_object)
1111 property_change_reply_object = 0;
1112 return Qnil;
1113 }
1114
1115 /* Actually wait for a property change.
1116 IDENTIFIER should be the value that expect_property_change returned. */
1117
1118 static void
1119 wait_for_property_change (struct prop_location *location)
1120 {
1121 int secs, usecs;
1122 int count = SPECPDL_INDEX ();
1123
1124 if (property_change_reply_object)
1125 abort ();
1126
1127 /* Make sure to do unexpect_property_change if we quit or err. */
1128 record_unwind_protect (wait_for_property_change_unwind,
1129 make_save_value (location, 0));
1130
1131 XSETCAR (property_change_reply, Qnil);
1132 property_change_reply_object = location;
1133
1134 /* If the event we are waiting for arrives beyond here, it will set
1135 property_change_reply, because property_change_reply_object says so. */
1136 if (! location->arrived)
1137 {
1138 secs = x_selection_timeout / 1000;
1139 usecs = (x_selection_timeout % 1000) * 1000;
1140 TRACE2 (" Waiting %d secs, %d usecs", secs, usecs);
1141 wait_reading_process_output (secs, usecs, 0, 0,
1142 property_change_reply, NULL, 0);
1143
1144 if (NILP (XCAR (property_change_reply)))
1145 {
1146 TRACE0 (" Timed out");
1147 error ("Timed out waiting for property-notify event");
1148 }
1149 }
1150
1151 unbind_to (count, Qnil);
1152 }
1153
1154 /* Called from XTread_socket in response to a PropertyNotify event. */
1155
1156 void
1157 x_handle_property_notify (XPropertyEvent *event)
1158 {
1159 struct prop_location *rest;
1160
1161 for (rest = property_change_wait_list; rest; rest = rest->next)
1162 {
1163 if (!rest->arrived
1164 && rest->property == event->atom
1165 && rest->window == event->window
1166 && rest->display == event->display
1167 && rest->desired_state == event->state)
1168 {
1169 TRACE2 ("Expected %s of property %s",
1170 (event->state == PropertyDelete ? "deletion" : "change"),
1171 XGetAtomName (event->display, event->atom));
1172
1173 rest->arrived = 1;
1174
1175 /* If this is the one wait_for_property_change is waiting for,
1176 tell it to wake up. */
1177 if (rest == property_change_reply_object)
1178 XSETCAR (property_change_reply, Qt);
1179
1180 return;
1181 }
1182 }
1183 }
1184
1185
1186 \f
1187 /* Variables for communication with x_handle_selection_notify. */
1188 static Atom reading_which_selection;
1189 static Lisp_Object reading_selection_reply;
1190 static Window reading_selection_window;
1191
1192 /* Do protocol to read selection-data from the server.
1193 Converts this to Lisp data and returns it.
1194 FRAME is the frame whose X window shall request the selection. */
1195
1196 static Lisp_Object
1197 x_get_foreign_selection (Lisp_Object selection_symbol, Lisp_Object target_type,
1198 Lisp_Object time_stamp, Lisp_Object frame)
1199 {
1200 struct frame *f = XFRAME (frame);
1201 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
1202 Display *display = dpyinfo->display;
1203 Window requestor_window = FRAME_X_WINDOW (f);
1204 Time requestor_time = last_event_timestamp;
1205 Atom target_property = dpyinfo->Xatom_EMACS_TMP;
1206 Atom selection_atom = symbol_to_x_atom (dpyinfo, selection_symbol);
1207 Atom type_atom = (CONSP (target_type)
1208 ? symbol_to_x_atom (dpyinfo, XCAR (target_type))
1209 : symbol_to_x_atom (dpyinfo, target_type));
1210 int secs, usecs;
1211
1212 if (!FRAME_LIVE_P (f))
1213 return Qnil;
1214
1215 if (! NILP (time_stamp))
1216 CONS_TO_INTEGER (time_stamp, Time, requestor_time);
1217
1218 BLOCK_INPUT;
1219 TRACE2 ("Get selection %s, type %s",
1220 XGetAtomName (display, type_atom),
1221 XGetAtomName (display, target_property));
1222
1223 x_catch_errors (display);
1224 XConvertSelection (display, selection_atom, type_atom, target_property,
1225 requestor_window, requestor_time);
1226 x_check_errors (display, "Can't convert selection: %s");
1227 x_uncatch_errors ();
1228
1229 /* Prepare to block until the reply has been read. */
1230 reading_selection_window = requestor_window;
1231 reading_which_selection = selection_atom;
1232 XSETCAR (reading_selection_reply, Qnil);
1233
1234 /* It should not be necessary to stop handling selection requests
1235 during this time. In fact, the SAVE_TARGETS mechanism requires
1236 us to handle a clipboard manager's requests before it returns
1237 SelectionNotify. */
1238 #if 0
1239 x_start_queuing_selection_requests ();
1240 record_unwind_protect (queue_selection_requests_unwind, Qnil);
1241 #endif
1242
1243 UNBLOCK_INPUT;
1244
1245 /* This allows quits. Also, don't wait forever. */
1246 secs = x_selection_timeout / 1000;
1247 usecs = (x_selection_timeout % 1000) * 1000;
1248 TRACE1 (" Start waiting %d secs for SelectionNotify", secs);
1249 wait_reading_process_output (secs, usecs, 0, 0,
1250 reading_selection_reply, NULL, 0);
1251 TRACE1 (" Got event = %d", !NILP (XCAR (reading_selection_reply)));
1252
1253 if (NILP (XCAR (reading_selection_reply)))
1254 error ("Timed out waiting for reply from selection owner");
1255 if (EQ (XCAR (reading_selection_reply), Qlambda))
1256 return Qnil;
1257
1258 /* Otherwise, the selection is waiting for us on the requested property. */
1259 return
1260 x_get_window_property_as_lisp_data (display, requestor_window,
1261 target_property, target_type,
1262 selection_atom);
1263 }
1264 \f
1265 /* Subroutines of x_get_window_property_as_lisp_data */
1266
1267 /* Use xfree, not XFree, to free the data obtained with this function. */
1268
1269 static void
1270 x_get_window_property (Display *display, Window window, Atom property,
1271 unsigned char **data_ret, int *bytes_ret,
1272 Atom *actual_type_ret, int *actual_format_ret,
1273 unsigned long *actual_size_ret, int delete_p)
1274 {
1275 int total_size;
1276 unsigned long bytes_remaining;
1277 int offset = 0;
1278 unsigned char *tmp_data = 0;
1279 int result;
1280 int buffer_size = SELECTION_QUANTUM (display);
1281
1282 if (buffer_size > MAX_SELECTION_QUANTUM)
1283 buffer_size = MAX_SELECTION_QUANTUM;
1284
1285 BLOCK_INPUT;
1286
1287 /* First probe the thing to find out how big it is. */
1288 result = XGetWindowProperty (display, window, property,
1289 0L, 0L, False, AnyPropertyType,
1290 actual_type_ret, actual_format_ret,
1291 actual_size_ret,
1292 &bytes_remaining, &tmp_data);
1293 if (result != Success)
1294 {
1295 UNBLOCK_INPUT;
1296 *data_ret = 0;
1297 *bytes_ret = 0;
1298 return;
1299 }
1300
1301 /* This was allocated by Xlib, so use XFree. */
1302 XFree ((char *) tmp_data);
1303
1304 if (*actual_type_ret == None || *actual_format_ret == 0)
1305 {
1306 UNBLOCK_INPUT;
1307 return;
1308 }
1309
1310 total_size = bytes_remaining + 1;
1311 *data_ret = (unsigned char *) xmalloc (total_size);
1312
1313 /* Now read, until we've gotten it all. */
1314 while (bytes_remaining)
1315 {
1316 #ifdef TRACE_SELECTION
1317 unsigned long last = bytes_remaining;
1318 #endif
1319 result
1320 = XGetWindowProperty (display, window, property,
1321 (long)offset/4, (long)buffer_size/4,
1322 False,
1323 AnyPropertyType,
1324 actual_type_ret, actual_format_ret,
1325 actual_size_ret, &bytes_remaining, &tmp_data);
1326
1327 TRACE2 ("Read %lu bytes from property %s",
1328 last - bytes_remaining,
1329 XGetAtomName (display, property));
1330
1331 /* If this doesn't return Success at this point, it means that
1332 some clod deleted the selection while we were in the midst of
1333 reading it. Deal with that, I guess.... */
1334 if (result != Success)
1335 break;
1336
1337 /* The man page for XGetWindowProperty says:
1338 "If the returned format is 32, the returned data is represented
1339 as a long array and should be cast to that type to obtain the
1340 elements."
1341 This applies even if long is more than 32 bits, the X library
1342 converts from 32 bit elements received from the X server to long
1343 and passes the long array to us. Thus, for that case memcpy can not
1344 be used. We convert to a 32 bit type here, because so much code
1345 assume on that.
1346
1347 The bytes and offsets passed to XGetWindowProperty refers to the
1348 property and those are indeed in 32 bit quantities if format is 32. */
1349
1350 if (32 < BITS_PER_LONG && *actual_format_ret == 32)
1351 {
1352 unsigned long i;
1353 int *idata = (int *) ((*data_ret) + offset);
1354 long *ldata = (long *) tmp_data;
1355
1356 for (i = 0; i < *actual_size_ret; ++i)
1357 {
1358 idata[i]= (int) ldata[i];
1359 offset += 4;
1360 }
1361 }
1362 else
1363 {
1364 *actual_size_ret *= *actual_format_ret / 8;
1365 memcpy ((*data_ret) + offset, tmp_data, *actual_size_ret);
1366 offset += *actual_size_ret;
1367 }
1368
1369 /* This was allocated by Xlib, so use XFree. */
1370 XFree ((char *) tmp_data);
1371 }
1372
1373 XFlush (display);
1374 UNBLOCK_INPUT;
1375 *bytes_ret = offset;
1376 }
1377 \f
1378 /* Use xfree, not XFree, to free the data obtained with this function. */
1379
1380 static void
1381 receive_incremental_selection (Display *display, Window window, Atom property,
1382 Lisp_Object target_type,
1383 unsigned int min_size_bytes,
1384 unsigned char **data_ret, int *size_bytes_ret,
1385 Atom *type_ret, int *format_ret,
1386 unsigned long *size_ret)
1387 {
1388 int offset = 0;
1389 struct prop_location *wait_object;
1390 *size_bytes_ret = min_size_bytes;
1391 *data_ret = (unsigned char *) xmalloc (*size_bytes_ret);
1392
1393 TRACE1 ("Read %d bytes incrementally", min_size_bytes);
1394
1395 /* At this point, we have read an INCR property.
1396 Delete the property to ack it.
1397 (But first, prepare to receive the next event in this handshake.)
1398
1399 Now, we must loop, waiting for the sending window to put a value on
1400 that property, then reading the property, then deleting it to ack.
1401 We are done when the sender places a property of length 0.
1402 */
1403 BLOCK_INPUT;
1404 XSelectInput (display, window, STANDARD_EVENT_SET | PropertyChangeMask);
1405 TRACE1 (" Delete property %s",
1406 SDATA (SYMBOL_NAME (x_atom_to_symbol (display, property))));
1407 XDeleteProperty (display, window, property);
1408 TRACE1 (" Expect new value of property %s",
1409 SDATA (SYMBOL_NAME (x_atom_to_symbol (display, property))));
1410 wait_object = expect_property_change (display, window, property,
1411 PropertyNewValue);
1412 XFlush (display);
1413 UNBLOCK_INPUT;
1414
1415 while (1)
1416 {
1417 unsigned char *tmp_data;
1418 int tmp_size_bytes;
1419
1420 TRACE0 (" Wait for property change");
1421 wait_for_property_change (wait_object);
1422
1423 /* expect it again immediately, because x_get_window_property may
1424 .. no it won't, I don't get it.
1425 .. Ok, I get it now, the Xt code that implements INCR is broken. */
1426 TRACE0 (" Get property value");
1427 x_get_window_property (display, window, property,
1428 &tmp_data, &tmp_size_bytes,
1429 type_ret, format_ret, size_ret, 1);
1430
1431 TRACE1 (" Read increment of %d bytes", tmp_size_bytes);
1432
1433 if (tmp_size_bytes == 0) /* we're done */
1434 {
1435 TRACE0 ("Done reading incrementally");
1436
1437 if (! waiting_for_other_props_on_window (display, window))
1438 XSelectInput (display, window, STANDARD_EVENT_SET);
1439 /* Use xfree, not XFree, because x_get_window_property
1440 calls xmalloc itself. */
1441 xfree (tmp_data);
1442 break;
1443 }
1444
1445 BLOCK_INPUT;
1446 TRACE1 (" ACK by deleting property %s",
1447 XGetAtomName (display, property));
1448 XDeleteProperty (display, window, property);
1449 wait_object = expect_property_change (display, window, property,
1450 PropertyNewValue);
1451 XFlush (display);
1452 UNBLOCK_INPUT;
1453
1454 if (*size_bytes_ret < offset + tmp_size_bytes)
1455 {
1456 *size_bytes_ret = offset + tmp_size_bytes;
1457 *data_ret = (unsigned char *) xrealloc (*data_ret, *size_bytes_ret);
1458 }
1459
1460 memcpy ((*data_ret) + offset, tmp_data, tmp_size_bytes);
1461 offset += tmp_size_bytes;
1462
1463 /* Use xfree, not XFree, because x_get_window_property
1464 calls xmalloc itself. */
1465 xfree (tmp_data);
1466 }
1467 }
1468
1469 \f
1470 /* Fetch a value from property PROPERTY of X window WINDOW on display
1471 DISPLAY. TARGET_TYPE and SELECTION_ATOM are used in error message
1472 if this fails. */
1473
1474 static Lisp_Object
1475 x_get_window_property_as_lisp_data (Display *display, Window window,
1476 Atom property,
1477 Lisp_Object target_type,
1478 Atom selection_atom)
1479 {
1480 Atom actual_type;
1481 int actual_format;
1482 unsigned long actual_size;
1483 unsigned char *data = 0;
1484 int bytes = 0;
1485 Lisp_Object val;
1486 struct x_display_info *dpyinfo = x_display_info_for_display (display);
1487
1488 TRACE0 ("Reading selection data");
1489
1490 x_get_window_property (display, window, property, &data, &bytes,
1491 &actual_type, &actual_format, &actual_size, 1);
1492 if (! data)
1493 {
1494 int there_is_a_selection_owner;
1495 BLOCK_INPUT;
1496 there_is_a_selection_owner
1497 = XGetSelectionOwner (display, selection_atom);
1498 UNBLOCK_INPUT;
1499 if (there_is_a_selection_owner)
1500 signal_error ("Selection owner couldn't convert",
1501 actual_type
1502 ? list2 (target_type,
1503 x_atom_to_symbol (display, actual_type))
1504 : target_type);
1505 else
1506 signal_error ("No selection",
1507 x_atom_to_symbol (display, selection_atom));
1508 }
1509
1510 if (actual_type == dpyinfo->Xatom_INCR)
1511 {
1512 /* That wasn't really the data, just the beginning. */
1513
1514 unsigned int min_size_bytes = * ((unsigned int *) data);
1515 BLOCK_INPUT;
1516 /* Use xfree, not XFree, because x_get_window_property
1517 calls xmalloc itself. */
1518 xfree ((char *) data);
1519 UNBLOCK_INPUT;
1520 receive_incremental_selection (display, window, property, target_type,
1521 min_size_bytes, &data, &bytes,
1522 &actual_type, &actual_format,
1523 &actual_size);
1524 }
1525
1526 BLOCK_INPUT;
1527 TRACE1 (" Delete property %s", XGetAtomName (display, property));
1528 XDeleteProperty (display, window, property);
1529 XFlush (display);
1530 UNBLOCK_INPUT;
1531
1532 /* It's been read. Now convert it to a lisp object in some semi-rational
1533 manner. */
1534 val = selection_data_to_lisp_data (display, data, bytes,
1535 actual_type, actual_format);
1536
1537 /* Use xfree, not XFree, because x_get_window_property
1538 calls xmalloc itself. */
1539 xfree ((char *) data);
1540 return val;
1541 }
1542 \f
1543 /* These functions convert from the selection data read from the server into
1544 something that we can use from Lisp, and vice versa.
1545
1546 Type: Format: Size: Lisp Type:
1547 ----- ------- ----- -----------
1548 * 8 * String
1549 ATOM 32 1 Symbol
1550 ATOM 32 > 1 Vector of Symbols
1551 * 16 1 Integer
1552 * 16 > 1 Vector of Integers
1553 * 32 1 if <=16 bits: Integer
1554 if > 16 bits: Cons of top16, bot16
1555 * 32 > 1 Vector of the above
1556
1557 When converting a Lisp number to C, it is assumed to be of format 16 if
1558 it is an integer, and of format 32 if it is a cons of two integers.
1559
1560 When converting a vector of numbers from Lisp to C, it is assumed to be
1561 of format 16 if every element in the vector is an integer, and is assumed
1562 to be of format 32 if any element is a cons of two integers.
1563
1564 When converting an object to C, it may be of the form (SYMBOL . <data>)
1565 where SYMBOL is what we should claim that the type is. Format and
1566 representation are as above.
1567
1568 Important: When format is 32, data should contain an array of int,
1569 not an array of long as the X library returns. This makes a difference
1570 when sizeof(long) != sizeof(int). */
1571
1572
1573
1574 static Lisp_Object
1575 selection_data_to_lisp_data (Display *display, const unsigned char *data,
1576 int size, Atom type, int format)
1577 {
1578 struct x_display_info *dpyinfo = x_display_info_for_display (display);
1579
1580 if (type == dpyinfo->Xatom_NULL)
1581 return QNULL;
1582
1583 /* Convert any 8-bit data to a string, for compactness. */
1584 else if (format == 8)
1585 {
1586 Lisp_Object str, lispy_type;
1587
1588 str = make_unibyte_string ((char *) data, size);
1589 /* Indicate that this string is from foreign selection by a text
1590 property `foreign-selection' so that the caller of
1591 x-get-selection-internal (usually x-get-selection) can know
1592 that the string must be decode. */
1593 if (type == dpyinfo->Xatom_COMPOUND_TEXT)
1594 lispy_type = QCOMPOUND_TEXT;
1595 else if (type == dpyinfo->Xatom_UTF8_STRING)
1596 lispy_type = QUTF8_STRING;
1597 else
1598 lispy_type = QSTRING;
1599 Fput_text_property (make_number (0), make_number (size),
1600 Qforeign_selection, lispy_type, str);
1601 return str;
1602 }
1603 /* Convert a single atom to a Lisp_Symbol. Convert a set of atoms to
1604 a vector of symbols. */
1605 else if (type == XA_ATOM
1606 /* Treat ATOM_PAIR type similar to list of atoms. */
1607 || type == dpyinfo->Xatom_ATOM_PAIR)
1608 {
1609 int i;
1610 /* On a 64 bit machine sizeof(Atom) == sizeof(long) == 8.
1611 But the callers of these function has made sure the data for
1612 format == 32 is an array of int. Thus, use int instead
1613 of Atom. */
1614 int *idata = (int *) data;
1615
1616 if (size == sizeof (int))
1617 return x_atom_to_symbol (display, (Atom) idata[0]);
1618 else
1619 {
1620 Lisp_Object v = Fmake_vector (make_number (size / sizeof (int)),
1621 make_number (0));
1622 for (i = 0; i < size / sizeof (int); i++)
1623 Faset (v, make_number (i),
1624 x_atom_to_symbol (display, (Atom) idata[i]));
1625 return v;
1626 }
1627 }
1628
1629 /* Convert a single 16-bit number or a small 32-bit number to a Lisp_Int.
1630 If the number is 32 bits and won't fit in a Lisp_Int,
1631 convert it to a cons of integers, 16 bits in each half.
1632 */
1633 else if (format == 32 && size == sizeof (int))
1634 return INTEGER_TO_CONS (((unsigned int *) data) [0]);
1635 else if (format == 16 && size == sizeof (short))
1636 return make_number ((int) (((unsigned short *) data) [0]));
1637
1638 /* Convert any other kind of data to a vector of numbers, represented
1639 as above (as an integer, or a cons of two 16 bit integers.)
1640 */
1641 else if (format == 16)
1642 {
1643 int i;
1644 Lisp_Object v;
1645 v = Fmake_vector (make_number (size / 2), make_number (0));
1646 for (i = 0; i < size / 2; i++)
1647 {
1648 int j = (int) ((unsigned short *) data) [i];
1649 Faset (v, make_number (i), make_number (j));
1650 }
1651 return v;
1652 }
1653 else
1654 {
1655 int i;
1656 Lisp_Object v = Fmake_vector (make_number (size / 4), make_number (0));
1657 for (i = 0; i < size / 4; i++)
1658 {
1659 unsigned int j = ((unsigned int *) data) [i];
1660 Faset (v, make_number (i), INTEGER_TO_CONS (j));
1661 }
1662 return v;
1663 }
1664 }
1665
1666
1667 /* Use xfree, not XFree, to free the data obtained with this function. */
1668
1669 static void
1670 lisp_data_to_selection_data (Display *display, Lisp_Object obj,
1671 unsigned char **data_ret, Atom *type_ret,
1672 unsigned int *size_ret,
1673 int *format_ret, int *nofree_ret)
1674 {
1675 Lisp_Object type = Qnil;
1676 struct x_display_info *dpyinfo = x_display_info_for_display (display);
1677
1678 *nofree_ret = 0;
1679
1680 if (CONSP (obj) && SYMBOLP (XCAR (obj)))
1681 {
1682 type = XCAR (obj);
1683 obj = XCDR (obj);
1684 if (CONSP (obj) && NILP (XCDR (obj)))
1685 obj = XCAR (obj);
1686 }
1687
1688 if (EQ (obj, QNULL) || (EQ (type, QNULL)))
1689 { /* This is not the same as declining */
1690 *format_ret = 32;
1691 *size_ret = 0;
1692 *data_ret = 0;
1693 type = QNULL;
1694 }
1695 else if (STRINGP (obj))
1696 {
1697 if (SCHARS (obj) < SBYTES (obj))
1698 /* OBJ is a multibyte string containing a non-ASCII char. */
1699 signal_error ("Non-ASCII string must be encoded in advance", obj);
1700 if (NILP (type))
1701 type = QSTRING;
1702 *format_ret = 8;
1703 *size_ret = SBYTES (obj);
1704 *data_ret = SDATA (obj);
1705 *nofree_ret = 1;
1706 }
1707 else if (SYMBOLP (obj))
1708 {
1709 *format_ret = 32;
1710 *size_ret = 1;
1711 *data_ret = (unsigned char *) xmalloc (sizeof (Atom) + 1);
1712 (*data_ret) [sizeof (Atom)] = 0;
1713 (*(Atom **) data_ret) [0] = symbol_to_x_atom (dpyinfo, obj);
1714 if (NILP (type)) type = QATOM;
1715 }
1716 else if (INTEGERP (obj)
1717 && XINT (obj) < 0xFFFF
1718 && XINT (obj) > -0xFFFF)
1719 {
1720 *format_ret = 16;
1721 *size_ret = 1;
1722 *data_ret = (unsigned char *) xmalloc (sizeof (short) + 1);
1723 (*data_ret) [sizeof (short)] = 0;
1724 (*(short **) data_ret) [0] = (short) XINT (obj);
1725 if (NILP (type)) type = QINTEGER;
1726 }
1727 else if (INTEGERP (obj)
1728 || (CONSP (obj) && INTEGERP (XCAR (obj))
1729 && (INTEGERP (XCDR (obj))
1730 || (CONSP (XCDR (obj))
1731 && INTEGERP (XCAR (XCDR (obj)))))))
1732 {
1733 *format_ret = 32;
1734 *size_ret = 1;
1735 *data_ret = (unsigned char *) xmalloc (sizeof (long) + 1);
1736 (*data_ret) [sizeof (long)] = 0;
1737 (*(unsigned long **) data_ret) [0] = cons_to_unsigned (obj, ULONG_MAX);
1738 if (NILP (type)) type = QINTEGER;
1739 }
1740 else if (VECTORP (obj))
1741 {
1742 /* Lisp_Vectors may represent a set of ATOMs;
1743 a set of 16 or 32 bit INTEGERs;
1744 or a set of ATOM_PAIRs (represented as [[A1 A2] [A3 A4] ...]
1745 */
1746 int i;
1747
1748 if (SYMBOLP (XVECTOR (obj)->contents [0]))
1749 /* This vector is an ATOM set */
1750 {
1751 if (NILP (type)) type = QATOM;
1752 *size_ret = ASIZE (obj);
1753 *format_ret = 32;
1754 for (i = 0; i < *size_ret; i++)
1755 if (!SYMBOLP (XVECTOR (obj)->contents [i]))
1756 signal_error ("All elements of selection vector must have same type", obj);
1757
1758 *data_ret = (unsigned char *) xmalloc ((*size_ret) * sizeof (Atom));
1759 for (i = 0; i < *size_ret; i++)
1760 (*(Atom **) data_ret) [i]
1761 = symbol_to_x_atom (dpyinfo, XVECTOR (obj)->contents [i]);
1762 }
1763 else
1764 /* This vector is an INTEGER set, or something like it */
1765 {
1766 int data_size = 2;
1767 *size_ret = ASIZE (obj);
1768 if (NILP (type)) type = QINTEGER;
1769 *format_ret = 16;
1770 for (i = 0; i < *size_ret; i++)
1771 if (CONSP (XVECTOR (obj)->contents [i]))
1772 *format_ret = 32;
1773 else if (!INTEGERP (XVECTOR (obj)->contents [i]))
1774 signal_error (/* Qselection_error */
1775 "Elements of selection vector must be integers or conses of integers",
1776 obj);
1777
1778 /* Use sizeof(long) even if it is more than 32 bits. See comment
1779 in x_get_window_property and x_fill_property_data. */
1780
1781 if (*format_ret == 32) data_size = sizeof(long);
1782 *data_ret = (unsigned char *) xmalloc (*size_ret * data_size);
1783 for (i = 0; i < *size_ret; i++)
1784 if (*format_ret == 32)
1785 (*((unsigned long **) data_ret)) [i] =
1786 cons_to_unsigned (XVECTOR (obj)->contents [i], ULONG_MAX);
1787 else
1788 (*((unsigned short **) data_ret)) [i] =
1789 cons_to_unsigned (XVECTOR (obj)->contents [i], USHRT_MAX);
1790 }
1791 }
1792 else
1793 signal_error (/* Qselection_error */ "Unrecognized selection data", obj);
1794
1795 *type_ret = symbol_to_x_atom (dpyinfo, type);
1796 }
1797
1798 static Lisp_Object
1799 clean_local_selection_data (Lisp_Object obj)
1800 {
1801 if (CONSP (obj)
1802 && INTEGERP (XCAR (obj))
1803 && CONSP (XCDR (obj))
1804 && INTEGERP (XCAR (XCDR (obj)))
1805 && NILP (XCDR (XCDR (obj))))
1806 obj = Fcons (XCAR (obj), XCDR (obj));
1807
1808 if (CONSP (obj)
1809 && INTEGERP (XCAR (obj))
1810 && INTEGERP (XCDR (obj)))
1811 {
1812 if (XINT (XCAR (obj)) == 0)
1813 return XCDR (obj);
1814 if (XINT (XCAR (obj)) == -1)
1815 return make_number (- XINT (XCDR (obj)));
1816 }
1817 if (VECTORP (obj))
1818 {
1819 int i;
1820 int size = ASIZE (obj);
1821 Lisp_Object copy;
1822 if (size == 1)
1823 return clean_local_selection_data (XVECTOR (obj)->contents [0]);
1824 copy = Fmake_vector (make_number (size), Qnil);
1825 for (i = 0; i < size; i++)
1826 XVECTOR (copy)->contents [i]
1827 = clean_local_selection_data (XVECTOR (obj)->contents [i]);
1828 return copy;
1829 }
1830 return obj;
1831 }
1832 \f
1833 /* Called from XTread_socket to handle SelectionNotify events.
1834 If it's the selection we are waiting for, stop waiting
1835 by setting the car of reading_selection_reply to non-nil.
1836 We store t there if the reply is successful, lambda if not. */
1837
1838 void
1839 x_handle_selection_notify (XSelectionEvent *event)
1840 {
1841 if (event->requestor != reading_selection_window)
1842 return;
1843 if (event->selection != reading_which_selection)
1844 return;
1845
1846 TRACE0 ("Received SelectionNotify");
1847 XSETCAR (reading_selection_reply,
1848 (event->property != 0 ? Qt : Qlambda));
1849 }
1850
1851 \f
1852 /* From a Lisp_Object, return a suitable frame for selection
1853 operations. OBJECT may be a frame, a terminal object, or nil
1854 (which stands for the selected frame--or, if that is not an X
1855 frame, the first X display on the list). If no suitable frame can
1856 be found, return NULL. */
1857
1858 static struct frame *
1859 frame_for_x_selection (Lisp_Object object)
1860 {
1861 Lisp_Object tail;
1862 struct frame *f;
1863
1864 if (NILP (object))
1865 {
1866 f = XFRAME (selected_frame);
1867 if (FRAME_X_P (f) && FRAME_LIVE_P (f))
1868 return f;
1869
1870 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1871 {
1872 f = XFRAME (XCAR (tail));
1873 if (FRAME_X_P (f) && FRAME_LIVE_P (f))
1874 return f;
1875 }
1876 }
1877 else if (TERMINALP (object))
1878 {
1879 struct terminal *t = get_terminal (object, 1);
1880 if (t->type == output_x_window)
1881 {
1882 for (tail = Vframe_list; CONSP (tail); tail = XCDR (tail))
1883 {
1884 f = XFRAME (XCAR (tail));
1885 if (FRAME_LIVE_P (f) && f->terminal == t)
1886 return f;
1887 }
1888 }
1889 }
1890 else if (FRAMEP (object))
1891 {
1892 f = XFRAME (object);
1893 if (FRAME_X_P (f) && FRAME_LIVE_P (f))
1894 return f;
1895 }
1896
1897 return NULL;
1898 }
1899
1900
1901 DEFUN ("x-own-selection-internal", Fx_own_selection_internal,
1902 Sx_own_selection_internal, 2, 3, 0,
1903 doc: /* Assert an X selection of type SELECTION and value VALUE.
1904 SELECTION is a symbol, typically `PRIMARY', `SECONDARY', or `CLIPBOARD'.
1905 \(Those are literal upper-case symbol names, since that's what X expects.)
1906 VALUE is typically a string, or a cons of two markers, but may be
1907 anything that the functions on `selection-converter-alist' know about.
1908
1909 FRAME should be a frame that should own the selection. If omitted or
1910 nil, it defaults to the selected frame. */)
1911 (Lisp_Object selection, Lisp_Object value, Lisp_Object frame)
1912 {
1913 if (NILP (frame)) frame = selected_frame;
1914 if (!FRAME_LIVE_P (XFRAME (frame)) || !FRAME_X_P (XFRAME (frame)))
1915 error ("X selection unavailable for this frame");
1916
1917 CHECK_SYMBOL (selection);
1918 if (NILP (value)) error ("VALUE may not be nil");
1919 x_own_selection (selection, value, frame);
1920 return value;
1921 }
1922
1923
1924 /* Request the selection value from the owner. If we are the owner,
1925 simply return our selection value. If we are not the owner, this
1926 will block until all of the data has arrived. */
1927
1928 DEFUN ("x-get-selection-internal", Fx_get_selection_internal,
1929 Sx_get_selection_internal, 2, 4, 0,
1930 doc: /* Return text selected from some X window.
1931 SELECTION is a symbol, typically `PRIMARY', `SECONDARY', or `CLIPBOARD'.
1932 \(Those are literal upper-case symbol names, since that's what X expects.)
1933 TYPE is the type of data desired, typically `STRING'.
1934 TIME_STAMP is the time to use in the XConvertSelection call for foreign
1935 selections. If omitted, defaults to the time for the last event.
1936
1937 TERMINAL should be a terminal object or a frame specifying the X
1938 server to query. If omitted or nil, that stands for the selected
1939 frame's display, or the first available X display. */)
1940 (Lisp_Object selection_symbol, Lisp_Object target_type,
1941 Lisp_Object time_stamp, Lisp_Object terminal)
1942 {
1943 Lisp_Object val = Qnil;
1944 struct gcpro gcpro1, gcpro2;
1945 struct frame *f = frame_for_x_selection (terminal);
1946 GCPRO2 (target_type, val); /* we store newly consed data into these */
1947
1948 CHECK_SYMBOL (selection_symbol);
1949 CHECK_SYMBOL (target_type);
1950 if (EQ (target_type, QMULTIPLE))
1951 error ("Retrieving MULTIPLE selections is currently unimplemented");
1952 if (!f)
1953 error ("X selection unavailable for this frame");
1954
1955 val = x_get_local_selection (selection_symbol, target_type, 1,
1956 FRAME_X_DISPLAY_INFO (f));
1957
1958 if (NILP (val) && FRAME_LIVE_P (f))
1959 {
1960 Lisp_Object frame;
1961 XSETFRAME (frame, f);
1962 RETURN_UNGCPRO (x_get_foreign_selection (selection_symbol, target_type,
1963 time_stamp, frame));
1964 }
1965
1966 if (CONSP (val) && SYMBOLP (XCAR (val)))
1967 {
1968 val = XCDR (val);
1969 if (CONSP (val) && NILP (XCDR (val)))
1970 val = XCAR (val);
1971 }
1972 RETURN_UNGCPRO (clean_local_selection_data (val));
1973 }
1974
1975 DEFUN ("x-disown-selection-internal", Fx_disown_selection_internal,
1976 Sx_disown_selection_internal, 1, 3, 0,
1977 doc: /* If we own the selection SELECTION, disown it.
1978 Disowning it means there is no such selection.
1979
1980 TERMINAL should be a terminal object or a frame specifying the X
1981 server to query. If omitted or nil, that stands for the selected
1982 frame's display, or the first available X display. */)
1983 (Lisp_Object selection, Lisp_Object time_object, Lisp_Object terminal)
1984 {
1985 Time timestamp;
1986 Atom selection_atom;
1987 union {
1988 struct selection_input_event sie;
1989 struct input_event ie;
1990 } event;
1991 struct frame *f = frame_for_x_selection (terminal);
1992 struct x_display_info *dpyinfo;
1993
1994 if (!f)
1995 return Qnil;
1996
1997 dpyinfo = FRAME_X_DISPLAY_INFO (f);
1998 CHECK_SYMBOL (selection);
1999
2000 /* Don't disown the selection when we're not the owner. */
2001 if (NILP (LOCAL_SELECTION (selection, dpyinfo)))
2002 return Qnil;
2003
2004 selection_atom = symbol_to_x_atom (dpyinfo, selection);
2005
2006 BLOCK_INPUT;
2007 if (NILP (time_object))
2008 timestamp = last_event_timestamp;
2009 else
2010 CONS_TO_INTEGER (time_object, Time, timestamp);
2011 XSetSelectionOwner (dpyinfo->display, selection_atom, None, timestamp);
2012 UNBLOCK_INPUT;
2013
2014 /* It doesn't seem to be guaranteed that a SelectionClear event will be
2015 generated for a window which owns the selection when that window sets
2016 the selection owner to None. The NCD server does, the MIT Sun4 server
2017 doesn't. So we synthesize one; this means we might get two, but
2018 that's ok, because the second one won't have any effect. */
2019 SELECTION_EVENT_DISPLAY (&event.sie) = dpyinfo->display;
2020 SELECTION_EVENT_SELECTION (&event.sie) = selection_atom;
2021 SELECTION_EVENT_TIME (&event.sie) = timestamp;
2022 x_handle_selection_clear (&event.ie);
2023
2024 return Qt;
2025 }
2026
2027 DEFUN ("x-selection-owner-p", Fx_selection_owner_p, Sx_selection_owner_p,
2028 0, 2, 0,
2029 doc: /* Whether the current Emacs process owns the given X Selection.
2030 The arg should be the name of the selection in question, typically one of
2031 the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'.
2032 \(Those are literal upper-case symbol names, since that's what X expects.)
2033 For convenience, the symbol nil is the same as `PRIMARY',
2034 and t is the same as `SECONDARY'.
2035
2036 TERMINAL should be a terminal object or a frame specifying the X
2037 server to query. If omitted or nil, that stands for the selected
2038 frame's display, or the first available X display. */)
2039 (Lisp_Object selection, Lisp_Object terminal)
2040 {
2041 struct frame *f = frame_for_x_selection (terminal);
2042
2043 CHECK_SYMBOL (selection);
2044 if (EQ (selection, Qnil)) selection = QPRIMARY;
2045 if (EQ (selection, Qt)) selection = QSECONDARY;
2046
2047 if (f && !NILP (LOCAL_SELECTION (selection, FRAME_X_DISPLAY_INFO (f))))
2048 return Qt;
2049 else
2050 return Qnil;
2051 }
2052
2053 DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
2054 0, 2, 0,
2055 doc: /* Whether there is an owner for the given X selection.
2056 SELECTION should be the name of the selection in question, typically
2057 one of the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'. (X expects
2058 these literal upper-case names.) The symbol nil is the same as
2059 `PRIMARY', and t is the same as `SECONDARY'.
2060
2061 TERMINAL should be a terminal object or a frame specifying the X
2062 server to query. If omitted or nil, that stands for the selected
2063 frame's display, or the first available X display. */)
2064 (Lisp_Object selection, Lisp_Object terminal)
2065 {
2066 Window owner;
2067 Atom atom;
2068 struct frame *f = frame_for_x_selection (terminal);
2069 struct x_display_info *dpyinfo;
2070
2071 CHECK_SYMBOL (selection);
2072 if (EQ (selection, Qnil)) selection = QPRIMARY;
2073 if (EQ (selection, Qt)) selection = QSECONDARY;
2074
2075 if (!f)
2076 return Qnil;
2077
2078 dpyinfo = FRAME_X_DISPLAY_INFO (f);
2079
2080 if (!NILP (LOCAL_SELECTION (selection, dpyinfo)))
2081 return Qt;
2082
2083 atom = symbol_to_x_atom (dpyinfo, selection);
2084 if (atom == 0) return Qnil;
2085 BLOCK_INPUT;
2086 owner = XGetSelectionOwner (dpyinfo->display, atom);
2087 UNBLOCK_INPUT;
2088 return (owner ? Qt : Qnil);
2089 }
2090
2091 \f
2092 /* Send clipboard manager a SAVE_TARGETS request with a UTF8_STRING
2093 property (http://www.freedesktop.org/wiki/ClipboardManager). */
2094
2095 static Lisp_Object
2096 x_clipboard_manager_save (Lisp_Object frame)
2097 {
2098 struct frame *f = XFRAME (frame);
2099 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
2100 Atom data = dpyinfo->Xatom_UTF8_STRING;
2101
2102 XChangeProperty (FRAME_X_DISPLAY (f), FRAME_X_WINDOW (f),
2103 dpyinfo->Xatom_EMACS_TMP,
2104 dpyinfo->Xatom_ATOM, 32, PropModeReplace,
2105 (unsigned char *) &data, 1);
2106 x_get_foreign_selection (QCLIPBOARD_MANAGER, QSAVE_TARGETS,
2107 Qnil, frame);
2108 return Qt;
2109 }
2110
2111 /* Error handler for x_clipboard_manager_save_frame. */
2112
2113 static Lisp_Object
2114 x_clipboard_manager_error_1 (Lisp_Object err)
2115 {
2116 Lisp_Object args[2];
2117 args[0] = build_string ("X clipboard manager error: %s\n\
2118 If the problem persists, set `x-select-enable-clipboard-manager' to nil.");
2119 args[1] = CAR (CDR (err));
2120 Fmessage (2, args);
2121 return Qnil;
2122 }
2123
2124 /* Error handler for x_clipboard_manager_save_all. */
2125
2126 static Lisp_Object
2127 x_clipboard_manager_error_2 (Lisp_Object err)
2128 {
2129 fprintf (stderr, "Error saving to X clipboard manager.\n\
2130 If the problem persists, set `x-select-enable-clipboard-manager' \
2131 to nil.\n");
2132 return Qnil;
2133 }
2134
2135 /* Called from delete_frame: save any clipboard owned by FRAME to the
2136 clipboard manager. Do nothing if FRAME does not own the clipboard,
2137 or if no clipboard manager is present. */
2138
2139 void
2140 x_clipboard_manager_save_frame (Lisp_Object frame)
2141 {
2142 struct frame *f;
2143
2144 if (!NILP (Vx_select_enable_clipboard_manager)
2145 && FRAMEP (frame)
2146 && (f = XFRAME (frame), FRAME_X_P (f))
2147 && FRAME_LIVE_P (f))
2148 {
2149 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
2150 Lisp_Object local_selection
2151 = LOCAL_SELECTION (QCLIPBOARD, dpyinfo);
2152
2153 if (!NILP (local_selection)
2154 && EQ (frame, XCAR (XCDR (XCDR (XCDR (local_selection)))))
2155 && XGetSelectionOwner (dpyinfo->display,
2156 dpyinfo->Xatom_CLIPBOARD_MANAGER))
2157 internal_condition_case_1 (x_clipboard_manager_save, frame, Qt,
2158 x_clipboard_manager_error_1);
2159 }
2160 }
2161
2162 /* Called from Fkill_emacs: save any clipboard owned by FRAME to the
2163 clipboard manager. Do nothing if FRAME does not own the clipboard,
2164 or if no clipboard manager is present. */
2165
2166 void
2167 x_clipboard_manager_save_all (void)
2168 {
2169 /* Loop through all X displays, saving owned clipboards. */
2170 struct x_display_info *dpyinfo;
2171 Lisp_Object local_selection, local_frame;
2172
2173 if (NILP (Vx_select_enable_clipboard_manager))
2174 return;
2175
2176 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
2177 {
2178 local_selection = LOCAL_SELECTION (QCLIPBOARD, dpyinfo);
2179 if (NILP (local_selection)
2180 || !XGetSelectionOwner (dpyinfo->display,
2181 dpyinfo->Xatom_CLIPBOARD_MANAGER))
2182 continue;
2183
2184 local_frame = XCAR (XCDR (XCDR (XCDR (local_selection))));
2185 if (FRAME_LIVE_P (XFRAME (local_frame)))
2186 internal_condition_case_1 (x_clipboard_manager_save, local_frame,
2187 Qt, x_clipboard_manager_error_2);
2188 }
2189 }
2190
2191 \f
2192 /***********************************************************************
2193 Drag and drop support
2194 ***********************************************************************/
2195 /* Check that lisp values are of correct type for x_fill_property_data.
2196 That is, number, string or a cons with two numbers (low and high 16
2197 bit parts of a 32 bit number). Return the number of items in DATA,
2198 or -1 if there is an error. */
2199
2200 int
2201 x_check_property_data (Lisp_Object data)
2202 {
2203 Lisp_Object iter;
2204 int size = 0;
2205
2206 for (iter = data; CONSP (iter); iter = XCDR (iter))
2207 {
2208 Lisp_Object o = XCAR (iter);
2209
2210 if (! NUMBERP (o) && ! STRINGP (o) && ! CONSP (o))
2211 return -1;
2212 else if (CONSP (o) &&
2213 (! NUMBERP (XCAR (o)) || ! NUMBERP (XCDR (o))))
2214 return -1;
2215 size++;
2216 }
2217
2218 return size;
2219 }
2220
2221 /* Convert lisp values to a C array. Values may be a number, a string
2222 which is taken as an X atom name and converted to the atom value, or
2223 a cons containing the two 16 bit parts of a 32 bit number.
2224
2225 DPY is the display use to look up X atoms.
2226 DATA is a Lisp list of values to be converted.
2227 RET is the C array that contains the converted values. It is assumed
2228 it is big enough to hold all values.
2229 FORMAT is 8, 16 or 32 and denotes char/short/long for each C value to
2230 be stored in RET. Note that long is used for 32 even if long is more
2231 than 32 bits (see man pages for XChangeProperty, XGetWindowProperty and
2232 XClientMessageEvent). */
2233
2234 void
2235 x_fill_property_data (Display *dpy, Lisp_Object data, void *ret, int format)
2236 {
2237 long val;
2238 long *d32 = (long *) ret;
2239 short *d16 = (short *) ret;
2240 char *d08 = (char *) ret;
2241 Lisp_Object iter;
2242
2243 for (iter = data; CONSP (iter); iter = XCDR (iter))
2244 {
2245 Lisp_Object o = XCAR (iter);
2246
2247 if (INTEGERP (o) || FLOATP (o) || CONSP (o))
2248 val = cons_to_signed (o, LONG_MIN, LONG_MAX);
2249 else if (STRINGP (o))
2250 {
2251 BLOCK_INPUT;
2252 val = (long) XInternAtom (dpy, SSDATA (o), False);
2253 UNBLOCK_INPUT;
2254 }
2255 else
2256 error ("Wrong type, must be string, number or cons");
2257
2258 if (format == 8)
2259 {
2260 if (CHAR_MIN <= val && val <= CHAR_MAX)
2261 *d08++ = val;
2262 else
2263 error ("Out of 'char' range");
2264 }
2265 else if (format == 16)
2266 {
2267 if (SHRT_MIN <= val && val <= SHRT_MAX)
2268 *d16++ = val;
2269 else
2270 error ("Out of 'short' range");
2271 }
2272 else
2273 *d32++ = val;
2274 }
2275 }
2276
2277 /* Convert an array of C values to a Lisp list.
2278 F is the frame to be used to look up X atoms if the TYPE is XA_ATOM.
2279 DATA is a C array of values to be converted.
2280 TYPE is the type of the data. Only XA_ATOM is special, it converts
2281 each number in DATA to its corresponfing X atom as a symbol.
2282 FORMAT is 8, 16 or 32 and gives the size in bits for each C value to
2283 be stored in RET.
2284 SIZE is the number of elements in DATA.
2285
2286 Important: When format is 32, data should contain an array of int,
2287 not an array of long as the X library returns. This makes a difference
2288 when sizeof(long) != sizeof(int).
2289
2290 Also see comment for selection_data_to_lisp_data above. */
2291
2292 Lisp_Object
2293 x_property_data_to_lisp (struct frame *f, const unsigned char *data,
2294 Atom type, int format, long unsigned int size)
2295 {
2296 return selection_data_to_lisp_data (FRAME_X_DISPLAY (f),
2297 data, size*format/8, type, format);
2298 }
2299
2300 /* Get the mouse position in frame relative coordinates. */
2301
2302 static void
2303 mouse_position_for_drop (FRAME_PTR f, int *x, int *y)
2304 {
2305 Window root, dummy_window;
2306 int dummy;
2307
2308 BLOCK_INPUT;
2309
2310 XQueryPointer (FRAME_X_DISPLAY (f),
2311 DefaultRootWindow (FRAME_X_DISPLAY (f)),
2312
2313 /* The root window which contains the pointer. */
2314 &root,
2315
2316 /* Window pointer is on, not used */
2317 &dummy_window,
2318
2319 /* The position on that root window. */
2320 x, y,
2321
2322 /* x/y in dummy_window coordinates, not used. */
2323 &dummy, &dummy,
2324
2325 /* Modifier keys and pointer buttons, about which
2326 we don't care. */
2327 (unsigned int *) &dummy);
2328
2329
2330 /* Absolute to relative. */
2331 *x -= f->left_pos + FRAME_OUTER_TO_INNER_DIFF_X (f);
2332 *y -= f->top_pos + FRAME_OUTER_TO_INNER_DIFF_Y (f);
2333
2334 UNBLOCK_INPUT;
2335 }
2336
2337 DEFUN ("x-get-atom-name", Fx_get_atom_name,
2338 Sx_get_atom_name, 1, 2, 0,
2339 doc: /* Return the X atom name for VALUE as a string.
2340 VALUE may be a number or a cons where the car is the upper 16 bits and
2341 the cdr is the lower 16 bits of a 32 bit value.
2342 Use the display for FRAME or the current frame if FRAME is not given or nil.
2343
2344 If the value is 0 or the atom is not known, return the empty string. */)
2345 (Lisp_Object value, Lisp_Object frame)
2346 {
2347 struct frame *f = check_x_frame (frame);
2348 char *name = 0;
2349 char empty[] = "";
2350 Lisp_Object ret = Qnil;
2351 Display *dpy = FRAME_X_DISPLAY (f);
2352 Atom atom;
2353 int had_errors;
2354
2355 CONS_TO_INTEGER (value, Atom, atom);
2356
2357 BLOCK_INPUT;
2358 x_catch_errors (dpy);
2359 name = atom ? XGetAtomName (dpy, atom) : empty;
2360 had_errors = x_had_errors_p (dpy);
2361 x_uncatch_errors ();
2362
2363 if (!had_errors)
2364 ret = build_string (name);
2365
2366 if (atom && name) XFree (name);
2367 if (NILP (ret)) ret = empty_unibyte_string;
2368
2369 UNBLOCK_INPUT;
2370
2371 return ret;
2372 }
2373
2374 DEFUN ("x-register-dnd-atom", Fx_register_dnd_atom,
2375 Sx_register_dnd_atom, 1, 2, 0,
2376 doc: /* Request that dnd events are made for ClientMessages with ATOM.
2377 ATOM can be a symbol or a string. The ATOM is interned on the display that
2378 FRAME is on. If FRAME is nil, the selected frame is used. */)
2379 (Lisp_Object atom, Lisp_Object frame)
2380 {
2381 Atom x_atom;
2382 struct frame *f = check_x_frame (frame);
2383 ptrdiff_t i;
2384 struct x_display_info *dpyinfo = FRAME_X_DISPLAY_INFO (f);
2385
2386
2387 if (SYMBOLP (atom))
2388 x_atom = symbol_to_x_atom (dpyinfo, atom);
2389 else if (STRINGP (atom))
2390 {
2391 BLOCK_INPUT;
2392 x_atom = XInternAtom (FRAME_X_DISPLAY (f), SSDATA (atom), False);
2393 UNBLOCK_INPUT;
2394 }
2395 else
2396 error ("ATOM must be a symbol or a string");
2397
2398 for (i = 0; i < dpyinfo->x_dnd_atoms_length; ++i)
2399 if (dpyinfo->x_dnd_atoms[i] == x_atom)
2400 return Qnil;
2401
2402 if (dpyinfo->x_dnd_atoms_length == dpyinfo->x_dnd_atoms_size)
2403 {
2404 if (min (PTRDIFF_MAX, SIZE_MAX) / sizeof *dpyinfo->x_dnd_atoms / 2
2405 < dpyinfo->x_dnd_atoms_size)
2406 memory_full (SIZE_MAX);
2407 dpyinfo->x_dnd_atoms_size *= 2;
2408 dpyinfo->x_dnd_atoms = xrealloc (dpyinfo->x_dnd_atoms,
2409 sizeof (*dpyinfo->x_dnd_atoms)
2410 * dpyinfo->x_dnd_atoms_size);
2411 }
2412
2413 dpyinfo->x_dnd_atoms[dpyinfo->x_dnd_atoms_length++] = x_atom;
2414 return Qnil;
2415 }
2416
2417 /* Convert an XClientMessageEvent to a Lisp event of type DRAG_N_DROP_EVENT. */
2418
2419 int
2420 x_handle_dnd_message (struct frame *f, XClientMessageEvent *event, struct x_display_info *dpyinfo, struct input_event *bufp)
2421 {
2422 Lisp_Object vec;
2423 Lisp_Object frame;
2424 /* format 32 => size 5, format 16 => size 10, format 8 => size 20 */
2425 unsigned long size = 160/event->format;
2426 int x, y;
2427 unsigned char *data = (unsigned char *) event->data.b;
2428 int idata[5];
2429 ptrdiff_t i;
2430
2431 for (i = 0; i < dpyinfo->x_dnd_atoms_length; ++i)
2432 if (dpyinfo->x_dnd_atoms[i] == event->message_type) break;
2433
2434 if (i == dpyinfo->x_dnd_atoms_length) return 0;
2435
2436 XSETFRAME (frame, f);
2437
2438 /* On a 64 bit machine, the event->data.l array members are 64 bits (long),
2439 but the x_property_data_to_lisp (or rather selection_data_to_lisp_data)
2440 function expects them to be of size int (i.e. 32). So to be able to
2441 use that function, put the data in the form it expects if format is 32. */
2442
2443 if (32 < BITS_PER_LONG && event->format == 32)
2444 {
2445 for (i = 0; i < 5; ++i) /* There are only 5 longs in a ClientMessage. */
2446 idata[i] = (int) event->data.l[i];
2447 data = (unsigned char *) idata;
2448 }
2449
2450 vec = Fmake_vector (make_number (4), Qnil);
2451 ASET (vec, 0, SYMBOL_NAME (x_atom_to_symbol (FRAME_X_DISPLAY (f),
2452 event->message_type)));
2453 ASET (vec, 1, frame);
2454 ASET (vec, 2, make_number (event->format));
2455 ASET (vec, 3, x_property_data_to_lisp (f,
2456 data,
2457 event->message_type,
2458 event->format,
2459 size));
2460
2461 mouse_position_for_drop (f, &x, &y);
2462 bufp->kind = DRAG_N_DROP_EVENT;
2463 bufp->frame_or_window = frame;
2464 bufp->timestamp = CurrentTime;
2465 bufp->x = make_number (x);
2466 bufp->y = make_number (y);
2467 bufp->arg = vec;
2468 bufp->modifiers = 0;
2469
2470 return 1;
2471 }
2472
2473 DEFUN ("x-send-client-message", Fx_send_client_event,
2474 Sx_send_client_message, 6, 6, 0,
2475 doc: /* Send a client message of MESSAGE-TYPE to window DEST on DISPLAY.
2476
2477 For DISPLAY, specify either a frame or a display name (a string).
2478 If DISPLAY is nil, that stands for the selected frame's display.
2479 DEST may be a number, in which case it is a Window id. The value 0 may
2480 be used to send to the root window of the DISPLAY.
2481 If DEST is a cons, it is converted to a 32 bit number
2482 with the high 16 bits from the car and the lower 16 bit from the cdr. That
2483 number is then used as a window id.
2484 If DEST is a frame the event is sent to the outer window of that frame.
2485 A value of nil means the currently selected frame.
2486 If DEST is the string "PointerWindow" the event is sent to the window that
2487 contains the pointer. If DEST is the string "InputFocus" the event is
2488 sent to the window that has the input focus.
2489 FROM is the frame sending the event. Use nil for currently selected frame.
2490 MESSAGE-TYPE is the name of an Atom as a string.
2491 FORMAT must be one of 8, 16 or 32 and determines the size of the values in
2492 bits. VALUES is a list of numbers, cons and/or strings containing the values
2493 to send. If a value is a string, it is converted to an Atom and the value of
2494 the Atom is sent. If a value is a cons, it is converted to a 32 bit number
2495 with the high 16 bits from the car and the lower 16 bit from the cdr.
2496 If more values than fits into the event is given, the excessive values
2497 are ignored. */)
2498 (Lisp_Object display, Lisp_Object dest, Lisp_Object from, Lisp_Object message_type, Lisp_Object format, Lisp_Object values)
2499 {
2500 struct x_display_info *dpyinfo = check_x_display_info (display);
2501
2502 CHECK_STRING (message_type);
2503 x_send_client_event(display, dest, from,
2504 XInternAtom (dpyinfo->display,
2505 SSDATA (message_type),
2506 False),
2507 format, values);
2508
2509 return Qnil;
2510 }
2511
2512 void
2513 x_send_client_event (Lisp_Object display, Lisp_Object dest, Lisp_Object from, Atom message_type, Lisp_Object format, Lisp_Object values)
2514 {
2515 struct x_display_info *dpyinfo = check_x_display_info (display);
2516 Window wdest;
2517 XEvent event;
2518 struct frame *f = check_x_frame (from);
2519 int to_root;
2520
2521 CHECK_NUMBER (format);
2522 CHECK_CONS (values);
2523
2524 if (x_check_property_data (values) == -1)
2525 error ("Bad data in VALUES, must be number, cons or string");
2526
2527 event.xclient.type = ClientMessage;
2528 event.xclient.format = XFASTINT (format);
2529
2530 if (event.xclient.format != 8 && event.xclient.format != 16
2531 && event.xclient.format != 32)
2532 error ("FORMAT must be one of 8, 16 or 32");
2533
2534 if (FRAMEP (dest) || NILP (dest))
2535 {
2536 struct frame *fdest = check_x_frame (dest);
2537 wdest = FRAME_OUTER_WINDOW (fdest);
2538 }
2539 else if (STRINGP (dest))
2540 {
2541 if (strcmp (SSDATA (dest), "PointerWindow") == 0)
2542 wdest = PointerWindow;
2543 else if (strcmp (SSDATA (dest), "InputFocus") == 0)
2544 wdest = InputFocus;
2545 else
2546 error ("DEST as a string must be one of PointerWindow or InputFocus");
2547 }
2548 else if (INTEGERP (dest) || FLOATP (dest) || CONSP (dest))
2549 CONS_TO_INTEGER (dest, Window, wdest);
2550 else
2551 error ("DEST must be a frame, nil, string, number or cons");
2552
2553 if (wdest == 0) wdest = dpyinfo->root_window;
2554 to_root = wdest == dpyinfo->root_window;
2555
2556 BLOCK_INPUT;
2557
2558 event.xclient.message_type = message_type;
2559 event.xclient.display = dpyinfo->display;
2560
2561 /* Some clients (metacity for example) expects sending window to be here
2562 when sending to the root window. */
2563 event.xclient.window = to_root ? FRAME_OUTER_WINDOW (f) : wdest;
2564
2565
2566 memset (event.xclient.data.b, 0, sizeof (event.xclient.data.b));
2567 x_fill_property_data (dpyinfo->display, values, event.xclient.data.b,
2568 event.xclient.format);
2569
2570 /* If event mask is 0 the event is sent to the client that created
2571 the destination window. But if we are sending to the root window,
2572 there is no such client. Then we set the event mask to 0xffff. The
2573 event then goes to clients selecting for events on the root window. */
2574 x_catch_errors (dpyinfo->display);
2575 {
2576 int propagate = to_root ? False : True;
2577 unsigned mask = to_root ? 0xffff : 0;
2578 XSendEvent (dpyinfo->display, wdest, propagate, mask, &event);
2579 XFlush (dpyinfo->display);
2580 }
2581 x_uncatch_errors ();
2582 UNBLOCK_INPUT;
2583 }
2584
2585 \f
2586 void
2587 syms_of_xselect (void)
2588 {
2589 defsubr (&Sx_get_selection_internal);
2590 defsubr (&Sx_own_selection_internal);
2591 defsubr (&Sx_disown_selection_internal);
2592 defsubr (&Sx_selection_owner_p);
2593 defsubr (&Sx_selection_exists_p);
2594
2595 defsubr (&Sx_get_atom_name);
2596 defsubr (&Sx_send_client_message);
2597 defsubr (&Sx_register_dnd_atom);
2598
2599 reading_selection_reply = Fcons (Qnil, Qnil);
2600 staticpro (&reading_selection_reply);
2601 reading_selection_window = 0;
2602 reading_which_selection = 0;
2603
2604 property_change_wait_list = 0;
2605 prop_location_identifier = 0;
2606 property_change_reply = Fcons (Qnil, Qnil);
2607 staticpro (&property_change_reply);
2608
2609 converted_selections = NULL;
2610 conversion_fail_tag = None;
2611
2612 DEFVAR_LISP ("selection-converter-alist", Vselection_converter_alist,
2613 doc: /* An alist associating X Windows selection-types with functions.
2614 These functions are called to convert the selection, with three args:
2615 the name of the selection (typically `PRIMARY', `SECONDARY', or `CLIPBOARD');
2616 a desired type to which the selection should be converted;
2617 and the local selection value (whatever was given to `x-own-selection').
2618
2619 The function should return the value to send to the X server
2620 \(typically a string). A return value of nil
2621 means that the conversion could not be done.
2622 A return value which is the symbol `NULL'
2623 means that a side-effect was executed,
2624 and there is no meaningful selection value. */);
2625 Vselection_converter_alist = Qnil;
2626
2627 DEFVAR_LISP ("x-lost-selection-functions", Vx_lost_selection_functions,
2628 doc: /* A list of functions to be called when Emacs loses an X selection.
2629 \(This happens when some other X client makes its own selection
2630 or when a Lisp program explicitly clears the selection.)
2631 The functions are called with one argument, the selection type
2632 \(a symbol, typically `PRIMARY', `SECONDARY', or `CLIPBOARD'). */);
2633 Vx_lost_selection_functions = Qnil;
2634
2635 DEFVAR_LISP ("x-sent-selection-functions", Vx_sent_selection_functions,
2636 doc: /* A list of functions to be called when Emacs answers a selection request.
2637 The functions are called with three arguments:
2638 - the selection name (typically `PRIMARY', `SECONDARY', or `CLIPBOARD');
2639 - the selection-type which Emacs was asked to convert the
2640 selection into before sending (for example, `STRING' or `LENGTH');
2641 - a flag indicating success or failure for responding to the request.
2642 We might have failed (and declined the request) for any number of reasons,
2643 including being asked for a selection that we no longer own, or being asked
2644 to convert into a type that we don't know about or that is inappropriate.
2645 This hook doesn't let you change the behavior of Emacs's selection replies,
2646 it merely informs you that they have happened. */);
2647 Vx_sent_selection_functions = Qnil;
2648
2649 DEFVAR_LISP ("x-select-enable-clipboard-manager",
2650 Vx_select_enable_clipboard_manager,
2651 doc: /* Whether to enable X clipboard manager support.
2652 If non-nil, then whenever Emacs is killed or an Emacs frame is deleted
2653 while owning the X clipboard, the clipboard contents are saved to the
2654 clipboard manager if one is present. */);
2655 Vx_select_enable_clipboard_manager = Qt;
2656
2657 DEFVAR_INT ("x-selection-timeout", x_selection_timeout,
2658 doc: /* Number of milliseconds to wait for a selection reply.
2659 If the selection owner doesn't reply in this time, we give up.
2660 A value of 0 means wait as long as necessary. This is initialized from the
2661 \"*selectionTimeout\" resource. */);
2662 x_selection_timeout = 0;
2663
2664 /* QPRIMARY is defined in keyboard.c. */
2665 DEFSYM (QSECONDARY, "SECONDARY");
2666 DEFSYM (QSTRING, "STRING");
2667 DEFSYM (QINTEGER, "INTEGER");
2668 DEFSYM (QCLIPBOARD, "CLIPBOARD");
2669 DEFSYM (QTIMESTAMP, "TIMESTAMP");
2670 DEFSYM (QTEXT, "TEXT");
2671 DEFSYM (QCOMPOUND_TEXT, "COMPOUND_TEXT");
2672 DEFSYM (QUTF8_STRING, "UTF8_STRING");
2673 DEFSYM (QDELETE, "DELETE");
2674 DEFSYM (QMULTIPLE, "MULTIPLE");
2675 DEFSYM (QINCR, "INCR");
2676 DEFSYM (QEMACS_TMP, "_EMACS_TMP_");
2677 DEFSYM (QTARGETS, "TARGETS");
2678 DEFSYM (QATOM, "ATOM");
2679 DEFSYM (QATOM_PAIR, "ATOM_PAIR");
2680 DEFSYM (QCLIPBOARD_MANAGER, "CLIPBOARD_MANAGER");
2681 DEFSYM (QSAVE_TARGETS, "SAVE_TARGETS");
2682 DEFSYM (QNULL, "NULL");
2683 DEFSYM (Qcompound_text_with_extensions, "compound-text-with-extensions");
2684 DEFSYM (Qforeign_selection, "foreign-selection");
2685 }