blob: 0b9b1a81904ac3814b0c8ce1a175ca012350e802 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
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{
67 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. */
71 struct PendingCommand *nextPtr;
72 /* Next in list of all outstanding commands.
73 * NULL means end of list. */
74} PendingCommand;
75
76static PendingCommand *pendingCommands = NULL;
77 /* List of all commands currently
78 * being waited for. */
79
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
182/* dummy node, header for circular queue */
183static 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);
195static int WaitForReply(void *p);
196static int WindowValid(Display *dpy, Window w);
197static void ServerWait(Display *dpy, Window w, EndCond endCond, void *endData, int localLoop, int seconds);
198static struct ServerReply *ServerReplyFind(Window w, enum ServerReplyOp op);
199static int AppendPropCarefully(Display *display, Window window, Atom property, char_u *value, int length);
200static int x_error_check(Display *dpy, XErrorEvent *error_event);
201static int IsSerialName(char_u *name);
202static void save_in_queue(char_u *buf, long_u len);
203static void server_parse_message(Display *dpy, char_u *propInfo, long_u numItems);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204
205/* Private variables for the "server" functionality */
206static Atom registryProperty = None;
207static Atom vimProperty = None;
208static int got_x_error = FALSE;
209
210static char_u *empty_prop = (char_u *)""; /* empty GetRegProp() result */
211
212/*
213 * Associate an ASCII name with Vim. Try real hard to get a unique one.
214 * Returns FAIL or OK.
215 */
216 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100217serverRegisterName(
218 Display *dpy, /* display to register with */
219 char_u *name) /* the name that will be used as a base */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000220{
221 int i;
222 int res;
223 char_u *p = NULL;
224
225 res = DoRegisterName(dpy, name);
226 if (res < 0)
227 {
228 i = 1;
229 do
230 {
231 if (res < -1 || i >= 1000)
232 {
233 MSG_ATTR(_("Unable to register a command server name"),
234 hl_attr(HLF_W));
235 return FAIL;
236 }
237 if (p == NULL)
238 p = alloc(STRLEN(name) + 10);
239 if (p == NULL)
240 {
241 res = -10;
242 continue;
243 }
244 sprintf((char *)p, "%s%d", name, i++);
245 res = DoRegisterName(dpy, p);
246 }
247 while (res < 0)
248 ;
249 vim_free(p);
250 }
251 return OK;
252}
253
254 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100255DoRegisterName(Display *dpy, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000256{
257 Window w;
258 XErrorHandler old_handler;
259#define MAX_NAME_LENGTH 100
260 char_u propInfo[MAX_NAME_LENGTH + 20];
261
262 if (commProperty == None)
263 {
264 if (SendInit(dpy) < 0)
265 return -2;
266 }
267
268 /*
269 * Make sure the name is unique, and append info about it to
270 * the registry property. It's important to lock the server
271 * here to prevent conflicting changes to the registry property.
272 * WARNING: Do not step through this while debugging, it will hangup the X
273 * server!
274 */
275 XGrabServer(dpy);
276 w = LookupName(dpy, name, FALSE, NULL);
277 if (w != (Window)0)
278 {
279 Status status;
280 int dummyInt;
281 unsigned int dummyUns;
282 Window dummyWin;
283
284 /*
285 * The name is currently registered. See if the commWindow
286 * associated with the name exists. If not, or if the commWindow
287 * is *our* commWindow, then just unregister the old name (this
288 * could happen if an application dies without cleaning up the
289 * registry).
290 */
291 old_handler = XSetErrorHandler(x_error_check);
292 status = XGetGeometry(dpy, w, &dummyWin, &dummyInt, &dummyInt,
293 &dummyUns, &dummyUns, &dummyUns, &dummyUns);
294 (void)XSetErrorHandler(old_handler);
295 if (status != Success && w != commWindow)
296 {
297 XUngrabServer(dpy);
298 XFlush(dpy);
299 return -1;
300 }
301 (void)LookupName(dpy, name, /*delete=*/TRUE, NULL);
302 }
303 sprintf((char *)propInfo, "%x %.*s", (int_u)commWindow,
304 MAX_NAME_LENGTH, name);
305 old_handler = XSetErrorHandler(x_error_check);
306 got_x_error = FALSE;
307 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
308 PropModeAppend, propInfo, STRLEN(propInfo) + 1);
309 XUngrabServer(dpy);
310 XSync(dpy, False);
311 (void)XSetErrorHandler(old_handler);
312
313 if (!got_x_error)
314 {
315#ifdef FEAT_EVAL
316 set_vim_var_string(VV_SEND_SERVER, name, -1);
317#endif
318 serverName = vim_strsave(name);
319#ifdef FEAT_TITLE
320 need_maketitle = TRUE;
321#endif
322 return 0;
323 }
324 return -2;
325}
326
327#if defined(FEAT_GUI) || defined(PROTO)
328/*
329 * Clean out new ID from registry and set it as comm win.
330 * Change any registered window ID.
331 */
332 void
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100333serverChangeRegisteredWindow(
334 Display *dpy, /* Display to register with */
335 Window newwin) /* Re-register to this ID */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000336{
337 char_u propInfo[MAX_NAME_LENGTH + 20];
338
339 commWindow = newwin;
340
341 /* Always call SendInit() here, to make sure commWindow is marked as a Vim
342 * window. */
343 if (SendInit(dpy) < 0)
344 return;
345
346 /* WARNING: Do not step through this while debugging, it will hangup the X
347 * server! */
348 XGrabServer(dpy);
349 DeleteAnyLingerer(dpy, newwin);
350 if (serverName != NULL)
351 {
352 /* Reinsert name if we was already registered */
353 (void)LookupName(dpy, serverName, /*delete=*/TRUE, NULL);
354 sprintf((char *)propInfo, "%x %.*s",
355 (int_u)newwin, MAX_NAME_LENGTH, serverName);
356 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING, 8,
357 PropModeAppend, (char_u *)propInfo,
358 STRLEN(propInfo) + 1);
359 }
360 XUngrabServer(dpy);
361}
362#endif
363
364/*
365 * Send to an instance of Vim via the X display.
366 * Returns 0 for OK, negative for an error.
367 */
368 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100369serverSendToVim(
370 Display *dpy, /* Where to send. */
371 char_u *name, /* Where to send. */
372 char_u *cmd, /* What to send. */
373 char_u **result, /* Result of eval'ed expression */
374 Window *server, /* Actual ID of receiving app */
375 Bool asExpr, /* Interpret as keystrokes or expr ? */
376 Bool localLoop, /* Throw away everything but result */
377 int silent) /* don't complain about no server */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000378{
379 Window w;
380 char_u *property;
381 int length;
382 int res;
383 static int serial = 0; /* Running count of sent commands.
384 * Used to give each command a
385 * different serial number. */
386 PendingCommand pending;
387 char_u *loosename = NULL;
388
389 if (result != NULL)
390 *result = NULL;
391 if (name == NULL || *name == NUL)
392 name = (char_u *)"GVIM"; /* use a default name */
393
394 if (commProperty == None && dpy != NULL)
395 {
396 if (SendInit(dpy) < 0)
397 return -1;
398 }
399
400 /* Execute locally if no display or target is ourselves */
401 if (dpy == NULL || (serverName != NULL && STRICMP(name, serverName) == 0))
402 {
403 if (asExpr)
404 {
405 char_u *ret;
406
407 ret = eval_client_expr_to_string(cmd);
408 if (result != NULL)
409 {
410 if (ret == NULL)
411 *result = vim_strsave((char_u *)_(e_invexprmsg));
412 else
413 *result = ret;
414 }
415 else
416 vim_free(ret);
417 return ret == NULL ? -1 : 0;
418 }
419 else
420 server_to_input_buf(cmd);
421 return 0;
422 }
423
424 /*
425 * Bind the server name to a communication window.
426 *
427 * Find any survivor with a serialno attached to the name if the
428 * original registrant of the wanted name is no longer present.
429 *
430 * Delete any lingering names from dead editors.
431 */
432 while (TRUE)
433 {
434 w = LookupName(dpy, name, FALSE, &loosename);
435 /* Check that the window is hot */
436 if (w != None)
437 {
438 if (!WindowValid(dpy, w))
439 {
440 LookupName(dpy, loosename ? loosename : name,
441 /*DELETE=*/TRUE, NULL);
442 continue;
443 }
444 }
445 break;
446 }
447 if (w == None)
448 {
449 if (!silent)
450 EMSG2(_(e_noserver), name);
451 return -1;
452 }
453 else if (loosename != NULL)
454 name = loosename;
455 if (server != NULL)
456 *server = w;
457
458 /*
459 * Send the command to target interpreter by appending it to the
460 * comm window in the communication window.
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000461 * Length must be computed exactly!
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000463#ifdef FEAT_MBYTE
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000464 length = STRLEN(name) + STRLEN(p_enc) + STRLEN(cmd) + 14;
465#else
466 length = STRLEN(name) + STRLEN(cmd) + 10;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000467#endif
468 property = (char_u *)alloc((unsigned)length + 30);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000470#ifdef FEAT_MBYTE
471 sprintf((char *)property, "%c%c%c-n %s%c-E %s%c-s %s",
472 0, asExpr ? 'c' : 'k', 0, name, 0, p_enc, 0, cmd);
473#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 sprintf((char *)property, "%c%c%c-n %s%c-s %s",
475 0, asExpr ? 'c' : 'k', 0, name, 0, cmd);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 if (name == loosename)
478 vim_free(loosename);
479 /* Add a back reference to our comm window */
480 serial++;
481 sprintf((char *)property + length, "%c-r %x %d",
482 0, (int_u)commWindow, serial);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000483 /* Add length of what "-r %x %d" resulted in, skipping the NUL. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 length += STRLEN(property + length + 1) + 1;
485
486 res = AppendPropCarefully(dpy, w, commProperty, property, length + 1);
487 vim_free(property);
488 if (res < 0)
489 {
490 EMSG(_("E248: Failed to send command to the destination program"));
491 return -1;
492 }
493
494 if (!asExpr) /* There is no answer for this - Keys are sent async */
495 return 0;
496
497 /*
498 * Register the fact that we're waiting for a command to
499 * complete (this is needed by SendEventProc and by
500 * AppendErrorProc to pass back the command's results).
501 */
502 pending.serial = serial;
503 pending.code = 0;
504 pending.result = NULL;
505 pending.nextPtr = pendingCommands;
506 pendingCommands = &pending;
507
508 ServerWait(dpy, w, WaitForPend, &pending, localLoop, 600);
509
510 /*
511 * Unregister the information about the pending command
512 * and return the result.
513 */
514 if (pendingCommands == &pending)
515 pendingCommands = pending.nextPtr;
516 else
517 {
518 PendingCommand *pcPtr;
519
520 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
521 if (pcPtr->nextPtr == &pending)
522 {
523 pcPtr->nextPtr = pending.nextPtr;
524 break;
525 }
526 }
527 if (result != NULL)
528 *result = pending.result;
529 else
530 vim_free(pending.result);
531
532 return pending.code == 0 ? 0 : -1;
533}
534
535 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100536WaitForPend(void *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000537{
538 PendingCommand *pending = (PendingCommand *) p;
539 return pending->result != NULL;
540}
541
542/*
543 * Return TRUE if window "w" exists and has a "Vim" property on it.
544 */
545 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100546WindowValid(Display *dpy, Window w)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547{
548 XErrorHandler old_handler;
549 Atom *plist;
550 int numProp;
551 int i;
552
553 old_handler = XSetErrorHandler(x_error_check);
554 got_x_error = 0;
555 plist = XListProperties(dpy, w, &numProp);
556 XSync(dpy, False);
557 XSetErrorHandler(old_handler);
558 if (plist == NULL || got_x_error)
559 return FALSE;
560
561 for (i = 0; i < numProp; i++)
562 if (plist[i] == vimProperty)
563 {
564 XFree(plist);
565 return TRUE;
566 }
567 XFree(plist);
568 return FALSE;
569}
570
571/*
572 * Enter a loop processing X events & polling chars until we see a result
573 */
574 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100575ServerWait(
576 Display *dpy,
577 Window w,
578 EndCond endCond,
579 void *endData,
580 int localLoop,
581 int seconds)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582{
583 time_t start;
584 time_t now;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585 XEvent event;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200586
587#define UI_MSEC_DELAY 50
588#define SEND_MSEC_POLL 500
589#ifndef HAVE_SELECT
590 struct pollfd fds;
591
592 fds.fd = ConnectionNumber(dpy);
593 fds.events = POLLIN;
594#else
595 fd_set fds;
596 struct timeval tv;
597
598 tv.tv_sec = 0;
599 tv.tv_usec = SEND_MSEC_POLL * 1000;
600 FD_ZERO(&fds);
601 FD_SET(ConnectionNumber(dpy), &fds);
602#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603
604 time(&start);
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200605 while (TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606 {
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200607 while (XCheckWindowEvent(dpy, commWindow, PropertyChangeMask, &event))
Bram Moolenaar93c88e02015-09-15 14:12:05 +0200608 serverEventProc(dpy, &event, 1);
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200609
610 if (endCond(endData) != 0)
611 break;
612 if (!WindowValid(dpy, w))
613 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 time(&now);
615 if (seconds >= 0 && (now - start) >= seconds)
616 break;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200617
618 /* Just look out for the answer without calling back into Vim */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619 if (localLoop)
620 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621#ifndef HAVE_SELECT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622 if (poll(&fds, 1, SEND_MSEC_POLL) < 0)
623 break;
624#else
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200625 if (select(FD_SETSIZE, &fds, NULL, NULL, &tv) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 break;
627#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628 }
629 else
630 {
631 if (got_int)
632 break;
Bram Moolenaar773c1ef2012-07-10 14:56:45 +0200633 ui_delay((long)UI_MSEC_DELAY, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 ui_breakcheck();
635 }
636 }
637}
638
639
640/*
641 * Fetch a list of all the Vim instance names currently registered for the
642 * display.
643 *
644 * Returns a newline separated list in allocated memory or NULL.
645 */
646 char_u *
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100647serverGetVimNames(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648{
649 char_u *regProp;
650 char_u *entry;
651 char_u *p;
652 long_u numItems;
653 int_u w;
654 garray_T ga;
655
656 if (registryProperty == None)
657 {
658 if (SendInit(dpy) < 0)
659 return NULL;
660 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661
662 /*
663 * Read the registry property.
664 */
665 if (GetRegProp(dpy, &regProp, &numItems, TRUE) == FAIL)
666 return NULL;
667
668 /*
669 * Scan all of the names out of the property.
670 */
671 ga_init2(&ga, 1, 100);
Bram Moolenaaraf0167f2009-05-16 15:31:32 +0000672 for (p = regProp; (long_u)(p - regProp) < numItems; p++)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673 {
674 entry = p;
675 while (*p != 0 && !isspace(*p))
676 p++;
677 if (*p != 0)
678 {
679 w = None;
680 sscanf((char *)entry, "%x", &w);
681 if (WindowValid(dpy, (Window)w))
682 {
683 ga_concat(&ga, p + 1);
684 ga_concat(&ga, (char_u *)"\n");
685 }
686 while (*p != 0)
687 p++;
688 }
689 }
690 if (regProp != empty_prop)
691 XFree(regProp);
Bram Moolenaar269ec652004-07-29 08:43:53 +0000692 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693 return ga.ga_data;
694}
695
696/* ----------------------------------------------------------
697 * Reply stuff
698 */
699
700 static struct ServerReply *
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100701ServerReplyFind(Window w, enum ServerReplyOp op)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702{
703 struct ServerReply *p;
704 struct ServerReply e;
705 int i;
706
707 p = (struct ServerReply *) serverReply.ga_data;
708 for (i = 0; i < serverReply.ga_len; i++, p++)
709 if (p->id == w)
710 break;
711 if (i >= serverReply.ga_len)
712 p = NULL;
713
714 if (p == NULL && op == SROP_Add)
715 {
716 if (serverReply.ga_growsize == 0)
717 ga_init2(&serverReply, sizeof(struct ServerReply), 1);
718 if (ga_grow(&serverReply, 1) == OK)
719 {
720 p = ((struct ServerReply *) serverReply.ga_data)
721 + serverReply.ga_len;
722 e.id = w;
723 ga_init2(&e.strings, 1, 100);
Bram Moolenaarfbc0cfa2008-11-12 13:52:46 +0000724 mch_memmove(p, &e, sizeof(e));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725 serverReply.ga_len++;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 }
727 }
728 else if (p != NULL && op == SROP_Delete)
729 {
730 ga_clear(&p->strings);
731 mch_memmove(p, p + 1, (serverReply.ga_len - i - 1) * sizeof(*p));
732 serverReply.ga_len--;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000733 }
734
735 return p;
736}
737
738/*
739 * Convert string to windowid.
740 * Issue an error if the id is invalid.
741 */
742 Window
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100743serverStrToWin(char_u *str)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744{
745 unsigned id = None;
746
747 sscanf((char *)str, "0x%x", &id);
748 if (id == None)
749 EMSG2(_("E573: Invalid server id used: %s"), str);
750
751 return (Window)id;
752}
753
754/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000755 * Send a reply string (notification) to client with id "name".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756 * Return -1 if the window is invalid.
757 */
758 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100759serverSendReply(char_u *name, char_u *str)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 char_u *property;
762 int length;
763 int res;
764 Display *dpy = X_DISPLAY;
765 Window win = serverStrToWin(name);
766
767 if (commProperty == None)
768 {
769 if (SendInit(dpy) < 0)
770 return -2;
771 }
772 if (!WindowValid(dpy, win))
773 return -1;
774
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000775#ifdef FEAT_MBYTE
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000776 length = STRLEN(p_enc) + STRLEN(str) + 14;
777#else
778 length = STRLEN(str) + 10;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000779#endif
780 if ((property = (char_u *)alloc((unsigned)length + 30)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000782#ifdef FEAT_MBYTE
783 sprintf((char *)property, "%cn%c-E %s%c-n %s%c-w %x",
784 0, 0, p_enc, 0, str, 0, (unsigned int)commWindow);
785#else
786 sprintf((char *)property, "%cn%c-n %s%c-w %x",
787 0, 0, str, 0, (unsigned int)commWindow);
788#endif
Bram Moolenaarac6e65f2005-08-29 22:25:38 +0000789 /* Add length of what "%x" resulted in. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 length += STRLEN(property + length);
791 res = AppendPropCarefully(dpy, win, commProperty, property, length + 1);
792 vim_free(property);
793 return res;
794 }
795 return -1;
796}
797
798 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100799WaitForReply(void *p)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800{
801 Window *w = (Window *) p;
802 return ServerReplyFind(*w, SROP_Find) != NULL;
803}
804
805/*
806 * Wait for replies from id (win)
807 * Return 0 and the malloc'ed string when a reply is available.
808 * Return -1 if the window becomes invalid while waiting.
809 */
810 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100811serverReadReply(
812 Display *dpy,
813 Window win,
814 char_u **str,
815 int localLoop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816{
817 int len;
818 char_u *s;
819 struct ServerReply *p;
820
821 ServerWait(dpy, win, WaitForReply, &win, localLoop, -1);
822
823 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
824 {
825 *str = vim_strsave(p->strings.ga_data);
826 len = STRLEN(*str) + 1;
827 if (len < p->strings.ga_len)
828 {
829 s = (char_u *) p->strings.ga_data;
830 mch_memmove(s, s + len, p->strings.ga_len - len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000831 p->strings.ga_len -= len;
832 }
833 else
834 {
835 /* Last string read. Remove from list */
836 ga_clear(&p->strings);
837 ServerReplyFind(win, SROP_Delete);
838 }
839 return 0;
840 }
841 return -1;
842}
843
844/*
845 * Check for replies from id (win).
846 * Return TRUE and a non-malloc'ed string if there is. Else return FALSE.
847 */
848 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100849serverPeekReply(Display *dpy, Window win, char_u **str)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850{
851 struct ServerReply *p;
852
853 if ((p = ServerReplyFind(win, SROP_Find)) != NULL && p->strings.ga_len > 0)
854 {
855 if (str != NULL)
856 *str = p->strings.ga_data;
857 return 1;
858 }
859 if (!WindowValid(dpy, win))
860 return -1;
861 return 0;
862}
863
864
865/*
866 * Initialize the communication channels for sending commands and receiving
867 * results.
868 */
869 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100870SendInit(Display *dpy)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000871{
872 XErrorHandler old_handler;
873
874 /*
875 * Create the window used for communication, and set up an
876 * event handler for it.
877 */
878 old_handler = XSetErrorHandler(x_error_check);
879 got_x_error = FALSE;
880
881 if (commProperty == None)
882 commProperty = XInternAtom(dpy, "Comm", False);
883 if (vimProperty == None)
884 vimProperty = XInternAtom(dpy, "Vim", False);
885 if (registryProperty == None)
886 registryProperty = XInternAtom(dpy, "VimRegistry", False);
887
888 if (commWindow == None)
889 {
890 commWindow = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy),
891 getpid(), 0, 10, 10, 0,
892 WhitePixel(dpy, DefaultScreen(dpy)),
893 WhitePixel(dpy, DefaultScreen(dpy)));
894 XSelectInput(dpy, commWindow, PropertyChangeMask);
895 /* WARNING: Do not step through this while debugging, it will hangup
896 * the X server! */
897 XGrabServer(dpy);
898 DeleteAnyLingerer(dpy, commWindow);
899 XUngrabServer(dpy);
900 }
901
902 /* Make window recognizable as a vim window */
903 XChangeProperty(dpy, commWindow, vimProperty, XA_STRING,
904 8, PropModeReplace, (char_u *)VIM_VERSION_SHORT,
905 (int)STRLEN(VIM_VERSION_SHORT) + 1);
906
907 XSync(dpy, False);
908 (void)XSetErrorHandler(old_handler);
909
910 return got_x_error ? -1 : 0;
911}
912
913/*
914 * Given a server name, see if the name exists in the registry for a
915 * particular display.
916 *
917 * If the given name is registered, return the ID of the window associated
918 * with the name. If the name isn't registered, then return 0.
919 *
920 * Side effects:
921 * If the registry property is improperly formed, then it is deleted.
922 * If "delete" is non-zero, then if the named server is found it is
923 * removed from the registry property.
924 */
925 static Window
Bram Moolenaar68c2f632016-01-30 17:24:07 +0100926LookupName(
927 Display *dpy, /* Display whose registry to check. */
928 char_u *name, /* Name of a server. */
929 int delete, /* If non-zero, delete info about name. */
930 char_u **loose) /* Do another search matching -999 if not found
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931 Return result here if a match is found */
932{
933 char_u *regProp, *entry;
934 char_u *p;
935 long_u numItems;
936 int_u returnValue;
937
938 /*
939 * Read the registry property.
940 */
941 if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL)
942 return 0;
943
944 /*
945 * Scan the property for the desired name.
946 */
947 returnValue = (int_u)None;
948 entry = NULL; /* Not needed, but eliminates compiler warning. */
Bram Moolenaaraf0167f2009-05-16 15:31:32 +0000949 for (p = regProp; (long_u)(p - regProp) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 {
951 entry = p;
952 while (*p != 0 && !isspace(*p))
953 p++;
954 if (*p != 0 && STRICMP(name, p + 1) == 0)
955 {
956 sscanf((char *)entry, "%x", &returnValue);
957 break;
958 }
959 while (*p != 0)
960 p++;
961 p++;
962 }
963
964 if (loose != NULL && returnValue == (int_u)None && !IsSerialName(name))
965 {
Bram Moolenaaraf0167f2009-05-16 15:31:32 +0000966 for (p = regProp; (long_u)(p - regProp) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 {
968 entry = p;
969 while (*p != 0 && !isspace(*p))
970 p++;
971 if (*p != 0 && IsSerialName(p + 1)
972 && STRNICMP(name, p + 1, STRLEN(name)) == 0)
973 {
974 sscanf((char *)entry, "%x", &returnValue);
975 *loose = vim_strsave(p + 1);
976 break;
977 }
978 while (*p != 0)
979 p++;
980 p++;
981 }
982 }
983
984 /*
985 * Delete the property, if that is desired (copy down the
986 * remainder of the registry property to overlay the deleted
987 * info, then rewrite the property).
988 */
989 if (delete && returnValue != (int_u)None)
990 {
991 int count;
992
993 while (*p != 0)
994 p++;
995 p++;
996 count = numItems - (p - regProp);
997 if (count > 0)
Bram Moolenaarfbc0cfa2008-11-12 13:52:46 +0000998 mch_memmove(entry, p, count);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty, XA_STRING,
1000 8, PropModeReplace, regProp,
1001 (int)(numItems - (p - entry)));
1002 XSync(dpy, False);
1003 }
1004
1005 if (regProp != empty_prop)
1006 XFree(regProp);
1007 return (Window)returnValue;
1008}
1009
1010/*
Bram Moolenaar82038d72007-05-10 17:15:45 +00001011 * Delete any lingering occurrence of window id. We promise that any
1012 * occurrence is not ours since it is not yet put into the registry (by us)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 *
1014 * This is necessary in the following scenario:
1015 * 1. There is an old windowid for an exit'ed vim in the registry
1016 * 2. We get that id for our commWindow but only want to send, not register.
1017 * 3. The window will mistakenly be regarded valid because of own commWindow
1018 */
1019 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001020DeleteAnyLingerer(
1021 Display *dpy, /* Display whose registry to check. */
1022 Window win) /* Window to remove */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023{
1024 char_u *regProp, *entry = NULL;
1025 char_u *p;
1026 long_u numItems;
Bram Moolenaar7171abe2004-10-11 10:06:20 +00001027 int_u wwin;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028
1029 /*
1030 * Read the registry property.
1031 */
1032 if (GetRegProp(dpy, &regProp, &numItems, FALSE) == FAIL)
1033 return;
1034
1035 /* Scan the property for the window id. */
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001036 for (p = regProp; (long_u)(p - regProp) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037 {
1038 if (*p != 0)
1039 {
Bram Moolenaar7171abe2004-10-11 10:06:20 +00001040 sscanf((char *)p, "%x", &wwin);
1041 if ((Window)wwin == win)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 {
1043 int lastHalf;
1044
1045 /* Copy down the remainder to delete entry */
1046 entry = p;
1047 while (*p != 0)
1048 p++;
1049 p++;
1050 lastHalf = numItems - (p - regProp);
1051 if (lastHalf > 0)
Bram Moolenaarfbc0cfa2008-11-12 13:52:46 +00001052 mch_memmove(entry, p, lastHalf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 numItems = (entry - regProp) + lastHalf;
1054 p = entry;
1055 continue;
1056 }
1057 }
1058 while (*p != 0)
1059 p++;
1060 p++;
1061 }
1062
1063 if (entry != NULL)
1064 {
1065 XChangeProperty(dpy, RootWindow(dpy, 0), registryProperty,
1066 XA_STRING, 8, PropModeReplace, regProp,
1067 (int)(p - regProp));
1068 XSync(dpy, False);
1069 }
1070
1071 if (regProp != empty_prop)
1072 XFree(regProp);
1073}
1074
1075/*
1076 * Read the registry property. Delete it when it's formatted wrong.
1077 * Return the property in "regPropp". "empty_prop" is used when it doesn't
1078 * exist yet.
1079 * Return OK when successful.
1080 */
1081 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001082GetRegProp(
1083 Display *dpy,
1084 char_u **regPropp,
1085 long_u *numItemsp,
1086 int domsg) /* When TRUE give error message. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087{
1088 int result, actualFormat;
1089 long_u bytesAfter;
1090 Atom actualType;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001091 XErrorHandler old_handler;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092
1093 *regPropp = NULL;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001094 old_handler = XSetErrorHandler(x_error_check);
1095 got_x_error = FALSE;
1096
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097 result = XGetWindowProperty(dpy, RootWindow(dpy, 0), registryProperty, 0L,
1098 (long)MAX_PROP_WORDS, False,
1099 XA_STRING, &actualType,
1100 &actualFormat, numItemsp, &bytesAfter,
1101 regPropp);
1102
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001103 XSync(dpy, FALSE);
1104 (void)XSetErrorHandler(old_handler);
1105 if (got_x_error)
1106 return FAIL;
1107
Bram Moolenaar071d4272004-06-13 20:20:40 +00001108 if (actualType == None)
1109 {
1110 /* No prop yet. Logically equal to the empty list */
1111 *numItemsp = 0;
1112 *regPropp = empty_prop;
1113 return OK;
1114 }
1115
1116 /* If the property is improperly formed, then delete it. */
1117 if (result != Success || actualFormat != 8 || actualType != XA_STRING)
1118 {
1119 if (*regPropp != NULL)
1120 XFree(*regPropp);
1121 XDeleteProperty(dpy, RootWindow(dpy, 0), registryProperty);
1122 if (domsg)
1123 EMSG(_("E251: VIM instance registry property is badly formed. Deleted!"));
1124 return FAIL;
1125 }
1126 return OK;
1127}
1128
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001129
Bram Moolenaar071d4272004-06-13 20:20:40 +00001130/*
Bram Moolenaar82038d72007-05-10 17:15:45 +00001131 * This procedure is invoked by the various X event loops throughout Vims when
Bram Moolenaar071d4272004-06-13 20:20:40 +00001132 * a property changes on the communication window. This procedure reads the
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001133 * property and enqueues command requests and responses. If immediate is true,
1134 * it runs the event immediatly instead of enqueuing it. Immediate can cause
1135 * unintended behavior and should only be used for code that blocks for a
1136 * response.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137 */
1138 void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001139serverEventProc(
1140 Display *dpy,
1141 XEvent *eventPtr, /* Information about event. */
1142 int immediate) /* Run event immediately. Should mostly be 0. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143{
1144 char_u *propInfo;
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001145 int result, actualFormat;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001146 long_u numItems, bytesAfter;
1147 Atom actualType;
1148
1149 if (eventPtr != NULL)
1150 {
1151 if (eventPtr->xproperty.atom != commProperty
1152 || eventPtr->xproperty.state != PropertyNewValue)
1153 return;
1154 }
1155
1156 /*
1157 * Read the comm property and delete it.
1158 */
1159 propInfo = NULL;
1160 result = XGetWindowProperty(dpy, commWindow, commProperty, 0L,
1161 (long)MAX_PROP_WORDS, True,
1162 XA_STRING, &actualType,
1163 &actualFormat, &numItems, &bytesAfter,
1164 &propInfo);
1165
1166 /* If the property doesn't exist or is improperly formed then ignore it. */
1167 if (result != Success || actualType != XA_STRING || actualFormat != 8)
1168 {
1169 if (propInfo != NULL)
1170 XFree(propInfo);
1171 return;
1172 }
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001173 if (immediate)
1174 server_parse_message(dpy, propInfo, numItems);
1175 else
1176 save_in_queue(propInfo, numItems);
1177}
1178
1179/*
1180 * Saves x clientserver commands in a queue so that they can be called when
1181 * vim is idle.
1182 */
1183 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001184save_in_queue(char_u *propInfo, long_u len)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001185{
1186 x_queue_T *node;
1187
1188 node = (x_queue_T *)alloc(sizeof(x_queue_T));
1189 if (node == NULL)
1190 return; /* out of memory */
1191 node->propInfo = propInfo;
1192 node->len = len;
1193
1194 if (head.next == NULL) /* initialize circular queue */
1195 {
1196 head.next = &head;
1197 head.prev = &head;
1198 }
1199
1200 /* insert node at tail of queue */
1201 node->next = &head;
1202 node->prev = head.prev;
1203 head.prev->next = node;
1204 head.prev = node;
1205}
1206
1207/*
1208 * Parses queued clientserver messages.
1209 */
1210 void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001211server_parse_messages(void)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001212{
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001213 x_queue_T *node;
1214
1215 if (!X_DISPLAY)
1216 return; /* cannot happen? */
1217 while (head.next != NULL && head.next != &head)
1218 {
1219 node = head.next;
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001220 head.next = node->next;
1221 node->next->prev = node->prev;
Bram Moolenaar4e861502015-10-13 20:21:49 +02001222 server_parse_message(X_DISPLAY, node->propInfo, node->len);
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001223 vim_free(node);
1224 }
1225}
1226
1227/*
1228 * Returns a non-zero value if there are clientserver messages waiting
1229 * int the queue.
1230 */
1231 int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001232server_waiting(void)
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001233{
1234 return head.next != NULL && head.next != &head;
1235}
1236
1237/*
1238 * Prases a single clientserver message. A single message may contain multiple
1239 * commands.
1240 * "propInfo" will be freed.
1241 */
1242 static void
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001243server_parse_message(
1244 Display *dpy,
1245 char_u *propInfo, /* A string containing 0 or more X commands */
1246 long_u numItems) /* The size of propInfo in bytes. */
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001247{
1248 char_u *p;
1249 int code;
1250 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251
1252 /*
1253 * Several commands and results could arrive in the property at
1254 * one time; each iteration through the outer loop handles a
1255 * single command or result.
1256 */
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001257 for (p = propInfo; (long_u)(p - propInfo) < numItems; )
Bram Moolenaar071d4272004-06-13 20:20:40 +00001258 {
1259 /*
1260 * Ignore leading NULs; each command or result starts with a
1261 * NUL so that no matter how badly formed a preceding command
1262 * is, we'll be able to tell that a new command/result is
1263 * starting.
1264 */
1265 if (*p == 0)
1266 {
1267 p++;
1268 continue;
1269 }
1270
1271 if ((*p == 'c' || *p == 'k') && (p[1] == 0))
1272 {
1273 Window resWindow;
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001274 char_u *name, *script, *serial, *end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001275 Bool asKeys = *p == 'k';
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001276 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277
1278 /*
1279 * This is an incoming command from some other application.
1280 * Iterate over all of its options. Stop when we reach
1281 * the end of the property or something that doesn't look
1282 * like an option.
1283 */
1284 p += 2;
1285 name = NULL;
1286 resWindow = None;
1287 serial = (char_u *)"";
1288 script = NULL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001289 enc = NULL;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001290 while ((long_u)(p - propInfo) < numItems && *p == '-')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291 {
1292 switch (p[1])
1293 {
1294 case 'r':
1295 end = skipwhite(p + 2);
1296 resWindow = 0;
1297 while (vim_isxdigit(*end))
1298 {
1299 resWindow = 16 * resWindow + (long_u)hex2nr(*end);
1300 ++end;
1301 }
1302 if (end == p + 2 || *end != ' ')
1303 resWindow = None;
1304 else
1305 {
1306 p = serial = end + 1;
1307 clientWindow = resWindow; /* Remember in global */
1308 }
1309 break;
1310 case 'n':
1311 if (p[2] == ' ')
1312 name = p + 3;
1313 break;
1314 case 's':
1315 if (p[2] == ' ')
1316 script = p + 3;
1317 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001318 case 'E':
1319 if (p[2] == ' ')
1320 enc = p + 3;
1321 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001322 }
1323 while (*p != 0)
1324 p++;
1325 p++;
1326 }
1327
1328 if (script == NULL || name == NULL)
1329 continue;
1330
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001331 if (serverName != NULL && STRICMP(name, serverName) == 0)
1332 {
1333 script = serverConvert(enc, script, &tofree);
1334 if (asKeys)
1335 server_to_input_buf(script);
1336 else
1337 {
1338 char_u *res;
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001339
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001340 res = eval_client_expr_to_string(script);
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001341 if (resWindow != None)
1342 {
1343 garray_T reply;
1344
1345 /* Initialize the result property. */
1346 ga_init2(&reply, 1, 100);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001347#ifdef FEAT_MBYTE
Bram Moolenaarcde88542015-08-11 19:14:00 +02001348 (void)ga_grow(&reply, 50 + STRLEN(p_enc));
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001349 sprintf(reply.ga_data, "%cr%c-E %s%c-s %s%c-r ",
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001350 0, 0, p_enc, 0, serial, 0);
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001351 reply.ga_len = 14 + STRLEN(p_enc) + STRLEN(serial);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001352#else
Bram Moolenaarcde88542015-08-11 19:14:00 +02001353 (void)ga_grow(&reply, 50);
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001354 sprintf(reply.ga_data, "%cr%c-s %s%c-r ",
1355 0, 0, serial, 0);
1356 reply.ga_len = 10 + STRLEN(serial);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00001357#endif
Bram Moolenaar52bf4692012-07-10 14:25:04 +02001358
1359 /* Evaluate the expression and return the result. */
1360 if (res != NULL)
1361 ga_concat(&reply, res);
1362 else
1363 {
1364 ga_concat(&reply, (char_u *)_(e_invexprmsg));
1365 ga_append(&reply, 0);
1366 ga_concat(&reply, (char_u *)"-c 1");
1367 }
1368 ga_append(&reply, NUL);
1369 (void)AppendPropCarefully(dpy, resWindow, commProperty,
1370 reply.ga_data, reply.ga_len);
1371 ga_clear(&reply);
1372 }
Bram Moolenaar93c88e02015-09-15 14:12:05 +02001373 vim_free(res);
1374 }
1375 vim_free(tofree);
1376 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001377 }
1378 else if (*p == 'r' && p[1] == 0)
1379 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001380 int serial, gotSerial;
1381 char_u *res;
1382 PendingCommand *pcPtr;
1383 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384
1385 /*
1386 * This is a reply to some command that we sent out. Iterate
1387 * over all of its options. Stop when we reach the end of the
1388 * property or something that doesn't look like an option.
1389 */
1390 p += 2;
1391 gotSerial = 0;
1392 res = (char_u *)"";
1393 code = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001394 enc = NULL;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001395 while ((long_u)(p - propInfo) < numItems && *p == '-')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396 {
1397 switch (p[1])
1398 {
1399 case 'r':
1400 if (p[2] == ' ')
1401 res = p + 3;
1402 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001403 case 'E':
1404 if (p[2] == ' ')
1405 enc = p + 3;
1406 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001407 case 's':
1408 if (sscanf((char *)p + 2, " %d", &serial) == 1)
1409 gotSerial = 1;
1410 break;
1411 case 'c':
1412 if (sscanf((char *)p + 2, " %d", &code) != 1)
1413 code = 0;
1414 break;
1415 }
1416 while (*p != 0)
1417 p++;
1418 p++;
1419 }
1420
1421 if (!gotSerial)
1422 continue;
1423
1424 /*
1425 * Give the result information to anyone who's
1426 * waiting for it.
1427 */
1428 for (pcPtr = pendingCommands; pcPtr != NULL; pcPtr = pcPtr->nextPtr)
1429 {
1430 if (serial != pcPtr->serial || pcPtr->result != NULL)
1431 continue;
1432
1433 pcPtr->code = code;
Bram Moolenaarcde88542015-08-11 19:14:00 +02001434 res = serverConvert(enc, res, &tofree);
1435 if (tofree == NULL)
1436 res = vim_strsave(res);
1437 pcPtr->result = res;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001438 break;
1439 }
1440 }
1441 else if (*p == 'n' && p[1] == 0)
1442 {
1443 Window win = 0;
1444 unsigned int u;
1445 int gotWindow;
1446 char_u *str;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447 struct ServerReply *r;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001448 char_u *enc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449
1450 /*
1451 * This is a (n)otification. Sent with serverreply_send in VimL.
1452 * Execute any autocommand and save it for later retrieval
1453 */
1454 p += 2;
1455 gotWindow = 0;
1456 str = (char_u *)"";
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001457 enc = NULL;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00001458 while ((long_u)(p - propInfo) < numItems && *p == '-')
Bram Moolenaar071d4272004-06-13 20:20:40 +00001459 {
1460 switch (p[1])
1461 {
1462 case 'n':
1463 if (p[2] == ' ')
1464 str = p + 3;
1465 break;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001466 case 'E':
1467 if (p[2] == ' ')
1468 enc = p + 3;
1469 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 case 'w':
1471 if (sscanf((char *)p + 2, " %x", &u) == 1)
1472 {
1473 win = u;
1474 gotWindow = 1;
1475 }
1476 break;
1477 }
1478 while (*p != 0)
1479 p++;
1480 p++;
1481 }
1482
1483 if (!gotWindow)
1484 continue;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001485 str = serverConvert(enc, str, &tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 if ((r = ServerReplyFind(win, SROP_Add)) != NULL)
1487 {
1488 ga_concat(&(r->strings), str);
Bram Moolenaar269ec652004-07-29 08:43:53 +00001489 ga_append(&(r->strings), NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 }
1491#ifdef FEAT_AUTOCMD
Bram Moolenaare37d50a2008-08-06 17:06:04 +00001492 {
1493 char_u winstr[30];
1494
1495 sprintf((char *)winstr, "0x%x", (unsigned int)win);
1496 apply_autocmds(EVENT_REMOTEREPLY, winstr, str, TRUE, curbuf);
1497 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001498#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001499 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001500 }
1501 else
1502 {
1503 /*
1504 * Didn't recognize this thing. Just skip through the next
1505 * null character and try again.
1506 * Even if we get an 'r'(eply) we will throw it away as we
1507 * never specify (and thus expect) one
1508 */
1509 while (*p != 0)
1510 p++;
1511 p++;
1512 }
1513 }
1514 XFree(propInfo);
1515}
1516
1517/*
1518 * Append a given property to a given window, but set up an X error handler so
1519 * that if the append fails this procedure can return an error code rather
1520 * than having Xlib panic.
1521 * Return: 0 for OK, -1 for error
1522 */
1523 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001524AppendPropCarefully(
1525 Display *dpy, /* Display on which to operate. */
1526 Window window, /* Window whose property is to be modified. */
1527 Atom property, /* Name of property. */
1528 char_u *value, /* Characters to append to property. */
1529 int length) /* How much to append */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530{
1531 XErrorHandler old_handler;
1532
1533 old_handler = XSetErrorHandler(x_error_check);
1534 got_x_error = FALSE;
1535 XChangeProperty(dpy, window, property, XA_STRING, 8,
1536 PropModeAppend, value, length);
1537 XSync(dpy, False);
1538 (void) XSetErrorHandler(old_handler);
1539 return got_x_error ? -1 : 0;
1540}
1541
1542
1543/*
1544 * Another X Error handler, just used to check for errors.
1545 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001547x_error_check(Display *dpy UNUSED, XErrorEvent *error_event UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548{
1549 got_x_error = TRUE;
1550 return 0;
1551}
1552
1553/*
1554 * Check if "str" looks like it had a serial number appended.
1555 * Actually just checks if the name ends in a digit.
1556 */
1557 static int
Bram Moolenaar68c2f632016-01-30 17:24:07 +01001558IsSerialName(char_u *str)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001559{
1560 int len = STRLEN(str);
1561
1562 return (len > 1 && vim_isdigit(str[len - 1]));
1563}
1564#endif /* FEAT_CLIENTSERVER */