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