]> code.delx.au - gnu-emacs/blob - src/xsmfns.c
Include-file cleanup for src directory
[gnu-emacs] / src / xsmfns.c
1 /* Session management module for systems which understand the X Session
2 management protocol.
3
4 Copyright (C) 2002-2015 Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
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.
12
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.
17
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/>. */
20
21 #include <config.h>
22
23 #ifdef HAVE_X_SM
24
25 #include <X11/SM/SMlib.h>
26 #include <X11/Xlib.h>
27 #include <X11/Xutil.h>
28
29 #include <unistd.h>
30 #include <sys/param.h>
31 #include <errno.h>
32 #include <stdio.h>
33
34 #include "lisp.h"
35 #include "frame.h"
36 #include "termhooks.h"
37 #include "xterm.h"
38 #include "process.h"
39 #include "keyboard.h"
40
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
44
45 /* This is the event used when SAVE_SESSION_EVENT occurs. */
46
47 static struct input_event emacs_event;
48
49 /* The descriptor that we use to check for data from the session manager. */
50
51 static int ice_fd = -1;
52
53 /* A flag that says if we are in shutdown interactions or not. */
54
55 static bool doing_interact;
56
57 /* The session manager object for the session manager connection. */
58
59 static SmcConn smc_conn;
60
61 /* The client session id for this session. */
62
63 static char *client_id;
64
65 /* The full path name to the Emacs program. */
66
67 static char *emacs_program;
68
69 /* The option we tell the session manager to start Emacs with when
70 restarting Emacs. The client_id is appended. */
71
72 #define SMID_OPT "--smid="
73
74
75 /* The option to start Emacs without the splash screen when
76 restarting Emacs. */
77
78 static char NOSPLASH_OPT[] = "--no-splash";
79
80 /* The option to make Emacs start in the given directory. */
81
82 #define CHDIR_OPT "--chdir="
83
84 static void
85 ice_connection_closed (void)
86 {
87 if (ice_fd >= 0)
88 delete_read_fd (ice_fd);
89 ice_fd = -1;
90 }
91
92
93 /* Handle any messages from the session manager. If no connection is
94 open to a session manager, just return. */
95
96 static void
97 x_session_check_input (int fd, void *data)
98 {
99 int ret;
100
101 if (ice_fd == -1) return;
102
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;
108
109 ret = IceProcessMessages (SmcGetIceConnection (smc_conn), 0, 0);
110 if (ret != IceProcessMessagesSuccess)
111 {
112 /* Either IO error or Connection closed. */
113 if (ret == IceProcessMessagesIOError)
114 IceCloseConnection (SmcGetIceConnection (smc_conn));
115
116 ice_connection_closed ();
117 }
118
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);
123 }
124
125 /* Return true if we have a connection to a session manager. */
126
127 bool
128 x_session_have_connection (void)
129 {
130 return ice_fd != -1;
131 }
132
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. */
136
137 static void
138 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
139 {
140 doing_interact = true;
141 emacs_event.kind = SAVE_SESSION_EVENT;
142 emacs_event.arg = Qnil;
143 }
144
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.
149
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. */
152
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)
160 {
161 #define NR_PROPS 5
162
163 SmProp *props[NR_PROPS];
164 SmProp prop_ptr[NR_PROPS];
165
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);
172
173 // Must have these.
174 if (! STRINGP (Vinvocation_name) || ! STRINGP (user_login_name))
175 return;
176
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;
186
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;
196
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;
206
207 char *cwd = get_current_dir_name ();
208 if (cwd)
209 {
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;
218 }
219
220
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_MAX - 3 < initial_argc)
227 memory_full (SIZE_MAX);
228 i = 3 + initial_argc;
229 props[props_idx]->num_vals = i;
230 vp = xnmalloc (i, sizeof *vp);
231 props[props_idx]->vals = vp;
232 props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
233 props[props_idx]->vals[vp_idx++].value = emacs_program;
234
235 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
236 strcpy (stpcpy (smid_opt, SMID_OPT), client_id);
237
238 props[props_idx]->vals[vp_idx].length = strlen (smid_opt);
239 props[props_idx]->vals[vp_idx++].value = smid_opt;
240
241 props[props_idx]->vals[vp_idx].length = strlen (NOSPLASH_OPT);
242 props[props_idx]->vals[vp_idx++].value = NOSPLASH_OPT;
243
244 if (cwd)
245 {
246 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
247 strcpy (stpcpy (chdir_opt, CHDIR_OPT), cwd);
248
249 props[props_idx]->vals[vp_idx].length = strlen (chdir_opt);
250 props[props_idx]->vals[vp_idx++].value = chdir_opt;
251 }
252
253 for (i = 1; i < initial_argc; ++i)
254 {
255 props[props_idx]->vals[vp_idx].length = strlen (initial_argv[i]);
256 props[props_idx]->vals[vp_idx++].value = initial_argv[i];
257 }
258
259 ++props_idx;
260
261 SmcSetProperties (smcConn, props_idx, props);
262
263 xfree (smid_opt);
264 xfree (chdir_opt);
265 xfree (cwd);
266 xfree (vp);
267
268 for (i = 0; i < props_idx; ++i)
269 {
270 xfree (props[i]->type);
271 xfree (props[i]->name);
272 }
273
274 /* See if we maybe shall interact with the user. */
275 if (interactStyle != SmInteractStyleAny
276 || ! shutdown
277 || saveType == SmSaveLocal
278 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
279 {
280 /* No interaction, we are done saving ourself. */
281 SmcSaveYourselfDone (smcConn, True);
282 }
283 }
284
285 /* According to the SM specification, this shall close the connection. */
286
287 static void
288 smc_die_CB (SmcConn smcConn, SmPointer clientData)
289 {
290 emacs_event.kind = SAVE_SESSION_EVENT;
291 emacs_event.arg = Qt;
292 }
293
294 /* We don't use the next two but they are mandatory, leave them empty.
295 According to the SM specification, we should not interact with the
296 user between smc_save_yourself_CB is called and until smc_save_complete_CB
297 is called. It seems like a lot of job to implement this and it doesn't
298 even seem necessary. */
299
300 static void
301 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
302 {
303 /* Empty */
304 }
305
306 static void
307 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
308 {
309 /* Empty */
310 }
311
312 /* Error handlers for SM and ICE. We don't want to exit Emacs just
313 because there is some error in the session management. */
314
315 static void
316 smc_error_handler (SmcConn smcConn,
317 Bool swap,
318 int offendingMinorOpcode,
319 unsigned long offendingSequence,
320 int errorClass,
321 int severity,
322 SmPointer values)
323 {
324 /* Empty */
325 }
326
327 static void
328 ice_error_handler (IceConn iceConn,
329 Bool swap,
330 int offendingMinorOpcode,
331 unsigned long offendingSequence,
332 int errorClass,
333 int severity,
334 IcePointer values)
335 {
336 /* Empty */
337 }
338
339
340 static void
341 ice_io_error_handler (IceConn iceConn)
342 {
343 /* Connection probably gone. */
344 ice_connection_closed ();
345 }
346
347 /* This is called when the ICE connection is created or closed. The SM library
348 uses ICE as it transport protocol. */
349
350 static void
351 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData,
352 int opening, IcePointer *watchData)
353 {
354 if (! opening)
355 {
356 ice_connection_closed ();
357 return;
358 }
359
360 ice_fd = IceConnectionNumber (iceConn);
361 add_read_fd (ice_fd, x_session_check_input, NULL);
362 }
363
364 /* Create the client leader window. */
365
366 #ifndef USE_GTK
367 static void
368 create_client_leader_window (struct x_display_info *dpyinfo, char *client_ID)
369 {
370 Window w;
371 XClassHint class_hints;
372
373 w = XCreateSimpleWindow (dpyinfo->display,
374 dpyinfo->root_window,
375 -1, -1, 1, 1,
376 CopyFromParent, CopyFromParent, CopyFromParent);
377
378 validate_x_resource_name ();
379 class_hints.res_name = SSDATA (Vx_resource_name);
380 class_hints.res_class = SSDATA (Vx_resource_class);
381 XSetClassHint (dpyinfo->display, w, &class_hints);
382 XStoreName (dpyinfo->display, w, class_hints.res_name);
383
384 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
385 XA_STRING, 8, PropModeReplace,
386 (unsigned char *) client_ID, strlen (client_ID));
387
388 dpyinfo->client_leader_window = w;
389 }
390 #endif /* ! USE_GTK */
391
392
393 /* Try to open a connection to the session manager. */
394
395 void
396 x_session_initialize (struct x_display_info *dpyinfo)
397 {
398 #define SM_ERRORSTRING_LEN 512
399 char errorstring[SM_ERRORSTRING_LEN];
400 char *previous_id = NULL;
401 SmcCallbacks callbacks;
402 ptrdiff_t name_len = 0;
403
404 /* libSM seems to crash if pwd is missing - see bug#18851. */
405 if (! get_current_dir_name ())
406 {
407 fprintf (stderr, "Disabling session management due to pwd error: %s\n",
408 emacs_strerror (errno));
409 return;
410 }
411
412 ice_fd = -1;
413 doing_interact = false;
414
415 /* Check if we where started by the session manager. If so, we will
416 have a previous id. */
417 if (STRINGP (Vx_session_previous_id))
418 previous_id = SSDATA (Vx_session_previous_id);
419
420 /* Construct the path to the Emacs program. */
421 if (STRINGP (Vinvocation_directory))
422 name_len += SBYTES (Vinvocation_directory);
423 if (STRINGP (Vinvocation_name))
424 name_len += SBYTES (Vinvocation_name);
425
426 /* This malloc will not be freed, but it is only done once, and hopefully
427 not very large */
428 emacs_program = xmalloc (name_len + 1);
429 char *z = emacs_program;
430
431 if (STRINGP (Vinvocation_directory))
432 z = lispstpcpy (z, Vinvocation_directory);
433 if (STRINGP (Vinvocation_name))
434 lispstpcpy (z, Vinvocation_name);
435
436 /* The SM protocol says all callbacks are mandatory, so set up all
437 here and in the mask passed to SmcOpenConnection. */
438 callbacks.save_yourself.callback = smc_save_yourself_CB;
439 callbacks.save_yourself.client_data = 0;
440 callbacks.die.callback = smc_die_CB;
441 callbacks.die.client_data = 0;
442 callbacks.save_complete.callback = smc_save_complete_CB;
443 callbacks.save_complete.client_data = 0;
444 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
445 callbacks.shutdown_cancelled.client_data = 0;
446
447 /* Set error handlers. */
448 SmcSetErrorHandler (smc_error_handler);
449 IceSetErrorHandler (ice_error_handler);
450 IceSetIOErrorHandler (ice_io_error_handler);
451
452 /* Install callback for when connection status changes. */
453 IceAddConnectionWatch (ice_conn_watch_CB, 0);
454
455 /* Open the connection to the session manager. A failure is not
456 critical, it usually means that no session manager is running.
457 The errorstring is here for debugging. */
458 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
459 (SmcSaveYourselfProcMask|
460 SmcDieProcMask|
461 SmcSaveCompleteProcMask|
462 SmcShutdownCancelledProcMask),
463 &callbacks,
464 previous_id,
465 &client_id,
466 SM_ERRORSTRING_LEN,
467 errorstring);
468
469 if (smc_conn != 0)
470 {
471 Vx_session_id = build_string (client_id);
472
473 #ifdef USE_GTK
474 /* GTK creates a leader window by itself, but we need to tell
475 it about our client_id. */
476 gdk_x11_set_sm_client_id (client_id);
477 #else
478 create_client_leader_window (dpyinfo, client_id);
479 #endif
480 }
481 }
482
483 /* Ensure that the session manager is not contacted again. */
484
485 void
486 x_session_close (void)
487 {
488 ice_connection_closed ();
489 }
490
491
492 DEFUN ("handle-save-session", Fhandle_save_session,
493 Shandle_save_session, 1, 1, "e",
494 doc: /* Handle the save_yourself event from a session manager.
495 A session manager can tell Emacs that the window system is shutting down
496 by sending Emacs a save_yourself message. Emacs executes this function when
497 such an event occurs. This function then executes `emacs-session-save'.
498 After that, this function informs the session manager that it can continue
499 or abort shutting down the window system depending on the return value
500 from `emacs-session-save' If the return value is non-nil the session manager
501 is told to abort the window system shutdown.
502
503 Do not call this function yourself. */)
504 (Lisp_Object event)
505 {
506 bool kill_emacs = (CONSP (event) && CONSP (XCDR (event))
507 && EQ (Qt, XCAR (XCDR (event))));
508
509 /* Check doing_interact so that we don't do anything if someone called
510 this at the wrong time. */
511 if (doing_interact && ! kill_emacs)
512 {
513 bool cancel_shutdown = ! NILP (call0 (intern ("emacs-session-save")));
514
515 SmcInteractDone (smc_conn, cancel_shutdown);
516 SmcSaveYourselfDone (smc_conn, True);
517
518 doing_interact = false;
519 }
520 else if (kill_emacs)
521 {
522 /* We should not do user interaction here, but it is not easy to
523 prevent. Fix this in next version. */
524 Fkill_emacs (Qnil);
525
526 #if false
527 /* This will not be reached, but we want kill-emacs-hook to be run. */
528 SmcCloseConnection (smc_conn, 0, 0);
529 ice_connection_closed ();
530 #endif
531 }
532
533 return Qnil;
534 }
535
536
537 \f
538 /***********************************************************************
539 Initialization
540 ***********************************************************************/
541 void
542 syms_of_xsmfns (void)
543 {
544 DEFVAR_LISP ("x-session-id", Vx_session_id,
545 doc: /* The session id Emacs got from the session manager for this session.
546 Changing the value does not change the session id used by Emacs.
547 The value is nil if no session manager is running.
548 See also `x-session-previous-id', `emacs-save-session-functions',
549 `emacs-session-save' and `emacs-session-restore'." */);
550 Vx_session_id = Qnil;
551
552 DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
553 doc: /* The previous session id Emacs got from session manager.
554 If Emacs is running on a window system that has a session manager, the
555 session manager gives Emacs a session id. It is feasible for Emacs Lisp
556 code to use the session id to save configuration in, for example, a file
557 with a file name based on the session id. If Emacs is running when the
558 window system is shut down, the session manager remembers that Emacs was
559 running and saves the session id Emacs had.
560
561 When the window system is started again, the session manager restarts
562 Emacs and hands Emacs the session id it had the last time it was
563 running. This is now the previous session id and the value of this
564 variable. If configuration was saved in a file as stated above, the
565 previous session id shall be used to reconstruct the file name.
566
567 The session id Emacs has while it is running is in the variable
568 `x-session-id'. The value of this variable and `x-session-id' may be the
569 same, depending on how the session manager works.
570
571 See also `emacs-save-session-functions', `emacs-session-save' and
572 `emacs-session-restore'." */);
573 Vx_session_previous_id = Qnil;
574
575 defsubr (&Shandle_save_session);
576 }
577
578 #endif /* HAVE_X_SM */