blob: 1aa09fd4a3c8d417dcf797d23f7374a3632b9993 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 * X command server by Flemming Madsen
5 *
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
9 *
10 * if_xcmdsrv.c: Functions for passing commands through an X11 display.
11 *
12 */
13
14#include "vim.h"
15#include "version.h"
16
17#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
18
19# ifdef FEAT_X11
20# include <X11/Intrinsic.h>
21# include <X11/Xatom.h>
22# endif
23
Bram Moolenaar071d4272004-06-13 20:20:40 +000024/*
Bram Moolenaar9964e462007-05-05 17:54:07 +000025 * This file provides procedures that implement the command server
26 * functionality of Vim when in contact with an X11 server.
Bram Moolenaar071d4272004-06-13 20:20:40 +000027 *
28 * Adapted from TCL/TK's send command in tkSend.c of the tk 3.6 distribution.
29 * Adapted for use in Vim by Flemming Madsen. Protocol changed to that of tk 4
30 */
31
32/*
33 * Copyright (c) 1989-1993 The Regents of the University of California.
34 * All rights reserved.
35 *
36 * Permission is hereby granted, without written agreement and without
37 * license or royalty fees, to use, copy, modify, and distribute this
38 * software and its documentation for any purpose, provided that the
39 * above copyright notice and the following two paragraphs appear in
40 * all copies of this software.
41 *
42 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
43 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
44 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
45 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 *
47 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
48 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
49 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
50 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
51 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
52 */
53
54
55/*
56 * When a result is being awaited from a sent command, one of
57 * the following structures is present on a list of all outstanding
58 * sent commands. The information in the structure is used to
59 * process the result when it arrives. You're probably wondering
60 * how there could ever be multiple outstanding sent commands.
61 * This could happen if Vim instances invoke each other recursively.
62 * It's unlikely, but possible.
63 */
64
65typedef struct PendingCommand
66{
Bram Moolenaar2ab2e862019-12-04 21:24:53 +010067 int serial; // Serial number expected in result.
68 int code; // Result Code. 0 is OK
69 char_u *result; // String result for command (malloc'ed).
70 // NULL means command still pending.
Bram Moolenaar071d4272004-06-13 20:20:40 +000071 struct PendingCommand *nextPtr;
Bram Moolenaar2ab2e862019-12-04 21:24:53 +010072 // Next in list of all outstanding commands.
73 // NULL means end of list.
Bram Moolenaar071d4272004-06-13 20:20:40 +000074} PendingCommand;
75
76static PendingCommand *pendingCommands = NULL;
Bram Moolenaar2ab2e862019-12-04 21:24:53 +010077 // List of all commands currently
78 // being waited for.
Bram Moolenaar071d4272004-06-13 20:20:40 +000079
80/*
81 * The information below is used for communication between processes
82 * during "send" commands. Each process keeps a private window, never
83 * even mapped, with one property, "Comm". When a command is sent to
84 * an interpreter, the command is appended to the comm property of the
85 * communication window associated with the interp's process. Similarly,
86 * when a result is returned from a sent command, it is also appended
87 * to the comm property.
88 *
89 * Each command and each result takes the form of ASCII text. For a
90 * command, the text consists of a nul character followed by several
Bram Moolenaar1cd871b2004-12-19 22:46:22 +000091 * nul-terminated ASCII strings. The first string consists of a
92 * single letter:
93 * "c" for an expression
94 * "k" for keystrokes
95 * "r" for reply
96 * "n" for notification.
97 * Subsequent strings have the form "option value" where the following options
98 * are supported:
Bram Moolenaar071d4272004-06-13 20:20:40 +000099 *
100 * -r commWindow serial
101 *
102 * This option means that a response should be sent to the window
103 * whose X identifier is "commWindow" (in hex), and the response should
104 * be identified with the serial number given by "serial" (in decimal).
105 * If this option isn't specified then the send is asynchronous and
106 * no response is sent.
107 *
108 * -n name
109 * "Name" gives the name of the application for which the command is
110 * intended. This option must be present.
111 *
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000112 * -E encoding
113 * Encoding name used for the text. This is the 'encoding' of the
114 * sender. The receiver may want to do conversion to his 'encoding'.
115 *
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116 * -s script
117 * "Script" is the script to be executed. This option must be
118 * present. Taken as a series of keystrokes in a "k" command where
119 * <Key>'s are expanded
120 *
121 * The options may appear in any order. The -n and -s options must be
122 * present, but -r may be omitted for asynchronous RPCs. For compatibility
123 * with future releases that may add new features, there may be additional
124 * options present; as long as they start with a "-" character, they will
125 * be ignored.
126 *
127 * A result also consists of a zero character followed by several null-
128 * terminated ASCII strings. The first string consists of the single
129 * letter "r". Subsequent strings have the form "option value" where
130 * the following options are supported:
131 *
132 * -s serial
133 * Identifies the command for which this is the result. It is the
134 * same as the "serial" field from the -s option in the command. This
135 * option must be present.
136 *
137 * -r result
138 * "Result" is the result string for the script, which may be either
139 * a result or an error message. If this field is omitted then it
140 * defaults to an empty string.
141 *
142 * -c code
143 * 0: for OK. This is the default.
144 * 1: for error: Result is the last error
145 *
146 * -i errorInfo
147 * -e errorCode
148 * Not applicable for Vim
149 *
150 * Options may appear in any order, and only the -s option must be
151 * present. As with commands, there may be additional options besides
152 * these; unknown options are ignored.
153 */
154
155/*
156 * Maximum size property that can be read at one time by
157 * this module:
158 */
159
160#define MAX_PROP_WORDS 100000
161
162struct ServerReply
163{
164 Window id;
165 garray_T strings;
166};
167static garray_T serverReply = { 0, 0, 0, 0, 0 };
168enum ServerReplyOp { SROP_Find, SROP_Add, SROP_Delete };
169
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100170typedef int (*EndCond)(void *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200172struct x_cmdqueue
173{
174 char_u *propInfo;
Bram Moolenaarb8603882015-09-17 23:20:42 +0200175 long_u len;
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200176 struct x_cmdqueue *next;
177 struct x_cmdqueue *prev;
178};
179
180typedef struct x_cmdqueue x_queue_T;
181
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100182// dummy node, header for circular queue
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200183static x_queue_T head = {NULL, 0, NULL, NULL};
184
Bram Moolenaar071d4272004-06-13 20:20:40 +0000185/*
186 * Forward declarations for procedures defined later in this file:
187 */
188
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100189static Window LookupName(Display *dpy, char_u *name, int delete, char_u **loose);
190static int SendInit(Display *dpy);
191static int DoRegisterName(Display *dpy, char_u *name);
192static void DeleteAnyLingerer(Display *dpy, Window w);
193static int GetRegProp(Display *dpy, char_u **regPropp, long_u *numItemsp, int domsg);
194static int WaitForPend(void *p);
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100195static int WindowValid(Display *dpy, Window w);
196static void ServerWait(Display *dpy, Window w, EndCond endCond, void *endData, int localLoop, int seconds);
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100197static int AppendPropCarefully(Display *display, Window window, Atom property, char_u *value, int length);
198static int x_error_check(Display *dpy, XErrorEvent *error_event);
199static int IsSerialName(char_u *name);
200static void save_in_queue(char_u *buf, long_u len);
201static void server_parse_message(Display *dpy, char_u *propInfo, long_u numItems);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000202
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100203// Private variables for the "server" functionality
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204static Atom registryProperty = None;
205static Atom vimProperty = None;
206static int got_x_error = FALSE;
207
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100208static char_u *empty_prop = (char_u *)""; // empty GetRegProp() result
Bram Moolenaar071d4272004-06-13 20:20:40 +0000209
210/*
211 * Associate an ASCII name with Vim. Try real hard to get a unique one.
212 * Returns FAIL or OK.
213 */
214 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100215serverRegisterName(
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100216 Display *dpy, // display to register with
217 char_u *name) // the name that will be used as a base
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218{
219 int i;
220 int res;
221 char_u *p = NULL;
222
223 res = DoRegisterName(dpy, name);
224 if (res < 0)
225 {
226 i = 1;
227 do
228 {
229 if (res < -1 || i >= 1000)
230 {
Bram Moolenaara502caa2019-01-19 18:23:41 +0100231 msg_attr(_("Unable to register a command server name"),
Bram Moolenaar8820b482017-03-16 17:23:31 +0100232 HL_ATTR(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000233 return FAIL;
234 }
235 if (p == NULL)
236 p = alloc(STRLEN(name) + 10);
237 if (p == NULL)
238 {
239 res = -10;
240 continue;
241 }
242 sprintf((char *)p, "%s%d", name, i++);
243 res = DoRegisterName(dpy, p);
244 }
245 while (res < 0)
246 ;
247 vim_free(p);
248 }
249 return OK;
250}
251
252 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100253DoRegisterName(Display *dpy, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000254{
255 Window w;
256 XErrorHandler old_handler;
257#define MAX_NAME_LENGTH 100
258 char_u propInfo[MAX_NAME_LENGTH + 20];
259
260 if (commProperty == None)
261 {
262 if (SendInit(dpy) < 0)
263 return -2;
264 }
265
266 /*
267 * Make sure the name is unique, and append info about it to
268 * the registry property. It's important to lock the server
269 * here to prevent conflicting changes to the registry property.
270 * WARNING: Do not step through this while debugging, it will hangup the X
271 * server!
272 */
273 XGrabServer(dpy);
274 w = LookupName(dpy, name, FALSE, NULL);
275 if (w != (Window)0)
276 {
277 Status status;
278 int dummyInt;
279 unsigned int dummyUns;
280 Window dummyWin;
281
282 /*
283 * The name is currently registered. See if the commWindow
284 * associated with the name exists. If not, or if the commWindow
285 * is *our* commWindow, then just unregister the old name (this
286 * could happen if an application dies without cleaning up the
287 * registry).
288 */
289 old_handler = XSetErrorHandler(x_error_check);
290 status = XGetGeometry(dpy, w, &dummyWin, &dummyInt, &dummyInt,
291 &dummyUns, &dummyUns, &dummyUns, &dummyUns);
292 (void)XSetErrorHandler(old_handler);
293 if (status != Success && w != commWindow)
294 {
295 XUngrabServer(dpy);
296 XFlush(dpy);
297 return -1;
298 }
299 (void)LookupName(dpy, name, /*delete=*/TRUE, NULL);
300 }
301 sprintf((char *)propInfo, "%x %.*s", (int_u)commWindow,
302 MAX_NAME_LENGTH, name);
303 old_handler = XSetErrorHandler(x_error_check);
304 got_x_error = FALSE;
305 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
306 PropModeAppend, propInfo, STRLEN(propInfo) + 1);
307 XUngrabServer(dpy);
308 XSync(dpy, False);
309 (void)XSetErrorHandler(old_handler);
310
311 if (!got_x_error)
312 {
313#ifdef FEAT_EVAL
314 set_vim_var_string(VV_SEND_SERVER, name, -1);
315#endif
316 serverName = vim_strsave(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000317 need_maketitle = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318 return 0;
319 }
320 return -2;
321}
322
323#if defined(FEAT_GUI) || defined(PROTO)
324/*
325 * Clean out new ID from registry and set it as comm win.
326 * Change any registered window ID.
327 */
328 void
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100329serverChangeRegisteredWindow(
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100330 Display *dpy, // Display to register with
331 Window newwin) // Re-register to this ID
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332{
333 char_u propInfo[MAX_NAME_LENGTH + 20];
334
335 commWindow = newwin;
336
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100337 // Always call SendInit() here, to make sure commWindow is marked as a Vim
338 // window.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339 if (SendInit(dpy) < 0)
340 return;
341
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100342 // WARNING: Do not step through this while debugging, it will hangup the X
343 // server!
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 XGrabServer(dpy);
345 DeleteAnyLingerer(dpy, newwin);
346 if (serverName != NULL)
347 {
Dominique Pelleaf4a61a2021-12-27 17:21:41 +0000348 // Reinsert name if it was already registered
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349 (void)LookupName(dpy, serverName, /*delete=*/TRUE, NULL);
350 sprintf((char *)propInfo, "%x %.*s",
351 (int_u)newwin, MAX_NAME_LENGTH, serverName);
352 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
353 PropModeAppend, (char_u *)propInfo,
354 STRLEN(propInfo) + 1);
355 }
356 XUngrabServer(dpy);
357}
358#endif
359
360/*
361 * Send to an instance of Vim via the X display.
362 * Returns 0 for OK, negative for an error.
363 */
364 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100365serverSendToVim(
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100366 Display *dpy, // Where to send.
367 char_u *name, // Where to send.
368 char_u *cmd, // What to send.
369 char_u **result, // Result of eval'ed expression
370 Window *server, // Actual ID of receiving app
371 Bool asExpr, // Interpret as keystrokes or expr ?
372 int timeout, // seconds to wait or zero
373 Bool localLoop, // Throw away everything but result
374 int silent) // don't complain about no server
Bram Moolenaar071d4272004-06-13 20:20:40 +0000375{
376 Window w;
377 char_u *property;
378 int length;
379 int res;
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100380 static int serial = 0; // Running count of sent commands.
381 // Used to give each command a
382 // different serial number.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000383 PendingCommand pending;
384 char_u *loosename = NULL;
385
386 if (result != NULL)
387 *result = NULL;
388 if (name == NULL || *name == NUL)
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100389 name = (char_u *)"GVIM"; // use a default name
Bram Moolenaar071d4272004-06-13 20:20:40 +0000390
Bram Moolenaar4c5678f2022-11-30 18:12:19 +0000391 if (commProperty == None && dpy != NULL && SendInit(dpy) < 0)
392 return -1;
393
394#if defined(FEAT_EVAL)
395 ch_log(NULL, "serverSendToVim(%s, %s)", name, cmd);
396#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100398 // Execute locally if no display or target is ourselves
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399 if (dpy == NULL || (serverName != NULL && STRICMP(name, serverName) == 0))
Bram Moolenaar7416f3e2017-03-18 18:10:13 +0100400 return sendToLocalVim(cmd, asExpr, result);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401
402 /*
403 * Bind the server name to a communication window.
404 *
405 * Find any survivor with a serialno attached to the name if the
406 * original registrant of the wanted name is no longer present.
407 *
408 * Delete any lingering names from dead editors.
409 */
410 while (TRUE)
411 {
412 w = LookupName(dpy, name, FALSE, &loosename);
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100413 // Check that the window is hot
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 if (w != None)
415 {
416 if (!WindowValid(dpy, w))
417 {
418 LookupName(dpy, loosename ? loosename : name,
419 /*DELETE=*/TRUE, NULL);
Bram Moolenaar09d6c382017-09-09 16:25:54 +0200420 vim_free(loosename);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 continue;
422 }
423 }
424 break;
425 }
426 if (w == None)
427 {
428 if (!silent)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000429 semsg(_(e_no_registered_server_named_str), name);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 return -1;
431 }
432 else if (loosename != NULL)
433 name = loosename;
434 if (server != NULL)
435 *server = w;
436
437 /*
438 * Send the command to target interpreter by appending it to the
439 * comm window in the communication window.
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000440 * Length must be computed exactly!
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 */
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000442 length = STRLEN(name) + STRLEN(p_enc) + STRLEN(cmd) + 14;
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200443 property = alloc(length + 30);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000445 sprintf((char *)property, "%c%c%c-n %s%c-E %s%c-s %s",
446 0, asExpr ? 'c' : 'k', 0, name, 0, p_enc, 0, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 if (name == loosename)
448 vim_free(loosename);
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100449 // Add a back reference to our comm window
Bram Moolenaar071d4272004-06-13 20:20:40 +0000450 serial++;
451 sprintf((char *)property + length, "%c-r %x %d",
452 0, (int_u)commWindow, serial);
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100453 // Add length of what "-r %x %d" resulted in, skipping the NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000454 length += STRLEN(property + length + 1) + 1;
455
456 res = AppendPropCarefully(dpy, w, commProperty, property, length + 1);
457 vim_free(property);
458 if (res < 0)
459 {
Bram Moolenaarcbadefe2022-01-01 19:33:50 +0000460 emsg(_(e_failed_to_send_command_to_destination_program));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000461 return -1;
462 }
463
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100464 if (!asExpr) // There is no answer for this - Keys are sent async
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 return 0;
466
467 /*
468 * Register the fact that we're waiting for a command to
469 * complete (this is needed by SendEventProc and by
470 * AppendErrorProc to pass back the command's results).
471 */
472 pending.serial = serial;
473 pending.code = 0;
474 pending.result = NULL;
475 pending.nextPtr = pendingCommands;
476 pendingCommands = &pending;
477
Bram Moolenaar81b9d0b2017-03-19 21:20:53 +0100478 ServerWait(dpy, w, WaitForPend, &pending, localLoop,
479 timeout > 0 ? timeout : 600);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480
481 /*
482 * Unregister the information about the pending command
483 * and return the result.
484 */
485 if (pendingCommands == &pending)
486 pendingCommands = pending.nextPtr;
487 else
488 {
489 PendingCommand *pcPtr;
490
491 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
492 if (pcPtr->nextPtr == &pending)
493 {
494 pcPtr->nextPtr = pending.nextPtr;
495 break;
496 }
497 }
Bram Moolenaar4c5678f2022-11-30 18:12:19 +0000498
499#if defined(FEAT_EVAL)
500 ch_log(NULL, "serverSendToVim() result: %s",
501 pending.result == NULL ? "NULL" : (char *)pending.result);
502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 if (result != NULL)
504 *result = pending.result;
505 else
506 vim_free(pending.result);
507
508 return pending.code == 0 ? 0 : -1;
509}
510
511 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100512WaitForPend(void *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000513{
514 PendingCommand *pending = (PendingCommand *) p;
515 return pending->result != NULL;
516}
517
518/*
519 * Return TRUE if window "w" exists and has a "Vim" property on it.
520 */
521 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100522WindowValid(Display *dpy, Window w)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523{
524 XErrorHandler old_handler;
525 Atom *plist;
526 int numProp;
527 int i;
528
529 old_handler = XSetErrorHandler(x_error_check);
530 got_x_error = 0;
531 plist = XListProperties(dpy, w, &numProp);
532 XSync(dpy, False);
533 XSetErrorHandler(old_handler);
534 if (plist == NULL || got_x_error)
535 return FALSE;
536
537 for (i = 0; i < numProp; i++)
538 if (plist[i] == vimProperty)
539 {
540 XFree(plist);
541 return TRUE;
542 }
543 XFree(plist);
544 return FALSE;
545}
546
547/*
548 * Enter a loop processing X events & polling chars until we see a result
549 */
550 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100551ServerWait(
552 Display *dpy,
553 Window w,
554 EndCond endCond,
555 void *endData,
556 int localLoop,
557 int seconds)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558{
559 time_t start;
560 time_t now;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561 XEvent event;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200562
Bram Moolenaareda1da02019-11-17 17:06:33 +0100563#define UI_MSEC_DELAY 53
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200564#define SEND_MSEC_POLL 500
jsecchiero6f953632022-03-20 11:07:17 +0000565#ifdef HAVE_SELECT
566 fd_set fds;
567
568 FD_ZERO(&fds);
569 FD_SET(ConnectionNumber(dpy), &fds);
570#else
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200571 struct pollfd fds;
572
573 fds.fd = ConnectionNumber(dpy);
574 fds.events = POLLIN;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200575#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576
577 time(&start);
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200578 while (TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000579 {
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200580 while (XCheckWindowEvent(dpy, commWindow, PropertyChangeMask, &event))
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200581 serverEventProc(dpy, &event, 1);
Bram Moolenaar1e7885a2016-03-25 19:03:03 +0100582 server_parse_messages();
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200583
584 if (endCond(endData) != 0)
585 break;
586 if (!WindowValid(dpy, w))
587 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588 time(&now);
589 if (seconds >= 0 && (now - start) >= seconds)
590 break;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200591
Bram Moolenaar42205552017-03-18 19:42:22 +0100592#ifdef FEAT_TIMERS
593 check_due_timer();
594#endif
595
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100596 // Just look out for the answer without calling back into Vim
Bram Moolenaar071d4272004-06-13 20:20:40 +0000597 if (localLoop)
598 {
jsecchiero6f953632022-03-20 11:07:17 +0000599#ifdef HAVE_SELECT
600 struct timeval tv;
601
602 // Set the time every call, select() may change it to the remaining
603 // time.
604 tv.tv_sec = 0;
605 tv.tv_usec = SEND_MSEC_POLL * 1000;
606 if (select(FD_SETSIZE, &fds, NULL, NULL, &tv) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 break;
608#else
jsecchiero6f953632022-03-20 11:07:17 +0000609 if (poll(&fds, 1, SEND_MSEC_POLL) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 break;
611#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000612 }
613 else
614 {
615 if (got_int)
616 break;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200617 ui_delay((long)UI_MSEC_DELAY, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 ui_breakcheck();
619 }
620 }
621}
622
623
624/*
625 * Fetch a list of all the Vim instance names currently registered for the
626 * display.
627 *
628 * Returns a newline separated list in allocated memory or NULL.
629 */
630 char_u *
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100631serverGetVimNames(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632{
633 char_u *regProp;
634 char_u *entry;
635 char_u *p;
636 long_u numItems;
637 int_u w;
638 garray_T ga;
639
640 if (registryProperty == None)
641 {
642 if (SendInit(dpy) < 0)
643 return NULL;
644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645
646 /*
647 * Read the registry property.
648 */
649 if (GetRegProp(dpy, &regProp, &numItems, TRUE) == FAIL)
650 return NULL;
651
652 /*
653 * Scan all of the names out of the property.
654 */
655 ga_init2(&ga, 1, 100);
Bram Moolenaaraf0167f2009-05-16 15:31:32 +0000656 for (p = regProp; (long_u)(p - regProp) < numItems; p++)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657 {
658 entry = p;
659 while (*p != 0 && !isspace(*p))
660 p++;
661 if (*p != 0)
662 {
663 w = None;
664 sscanf((char *)entry, "%x", &w);
665 if (WindowValid(dpy, (Window)w))
666 {
667 ga_concat(&ga, p + 1);
668 ga_concat(&ga, (char_u *)"\n");
669 }
670 while (*p != 0)
671 p++;
672 }
673 }
674 if (regProp != empty_prop)
675 XFree(regProp);
Bram Moolenaar269ec652004-07-29 08:43:53 +0000676 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677 return ga.ga_data;
678}
679
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100680/////////////////////////////////////////////////////////////
681// Reply stuff
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682
683 static struct ServerReply *
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100684ServerReplyFind(Window w, enum ServerReplyOp op)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 struct ServerReply *p;
687 struct ServerReply e;
688 int i;
689
690 p = (struct ServerReply *) serverReply.ga_data;
691 for (i = 0; i < serverReply.ga_len; i++, p++)
692 if (p->id == w)
693 break;
694 if (i >= serverReply.ga_len)
695 p = NULL;
696
697 if (p == NULL && op == SROP_Add)
698 {
699 if (serverReply.ga_growsize == 0)
700 ga_init2(&serverReply, sizeof(struct ServerReply), 1);
701 if (ga_grow(&serverReply, 1) == OK)
702 {
703 p = ((struct ServerReply *) serverReply.ga_data)
704 + serverReply.ga_len;
705 e.id = w;
706 ga_init2(&e.strings, 1, 100);
Bram Moolenaarfbc0cfa2008-11-12 13:52:46 +0000707 mch_memmove(p, &e, sizeof(e));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708 serverReply.ga_len++;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709 }
710 }
711 else if (p != NULL && op == SROP_Delete)
712 {
713 ga_clear(&p->strings);
714 mch_memmove(p, p + 1, (serverReply.ga_len - i - 1) * sizeof(*p));
715 serverReply.ga_len--;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716 }
717
718 return p;
719}
720
721/*
722 * Convert string to windowid.
723 * Issue an error if the id is invalid.
724 */
725 Window
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100726serverStrToWin(char_u *str)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727{
728 unsigned id = None;
729
730 sscanf((char *)str, "0x%x", &id);
731 if (id == None)
Bram Moolenaar1d423ef2022-01-02 21:26:16 +0000732 semsg(_(e_invalid_server_id_used_str), str);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000733
734 return (Window)id;
735}
736
737/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000738 * Send a reply string (notification) to client with id "name".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 * Return -1 if the window is invalid.
740 */
741 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100742serverSendReply(char_u *name, char_u *str)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743{
744 char_u *property;
745 int length;
746 int res;
747 Display *dpy = X_DISPLAY;
748 Window win = serverStrToWin(name);
749
750 if (commProperty == None)
751 {
752 if (SendInit(dpy) < 0)
753 return -2;
754 }
755 if (!WindowValid(dpy, win))
756 return -1;
757
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000758 length = STRLEN(p_enc) + STRLEN(str) + 14;
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200759 if ((property = alloc(length + 30)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000761 sprintf((char *)property, "%cn%c-E %s%c-n %s%c-w %x",
762 0, 0, p_enc, 0, str, 0, (unsigned int)commWindow);
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100763 // Add length of what "%x" resulted in.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 length += STRLEN(property + length);
765 res = AppendPropCarefully(dpy, win, commProperty, property, length + 1);
766 vim_free(property);
767 return res;
768 }
769 return -1;
770}
771
772 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100773WaitForReply(void *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 Window *w = (Window *) p;
Bram Moolenaar7416f3e2017-03-18 18:10:13 +0100776
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 return ServerReplyFind(*w, SROP_Find) != NULL;
778}
779
780/*
781 * Wait for replies from id (win)
Bram Moolenaar81b9d0b2017-03-19 21:20:53 +0100782 * When "timeout" is non-zero wait up to this many seconds.
Bram Moolenaar747f1102022-09-18 13:06:41 +0100783 * Return 0 and the allocated string in "*str" when a reply is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000784 * Return -1 if the window becomes invalid while waiting.
785 */
786 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100787serverReadReply(
788 Display *dpy,
789 Window win,
790 char_u **str,
Bram Moolenaar81b9d0b2017-03-19 21:20:53 +0100791 int localLoop,
792 int timeout)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793{
794 int len;
795 char_u *s;
796 struct ServerReply *p;
797
Bram Moolenaar81b9d0b2017-03-19 21:20:53 +0100798 ServerWait(dpy, win, WaitForReply, &win, localLoop,
799 timeout > 0 ? timeout : -1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800
801 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
802 {
803 *str = vim_strsave(p->strings.ga_data);
804 len = STRLEN(*str) + 1;
805 if (len < p->strings.ga_len)
806 {
807 s = (char_u *) p->strings.ga_data;
808 mch_memmove(s, s + len, p->strings.ga_len - len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000809 p->strings.ga_len -= len;
810 }
811 else
812 {
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100813 // Last string read. Remove from list
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 ga_clear(&p->strings);
815 ServerReplyFind(win, SROP_Delete);
816 }
817 return 0;
818 }
819 return -1;
820}
821
822/*
823 * Check for replies from id (win).
824 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
825 */
826 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100827serverPeekReply(Display *dpy, Window win, char_u **str)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828{
829 struct ServerReply *p;
830
831 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
832 {
833 if (str != NULL)
834 *str = p->strings.ga_data;
835 return 1;
836 }
837 if (!WindowValid(dpy, win))
838 return -1;
839 return 0;
840}
841
842
843/*
844 * Initialize the communication channels for sending commands and receiving
845 * results.
846 */
847 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100848SendInit(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000849{
850 XErrorHandler old_handler;
851
852 /*
853 * Create the window used for communication, and set up an
854 * event handler for it.
855 */
856 old_handler = XSetErrorHandler(x_error_check);
857 got_x_error = FALSE;
858
859 if (commProperty == None)
860 commProperty = XInternAtom(dpy, "Comm", False);
861 if (vimProperty == None)
862 vimProperty = XInternAtom(dpy, "Vim", False);
863 if (registryProperty == None)
864 registryProperty = XInternAtom(dpy, "VimRegistry", False);
865
866 if (commWindow == None)
867 {
868 commWindow = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy),
869 getpid(), 0, 10, 10, 0,
870 WhitePixel(dpy, DefaultScreen(dpy)),
871 WhitePixel(dpy, DefaultScreen(dpy)));
872 XSelectInput(dpy, commWindow, PropertyChangeMask);
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100873 // WARNING: Do not step through this while debugging, it will hangup
874 // the X server!
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875 XGrabServer(dpy);
876 DeleteAnyLingerer(dpy, commWindow);
877 XUngrabServer(dpy);
878 }
879
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100880 // Make window recognizable as a vim window
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 XChangeProperty(dpy, commWindow, vimProperty, XA_STRING,
882 8, PropModeReplace, (char_u *)VIM_VERSION_SHORT,
883 (int)STRLEN(VIM_VERSION_SHORT) + 1);
884
885 XSync(dpy, False);
886 (void)XSetErrorHandler(old_handler);
887
888 return got_x_error ? -1 : 0;
889}
890
891/*
892 * Given a server name, see if the name exists in the registry for a
893 * particular display.
894 *
895 * If the given name is registered, return the ID of the window associated
896 * with the name. If the name isn't registered, then return 0.
897 *
898 * Side effects:
899 * If the registry property is improperly formed, then it is deleted.
900 * If "delete" is non-zero, then if the named server is found it is
901 * removed from the registry property.
902 */
903 static Window
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100904LookupName(
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100905 Display *dpy, // Display whose registry to check.
906 char_u *name, // Name of a server.
907 int delete, // If non-zero, delete info about name.
908 char_u **loose) // Do another search matching -999 if not found
909 // Return result here if a match is found
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910{
911 char_u *regProp, *entry;
912 char_u *p;
913 long_u numItems;
914 int_u returnValue;
915
916 /*
917 * Read the registry property.
918 */
919 if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL)
920 return 0;
921
922 /*
923 * Scan the property for the desired name.
924 */
925 returnValue = (int_u)None;
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100926 entry = NULL; // Not needed, but eliminates compiler warning.
Bram Moolenaaraf0167f2009-05-16 15:31:32 +0000927 for (p = regProp; (long_u)(p - regProp) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928 {
929 entry = p;
930 while (*p != 0 && !isspace(*p))
931 p++;
932 if (*p != 0 && STRICMP(name, p + 1) == 0)
933 {
934 sscanf((char *)entry, "%x", &returnValue);
935 break;
936 }
937 while (*p != 0)
938 p++;
939 p++;
940 }
941
942 if (loose != NULL && returnValue == (int_u)None && !IsSerialName(name))
943 {
Bram Moolenaaraf0167f2009-05-16 15:31:32 +0000944 for (p = regProp; (long_u)(p - regProp) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 {
946 entry = p;
947 while (*p != 0 && !isspace(*p))
948 p++;
949 if (*p != 0 && IsSerialName(p + 1)
950 && STRNICMP(name, p + 1, STRLEN(name)) == 0)
951 {
952 sscanf((char *)entry, "%x", &returnValue);
953 *loose = vim_strsave(p + 1);
954 break;
955 }
956 while (*p != 0)
957 p++;
958 p++;
959 }
960 }
961
962 /*
963 * Delete the property, if that is desired (copy down the
964 * remainder of the registry property to overlay the deleted
965 * info, then rewrite the property).
966 */
967 if (delete && returnValue != (int_u)None)
968 {
969 int count;
970
971 while (*p != 0)
972 p++;
973 p++;
974 count = numItems - (p - regProp);
975 if (count > 0)
Bram Moolenaarfbc0cfa2008-11-12 13:52:46 +0000976 mch_memmove(entry, p, count);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING,
978 8, PropModeReplace, regProp,
979 (int)(numItems - (p - entry)));
980 XSync(dpy, False);
981 }
982
983 if (regProp != empty_prop)
984 XFree(regProp);
985 return (Window)returnValue;
986}
987
988/*
Bram Moolenaar82038d72007-05-10 17:15:45 +0000989 * Delete any lingering occurrence of window id. We promise that any
990 * occurrence is not ours since it is not yet put into the registry (by us)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 *
992 * This is necessary in the following scenario:
993 * 1. There is an old windowid for an exit'ed vim in the registry
994 * 2. We get that id for our commWindow but only want to send, not register.
995 * 3. The window will mistakenly be regarded valid because of own commWindow
996 */
997 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100998DeleteAnyLingerer(
Bram Moolenaar2ab2e862019-12-04 21:24:53 +0100999 Display *dpy, // Display whose registry to check.
1000 Window win) // Window to remove
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001{
1002 char_u *regProp, *entry = NULL;
1003 char_u *p;
1004 long_u numItems;
Bram Moolenaar7171abe2004-10-11 10:06:20 +00001005 int_u wwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006
1007 /*
1008 * Read the registry property.
1009 */
1010 if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL)
1011 return;
1012
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001013 // Scan the property for the window id.
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001014 for (p = regProp; (long_u)(p - regProp) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015 {
1016 if (*p != 0)
1017 {
Bram Moolenaar7171abe2004-10-11 10:06:20 +00001018 sscanf((char *)p, "%x", &wwin);
1019 if ((Window)wwin == win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 {
1021 int lastHalf;
1022
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001023 // Copy down the remainder to delete entry
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024 entry = p;
1025 while (*p != 0)
1026 p++;
1027 p++;
1028 lastHalf = numItems - (p - regProp);
1029 if (lastHalf > 0)
Bram Moolenaarfbc0cfa2008-11-12 13:52:46 +00001030 mch_memmove(entry, p, lastHalf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 numItems = (entry - regProp) + lastHalf;
1032 p = entry;
1033 continue;
1034 }
1035 }
1036 while (*p != 0)
1037 p++;
1038 p++;
1039 }
1040
1041 if (entry != NULL)
1042 {
1043 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty,
1044 XA_STRING, 8, PropModeReplace, regProp,
1045 (int)(p - regProp));
1046 XSync(dpy, False);
1047 }
1048
1049 if (regProp != empty_prop)
1050 XFree(regProp);
1051}
1052
1053/*
1054 * Read the registry property. Delete it when it's formatted wrong.
1055 * Return the property in "regPropp". "empty_prop" is used when it doesn't
1056 * exist yet.
1057 * Return OK when successful.
1058 */
1059 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001060GetRegProp(
1061 Display *dpy,
1062 char_u **regPropp,
1063 long_u *numItemsp,
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001064 int domsg) // When TRUE give error message.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065{
1066 int result, actualFormat;
1067 long_u bytesAfter;
1068 Atom actualType;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001069 XErrorHandler old_handler;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070
1071 *regPropp = NULL;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001072 old_handler = XSetErrorHandler(x_error_check);
1073 got_x_error = FALSE;
1074
Bram Moolenaar071d4272004-06-13 20:20:40 +00001075 result = XGetWindowProperty(dpy, RootWindow(dpy, 0), registryProperty, 0L,
1076 (long)MAX_PROP_WORDS, False,
1077 XA_STRING, &actualType,
1078 &actualFormat, numItemsp, &bytesAfter,
1079 regPropp);
1080
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001081 XSync(dpy, FALSE);
1082 (void)XSetErrorHandler(old_handler);
1083 if (got_x_error)
1084 return FAIL;
1085
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086 if (actualType == None)
1087 {
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001088 // No prop yet. Logically equal to the empty list
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089 *numItemsp = 0;
1090 *regPropp = empty_prop;
1091 return OK;
1092 }
1093
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001094 // If the property is improperly formed, then delete it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095 if (result != Success || actualFormat != 8 || actualType != XA_STRING)
1096 {
1097 if (*regPropp != NULL)
1098 XFree(*regPropp);
1099 XDeleteProperty(dpy, RootWindow(dpy, 0), registryProperty);
1100 if (domsg)
Bram Moolenaarcbadefe2022-01-01 19:33:50 +00001101 emsg(_(e_vim_instance_registry_property_is_badly_formed_deleted));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001102 return FAIL;
1103 }
1104 return OK;
1105}
1106
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001107
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108/*
Bram Moolenaar82038d72007-05-10 17:15:45 +00001109 * This procedure is invoked by the various X event loops throughout Vims when
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110 * a property changes on the communication window. This procedure reads the
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001111 * property and enqueues command requests and responses. If immediate is true,
Bram Moolenaar792f0e32018-02-27 17:27:13 +01001112 * it runs the event immediately instead of enqueuing it. Immediate can cause
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001113 * unintended behavior and should only be used for code that blocks for a
1114 * response.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115 */
1116 void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001117serverEventProc(
1118 Display *dpy,
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001119 XEvent *eventPtr, // Information about event.
1120 int immediate) // Run event immediately. Should mostly be 0.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001121{
1122 char_u *propInfo;
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001123 int result, actualFormat;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 long_u numItems, bytesAfter;
1125 Atom actualType;
1126
1127 if (eventPtr != NULL)
1128 {
1129 if (eventPtr->xproperty.atom != commProperty
1130 || eventPtr->xproperty.state != PropertyNewValue)
1131 return;
1132 }
1133
1134 /*
1135 * Read the comm property and delete it.
1136 */
1137 propInfo = NULL;
1138 result = XGetWindowProperty(dpy, commWindow, commProperty, 0L,
1139 (long)MAX_PROP_WORDS, True,
1140 XA_STRING, &actualType,
1141 &actualFormat, &numItems, &bytesAfter,
1142 &propInfo);
1143
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001144 // If the property doesn't exist or is improperly formed then ignore it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001145 if (result != Success || actualType != XA_STRING || actualFormat != 8)
1146 {
1147 if (propInfo != NULL)
1148 XFree(propInfo);
1149 return;
1150 }
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001151 if (immediate)
1152 server_parse_message(dpy, propInfo, numItems);
1153 else
1154 save_in_queue(propInfo, numItems);
1155}
1156
1157/*
1158 * Saves x clientserver commands in a queue so that they can be called when
1159 * vim is idle.
1160 */
1161 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001162save_in_queue(char_u *propInfo, long_u len)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001163{
1164 x_queue_T *node;
1165
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001166 node = ALLOC_ONE(x_queue_T);
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001167 if (node == NULL)
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001168 return; // out of memory
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001169 node->propInfo = propInfo;
1170 node->len = len;
1171
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001172 if (head.next == NULL) // initialize circular queue
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001173 {
1174 head.next = &head;
1175 head.prev = &head;
1176 }
1177
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001178 // insert node at tail of queue
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001179 node->next = &head;
1180 node->prev = head.prev;
1181 head.prev->next = node;
1182 head.prev = node;
1183}
1184
1185/*
1186 * Parses queued clientserver messages.
1187 */
1188 void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001189server_parse_messages(void)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001190{
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001191 x_queue_T *node;
1192
1193 if (!X_DISPLAY)
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001194 return; // cannot happen?
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001195 while (head.next != NULL && head.next != &head)
1196 {
1197 node = head.next;
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001198 head.next = node->next;
1199 node->next->prev = node->prev;
Bram Moolenaar4e861502015-10-13 20:21:49 +02001200 server_parse_message(X_DISPLAY, node->propInfo, node->len);
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001201 vim_free(node);
1202 }
1203}
1204
1205/*
1206 * Returns a non-zero value if there are clientserver messages waiting
1207 * int the queue.
1208 */
1209 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001210server_waiting(void)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001211{
1212 return head.next != NULL && head.next != &head;
1213}
1214
1215/*
1216 * Prases a single clientserver message. A single message may contain multiple
1217 * commands.
1218 * "propInfo" will be freed.
1219 */
1220 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001221server_parse_message(
1222 Display *dpy,
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001223 char_u *propInfo, // A string containing 0 or more X commands
1224 long_u numItems) // The size of propInfo in bytes.
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001225{
1226 char_u *p;
1227 int code;
1228 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00001230#if defined(FEAT_EVAL)
1231 ch_log(NULL, "server_parse_message() numItems: %ld", numItems);
1232#endif
1233
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 /*
1235 * Several commands and results could arrive in the property at
1236 * one time; each iteration through the outer loop handles a
1237 * single command or result.
1238 */
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001239 for (p = propInfo; (long_u)(p - propInfo) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240 {
1241 /*
1242 * Ignore leading NULs; each command or result starts with a
1243 * NUL so that no matter how badly formed a preceding command
1244 * is, we'll be able to tell that a new command/result is
1245 * starting.
1246 */
1247 if (*p == 0)
1248 {
1249 p++;
1250 continue;
1251 }
1252
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00001253 if ((*p == 'c' || *p == 'k') && p[1] == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001254 {
1255 Window resWindow;
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001256 char_u *name, *script, *serial, *end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257 Bool asKeys = *p == 'k';
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001258 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259
1260 /*
1261 * This is an incoming command from some other application.
1262 * Iterate over all of its options. Stop when we reach
1263 * the end of the property or something that doesn't look
1264 * like an option.
1265 */
1266 p += 2;
1267 name = NULL;
1268 resWindow = None;
1269 serial = (char_u *)"";
1270 script = NULL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001271 enc = NULL;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001272 while ((long_u)(p - propInfo) < numItems && *p == '-')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 {
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00001274#if defined(FEAT_EVAL)
1275 ch_log(NULL, "server_parse_message() item: %c, %s", p[-2], p);
1276#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277 switch (p[1])
1278 {
1279 case 'r':
1280 end = skipwhite(p + 2);
1281 resWindow = 0;
1282 while (vim_isxdigit(*end))
1283 {
1284 resWindow = 16 * resWindow + (long_u)hex2nr(*end);
1285 ++end;
1286 }
1287 if (end == p + 2 || *end != ' ')
1288 resWindow = None;
1289 else
1290 {
1291 p = serial = end + 1;
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001292 clientWindow = resWindow; // Remember in global
Bram Moolenaar071d4272004-06-13 20:20:40 +00001293 }
1294 break;
1295 case 'n':
1296 if (p[2] == ' ')
1297 name = p + 3;
1298 break;
1299 case 's':
1300 if (p[2] == ' ')
1301 script = p + 3;
1302 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001303 case 'E':
1304 if (p[2] == ' ')
1305 enc = p + 3;
1306 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001307 }
1308 while (*p != 0)
1309 p++;
1310 p++;
1311 }
1312
1313 if (script == NULL || name == NULL)
1314 continue;
1315
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001316 if (serverName != NULL && STRICMP(name, serverName) == 0)
1317 {
1318 script = serverConvert(enc, script, &tofree);
1319 if (asKeys)
1320 server_to_input_buf(script);
1321 else
1322 {
1323 char_u *res;
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001324
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001325 res = eval_client_expr_to_string(script);
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001326 if (resWindow != None)
1327 {
1328 garray_T reply;
1329
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001330 // Initialize the result property.
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001331 ga_init2(&reply, 1, 100);
Bram Moolenaarcde88542015-08-11 19:14:00 +02001332 (void)ga_grow(&reply, 50 + STRLEN(p_enc));
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001333 sprintf(reply.ga_data, "%cr%c-E %s%c-s %s%c-r ",
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001334 0, 0, p_enc, 0, serial, 0);
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001335 reply.ga_len = 14 + STRLEN(p_enc) + STRLEN(serial);
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001336
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001337 // Evaluate the expression and return the result.
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001338 if (res != NULL)
1339 ga_concat(&reply, res);
1340 else
1341 {
Bram Moolenaar4c5678f2022-11-30 18:12:19 +00001342 ga_concat(&reply,
1343 (char_u *)_(e_invalid_expression_received));
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001344 ga_append(&reply, 0);
1345 ga_concat(&reply, (char_u *)"-c 1");
1346 }
1347 ga_append(&reply, NUL);
1348 (void)AppendPropCarefully(dpy, resWindow, commProperty,
1349 reply.ga_data, reply.ga_len);
1350 ga_clear(&reply);
1351 }
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001352 vim_free(res);
1353 }
1354 vim_free(tofree);
1355 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 }
1357 else if (*p == 'r' && p[1] == 0)
1358 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001359 int serial, gotSerial;
1360 char_u *res;
1361 PendingCommand *pcPtr;
1362 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001363
1364 /*
1365 * This is a reply to some command that we sent out. Iterate
1366 * over all of its options. Stop when we reach the end of the
1367 * property or something that doesn't look like an option.
1368 */
1369 p += 2;
1370 gotSerial = 0;
1371 res = (char_u *)"";
1372 code = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001373 enc = NULL;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001374 while ((long_u)(p - propInfo) < numItems && *p == '-')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375 {
1376 switch (p[1])
1377 {
1378 case 'r':
1379 if (p[2] == ' ')
1380 res = p + 3;
1381 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001382 case 'E':
1383 if (p[2] == ' ')
1384 enc = p + 3;
1385 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001386 case 's':
1387 if (sscanf((char *)p + 2, " %d", &serial) == 1)
1388 gotSerial = 1;
1389 break;
1390 case 'c':
1391 if (sscanf((char *)p + 2, " %d", &code) != 1)
1392 code = 0;
1393 break;
1394 }
1395 while (*p != 0)
1396 p++;
1397 p++;
1398 }
1399
1400 if (!gotSerial)
1401 continue;
1402
1403 /*
1404 * Give the result information to anyone who's
1405 * waiting for it.
1406 */
1407 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
1408 {
1409 if (serial != pcPtr->serial || pcPtr->result != NULL)
1410 continue;
1411
1412 pcPtr->code = code;
Bram Moolenaarcde88542015-08-11 19:14:00 +02001413 res = serverConvert(enc, res, &tofree);
1414 if (tofree == NULL)
1415 res = vim_strsave(res);
1416 pcPtr->result = res;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001417 break;
1418 }
1419 }
1420 else if (*p == 'n' && p[1] == 0)
1421 {
1422 Window win = 0;
1423 unsigned int u;
1424 int gotWindow;
1425 char_u *str;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001426 struct ServerReply *r;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001427 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001428
1429 /*
Bram Moolenaarb544f3c2017-02-23 19:03:28 +01001430 * This is a (n)otification. Sent with serverreply_send in Vim
1431 * script. Execute any autocommand and save it for later retrieval
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432 */
1433 p += 2;
1434 gotWindow = 0;
1435 str = (char_u *)"";
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001436 enc = NULL;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001437 while ((long_u)(p - propInfo) < numItems && *p == '-')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 {
1439 switch (p[1])
1440 {
1441 case 'n':
1442 if (p[2] == ' ')
1443 str = p + 3;
1444 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001445 case 'E':
1446 if (p[2] == ' ')
1447 enc = p + 3;
1448 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449 case 'w':
1450 if (sscanf((char *)p + 2, " %x", &u) == 1)
1451 {
1452 win = u;
1453 gotWindow = 1;
1454 }
1455 break;
1456 }
1457 while (*p != 0)
1458 p++;
1459 p++;
1460 }
1461
1462 if (!gotWindow)
1463 continue;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001464 str = serverConvert(enc, str, &tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 if ((r = ServerReplyFind(win, SROP_Add)) != NULL)
1466 {
1467 ga_concat(&(r->strings), str);
Bram Moolenaar269ec652004-07-29 08:43:53 +00001468 ga_append(&(r->strings), NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469 }
Bram Moolenaare37d50a2008-08-06 17:06:04 +00001470 {
1471 char_u winstr[30];
1472
1473 sprintf((char *)winstr, "0x%x", (unsigned int)win);
1474 apply_autocmds(EVENT_REMOTEREPLY, winstr, str, TRUE, curbuf);
1475 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001476 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477 }
1478 else
1479 {
1480 /*
1481 * Didn't recognize this thing. Just skip through the next
1482 * null character and try again.
1483 * Even if we get an 'r'(eply) we will throw it away as we
1484 * never specify (and thus expect) one
1485 */
1486 while (*p != 0)
1487 p++;
1488 p++;
1489 }
1490 }
1491 XFree(propInfo);
1492}
1493
1494/*
1495 * Append a given property to a given window, but set up an X error handler so
1496 * that if the append fails this procedure can return an error code rather
1497 * than having Xlib panic.
1498 * Return: 0 for OK, -1 for error
1499 */
1500 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001501AppendPropCarefully(
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001502 Display *dpy, // Display on which to operate.
1503 Window window, // Window whose property is to be modified.
1504 Atom property, // Name of property.
1505 char_u *value, // Characters to append to property.
1506 int length) // How much to append
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507{
1508 XErrorHandler old_handler;
1509
1510 old_handler = XSetErrorHandler(x_error_check);
1511 got_x_error = FALSE;
1512 XChangeProperty(dpy, window, property, XA_STRING, 8,
1513 PropModeAppend, value, length);
1514 XSync(dpy, False);
1515 (void) XSetErrorHandler(old_handler);
1516 return got_x_error ? -1 : 0;
1517}
1518
1519
1520/*
1521 * Another X Error handler, just used to check for errors.
1522 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001524x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525{
1526 got_x_error = TRUE;
1527 return 0;
1528}
1529
1530/*
1531 * Check if "str" looks like it had a serial number appended.
1532 * Actually just checks if the name ends in a digit.
1533 */
1534 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001535IsSerialName(char_u *str)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536{
1537 int len = STRLEN(str);
1538
1539 return (len > 1 && vim_isdigit(str[len - 1]));
1540}
Bram Moolenaar2ab2e862019-12-04 21:24:53 +01001541#endif // FEAT_CLIENTSERVER