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