* lisp/mail/rmail.el (rmail-highlighted-headers): Fix :type.
[emacs.git] / src / xsmfns.c
blob48aaa9bef8a1870c968df49e7b18f76bea3d9f91
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 <stdio.h>
33 #include "lisp.h"
34 #include "systime.h"
35 #include "sysselect.h"
36 #include "frame.h"
37 #include "termhooks.h"
38 #include "xterm.h"
39 #include "process.h"
40 #include "keyboard.h"
42 #if defined USE_GTK && !defined HAVE_GTK3
43 #define gdk_x11_set_sm_client_id(w) gdk_set_sm_client_id (w)
44 #endif
46 /* This is the event used when SAVE_SESSION_EVENT occurs. */
48 static struct input_event emacs_event;
50 /* The descriptor that we use to check for data from the session manager. */
52 static int ice_fd = -1;
54 /* A flag that says if we are in shutdown interactions or not. */
56 static bool doing_interact;
58 /* The session manager object for the session manager connection. */
60 static SmcConn smc_conn;
62 /* The client session id for this session. */
64 static char *client_id;
66 /* The full path name to the Emacs program. */
68 static char *emacs_program;
70 /* The option we tell the session manager to start Emacs with when
71 restarting Emacs. The client_id is appended. */
73 #define SMID_OPT "--smid="
76 /* The option to start Emacs without the splash screen when
77 restarting Emacs. */
79 static char NOSPLASH_OPT[] = "--no-splash";
81 /* The option to make Emacs start in the given directory. */
83 #define CHDIR_OPT "--chdir="
85 static void
86 ice_connection_closed (void)
88 if (ice_fd >= 0)
89 delete_read_fd (ice_fd);
90 ice_fd = -1;
94 /* Handle any messages from the session manager. If no connection is
95 open to a session manager, just return. */
97 static void
98 x_session_check_input (int fd, void *data)
100 int ret;
102 if (ice_fd == -1) return;
104 /* Reset this so wo can check kind after callbacks have been called by
105 IceProcessMessages. The smc_interact_CB sets the kind to
106 SAVE_SESSION_EVENT, but we don't know beforehand if that callback
107 will be called. */
108 emacs_event.kind = NO_EVENT;
110 ret = IceProcessMessages (SmcGetIceConnection (smc_conn), 0, 0);
111 if (ret != IceProcessMessagesSuccess)
113 /* Either IO error or Connection closed. */
114 if (ret == IceProcessMessagesIOError)
115 IceCloseConnection (SmcGetIceConnection (smc_conn));
117 ice_connection_closed ();
120 /* Check if smc_interact_CB was called and we shall generate a
121 SAVE_SESSION_EVENT. */
122 if (emacs_event.kind != NO_EVENT)
123 kbd_buffer_store_event (&emacs_event);
126 /* Return true if we have a connection to a session manager. */
128 bool
129 x_session_have_connection (void)
131 return ice_fd != -1;
134 /* This is called when the session manager says it is OK to interact with the
135 user. Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
136 Then lisp code can interact with the user. */
138 static void
139 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
141 doing_interact = true;
142 emacs_event.kind = SAVE_SESSION_EVENT;
143 emacs_event.arg = Qnil;
146 /* This is called when the session manager tells us to save ourselves.
147 We set the required properties so the session manager can restart us,
148 plus the current working directory property (not mandatory) so we
149 are started in the correct directory.
151 If this is a shutdown and we can request to interact with the user,
152 we do so, because we don't know what the lisp code might do. */
154 static void
155 smc_save_yourself_CB (SmcConn smcConn,
156 SmPointer clientData,
157 int saveType,
158 Bool shutdown,
159 int interactStyle,
160 Bool fast)
162 #define NR_PROPS 5
164 SmProp *props[NR_PROPS];
165 SmProp prop_ptr[NR_PROPS];
167 SmPropValue values[20], *vp;
168 int val_idx = 0, vp_idx = 0;
169 int props_idx = 0;
170 int i;
171 char *smid_opt, *chdir_opt = NULL;
172 Lisp_Object user_login_name = Fuser_login_name (Qnil);
174 // Must have these.
175 if (! STRINGP (Vinvocation_name) || ! STRINGP (user_login_name))
176 return;
178 /* How to start a new instance of Emacs. */
179 props[props_idx] = &prop_ptr[props_idx];
180 props[props_idx]->name = xstrdup (SmCloneCommand);
181 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
182 props[props_idx]->num_vals = 1;
183 props[props_idx]->vals = &values[val_idx++];
184 props[props_idx]->vals[0].length = strlen (emacs_program);
185 props[props_idx]->vals[0].value = emacs_program;
186 ++props_idx;
188 /* The name of the program. */
189 props[props_idx] = &prop_ptr[props_idx];
190 props[props_idx]->name = xstrdup (SmProgram);
191 props[props_idx]->type = xstrdup (SmARRAY8);
192 props[props_idx]->num_vals = 1;
193 props[props_idx]->vals = &values[val_idx++];
194 props[props_idx]->vals[0].length = SBYTES (Vinvocation_name);
195 props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
196 ++props_idx;
198 /* User id. */
199 props[props_idx] = &prop_ptr[props_idx];
200 props[props_idx]->name = xstrdup (SmUserID);
201 props[props_idx]->type = xstrdup (SmARRAY8);
202 props[props_idx]->num_vals = 1;
203 props[props_idx]->vals = &values[val_idx++];
204 props[props_idx]->vals[0].length = SBYTES (user_login_name);
205 props[props_idx]->vals[0].value = SDATA (user_login_name);
206 ++props_idx;
208 char *cwd = get_current_dir_name ();
209 if (cwd)
211 props[props_idx] = &prop_ptr[props_idx];
212 props[props_idx]->name = xstrdup (SmCurrentDirectory);
213 props[props_idx]->type = xstrdup (SmARRAY8);
214 props[props_idx]->num_vals = 1;
215 props[props_idx]->vals = &values[val_idx++];
216 props[props_idx]->vals[0].length = strlen (cwd);
217 props[props_idx]->vals[0].value = cwd;
218 ++props_idx;
222 /* How to restart Emacs. */
223 props[props_idx] = &prop_ptr[props_idx];
224 props[props_idx]->name = xstrdup (SmRestartCommand);
225 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
226 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */
227 if (INT_MAX - 3 < initial_argc)
228 memory_full (SIZE_MAX);
229 i = 3 + initial_argc;
230 props[props_idx]->num_vals = i;
231 vp = xnmalloc (i, sizeof *vp);
232 props[props_idx]->vals = vp;
233 props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
234 props[props_idx]->vals[vp_idx++].value = emacs_program;
236 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
237 strcpy (stpcpy (smid_opt, SMID_OPT), client_id);
239 props[props_idx]->vals[vp_idx].length = strlen (smid_opt);
240 props[props_idx]->vals[vp_idx++].value = smid_opt;
242 props[props_idx]->vals[vp_idx].length = strlen (NOSPLASH_OPT);
243 props[props_idx]->vals[vp_idx++].value = NOSPLASH_OPT;
245 if (cwd)
247 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
248 strcpy (stpcpy (chdir_opt, CHDIR_OPT), cwd);
250 props[props_idx]->vals[vp_idx].length = strlen (chdir_opt);
251 props[props_idx]->vals[vp_idx++].value = chdir_opt;
254 for (i = 1; i < initial_argc; ++i)
256 props[props_idx]->vals[vp_idx].length = strlen (initial_argv[i]);
257 props[props_idx]->vals[vp_idx++].value = initial_argv[i];
260 ++props_idx;
262 SmcSetProperties (smcConn, props_idx, props);
264 xfree (smid_opt);
265 xfree (chdir_opt);
266 xfree (cwd);
267 xfree (vp);
269 for (i = 0; i < props_idx; ++i)
271 xfree (props[i]->type);
272 xfree (props[i]->name);
275 /* See if we maybe shall interact with the user. */
276 if (interactStyle != SmInteractStyleAny
277 || ! shutdown
278 || saveType == SmSaveLocal
279 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
281 /* No interaction, we are done saving ourself. */
282 SmcSaveYourselfDone (smcConn, True);
286 /* According to the SM specification, this shall close the connection. */
288 static void
289 smc_die_CB (SmcConn smcConn, SmPointer clientData)
291 emacs_event.kind = SAVE_SESSION_EVENT;
292 emacs_event.arg = Qt;
295 /* We don't use the next two but they are mandatory, leave them empty.
296 According to the SM specification, we should not interact with the
297 user between smc_save_yourself_CB is called and until smc_save_complete_CB
298 is called. It seems like a lot of job to implement this and it doesn't
299 even seem necessary. */
301 static void
302 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
304 /* Empty */
307 static void
308 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
310 /* Empty */
313 /* Error handlers for SM and ICE. We don't want to exit Emacs just
314 because there is some error in the session management. */
316 static void
317 smc_error_handler (SmcConn smcConn,
318 Bool swap,
319 int offendingMinorOpcode,
320 unsigned long offendingSequence,
321 int errorClass,
322 int severity,
323 SmPointer values)
325 /* Empty */
328 static void
329 ice_error_handler (IceConn iceConn,
330 Bool swap,
331 int offendingMinorOpcode,
332 unsigned long offendingSequence,
333 int errorClass,
334 int severity,
335 IcePointer values)
337 /* Empty */
341 static void
342 ice_io_error_handler (IceConn iceConn)
344 /* Connection probably gone. */
345 ice_connection_closed ();
348 /* This is called when the ICE connection is created or closed. The SM library
349 uses ICE as it transport protocol. */
351 static void
352 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData,
353 int opening, IcePointer *watchData)
355 if (! opening)
357 ice_connection_closed ();
358 return;
361 ice_fd = IceConnectionNumber (iceConn);
362 add_read_fd (ice_fd, x_session_check_input, NULL);
365 /* Create the client leader window. */
367 #ifndef USE_GTK
368 static void
369 create_client_leader_window (struct x_display_info *dpyinfo, char *client_ID)
371 Window w;
372 XClassHint class_hints;
374 w = XCreateSimpleWindow (dpyinfo->display,
375 dpyinfo->root_window,
376 -1, -1, 1, 1,
377 CopyFromParent, CopyFromParent, CopyFromParent);
379 validate_x_resource_name ();
380 class_hints.res_name = SSDATA (Vx_resource_name);
381 class_hints.res_class = SSDATA (Vx_resource_class);
382 XSetClassHint (dpyinfo->display, w, &class_hints);
383 XStoreName (dpyinfo->display, w, class_hints.res_name);
385 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
386 XA_STRING, 8, PropModeReplace,
387 (unsigned char *) client_ID, strlen (client_ID));
389 dpyinfo->client_leader_window = w;
391 #endif /* ! USE_GTK */
394 /* Try to open a connection to the session manager. */
396 void
397 x_session_initialize (struct x_display_info *dpyinfo)
399 #define SM_ERRORSTRING_LEN 512
400 char errorstring[SM_ERRORSTRING_LEN];
401 char *previous_id = NULL;
402 SmcCallbacks callbacks;
403 ptrdiff_t name_len = 0;
405 ice_fd = -1;
406 doing_interact = false;
408 /* Check if we where started by the session manager. If so, we will
409 have a previous id. */
410 if (STRINGP (Vx_session_previous_id))
411 previous_id = SSDATA (Vx_session_previous_id);
413 /* Construct the path to the Emacs program. */
414 if (STRINGP (Vinvocation_directory))
415 name_len += SBYTES (Vinvocation_directory);
416 if (STRINGP (Vinvocation_name))
417 name_len += SBYTES (Vinvocation_name);
419 /* This malloc will not be freed, but it is only done once, and hopefully
420 not very large */
421 emacs_program = xmalloc (name_len + 1);
422 char *z = emacs_program;
424 if (STRINGP (Vinvocation_directory))
425 z = lispstpcpy (z, Vinvocation_directory);
426 if (STRINGP (Vinvocation_name))
427 lispstpcpy (z, Vinvocation_name);
429 /* The SM protocol says all callbacks are mandatory, so set up all
430 here and in the mask passed to SmcOpenConnection. */
431 callbacks.save_yourself.callback = smc_save_yourself_CB;
432 callbacks.save_yourself.client_data = 0;
433 callbacks.die.callback = smc_die_CB;
434 callbacks.die.client_data = 0;
435 callbacks.save_complete.callback = smc_save_complete_CB;
436 callbacks.save_complete.client_data = 0;
437 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
438 callbacks.shutdown_cancelled.client_data = 0;
440 /* Set error handlers. */
441 SmcSetErrorHandler (smc_error_handler);
442 IceSetErrorHandler (ice_error_handler);
443 IceSetIOErrorHandler (ice_io_error_handler);
445 /* Install callback for when connection status changes. */
446 IceAddConnectionWatch (ice_conn_watch_CB, 0);
448 /* Open the connection to the session manager. A failure is not
449 critical, it usually means that no session manager is running.
450 The errorstring is here for debugging. */
451 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
452 (SmcSaveYourselfProcMask|
453 SmcDieProcMask|
454 SmcSaveCompleteProcMask|
455 SmcShutdownCancelledProcMask),
456 &callbacks,
457 previous_id,
458 &client_id,
459 SM_ERRORSTRING_LEN,
460 errorstring);
462 if (smc_conn != 0)
464 Vx_session_id = build_string (client_id);
466 #ifdef USE_GTK
467 /* GTK creates a leader window by itself, but we need to tell
468 it about our client_id. */
469 gdk_x11_set_sm_client_id (client_id);
470 #else
471 create_client_leader_window (dpyinfo, client_id);
472 #endif
476 /* Ensure that the session manager is not contacted again. */
478 void
479 x_session_close (void)
481 ice_connection_closed ();
485 DEFUN ("handle-save-session", Fhandle_save_session,
486 Shandle_save_session, 1, 1, "e",
487 doc: /* Handle the save_yourself event from a session manager.
488 A session manager can tell Emacs that the window system is shutting down
489 by sending Emacs a save_yourself message. Emacs executes this function when
490 such an event occurs. This function then executes `emacs-session-save'.
491 After that, this function informs the session manager that it can continue
492 or abort shutting down the window system depending on the return value
493 from `emacs-session-save' If the return value is non-nil the session manager
494 is told to abort the window system shutdown.
496 Do not call this function yourself. */)
497 (Lisp_Object event)
499 bool kill_emacs = (CONSP (event) && CONSP (XCDR (event))
500 && EQ (Qt, XCAR (XCDR (event))));
502 /* Check doing_interact so that we don't do anything if someone called
503 this at the wrong time. */
504 if (doing_interact && ! kill_emacs)
506 bool cancel_shutdown = ! NILP (call0 (intern ("emacs-session-save")));
508 SmcInteractDone (smc_conn, cancel_shutdown);
509 SmcSaveYourselfDone (smc_conn, True);
511 doing_interact = false;
513 else if (kill_emacs)
515 /* We should not do user interaction here, but it is not easy to
516 prevent. Fix this in next version. */
517 Fkill_emacs (Qnil);
519 #if false
520 /* This will not be reached, but we want kill-emacs-hook to be run. */
521 SmcCloseConnection (smc_conn, 0, 0);
522 ice_connection_closed ();
523 #endif
526 return Qnil;
531 /***********************************************************************
532 Initialization
533 ***********************************************************************/
534 void
535 syms_of_xsmfns (void)
537 DEFVAR_LISP ("x-session-id", Vx_session_id,
538 doc: /* The session id Emacs got from the session manager for this session.
539 Changing the value does not change the session id used by Emacs.
540 The value is nil if no session manager is running.
541 See also `x-session-previous-id', `emacs-save-session-functions',
542 `emacs-session-save' and `emacs-session-restore'." */);
543 Vx_session_id = Qnil;
545 DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
546 doc: /* The previous session id Emacs got from session manager.
547 If Emacs is running on a window system that has a session manager, the
548 session manager gives Emacs a session id. It is feasible for Emacs Lisp
549 code to use the session id to save configuration in, for example, a file
550 with a file name based on the session id. If Emacs is running when the
551 window system is shut down, the session manager remembers that Emacs was
552 running and saves the session id Emacs had.
554 When the window system is started again, the session manager restarts
555 Emacs and hands Emacs the session id it had the last time it was
556 running. This is now the previous session id and the value of this
557 variable. If configuration was saved in a file as stated above, the
558 previous session id shall be used to reconstruct the file name.
560 The session id Emacs has while it is running is in the variable
561 `x-session-id'. The value of this variable and `x-session-id' may be the
562 same, depending on how the session manager works.
564 See also `emacs-save-session-functions', `emacs-session-save' and
565 `emacs-session-restore'." */);
566 Vx_session_previous_id = Qnil;
568 defsubr (&Shandle_save_session);
571 #endif /* HAVE_X_SM */