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