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