]> code.delx.au - gnu-emacs/blob - src/xsmfns.c
Convert consecutive FSF copyright years to ranges.
[gnu-emacs] / src / xsmfns.c
1 /* Session management module for systems which understand the X Session
2 management protocol.
3 Copyright (C) 2002-2011
4 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 <stdio.h>
32 #include <setjmp.h>
33
34 #include "lisp.h"
35 #include "systime.h"
36 #include "sysselect.h"
37 #include "frame.h"
38 #include "termhooks.h"
39 #include "termopts.h"
40 #include "xterm.h"
41
42 /* This is the event used when SAVE_SESSION_EVENT occurs. */
43
44 static struct input_event emacs_event;
45
46 /* The descriptor that we use to check for data from the session manager. */
47
48 static int ice_fd;
49
50 /* A flag that says if we are in shutdown interactions or not. */
51
52 static int doing_interact;
53
54 /* The session manager object for the session manager connection. */
55
56 static SmcConn smc_conn;
57
58 /* The client session id for this session. */
59
60 static char *client_id;
61
62 /* The full path name to the Emacs program. */
63
64 static char *emacs_program;
65
66 /* The option we tell the session manager to start Emacs with when
67 restarting Emacs. The client_id is appended. */
68
69 #define SMID_OPT "--smid="
70
71
72 /* The option to start Emacs without the splash screen when
73 restarting Emacs. */
74
75 static char NOSPLASH_OPT[] = "--no-splash";
76
77 /* The option to make Emacs start in the given directory. */
78
79 #define CHDIR_OPT "--chdir="
80
81 static void
82 ice_connection_closed (void)
83 {
84 if (ice_fd >= 0)
85 delete_keyboard_wait_descriptor (ice_fd);
86 ice_fd = -1;
87 }
88
89
90 /* Handle any messages from the session manager. If no connection is
91 open to a session manager, just return 0.
92 Otherwise returns 1 if SAVE_SESSION_EVENT is stored in buffer BUFP. */
93
94 int
95 x_session_check_input (struct input_event *bufp)
96 {
97 SELECT_TYPE read_fds;
98 EMACS_TIME tmout;
99 int ret;
100
101 if (ice_fd == -1) return 0;
102 FD_ZERO (&read_fds);
103 FD_SET (ice_fd, &read_fds);
104
105 tmout.tv_sec = 0;
106 tmout.tv_usec = 0;
107
108 /* Reset this so wo can check kind after callbacks have been called by
109 IceProcessMessages. The smc_interact_CB sets the kind to
110 SAVE_SESSION_EVENT, but we don't know beforehand if that callback
111 will be called. */
112 emacs_event.kind = NO_EVENT;
113
114 ret = select (ice_fd+1, &read_fds,
115 (SELECT_TYPE *)0, (SELECT_TYPE *)0, &tmout);
116
117 if (ret < 0)
118 {
119 ice_connection_closed ();
120 }
121 else if (ret > 0 && FD_ISSET (ice_fd, &read_fds))
122 {
123 ret = IceProcessMessages (SmcGetIceConnection (smc_conn),
124 (IceReplyWaitInfo *)0, (Bool *)0);
125 if (ret != IceProcessMessagesSuccess)
126 {
127 /* Either IO error or Connection closed. */
128 if (ret == IceProcessMessagesIOError)
129 IceCloseConnection (SmcGetIceConnection (smc_conn));
130
131 ice_connection_closed ();
132 }
133 }
134
135 /* Check if smc_interact_CB was called and we shall generate a
136 SAVE_SESSION_EVENT. */
137 if (emacs_event.kind != NO_EVENT)
138 memcpy (bufp, &emacs_event, sizeof (struct input_event));
139
140 return emacs_event.kind != NO_EVENT ? 1 : 0;
141 }
142
143 /* Return non-zero if we have a connection to a session manager. */
144
145 int
146 x_session_have_connection (void)
147 {
148 return ice_fd != -1;
149 }
150
151 /* This is called when the session manager says it is OK to interact with the
152 user. Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
153 Then lisp code can interact with the user. */
154
155 static void
156 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
157 {
158 doing_interact = True;
159 emacs_event.kind = SAVE_SESSION_EVENT;
160 emacs_event.arg = Qnil;
161 }
162
163 /* This is called when the session manager tells us to save ourselves.
164 We set the required properties so the session manager can restart us,
165 plus the current working directory property (not mandatory) so we
166 are started in the correct directory.
167
168 If this is a shutdown and we can request to interact with the user,
169 we do so, because we don't know what the lisp code might do. */
170
171 static void
172 smc_save_yourself_CB (SmcConn smcConn,
173 SmPointer clientData,
174 int saveType,
175 Bool shutdown,
176 int interactStyle,
177 Bool fast)
178 {
179 #define NR_PROPS 5
180
181 SmProp *props[NR_PROPS];
182 SmProp prop_ptr[NR_PROPS];
183
184 SmPropValue values[20];
185 int val_idx = 0;
186 int props_idx = 0;
187 int i;
188 char *cwd = NULL;
189 char *smid_opt, *chdir_opt = NULL;
190
191 /* How to start a new instance of Emacs. */
192 props[props_idx] = &prop_ptr[props_idx];
193 props[props_idx]->name = xstrdup (SmCloneCommand);
194 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
195 props[props_idx]->num_vals = 1;
196 props[props_idx]->vals = &values[val_idx++];
197 props[props_idx]->vals[0].length = strlen (emacs_program);
198 props[props_idx]->vals[0].value = emacs_program;
199 ++props_idx;
200
201 /* The name of the program. */
202 props[props_idx] = &prop_ptr[props_idx];
203 props[props_idx]->name = xstrdup (SmProgram);
204 props[props_idx]->type = xstrdup (SmARRAY8);
205 props[props_idx]->num_vals = 1;
206 props[props_idx]->vals = &values[val_idx++];
207 props[props_idx]->vals[0].length = strlen (SSDATA (Vinvocation_name));
208 props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
209 ++props_idx;
210
211 /* How to restart Emacs. */
212 props[props_idx] = &prop_ptr[props_idx];
213 props[props_idx]->name = xstrdup (SmRestartCommand);
214 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
215 /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir */
216 props[props_idx]->num_vals = 4;
217 props[props_idx]->vals = &values[val_idx];
218 props[props_idx]->vals[0].length = strlen (emacs_program);
219 props[props_idx]->vals[0].value = emacs_program;
220
221 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
222 strcpy (smid_opt, SMID_OPT);
223 strcat (smid_opt, client_id);
224
225 props[props_idx]->vals[1].length = strlen (smid_opt);
226 props[props_idx]->vals[1].value = smid_opt;
227
228 props[props_idx]->vals[2].length = strlen (NOSPLASH_OPT);
229 props[props_idx]->vals[2].value = NOSPLASH_OPT;
230
231 cwd = get_current_dir_name ();
232 if (cwd)
233 {
234 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
235 strcpy (chdir_opt, CHDIR_OPT);
236 strcat (chdir_opt, cwd);
237
238 props[props_idx]->vals[3].length = strlen (chdir_opt);
239 props[props_idx]->vals[3].value = chdir_opt;
240 }
241
242 val_idx += cwd ? 4 : 3;
243 ++props_idx;
244
245 /* User id. */
246 props[props_idx] = &prop_ptr[props_idx];
247 props[props_idx]->name = xstrdup (SmUserID);
248 props[props_idx]->type = xstrdup (SmARRAY8);
249 props[props_idx]->num_vals = 1;
250 props[props_idx]->vals = &values[val_idx++];
251 props[props_idx]->vals[0].length = strlen (SSDATA (Vuser_login_name));
252 props[props_idx]->vals[0].value = SDATA (Vuser_login_name);
253 ++props_idx;
254
255
256 if (cwd)
257 {
258 props[props_idx] = &prop_ptr[props_idx];
259 props[props_idx]->name = xstrdup (SmCurrentDirectory);
260 props[props_idx]->type = xstrdup (SmARRAY8);
261 props[props_idx]->num_vals = 1;
262 props[props_idx]->vals = &values[val_idx++];
263 props[props_idx]->vals[0].length = strlen (cwd);
264 props[props_idx]->vals[0].value = cwd;
265 ++props_idx;
266 }
267
268
269 SmcSetProperties (smcConn, props_idx, props);
270
271 xfree (smid_opt);
272 xfree (chdir_opt);
273
274 free (cwd);
275 for (i = 0; i < props_idx; ++i)
276 {
277 xfree (props[i]->type);
278 xfree (props[i]->name);
279 }
280
281 /* See if we maybe shall interact with the user. */
282 if (interactStyle != SmInteractStyleAny
283 || ! shutdown
284 || saveType == SmSaveLocal
285 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
286 {
287 /* No interaction, we are done saving ourself. */
288 SmcSaveYourselfDone (smcConn, True);
289 }
290 }
291
292 /* According to the SM specification, this shall close the connection. */
293
294 static void
295 smc_die_CB (SmcConn smcConn, SmPointer clientData)
296 {
297 emacs_event.kind = SAVE_SESSION_EVENT;
298 emacs_event.arg = Qt;
299 }
300
301 /* We don't use the next two but they are mandatory, leave them empty.
302 According to the SM specification, we should not interact with the
303 user between smc_save_yourself_CB is called and until smc_save_complete_CB
304 is called. It seems like a lot of job to implement this and it doesn't
305 even seem necessary. */
306
307 static void
308 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
309 {
310 /* Empty */
311 }
312
313 static void
314 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
315 {
316 /* Empty */
317 }
318
319 /* Error handlers for SM and ICE. We don't want to exit Emacs just
320 because there is some error in the session management. */
321
322 static void
323 smc_error_handler (SmcConn smcConn,
324 Bool swap,
325 int offendingMinorOpcode,
326 unsigned long offendingSequence,
327 int errorClass,
328 int severity,
329 SmPointer values)
330 {
331 /* Empty */
332 }
333
334 static void
335 ice_error_handler (IceConn iceConn,
336 Bool swap,
337 int offendingMinorOpcode,
338 unsigned long offendingSequence,
339 int errorClass,
340 int severity,
341 IcePointer values)
342 {
343 /* Empty */
344 }
345
346
347 static void
348 ice_io_error_handler (IceConn iceConn)
349 {
350 /* Connection probably gone. */
351 ice_connection_closed ();
352 }
353
354 /* This is called when the ICE connection is created or closed. The SM library
355 uses ICE as it transport protocol. */
356
357 static void
358 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData, int opening, IcePointer *watchData)
359 {
360 if (! opening)
361 {
362 ice_connection_closed ();
363 return;
364 }
365
366 ice_fd = IceConnectionNumber (iceConn);
367 #ifdef F_SETOWN
368 fcntl (ice_fd, F_SETOWN, getpid ());
369 #endif /* ! defined (F_SETOWN) */
370
371 #ifdef SIGIO
372 if (interrupt_input)
373 init_sigio (ice_fd);
374 #endif /* ! defined (SIGIO) */
375
376 add_keyboard_wait_descriptor (ice_fd);
377 }
378
379 /* Create the client leader window. */
380
381 #ifndef USE_GTK
382 static void
383 create_client_leader_window (struct x_display_info *dpyinfo, char *client_id)
384 {
385 Window w;
386 XClassHint class_hints;
387 Atom sm_id;
388
389 w = XCreateSimpleWindow (dpyinfo->display,
390 dpyinfo->root_window,
391 -1, -1, 1, 1,
392 CopyFromParent, CopyFromParent, CopyFromParent);
393
394 class_hints.res_name = SSDATA (Vx_resource_name);
395 class_hints.res_class = SSDATA (Vx_resource_class);
396 XSetClassHint (dpyinfo->display, w, &class_hints);
397 XStoreName (dpyinfo->display, w, class_hints.res_name);
398
399 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
400 XA_STRING, 8, PropModeReplace,
401 (unsigned char *)client_id, strlen (client_id));
402
403 dpyinfo->client_leader_window = w;
404 }
405 #endif /* ! USE_GTK */
406
407
408 /* Try to open a connection to the session manager. */
409
410 void
411 x_session_initialize (struct x_display_info *dpyinfo)
412 {
413 #define SM_ERRORSTRING_LEN 512
414 char errorstring[SM_ERRORSTRING_LEN];
415 char* previous_id = NULL;
416 SmcCallbacks callbacks;
417 int name_len = 0;
418
419 ice_fd = -1;
420 doing_interact = False;
421
422 /* Check if we where started by the session manager. If so, we will
423 have a previous id. */
424 if (! EQ (Vx_session_previous_id, Qnil) && STRINGP (Vx_session_previous_id))
425 previous_id = SSDATA (Vx_session_previous_id);
426
427 /* Construct the path to the Emacs program. */
428 if (! EQ (Vinvocation_directory, Qnil))
429 name_len += strlen (SSDATA (Vinvocation_directory));
430 name_len += strlen (SSDATA (Vinvocation_name));
431
432 /* This malloc will not be freed, but it is only done once, and hopefully
433 not very large */
434 emacs_program = xmalloc (name_len + 1);
435 emacs_program[0] = '\0';
436
437 if (! EQ (Vinvocation_directory, Qnil))
438 strcpy (emacs_program, SSDATA (Vinvocation_directory));
439 strcat (emacs_program, SSDATA (Vinvocation_name));
440
441 /* The SM protocol says all callbacks are mandatory, so set up all
442 here and in the mask passed to SmcOpenConnection. */
443 callbacks.save_yourself.callback = smc_save_yourself_CB;
444 callbacks.save_yourself.client_data = 0;
445 callbacks.die.callback = smc_die_CB;
446 callbacks.die.client_data = 0;
447 callbacks.save_complete.callback = smc_save_complete_CB;
448 callbacks.save_complete.client_data = 0;
449 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
450 callbacks.shutdown_cancelled.client_data = 0;
451
452 /* Set error handlers. */
453 SmcSetErrorHandler (smc_error_handler);
454 IceSetErrorHandler (ice_error_handler);
455 IceSetIOErrorHandler (ice_io_error_handler);
456
457 /* Install callback for when connection status changes. */
458 IceAddConnectionWatch (ice_conn_watch_CB, 0);
459
460 /* Open the connection to the session manager. A failure is not
461 critical, it usually means that no session manager is running.
462 The errorstring is here for debugging. */
463 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
464 (SmcSaveYourselfProcMask|
465 SmcDieProcMask|
466 SmcSaveCompleteProcMask|
467 SmcShutdownCancelledProcMask),
468 &callbacks,
469 previous_id,
470 &client_id,
471 SM_ERRORSTRING_LEN,
472 errorstring);
473
474 if (smc_conn != 0)
475 {
476 Vx_session_id = make_string (client_id, strlen (client_id));
477
478 #ifdef USE_GTK
479 /* GTK creats a leader window by itself, but we need to tell
480 it about our client_id. */
481 gdk_set_sm_client_id (client_id);
482 #else
483 create_client_leader_window (dpyinfo, client_id);
484 #endif
485 }
486 }
487
488 /* Ensure that the session manager is not contacted again. */
489
490 void
491 x_session_close (void)
492 {
493 ice_connection_closed ();
494 }
495
496
497 DEFUN ("handle-save-session", Fhandle_save_session,
498 Shandle_save_session, 1, 1, "e",
499 doc: /* Handle the save_yourself event from a session manager.
500 A session manager can tell Emacs that the window system is shutting down
501 by sending Emacs a save_yourself message. Emacs executes this function when
502 such an event occurs. This function then executes `emacs-session-save'.
503 After that, this function informs the session manager that it can continue
504 or abort shutting down the window system depending on the return value
505 from `emacs-session-save' If the return value is non-nil the session manager
506 is told to abort the window system shutdown.
507
508 Do not call this function yourself. */)
509 (Lisp_Object event)
510 {
511 int kill_emacs = CONSP (event) && CONSP (XCDR (event))
512 && EQ (Qt, XCAR (XCDR (event)));
513
514 /* Check doing_interact so that we don't do anything if someone called
515 this at the wrong time. */
516 if (doing_interact && ! kill_emacs)
517 {
518 Bool cancel_shutdown = False;
519
520 cancel_shutdown = ! EQ (call0 (intern ("emacs-session-save")), Qnil);
521
522 SmcInteractDone (smc_conn, cancel_shutdown);
523 SmcSaveYourselfDone (smc_conn, True);
524
525 doing_interact = False;
526 }
527 else if (kill_emacs)
528 {
529 /* We should not do user interaction here, but it is not easy to
530 prevent. Fix this in next version. */
531 Fkill_emacs (Qnil);
532
533 /* This will not be reached, but we want kill-emacs-hook to be run. */
534 SmcCloseConnection (smc_conn, 0, 0);
535 ice_connection_closed ();
536 }
537
538 return Qnil;
539 }
540
541
542 \f
543 /***********************************************************************
544 Initialization
545 ***********************************************************************/
546 void
547 syms_of_xsmfns (void)
548 {
549 DEFVAR_LISP ("x-session-id", Vx_session_id,
550 doc: /* The session id Emacs got from the session manager for this session.
551 Changing the value does not change the session id used by Emacs.
552 The value is nil if no session manager is running.
553 See also `x-session-previous-id', `emacs-save-session-functions',
554 `emacs-session-save' and `emacs-session-restore'." */);
555 Vx_session_id = Qnil;
556
557 DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
558 doc: /* The previous session id Emacs got from session manager.
559 If Emacs is running on a window system that has a session manager, the
560 session manager gives Emacs a session id. It is feasible for Emacs Lisp
561 code to use the session id to save configuration in, for example, a file
562 with a file name based on the session id. If Emacs is running when the
563 window system is shut down, the session manager remembers that Emacs was
564 running and saves the session id Emacs had.
565
566 When the window system is started again, the session manager restarts
567 Emacs and hands Emacs the session id it had the last time it was
568 running. This is now the previous session id and the value of this
569 variable. If configuration was saved in a file as stated above, the
570 previous session id shall be used to reconstruct the file name.
571
572 The session id Emacs has while it is running is in the variable
573 `x-session-id'. The value of this variable and `x-session-id' may be the
574 same, depending on how the session manager works.
575
576 See also `emacs-save-session-functions', `emacs-session-save' and
577 `emacs-session-restore'." */);
578 Vx_session_previous_id = Qnil;
579
580 defsubr (&Shandle_save_session);
581 }
582
583 #endif /* HAVE_X_SM */