]> code.delx.au - gnu-emacs/blob - src/xsmfns.c
Merge from mainline.
[gnu-emacs] / 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, 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 /* Avoid "differ in sign" warnings */
43 #define SSDATA(x) ((char *) SDATA (x))
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;
52
53 /* A flag that says if we are in shutdown interactions or not. */
54
55 static int 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 client session id for this session as a lisp object. */
70
71 Lisp_Object Vx_session_id;
72
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. */
75
76 Lisp_Object Vx_session_previous_id;
77
78 /* The option we tell the session manager to start Emacs with when
79 restarting Emacs. The client_id is appended. */
80
81 #define SMID_OPT "--smid="
82
83
84 /* The option to start Emacs without the splash screen when
85 restarting Emacs. */
86
87 static char NOSPLASH_OPT[] = "--no-splash";
88
89 /* The option to make Emacs start in the given directory. */
90
91 #define CHDIR_OPT "--chdir="
92
93 static void
94 ice_connection_closed (void)
95 {
96 if (ice_fd >= 0)
97 delete_keyboard_wait_descriptor (ice_fd);
98 ice_fd = -1;
99 }
100
101
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. */
105
106 int
107 x_session_check_input (struct input_event *bufp)
108 {
109 SELECT_TYPE read_fds;
110 EMACS_TIME tmout;
111 int ret;
112
113 if (ice_fd == -1) return 0;
114 FD_ZERO (&read_fds);
115 FD_SET (ice_fd, &read_fds);
116
117 tmout.tv_sec = 0;
118 tmout.tv_usec = 0;
119
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;
125
126 ret = select (ice_fd+1, &read_fds,
127 (SELECT_TYPE *)0, (SELECT_TYPE *)0, &tmout);
128
129 if (ret < 0)
130 {
131 ice_connection_closed ();
132 }
133 else if (ret > 0 && FD_ISSET (ice_fd, &read_fds))
134 {
135 ret = IceProcessMessages (SmcGetIceConnection (smc_conn),
136 (IceReplyWaitInfo *)0, (Bool *)0);
137 if (ret != IceProcessMessagesSuccess)
138 {
139 /* Either IO error or Connection closed. */
140 if (ret == IceProcessMessagesIOError)
141 IceCloseConnection (SmcGetIceConnection (smc_conn));
142
143 ice_connection_closed ();
144 }
145 }
146
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));
151
152 return emacs_event.kind != NO_EVENT ? 1 : 0;
153 }
154
155 /* Return non-zero if we have a connection to a session manager. */
156
157 int
158 x_session_have_connection (void)
159 {
160 return ice_fd != -1;
161 }
162
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. */
166
167 static void
168 smc_interact_CB (SmcConn smcConn, SmPointer clientData)
169 {
170 doing_interact = True;
171 emacs_event.kind = SAVE_SESSION_EVENT;
172 emacs_event.arg = Qnil;
173 }
174
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.
179
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. */
182
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)
190 {
191 #define NR_PROPS 5
192
193 SmProp *props[NR_PROPS];
194 SmProp prop_ptr[NR_PROPS];
195
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;
202
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;
212
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;
222
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;
232
233 smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
234 strcpy (smid_opt, SMID_OPT);
235 strcat (smid_opt, client_id);
236
237 props[props_idx]->vals[1].length = strlen (smid_opt);
238 props[props_idx]->vals[1].value = smid_opt;
239
240 props[props_idx]->vals[2].length = strlen (NOSPLASH_OPT);
241 props[props_idx]->vals[2].value = NOSPLASH_OPT;
242
243 cwd = get_current_dir_name ();
244 if (cwd)
245 {
246 chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
247 strcpy (chdir_opt, CHDIR_OPT);
248 strcat (chdir_opt, cwd);
249
250 props[props_idx]->vals[3].length = strlen (chdir_opt);
251 props[props_idx]->vals[3].value = chdir_opt;
252 }
253
254 val_idx += cwd ? 4 : 3;
255 ++props_idx;
256
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;
266
267
268 if (cwd)
269 {
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;
278 }
279
280
281 SmcSetProperties (smcConn, props_idx, props);
282
283 xfree (smid_opt);
284 xfree (chdir_opt);
285
286 free (cwd);
287 for (i = 0; i < props_idx; ++i)
288 {
289 xfree (props[i]->type);
290 xfree (props[i]->name);
291 }
292
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))
298 {
299 /* No interaction, we are done saving ourself. */
300 SmcSaveYourselfDone (smcConn, True);
301 }
302 }
303
304 /* According to the SM specification, this shall close the connection. */
305
306 static void
307 smc_die_CB (SmcConn smcConn, SmPointer clientData)
308 {
309 emacs_event.kind = SAVE_SESSION_EVENT;
310 emacs_event.arg = Qt;
311 }
312
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. */
318
319 static void
320 smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
321 {
322 /* Empty */
323 }
324
325 static void
326 smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
327 {
328 /* Empty */
329 }
330
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. */
333
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)
342 {
343 /* Empty */
344 }
345
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)
354 {
355 /* Empty */
356 }
357
358
359 static void
360 ice_io_error_handler (IceConn iceConn)
361 {
362 /* Connection probably gone. */
363 ice_connection_closed ();
364 }
365
366 /* This is called when the ICE connection is created or closed. The SM library
367 uses ICE as it transport protocol. */
368
369 static void
370 ice_conn_watch_CB (IceConn iceConn, IcePointer clientData, int opening, IcePointer *watchData)
371 {
372 if (! opening)
373 {
374 ice_connection_closed ();
375 return;
376 }
377
378 ice_fd = IceConnectionNumber (iceConn);
379 #ifdef F_SETOWN
380 fcntl (ice_fd, F_SETOWN, getpid ());
381 #endif /* ! defined (F_SETOWN) */
382
383 #ifdef SIGIO
384 if (interrupt_input)
385 init_sigio (ice_fd);
386 #endif /* ! defined (SIGIO) */
387
388 add_keyboard_wait_descriptor (ice_fd);
389 }
390
391 /* Create the client leader window. */
392
393 #ifndef USE_GTK
394 static void
395 create_client_leader_window (struct x_display_info *dpyinfo, char *client_id)
396 {
397 Window w;
398 XClassHint class_hints;
399 Atom sm_id;
400
401 w = XCreateSimpleWindow (dpyinfo->display,
402 dpyinfo->root_window,
403 -1, -1, 1, 1,
404 CopyFromParent, CopyFromParent, CopyFromParent);
405
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);
410
411 XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
412 XA_STRING, 8, PropModeReplace,
413 (unsigned char *)client_id, strlen (client_id));
414
415 dpyinfo->client_leader_window = w;
416 }
417 #endif /* ! USE_GTK */
418
419
420 /* Try to open a connection to the session manager. */
421
422 void
423 x_session_initialize (struct x_display_info *dpyinfo)
424 {
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;
430
431 ice_fd = -1;
432 doing_interact = False;
433
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);
438
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));
443
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';
448
449 if (! EQ (Vinvocation_directory, Qnil))
450 strcpy (emacs_program, SSDATA (Vinvocation_directory));
451 strcat (emacs_program, SSDATA (Vinvocation_name));
452
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;
463
464 /* Set error handlers. */
465 SmcSetErrorHandler (smc_error_handler);
466 IceSetErrorHandler (ice_error_handler);
467 IceSetIOErrorHandler (ice_io_error_handler);
468
469 /* Install callback for when connection status changes. */
470 IceAddConnectionWatch (ice_conn_watch_CB, 0);
471
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);
485
486 if (smc_conn != 0)
487 {
488 Vx_session_id = make_string (client_id, strlen (client_id));
489
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
497 }
498 }
499
500 /* Ensure that the session manager is not contacted again. */
501
502 void
503 x_session_close (void)
504 {
505 ice_connection_closed ();
506 }
507
508
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.
519
520 Do not call this function yourself. */)
521 (Lisp_Object event)
522 {
523 int kill_emacs = CONSP (event) && CONSP (XCDR (event))
524 && EQ (Qt, XCAR (XCDR (event)));
525
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)
529 {
530 Bool cancel_shutdown = False;
531
532 cancel_shutdown = ! EQ (call0 (intern ("emacs-session-save")), Qnil);
533
534 SmcInteractDone (smc_conn, cancel_shutdown);
535 SmcSaveYourselfDone (smc_conn, True);
536
537 doing_interact = False;
538 }
539 else if (kill_emacs)
540 {
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);
544
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 ();
548 }
549
550 return Qnil;
551 }
552
553
554 \f
555 /***********************************************************************
556 Initialization
557 ***********************************************************************/
558 void
559 syms_of_xsmfns (void)
560 {
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;
568
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.
577
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.
583
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.
587
588 See also `emacs-save-session-functions', `emacs-session-save' and
589 `emacs-session-restore'." */);
590 Vx_session_previous_id = Qnil;
591
592 defsubr (&Shandle_save_session);
593 }
594
595 #endif /* HAVE_X_SM */
596
597 /* arch-tag: 56a2c58c-adfa-430a-b772-130abd29fd2e
598 (do not change this comment) */