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