Merge from mainline.
[emacs.git] / src / xsmfns.c
blobd67166e48fa89aae4d56642c18ee420b3e31dad8
1 /* Session management module for systems which understand the X Session
2 management protocol.
3 Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 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>
32 #include <setjmp.h>
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"
42 /* Avoid "differ in sign" warnings */
43 #define SSDATA(x) ((char *) SDATA (x))
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;
53 /* A flag that says if we are in shutdown interactions or not. */
55 static int 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 client session id for this session as a lisp object. */
71 Lisp_Object Vx_session_id;
73 /* The id we had the previous session. This is only available if we
74 have been started by the session manager with SMID_OPT. */
76 Lisp_Object Vx_session_previous_id;
78 /* The option we tell the session manager to start Emacs with when
79 restarting Emacs. The client_id is appended. */
81 #define SMID_OPT "--smid="
84 /* The option to start Emacs without the splash screen when
85 restarting Emacs. */
87 static char NOSPLASH_OPT[] = "--no-splash";
89 /* The option to make Emacs start in the given directory. */
91 #define CHDIR_OPT "--chdir="
93 static void
94 ice_connection_closed (void)
96 if (ice_fd >= 0)
97 delete_keyboard_wait_descriptor (ice_fd);
98 ice_fd = -1;
102 /* Handle any messages from the session manager. If no connection is
103 open to a session manager, just return 0.
104 Otherwise returns 1 if SAVE_SESSION_EVENT is stored in buffer BUFP. */
107 x_session_check_input (struct input_event *bufp)
109 SELECT_TYPE read_fds;
110 EMACS_TIME tmout;
111 int ret;
113 if (ice_fd == -1) return 0;
114 FD_ZERO (&read_fds);
115 FD_SET (ice_fd, &read_fds);
117 tmout.tv_sec = 0;
118 tmout.tv_usec = 0;
120 /* Reset this so wo can check kind after callbacks have been called by
121 IceProcessMessages. The smc_interact_CB sets the kind to
122 SAVE_SESSION_EVENT, but we don't know beforehand if that callback
123 will be called. */
124 emacs_event.kind = NO_EVENT;
126 ret = select (ice_fd+1, &read_fds,
127 (SELECT_TYPE *)0, (SELECT_TYPE *)0, &tmout);
129 if (ret < 0)
131 ice_connection_closed ();
133 else if (ret > 0 && FD_ISSET (ice_fd, &read_fds))
135 ret = IceProcessMessages (SmcGetIceConnection (smc_conn),
136 (IceReplyWaitInfo *)0, (Bool *)0);
137 if (ret != IceProcessMessagesSuccess)
139 /* Either IO error or Connection closed. */
140 if (ret == IceProcessMessagesIOError)
141 IceCloseConnection (SmcGetIceConnection (smc_conn));
143 ice_connection_closed ();
147 /* Check if smc_interact_CB was called and we shall generate a
148 SAVE_SESSION_EVENT. */
149 if (emacs_event.kind != NO_EVENT)
150 memcpy (bufp, &emacs_event, sizeof (struct input_event));
152 return emacs_event.kind != NO_EVENT ? 1 : 0;
155 /* Return non-zero if we have a connection to a session manager. */
158 x_session_have_connection (void)
160 return ice_fd != -1;
163 /* This is called when the session manager says it is OK to interact with the
164 user. Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
165 Then lisp code can interact with the user. */
167 static void
168 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
170 doing_interact = True;
171 emacs_event.kind = SAVE_SESSION_EVENT;
172 emacs_event.arg = Qnil;
175 /* This is called when the session manager tells us to save ourselves.
176 We set the required properties so the session manager can restart us,
177 plus the current working directory property (not mandatory) so we
178 are started in the correct directory.
180 If this is a shutdown and we can request to interact with the user,
181 we do so, because we don't know what the lisp code might do. */
183 static void
184 smc_save_yourself_CB (SmcConn smcConn,
185 SmPointer clientData,
186 int saveType,
187 Bool shutdown,
188 int interactStyle,
189 Bool fast)
191 #define NR_PROPS 5
193 SmProp *props[NR_PROPS];
194 SmProp prop_ptr[NR_PROPS];
196 SmPropValue values[20];
197 int val_idx = 0;
198 int props_idx = 0;
199 int i;
200 char *cwd = NULL;
201 char *smid_opt, *chdir_opt = NULL;
203 /* How to start a new instance of Emacs. */
204 props[props_idx] = &prop_ptr[props_idx];
205 props[props_idx]->name = xstrdup (SmCloneCommand);
206 props[props_idx]->type = xstrdup (SmLISTofARRAY8);
207 props[props_idx]->num_vals = 1;
208 props[props_idx]->vals = &values[val_idx++];
209 props[props_idx]->vals[0].length = strlen (emacs_program);
210 props[props_idx]->vals[0].value = emacs_program;
211 ++props_idx;
213 /* The name of the program. */
214 props[props_idx] = &prop_ptr[props_idx];
215 props[props_idx]->name = xstrdup (SmProgram);
216 props[props_idx]->type = xstrdup (SmARRAY8);
217 props[props_idx]->num_vals = 1;
218 props[props_idx]->vals = &values[val_idx++];
219 props[props_idx]->vals[0].length = strlen (SSDATA (Vinvocation_name));
220 props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
221 ++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 props[props_idx]->num_vals = 4;
229 props[props_idx]->vals = &values[val_idx];
230 props[props_idx]->vals[0].length = strlen (emacs_program);
231 props[props_idx]->vals[0].value = emacs_program;
233 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
234 strcpy (smid_opt, SMID_OPT);
235 strcat (smid_opt, client_id);
237 props[props_idx]->vals[1].length = strlen (smid_opt);
238 props[props_idx]->vals[1].value = smid_opt;
240 props[props_idx]->vals[2].length = strlen (NOSPLASH_OPT);
241 props[props_idx]->vals[2].value = NOSPLASH_OPT;
243 cwd = get_current_dir_name ();
244 if (cwd)
246 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
247 strcpy (chdir_opt, CHDIR_OPT);
248 strcat (chdir_opt, cwd);
250 props[props_idx]->vals[3].length = strlen (chdir_opt);
251 props[props_idx]->vals[3].value = chdir_opt;
254 val_idx += cwd ? 4 : 3;
255 ++props_idx;
257 /* User id. */
258 props[props_idx] = &prop_ptr[props_idx];
259 props[props_idx]->name = xstrdup (SmUserID);
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 (SSDATA (Vuser_login_name));
264 props[props_idx]->vals[0].value = SDATA (Vuser_login_name);
265 ++props_idx;
268 if (cwd)
270 props[props_idx] = &prop_ptr[props_idx];
271 props[props_idx]->name = xstrdup (SmCurrentDirectory);
272 props[props_idx]->type = xstrdup (SmARRAY8);
273 props[props_idx]->num_vals = 1;
274 props[props_idx]->vals = &values[val_idx++];
275 props[props_idx]->vals[0].length = strlen (cwd);
276 props[props_idx]->vals[0].value = cwd;
277 ++props_idx;
281 SmcSetProperties (smcConn, props_idx, props);
283 xfree (smid_opt);
284 xfree (chdir_opt);
286 free (cwd);
287 for (i = 0; i < props_idx; ++i)
289 xfree (props[i]->type);
290 xfree (props[i]->name);
293 /* See if we maybe shall interact with the user. */
294 if (interactStyle != SmInteractStyleAny
295 || ! shutdown
296 || saveType == SmSaveLocal
297 || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
299 /* No interaction, we are done saving ourself. */
300 SmcSaveYourselfDone (smcConn, True);
304 /* According to the SM specification, this shall close the connection. */
306 static void
307 smc_die_CB (SmcConn smcConn, SmPointer clientData)
309 emacs_event.kind = SAVE_SESSION_EVENT;
310 emacs_event.arg = Qt;
313 /* We don't use the next two but they are mandatory, leave them empty.
314 According to the SM specification, we should not interact with the
315 user between smc_save_yourself_CB is called and until smc_save_complete_CB
316 is called. It seems like a lot of job to implement this and it doesn't
317 even seem necessary. */
319 static void
320 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
322 /* Empty */
325 static void
326 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
328 /* Empty */
331 /* Error handlers for SM and ICE. We don't want to exit Emacs just
332 because there is some error in the session management. */
334 static void
335 smc_error_handler (SmcConn smcConn,
336 Bool swap,
337 int offendingMinorOpcode,
338 unsigned long offendingSequence,
339 int errorClass,
340 int severity,
341 SmPointer values)
343 /* Empty */
346 static void
347 ice_error_handler (IceConn iceConn,
348 Bool swap,
349 int offendingMinorOpcode,
350 unsigned long offendingSequence,
351 int errorClass,
352 int severity,
353 IcePointer values)
355 /* Empty */
359 static void
360 ice_io_error_handler (IceConn iceConn)
362 /* Connection probably gone. */
363 ice_connection_closed ();
366 /* This is called when the ICE connection is created or closed. The SM library
367 uses ICE as it transport protocol. */
369 static void
370 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData, int opening, IcePointer *watchData)
372 if (! opening)
374 ice_connection_closed ();
375 return;
378 ice_fd = IceConnectionNumber (iceConn);
379 #ifdef F_SETOWN
380 fcntl (ice_fd, F_SETOWN, getpid ());
381 #endif /* ! defined (F_SETOWN) */
383 #ifdef SIGIO
384 if (interrupt_input)
385 init_sigio (ice_fd);
386 #endif /* ! defined (SIGIO) */
388 add_keyboard_wait_descriptor (ice_fd);
391 /* Create the client leader window. */
393 #ifndef USE_GTK
394 static void
395 create_client_leader_window (struct x_display_info *dpyinfo, char *client_id)
397 Window w;
398 XClassHint class_hints;
399 Atom sm_id;
401 w = XCreateSimpleWindow (dpyinfo->display,
402 dpyinfo->root_window,
403 -1, -1, 1, 1,
404 CopyFromParent, CopyFromParent, CopyFromParent);
406 class_hints.res_name = (char *) SDATA (Vx_resource_name);
407 class_hints.res_class = (char *) SDATA (Vx_resource_class);
408 XSetClassHint (dpyinfo->display, w, &class_hints);
409 XStoreName (dpyinfo->display, w, class_hints.res_name);
411 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
412 XA_STRING, 8, PropModeReplace,
413 (unsigned char *)client_id, strlen (client_id));
415 dpyinfo->client_leader_window = w;
417 #endif /* ! USE_GTK */
420 /* Try to open a connection to the session manager. */
422 void
423 x_session_initialize (struct x_display_info *dpyinfo)
425 #define SM_ERRORSTRING_LEN 512
426 char errorstring[SM_ERRORSTRING_LEN];
427 char* previous_id = NULL;
428 SmcCallbacks callbacks;
429 int name_len = 0;
431 ice_fd = -1;
432 doing_interact = False;
434 /* Check if we where started by the session manager. If so, we will
435 have a previous id. */
436 if (! EQ (Vx_session_previous_id, Qnil) && STRINGP (Vx_session_previous_id))
437 previous_id = SSDATA (Vx_session_previous_id);
439 /* Construct the path to the Emacs program. */
440 if (! EQ (Vinvocation_directory, Qnil))
441 name_len += strlen (SSDATA (Vinvocation_directory));
442 name_len += strlen (SSDATA (Vinvocation_name));
444 /* This malloc will not be freed, but it is only done once, and hopefully
445 not very large */
446 emacs_program = xmalloc (name_len + 1);
447 emacs_program[0] = '\0';
449 if (! EQ (Vinvocation_directory, Qnil))
450 strcpy (emacs_program, SSDATA (Vinvocation_directory));
451 strcat (emacs_program, SSDATA (Vinvocation_name));
453 /* The SM protocol says all callbacks are mandatory, so set up all
454 here and in the mask passed to SmcOpenConnection. */
455 callbacks.save_yourself.callback = smc_save_yourself_CB;
456 callbacks.save_yourself.client_data = 0;
457 callbacks.die.callback = smc_die_CB;
458 callbacks.die.client_data = 0;
459 callbacks.save_complete.callback = smc_save_complete_CB;
460 callbacks.save_complete.client_data = 0;
461 callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
462 callbacks.shutdown_cancelled.client_data = 0;
464 /* Set error handlers. */
465 SmcSetErrorHandler (smc_error_handler);
466 IceSetErrorHandler (ice_error_handler);
467 IceSetIOErrorHandler (ice_io_error_handler);
469 /* Install callback for when connection status changes. */
470 IceAddConnectionWatch (ice_conn_watch_CB, 0);
472 /* Open the connection to the session manager. A failure is not
473 critical, it usually means that no session manager is running.
474 The errorstring is here for debugging. */
475 smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
476 (SmcSaveYourselfProcMask|
477 SmcDieProcMask|
478 SmcSaveCompleteProcMask|
479 SmcShutdownCancelledProcMask),
480 &callbacks,
481 previous_id,
482 &client_id,
483 SM_ERRORSTRING_LEN,
484 errorstring);
486 if (smc_conn != 0)
488 Vx_session_id = make_string (client_id, strlen (client_id));
490 #ifdef USE_GTK
491 /* GTK creats a leader window by itself, but we need to tell
492 it about our client_id. */
493 gdk_set_sm_client_id (client_id);
494 #else
495 create_client_leader_window (dpyinfo, client_id);
496 #endif
500 /* Ensure that the session manager is not contacted again. */
502 void
503 x_session_close (void)
505 ice_connection_closed ();
509 DEFUN ("handle-save-session", Fhandle_save_session,
510 Shandle_save_session, 1, 1, "e",
511 doc: /* Handle the save_yourself event from a session manager.
512 A session manager can tell Emacs that the window system is shutting down
513 by sending Emacs a save_yourself message. Emacs executes this function when
514 such an event occurs. This function then executes `emacs-session-save'.
515 After that, this function informs the session manager that it can continue
516 or abort shutting down the window system depending on the return value
517 from `emacs-session-save' If the return value is non-nil the session manager
518 is told to abort the window system shutdown.
520 Do not call this function yourself. */)
521 (Lisp_Object event)
523 int kill_emacs = CONSP (event) && CONSP (XCDR (event))
524 && EQ (Qt, XCAR (XCDR (event)));
526 /* Check doing_interact so that we don't do anything if someone called
527 this at the wrong time. */
528 if (doing_interact && ! kill_emacs)
530 Bool cancel_shutdown = False;
532 cancel_shutdown = ! EQ (call0 (intern ("emacs-session-save")), Qnil);
534 SmcInteractDone (smc_conn, cancel_shutdown);
535 SmcSaveYourselfDone (smc_conn, True);
537 doing_interact = False;
539 else if (kill_emacs)
541 /* We should not do user interaction here, but it is not easy to
542 prevent. Fix this in next version. */
543 Fkill_emacs (Qnil);
545 /* This will not be reached, but we want kill-emacs-hook to be run. */
546 SmcCloseConnection (smc_conn, 0, 0);
547 ice_connection_closed ();
550 return Qnil;
555 /***********************************************************************
556 Initialization
557 ***********************************************************************/
558 void
559 syms_of_xsmfns (void)
561 DEFVAR_LISP ("x-session-id", &Vx_session_id,
562 doc: /* The session id Emacs got from the session manager for this session.
563 Changing the value does not change the session id used by Emacs.
564 The value is nil if no session manager is running.
565 See also `x-session-previous-id', `emacs-save-session-functions',
566 `emacs-session-save' and `emacs-session-restore'." */);
567 Vx_session_id = Qnil;
569 DEFVAR_LISP ("x-session-previous-id", &Vx_session_previous_id,
570 doc: /* The previous session id Emacs got from session manager.
571 If Emacs is running on a window system that has a session manager, the
572 session manager gives Emacs a session id. It is feasible for Emacs Lisp
573 code to use the session id to save configuration in, for example, a file
574 with a file name based on the session id. If Emacs is running when the
575 window system is shut down, the session manager remembers that Emacs was
576 running and saves the session id Emacs had.
578 When the window system is started again, the session manager restarts
579 Emacs and hands Emacs the session id it had the last time it was
580 running. This is now the previous session id and the value of this
581 variable. If configuration was saved in a file as stated above, the
582 previous session id shall be used to reconstruct the file name.
584 The session id Emacs has while it is running is in the variable
585 `x-session-id'. The value of this variable and `x-session-id' may be the
586 same, depending on how the session manager works.
588 See also `emacs-save-session-functions', `emacs-session-save' and
589 `emacs-session-restore'." */);
590 Vx_session_previous_id = Qnil;
592 defsubr (&Shandle_save_session);
595 #endif /* HAVE_X_SM */
597 /* arch-tag: 56a2c58c-adfa-430a-b772-130abd29fd2e
598 (do not change this comment) */