Minor ABLOCKS_BUSY cleanups in alloc.c
[emacs.git] / src / xsmfns.c
bloba7ec8e0c7e2f549b78b6a1fbea6fe7a41cf4187d
1 /* Session management module for systems which understand the X Session
2 management protocol.
4 Copyright (C) 2002-2016 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #ifdef HAVE_X_SM
25 #include <X11/SM/SMlib.h>
26 #include <X11/Xlib.h>
27 #include <X11/Xutil.h>
29 #include <unistd.h>
30 #include <sys/param.h>
31 #include <errno.h>
32 #include <stdio.h>
34 #include "lisp.h"
35 #include "frame.h"
36 #include "termhooks.h"
37 #include "xterm.h"
38 #include "process.h"
39 #include "keyboard.h"
41 #if defined USE_GTK && !defined HAVE_GTK3
42 #define gdk_x11_set_sm_client_id(w) gdk_set_sm_client_id (w)
43 #endif
45 /* This is the event used when SAVE_SESSION_EVENT occurs. */
47 static struct input_event emacs_event;
49 /* The descriptor that we use to check for data from the session manager. */
51 static int ice_fd = -1;
53 /* A flag that says if we are in shutdown interactions or not. */
55 static bool doing_interact;
57 /* The session manager object for the session manager connection. */
59 static SmcConn smc_conn;
61 /* The client session id for this session. */
63 static char *client_id;
65 /* The full path name to the Emacs program. */
67 static char *emacs_program;
69 /* The option we tell the session manager to start Emacs with when
70 restarting Emacs. The client_id is appended. */
72 #define SMID_OPT "--smid="
75 /* The option to start Emacs without the splash screen when
76 restarting Emacs. */
78 static char NOSPLASH_OPT[] = "--no-splash";
80 /* The option to make Emacs start in the given directory. */
82 #define CHDIR_OPT "--chdir="
84 static void
85 ice_connection_closed (void)
87 if (ice_fd >= 0)
88 delete_read_fd (ice_fd);
89 ice_fd = -1;
93 /* Handle any messages from the session manager. If no connection is
94 open to a session manager, just return. */
96 static void
97 x_session_check_input (int fd, void *data)
99 int ret;
101 if (ice_fd == -1) return;
103 /* Reset this so wo can check kind after callbacks have been called by
104 IceProcessMessages. The smc_interact_CB sets the kind to
105 SAVE_SESSION_EVENT, but we don't know beforehand if that callback
106 will be called. */
107 emacs_event.kind = NO_EVENT;
109 ret = IceProcessMessages (SmcGetIceConnection (smc_conn), 0, 0);
110 if (ret != IceProcessMessagesSuccess)
112 /* Either IO error or Connection closed. */
113 if (ret == IceProcessMessagesIOError)
114 IceCloseConnection (SmcGetIceConnection (smc_conn));
116 ice_connection_closed ();
119 /* Check if smc_interact_CB was called and we shall generate a
120 SAVE_SESSION_EVENT. */
121 if (emacs_event.kind != NO_EVENT)
122 kbd_buffer_store_event (&emacs_event);
125 /* Return true if we have a connection to a session manager. */
127 bool
128 x_session_have_connection (void)
130 return ice_fd != -1;
133 /* This is called when the session manager says it is OK to interact with the
134 user. Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
135 Then lisp code can interact with the user. */
137 static void
138 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
140 doing_interact = true;
141 emacs_event.kind = SAVE_SESSION_EVENT;
142 emacs_event.arg = Qnil;
145 /* This is called when the session manager tells us to save ourselves.
146 We set the required properties so the session manager can restart us,
147 plus the current working directory property (not mandatory) so we
148 are started in the correct directory.
150 If this is a shutdown and we can request to interact with the user,
151 we do so, because we don't know what the lisp code might do. */
153 static void
154 smc_save_yourself_CB (SmcConn smcConn,
155 SmPointer clientData,
156 int saveType,
157 Bool shutdown,
158 int interactStyle,
159 Bool fast)
161 #define NR_PROPS 5
163 SmProp *props[NR_PROPS];
164 SmProp prop_ptr[NR_PROPS];
166 SmPropValue values[20], *vp;
167 int val_idx = 0, vp_idx = 0;
168 int props_idx = 0;
169 int i;
170 char *smid_opt, *chdir_opt = NULL;
171 Lisp_Object user_login_name = Fuser_login_name (Qnil);
173 // Must have these.
174 if (! STRINGP (Vinvocation_name) || ! STRINGP (user_login_name))
175 return;
177 /* How to start a new instance of Emacs. */
178 props[props_idx] = &prop_ptr[props_idx];
179 props[props_idx]->name = xstrdup (SmCloneCommand);
180 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
181 props[props_idx]->num_vals = 1;
182 props[props_idx]->vals = &values[val_idx++];
183 props[props_idx]->vals[0].length = strlen (emacs_program);
184 props[props_idx]->vals[0].value = emacs_program;
185 ++props_idx;
187 /* The name of the program. */
188 props[props_idx] = &prop_ptr[props_idx];
189 props[props_idx]->name = xstrdup (SmProgram);
190 props[props_idx]->type = xstrdup (SmARRAY8);
191 props[props_idx]->num_vals = 1;
192 props[props_idx]->vals = &values[val_idx++];
193 props[props_idx]->vals[0].length = SBYTES (Vinvocation_name);
194 props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
195 ++props_idx;
197 /* User id. */
198 props[props_idx] = &prop_ptr[props_idx];
199 props[props_idx]->name = xstrdup (SmUserID);
200 props[props_idx]->type = xstrdup (SmARRAY8);
201 props[props_idx]->num_vals = 1;
202 props[props_idx]->vals = &values[val_idx++];
203 props[props_idx]->vals[0].length = SBYTES (user_login_name);
204 props[props_idx]->vals[0].value = SDATA (user_login_name);
205 ++props_idx;
207 char *cwd = emacs_get_current_dir_name ();
208 if (cwd)
210 props[props_idx] = &prop_ptr[props_idx];
211 props[props_idx]->name = xstrdup (SmCurrentDirectory);
212 props[props_idx]->type = xstrdup (SmARRAY8);
213 props[props_idx]->num_vals = 1;
214 props[props_idx]->vals = &values[val_idx++];
215 props[props_idx]->vals[0].length = strlen (cwd);
216 props[props_idx]->vals[0].value = cwd;
217 ++props_idx;
221 /* How to restart Emacs. */
222 props[props_idx] = &prop_ptr[props_idx];
223 props[props_idx]->name = xstrdup (SmRestartCommand);
224 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
225 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */
226 if (INT_ADD_WRAPV (initial_argc, 3, &i))
227 memory_full (SIZE_MAX);
228 props[props_idx]->num_vals = i;
229 vp = xnmalloc (i, sizeof *vp);
230 props[props_idx]->vals = vp;
231 props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
232 props[props_idx]->vals[vp_idx++].value = emacs_program;
234 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
235 strcpy (stpcpy (smid_opt, SMID_OPT), client_id);
237 props[props_idx]->vals[vp_idx].length = strlen (smid_opt);
238 props[props_idx]->vals[vp_idx++].value = smid_opt;
240 props[props_idx]->vals[vp_idx].length = strlen (NOSPLASH_OPT);
241 props[props_idx]->vals[vp_idx++].value = NOSPLASH_OPT;
243 if (cwd)
245 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
246 strcpy (stpcpy (chdir_opt, CHDIR_OPT), cwd);
248 props[props_idx]->vals[vp_idx].length = strlen (chdir_opt);
249 props[props_idx]->vals[vp_idx++].value = chdir_opt;
252 for (i = 1; i < initial_argc; ++i)
254 props[props_idx]->vals[vp_idx].length = strlen (initial_argv[i]);
255 props[props_idx]->vals[vp_idx++].value = initial_argv[i];
258 ++props_idx;
260 SmcSetProperties (smcConn, props_idx, props);
262 xfree (smid_opt);
263 xfree (chdir_opt);
264 xfree (cwd);
265 xfree (vp);
267 for (i = 0; i < props_idx; ++i)
269 xfree (props[i]->type);
270 xfree (props[i]->name);
273 /* See if we maybe shall interact with the user. */
274 if (interactStyle != SmInteractStyleAny
275 || ! shutdown
276 || saveType == SmSaveLocal
277 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
279 /* No interaction, we are done saving ourself. */
280 SmcSaveYourselfDone (smcConn, True);
284 /* According to the SM specification, this shall close the connection. */
286 static void
287 smc_die_CB (SmcConn smcConn, SmPointer clientData)
289 emacs_event.kind = SAVE_SESSION_EVENT;
290 emacs_event.arg = Qt;
293 /* We don't use the next two but they are mandatory, leave them empty.
294 According to the SM specification, we should not interact with the
295 user between smc_save_yourself_CB is called and until smc_save_complete_CB
296 is called. It seems like a lot of job to implement this and it doesn't
297 even seem necessary. */
299 static void
300 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
302 /* Empty */
305 static void
306 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
308 /* Empty */
311 /* Error handlers for SM and ICE. We don't want to exit Emacs just
312 because there is some error in the session management. */
314 static void
315 smc_error_handler (SmcConn smcConn,
316 Bool swap,
317 int offendingMinorOpcode,
318 unsigned long offendingSequence,
319 int errorClass,
320 int severity,
321 SmPointer values)
323 /* Empty */
326 static void
327 ice_error_handler (IceConn iceConn,
328 Bool swap,
329 int offendingMinorOpcode,
330 unsigned long offendingSequence,
331 int errorClass,
332 int severity,
333 IcePointer values)
335 /* Empty */
339 static void
340 ice_io_error_handler (IceConn iceConn)
342 /* Connection probably gone. */
343 ice_connection_closed ();
346 /* This is called when the ICE connection is created or closed. The SM library
347 uses ICE as it transport protocol. */
349 static void
350 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData,
351 int opening, IcePointer *watchData)
353 if (! opening)
355 ice_connection_closed ();
356 return;
359 ice_fd = IceConnectionNumber (iceConn);
360 add_read_fd (ice_fd, x_session_check_input, NULL);
363 /* Create the client leader window. */
365 #ifndef USE_GTK
366 static void
367 create_client_leader_window (struct x_display_info *dpyinfo, char *client_ID)
369 Window w;
370 XClassHint class_hints;
372 w = XCreateSimpleWindow (dpyinfo->display,
373 dpyinfo->root_window,
374 -1, -1, 1, 1,
375 CopyFromParent, CopyFromParent, CopyFromParent);
377 validate_x_resource_name ();
378 class_hints.res_name = SSDATA (Vx_resource_name);
379 class_hints.res_class = SSDATA (Vx_resource_class);
380 XSetClassHint (dpyinfo->display, w, &class_hints);
381 XStoreName (dpyinfo->display, w, class_hints.res_name);
383 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
384 XA_STRING, 8, PropModeReplace,
385 (unsigned char *) client_ID, strlen (client_ID));
387 dpyinfo->client_leader_window = w;
389 #endif /* ! USE_GTK */
392 /* Try to open a connection to the session manager. */
394 void
395 x_session_initialize (struct x_display_info *dpyinfo)
397 #define SM_ERRORSTRING_LEN 512
398 char errorstring[SM_ERRORSTRING_LEN];
399 char *previous_id = NULL;
400 SmcCallbacks callbacks;
401 ptrdiff_t name_len = 0;
403 /* libSM seems to crash if pwd is missing - see bug#18851. */
404 if (! emacs_get_current_dir_name ())
406 fprintf (stderr, "Disabling session management due to pwd error: %s\n",
407 emacs_strerror (errno));
408 return;
411 ice_fd = -1;
412 doing_interact = false;
414 /* Check if we where started by the session manager. If so, we will
415 have a previous id. */
416 if (STRINGP (Vx_session_previous_id))
417 previous_id = SSDATA (Vx_session_previous_id);
419 /* Construct the path to the Emacs program. */
420 if (STRINGP (Vinvocation_directory))
421 name_len += SBYTES (Vinvocation_directory);
422 if (STRINGP (Vinvocation_name))
423 name_len += SBYTES (Vinvocation_name);
425 /* This malloc will not be freed, but it is only done once, and hopefully
426 not very large */
427 emacs_program = xmalloc (name_len + 1);
428 char *z = emacs_program;
430 if (STRINGP (Vinvocation_directory))
431 z = lispstpcpy (z, Vinvocation_directory);
432 if (STRINGP (Vinvocation_name))
433 lispstpcpy (z, Vinvocation_name);
435 /* The SM protocol says all callbacks are mandatory, so set up all
436 here and in the mask passed to SmcOpenConnection. */
437 callbacks.save_yourself.callback = smc_save_yourself_CB;
438 callbacks.save_yourself.client_data = 0;
439 callbacks.die.callback = smc_die_CB;
440 callbacks.die.client_data = 0;
441 callbacks.save_complete.callback = smc_save_complete_CB;
442 callbacks.save_complete.client_data = 0;
443 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
444 callbacks.shutdown_cancelled.client_data = 0;
446 /* Set error handlers. */
447 SmcSetErrorHandler (smc_error_handler);
448 IceSetErrorHandler (ice_error_handler);
449 IceSetIOErrorHandler (ice_io_error_handler);
451 /* Install callback for when connection status changes. */
452 IceAddConnectionWatch (ice_conn_watch_CB, 0);
454 /* Open the connection to the session manager. A failure is not
455 critical, it usually means that no session manager is running.
456 The errorstring is here for debugging. */
457 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
458 (SmcSaveYourselfProcMask|
459 SmcDieProcMask|
460 SmcSaveCompleteProcMask|
461 SmcShutdownCancelledProcMask),
462 &callbacks,
463 previous_id,
464 &client_id,
465 SM_ERRORSTRING_LEN,
466 errorstring);
468 if (smc_conn != 0)
470 Vx_session_id = build_string (client_id);
472 #ifdef USE_GTK
473 /* GTK creates a leader window by itself, but we need to tell
474 it about our client_id. */
475 gdk_x11_set_sm_client_id (client_id);
476 #else
477 create_client_leader_window (dpyinfo, client_id);
478 #endif
482 /* Ensure that the session manager is not contacted again. */
484 void
485 x_session_close (void)
487 ice_connection_closed ();
491 DEFUN ("handle-save-session", Fhandle_save_session,
492 Shandle_save_session, 1, 1, "e",
493 doc: /* Handle the save_yourself event from a session manager.
494 A session manager can tell Emacs that the window system is shutting down
495 by sending Emacs a save_yourself message. Emacs executes this function when
496 such an event occurs. This function then executes `emacs-session-save'.
497 After that, this function informs the session manager that it can continue
498 or abort shutting down the window system depending on the return value
499 from `emacs-session-save' If the return value is non-nil the session manager
500 is told to abort the window system shutdown.
502 Do not call this function yourself. */)
503 (Lisp_Object event)
505 bool kill_emacs = (CONSP (event) && CONSP (XCDR (event))
506 && EQ (Qt, XCAR (XCDR (event))));
508 /* Check doing_interact so that we don't do anything if someone called
509 this at the wrong time. */
510 if (doing_interact && ! kill_emacs)
512 bool cancel_shutdown = ! NILP (call0 (intern ("emacs-session-save")));
514 SmcInteractDone (smc_conn, cancel_shutdown);
515 SmcSaveYourselfDone (smc_conn, True);
517 doing_interact = false;
519 else if (kill_emacs)
521 /* We should not do user interaction here, but it is not easy to
522 prevent. Fix this in next version. */
523 Fkill_emacs (Qnil);
525 #if false
526 /* This will not be reached, but we want kill-emacs-hook to be run. */
527 SmcCloseConnection (smc_conn, 0, 0);
528 ice_connection_closed ();
529 #endif
532 return Qnil;
537 /***********************************************************************
538 Initialization
539 ***********************************************************************/
540 void
541 syms_of_xsmfns (void)
543 DEFVAR_LISP ("x-session-id", Vx_session_id,
544 doc: /* The session id Emacs got from the session manager for this session.
545 Changing the value does not change the session id used by Emacs.
546 The value is nil if no session manager is running.
547 See also `x-session-previous-id', `emacs-save-session-functions',
548 `emacs-session-save' and `emacs-session-restore'. */);
549 Vx_session_id = Qnil;
551 DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
552 doc: /* The previous session id Emacs got from session manager.
553 If Emacs is running on a window system that has a session manager, the
554 session manager gives Emacs a session id. It is feasible for Emacs Lisp
555 code to use the session id to save configuration in, for example, a file
556 with a file name based on the session id. If Emacs is running when the
557 window system is shut down, the session manager remembers that Emacs was
558 running and saves the session id Emacs had.
560 When the window system is started again, the session manager restarts
561 Emacs and hands Emacs the session id it had the last time it was
562 running. This is now the previous session id and the value of this
563 variable. If configuration was saved in a file as stated above, the
564 previous session id shall be used to reconstruct the file name.
566 The session id Emacs has while it is running is in the variable
567 `x-session-id'. The value of this variable and `x-session-id' may be the
568 same, depending on how the session manager works.
570 See also `emacs-save-session-functions', `emacs-session-save' and
571 `emacs-session-restore'. */);
572 Vx_session_previous_id = Qnil;
574 defsubr (&Shandle_save_session);
577 #endif /* HAVE_X_SM */