* lisp/progmodes/cc-mode.el (c-after-font-lock-init): Only *move*
[emacs.git] / src / xsmfns.c
blob3b06f7133c756a8470f1480855caf7e30317bc16
1 /* Session management module for systems which understand the X Session
2 management protocol.
4 Copyright (C) 2002-2015 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
11 (at 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 "systime.h"
36 #include "sysselect.h"
37 #include "frame.h"
38 #include "termhooks.h"
39 #include "xterm.h"
40 #include "process.h"
41 #include "keyboard.h"
43 #if defined USE_GTK && !defined HAVE_GTK3
44 #define gdk_x11_set_sm_client_id(w) gdk_set_sm_client_id (w)
45 #endif
47 /* This is the event used when SAVE_SESSION_EVENT occurs. */
49 static struct input_event emacs_event;
51 /* The descriptor that we use to check for data from the session manager. */
53 static int ice_fd = -1;
55 /* A flag that says if we are in shutdown interactions or not. */
57 static bool doing_interact;
59 /* The session manager object for the session manager connection. */
61 static SmcConn smc_conn;
63 /* The client session id for this session. */
65 static char *client_id;
67 /* The full path name to the Emacs program. */
69 static char *emacs_program;
71 /* The option we tell the session manager to start Emacs with when
72 restarting Emacs. The client_id is appended. */
74 #define SMID_OPT "--smid="
77 /* The option to start Emacs without the splash screen when
78 restarting Emacs. */
80 static char NOSPLASH_OPT[] = "--no-splash";
82 /* The option to make Emacs start in the given directory. */
84 #define CHDIR_OPT "--chdir="
86 static void
87 ice_connection_closed (void)
89 if (ice_fd >= 0)
90 delete_read_fd (ice_fd);
91 ice_fd = -1;
95 /* Handle any messages from the session manager. If no connection is
96 open to a session manager, just return. */
98 static void
99 x_session_check_input (int fd, void *data)
101 int ret;
103 if (ice_fd == -1) return;
105 /* Reset this so wo can check kind after callbacks have been called by
106 IceProcessMessages. The smc_interact_CB sets the kind to
107 SAVE_SESSION_EVENT, but we don't know beforehand if that callback
108 will be called. */
109 emacs_event.kind = NO_EVENT;
111 ret = IceProcessMessages (SmcGetIceConnection (smc_conn), 0, 0);
112 if (ret != IceProcessMessagesSuccess)
114 /* Either IO error or Connection closed. */
115 if (ret == IceProcessMessagesIOError)
116 IceCloseConnection (SmcGetIceConnection (smc_conn));
118 ice_connection_closed ();
121 /* Check if smc_interact_CB was called and we shall generate a
122 SAVE_SESSION_EVENT. */
123 if (emacs_event.kind != NO_EVENT)
124 kbd_buffer_store_event (&emacs_event);
127 /* Return true if we have a connection to a session manager. */
129 bool
130 x_session_have_connection (void)
132 return ice_fd != -1;
135 /* This is called when the session manager says it is OK to interact with the
136 user. Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
137 Then lisp code can interact with the user. */
139 static void
140 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
142 doing_interact = true;
143 emacs_event.kind = SAVE_SESSION_EVENT;
144 emacs_event.arg = Qnil;
147 /* This is called when the session manager tells us to save ourselves.
148 We set the required properties so the session manager can restart us,
149 plus the current working directory property (not mandatory) so we
150 are started in the correct directory.
152 If this is a shutdown and we can request to interact with the user,
153 we do so, because we don't know what the lisp code might do. */
155 static void
156 smc_save_yourself_CB (SmcConn smcConn,
157 SmPointer clientData,
158 int saveType,
159 Bool shutdown,
160 int interactStyle,
161 Bool fast)
163 #define NR_PROPS 5
165 SmProp *props[NR_PROPS];
166 SmProp prop_ptr[NR_PROPS];
168 SmPropValue values[20], *vp;
169 int val_idx = 0, vp_idx = 0;
170 int props_idx = 0;
171 int i;
172 char *smid_opt, *chdir_opt = NULL;
173 Lisp_Object user_login_name = Fuser_login_name (Qnil);
175 // Must have these.
176 if (! STRINGP (Vinvocation_name) || ! STRINGP (user_login_name))
177 return;
179 /* How to start a new instance of Emacs. */
180 props[props_idx] = &prop_ptr[props_idx];
181 props[props_idx]->name = xstrdup (SmCloneCommand);
182 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
183 props[props_idx]->num_vals = 1;
184 props[props_idx]->vals = &values[val_idx++];
185 props[props_idx]->vals[0].length = strlen (emacs_program);
186 props[props_idx]->vals[0].value = emacs_program;
187 ++props_idx;
189 /* The name of the program. */
190 props[props_idx] = &prop_ptr[props_idx];
191 props[props_idx]->name = xstrdup (SmProgram);
192 props[props_idx]->type = xstrdup (SmARRAY8);
193 props[props_idx]->num_vals = 1;
194 props[props_idx]->vals = &values[val_idx++];
195 props[props_idx]->vals[0].length = SBYTES (Vinvocation_name);
196 props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
197 ++props_idx;
199 /* User id. */
200 props[props_idx] = &prop_ptr[props_idx];
201 props[props_idx]->name = xstrdup (SmUserID);
202 props[props_idx]->type = xstrdup (SmARRAY8);
203 props[props_idx]->num_vals = 1;
204 props[props_idx]->vals = &values[val_idx++];
205 props[props_idx]->vals[0].length = SBYTES (user_login_name);
206 props[props_idx]->vals[0].value = SDATA (user_login_name);
207 ++props_idx;
209 char *cwd = get_current_dir_name ();
210 if (cwd)
212 props[props_idx] = &prop_ptr[props_idx];
213 props[props_idx]->name = xstrdup (SmCurrentDirectory);
214 props[props_idx]->type = xstrdup (SmARRAY8);
215 props[props_idx]->num_vals = 1;
216 props[props_idx]->vals = &values[val_idx++];
217 props[props_idx]->vals[0].length = strlen (cwd);
218 props[props_idx]->vals[0].value = cwd;
219 ++props_idx;
223 /* How to restart Emacs. */
224 props[props_idx] = &prop_ptr[props_idx];
225 props[props_idx]->name = xstrdup (SmRestartCommand);
226 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
227 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */
228 if (INT_MAX - 3 < initial_argc)
229 memory_full (SIZE_MAX);
230 i = 3 + initial_argc;
231 props[props_idx]->num_vals = i;
232 vp = xnmalloc (i, sizeof *vp);
233 props[props_idx]->vals = vp;
234 props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
235 props[props_idx]->vals[vp_idx++].value = emacs_program;
237 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
238 strcpy (stpcpy (smid_opt, SMID_OPT), client_id);
240 props[props_idx]->vals[vp_idx].length = strlen (smid_opt);
241 props[props_idx]->vals[vp_idx++].value = smid_opt;
243 props[props_idx]->vals[vp_idx].length = strlen (NOSPLASH_OPT);
244 props[props_idx]->vals[vp_idx++].value = NOSPLASH_OPT;
246 if (cwd)
248 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
249 strcpy (stpcpy (chdir_opt, CHDIR_OPT), cwd);
251 props[props_idx]->vals[vp_idx].length = strlen (chdir_opt);
252 props[props_idx]->vals[vp_idx++].value = chdir_opt;
255 for (i = 1; i < initial_argc; ++i)
257 props[props_idx]->vals[vp_idx].length = strlen (initial_argv[i]);
258 props[props_idx]->vals[vp_idx++].value = initial_argv[i];
261 ++props_idx;
263 SmcSetProperties (smcConn, props_idx, props);
265 xfree (smid_opt);
266 xfree (chdir_opt);
267 xfree (cwd);
268 xfree (vp);
270 for (i = 0; i < props_idx; ++i)
272 xfree (props[i]->type);
273 xfree (props[i]->name);
276 /* See if we maybe shall interact with the user. */
277 if (interactStyle != SmInteractStyleAny
278 || ! shutdown
279 || saveType == SmSaveLocal
280 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
282 /* No interaction, we are done saving ourself. */
283 SmcSaveYourselfDone (smcConn, True);
287 /* According to the SM specification, this shall close the connection. */
289 static void
290 smc_die_CB (SmcConn smcConn, SmPointer clientData)
292 emacs_event.kind = SAVE_SESSION_EVENT;
293 emacs_event.arg = Qt;
296 /* We don't use the next two but they are mandatory, leave them empty.
297 According to the SM specification, we should not interact with the
298 user between smc_save_yourself_CB is called and until smc_save_complete_CB
299 is called. It seems like a lot of job to implement this and it doesn't
300 even seem necessary. */
302 static void
303 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
305 /* Empty */
308 static void
309 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
311 /* Empty */
314 /* Error handlers for SM and ICE. We don't want to exit Emacs just
315 because there is some error in the session management. */
317 static void
318 smc_error_handler (SmcConn smcConn,
319 Bool swap,
320 int offendingMinorOpcode,
321 unsigned long offendingSequence,
322 int errorClass,
323 int severity,
324 SmPointer values)
326 /* Empty */
329 static void
330 ice_error_handler (IceConn iceConn,
331 Bool swap,
332 int offendingMinorOpcode,
333 unsigned long offendingSequence,
334 int errorClass,
335 int severity,
336 IcePointer values)
338 /* Empty */
342 static void
343 ice_io_error_handler (IceConn iceConn)
345 /* Connection probably gone. */
346 ice_connection_closed ();
349 /* This is called when the ICE connection is created or closed. The SM library
350 uses ICE as it transport protocol. */
352 static void
353 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData,
354 int opening, IcePointer *watchData)
356 if (! opening)
358 ice_connection_closed ();
359 return;
362 ice_fd = IceConnectionNumber (iceConn);
363 add_read_fd (ice_fd, x_session_check_input, NULL);
366 /* Create the client leader window. */
368 #ifndef USE_GTK
369 static void
370 create_client_leader_window (struct x_display_info *dpyinfo, char *client_ID)
372 Window w;
373 XClassHint class_hints;
375 w = XCreateSimpleWindow (dpyinfo->display,
376 dpyinfo->root_window,
377 -1, -1, 1, 1,
378 CopyFromParent, CopyFromParent, CopyFromParent);
380 validate_x_resource_name ();
381 class_hints.res_name = SSDATA (Vx_resource_name);
382 class_hints.res_class = SSDATA (Vx_resource_class);
383 XSetClassHint (dpyinfo->display, w, &class_hints);
384 XStoreName (dpyinfo->display, w, class_hints.res_name);
386 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
387 XA_STRING, 8, PropModeReplace,
388 (unsigned char *) client_ID, strlen (client_ID));
390 dpyinfo->client_leader_window = w;
392 #endif /* ! USE_GTK */
395 /* Try to open a connection to the session manager. */
397 void
398 x_session_initialize (struct x_display_info *dpyinfo)
400 #define SM_ERRORSTRING_LEN 512
401 char errorstring[SM_ERRORSTRING_LEN];
402 char *previous_id = NULL;
403 SmcCallbacks callbacks;
404 ptrdiff_t name_len = 0;
406 /* libSM seems to crash if pwd is missing - see bug#18851. */
407 if (! get_current_dir_name ())
409 fprintf (stderr, "Disabling session management due to pwd error: %s\n",
410 emacs_strerror (errno));
411 return;
414 ice_fd = -1;
415 doing_interact = false;
417 /* Check if we where started by the session manager. If so, we will
418 have a previous id. */
419 if (STRINGP (Vx_session_previous_id))
420 previous_id = SSDATA (Vx_session_previous_id);
422 /* Construct the path to the Emacs program. */
423 if (STRINGP (Vinvocation_directory))
424 name_len += SBYTES (Vinvocation_directory);
425 if (STRINGP (Vinvocation_name))
426 name_len += SBYTES (Vinvocation_name);
428 /* This malloc will not be freed, but it is only done once, and hopefully
429 not very large */
430 emacs_program = xmalloc (name_len + 1);
431 char *z = emacs_program;
433 if (STRINGP (Vinvocation_directory))
434 z = lispstpcpy (z, Vinvocation_directory);
435 if (STRINGP (Vinvocation_name))
436 lispstpcpy (z, Vinvocation_name);
438 /* The SM protocol says all callbacks are mandatory, so set up all
439 here and in the mask passed to SmcOpenConnection. */
440 callbacks.save_yourself.callback = smc_save_yourself_CB;
441 callbacks.save_yourself.client_data = 0;
442 callbacks.die.callback = smc_die_CB;
443 callbacks.die.client_data = 0;
444 callbacks.save_complete.callback = smc_save_complete_CB;
445 callbacks.save_complete.client_data = 0;
446 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
447 callbacks.shutdown_cancelled.client_data = 0;
449 /* Set error handlers. */
450 SmcSetErrorHandler (smc_error_handler);
451 IceSetErrorHandler (ice_error_handler);
452 IceSetIOErrorHandler (ice_io_error_handler);
454 /* Install callback for when connection status changes. */
455 IceAddConnectionWatch (ice_conn_watch_CB, 0);
457 /* Open the connection to the session manager. A failure is not
458 critical, it usually means that no session manager is running.
459 The errorstring is here for debugging. */
460 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
461 (SmcSaveYourselfProcMask|
462 SmcDieProcMask|
463 SmcSaveCompleteProcMask|
464 SmcShutdownCancelledProcMask),
465 &callbacks,
466 previous_id,
467 &client_id,
468 SM_ERRORSTRING_LEN,
469 errorstring);
471 if (smc_conn != 0)
473 Vx_session_id = build_string (client_id);
475 #ifdef USE_GTK
476 /* GTK creates a leader window by itself, but we need to tell
477 it about our client_id. */
478 gdk_x11_set_sm_client_id (client_id);
479 #else
480 create_client_leader_window (dpyinfo, client_id);
481 #endif
485 /* Ensure that the session manager is not contacted again. */
487 void
488 x_session_close (void)
490 ice_connection_closed ();
494 DEFUN ("handle-save-session", Fhandle_save_session,
495 Shandle_save_session, 1, 1, "e",
496 doc: /* Handle the save_yourself event from a session manager.
497 A session manager can tell Emacs that the window system is shutting down
498 by sending Emacs a save_yourself message. Emacs executes this function when
499 such an event occurs. This function then executes `emacs-session-save'.
500 After that, this function informs the session manager that it can continue
501 or abort shutting down the window system depending on the return value
502 from `emacs-session-save' If the return value is non-nil the session manager
503 is told to abort the window system shutdown.
505 Do not call this function yourself. */)
506 (Lisp_Object event)
508 bool kill_emacs = (CONSP (event) && CONSP (XCDR (event))
509 && EQ (Qt, XCAR (XCDR (event))));
511 /* Check doing_interact so that we don't do anything if someone called
512 this at the wrong time. */
513 if (doing_interact && ! kill_emacs)
515 bool cancel_shutdown = ! NILP (call0 (intern ("emacs-session-save")));
517 SmcInteractDone (smc_conn, cancel_shutdown);
518 SmcSaveYourselfDone (smc_conn, True);
520 doing_interact = false;
522 else if (kill_emacs)
524 /* We should not do user interaction here, but it is not easy to
525 prevent. Fix this in next version. */
526 Fkill_emacs (Qnil);
528 #if false
529 /* This will not be reached, but we want kill-emacs-hook to be run. */
530 SmcCloseConnection (smc_conn, 0, 0);
531 ice_connection_closed ();
532 #endif
535 return Qnil;
540 /***********************************************************************
541 Initialization
542 ***********************************************************************/
543 void
544 syms_of_xsmfns (void)
546 DEFVAR_LISP ("x-session-id", Vx_session_id,
547 doc: /* The session id Emacs got from the session manager for this session.
548 Changing the value does not change the session id used by Emacs.
549 The value is nil if no session manager is running.
550 See also `x-session-previous-id', `emacs-save-session-functions',
551 `emacs-session-save' and `emacs-session-restore'." */);
552 Vx_session_id = Qnil;
554 DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
555 doc: /* The previous session id Emacs got from session manager.
556 If Emacs is running on a window system that has a session manager, the
557 session manager gives Emacs a session id. It is feasible for Emacs Lisp
558 code to use the session id to save configuration in, for example, a file
559 with a file name based on the session id. If Emacs is running when the
560 window system is shut down, the session manager remembers that Emacs was
561 running and saves the session id Emacs had.
563 When the window system is started again, the session manager restarts
564 Emacs and hands Emacs the session id it had the last time it was
565 running. This is now the previous session id and the value of this
566 variable. If configuration was saved in a file as stated above, the
567 previous session id shall be used to reconstruct the file name.
569 The session id Emacs has while it is running is in the variable
570 `x-session-id'. The value of this variable and `x-session-id' may be the
571 same, depending on how the session manager works.
573 See also `emacs-save-session-functions', `emacs-session-save' and
574 `emacs-session-restore'." */);
575 Vx_session_previous_id = Qnil;
577 defsubr (&Shandle_save_session);
580 #endif /* HAVE_X_SM */