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