xsmfns.c 17.2 KB
Newer Older
1 2
/* Session management module for systems which understand the X Session
   management protocol.
3

Paul Eggert's avatar
Paul Eggert committed
4
Copyright (C) 2002-2020 Free Software Foundation, Inc.
5 6 7

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 11
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
12 13 14 15 16 17 18

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
19
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
20 21 22 23 24 25

#include <config.h>

#ifdef HAVE_X_SM

#include <X11/SM/SMlib.h>
26 27 28
#include <X11/Xlib.h>
#include <X11/Xutil.h>

29 30
#include <unistd.h>
#include <sys/param.h>
31
#include <errno.h>
32
#include <stdio.h>
33

34
#include "lisp.h"
35
#include "frame.h"
36
#include "termhooks.h"
37
#include "xterm.h"
38 39
#include "process.h"
#include "keyboard.h"
40

41
#if defined USE_GTK && !defined HAVE_GTK3
42
#define gdk_x11_set_sm_client_id(w) gdk_set_sm_client_id (w)
43 44
#endif

Pavel Janík's avatar
Pavel Janík committed
45
/* This is the event used when SAVE_SESSION_EVENT occurs.  */
46 47 48

static struct input_event emacs_event;

Pavel Janík's avatar
Pavel Janík committed
49
/* The descriptor that we use to check for data from the session manager.  */
50

Jan Djärv's avatar
Jan Djärv committed
51
static int ice_fd = -1;
52

Pavel Janík's avatar
Pavel Janík committed
53
/* A flag that says if we are in shutdown interactions or not.  */
54

Paul Eggert's avatar
Paul Eggert committed
55
static bool doing_interact;
56

57
/* The session manager object for the session manager connection.  */
58 59 60

static SmcConn smc_conn;

61 62
/* The client session id for this session.  */

63 64
static char *client_id;

65 66
/* The full path name to the Emacs program.  */

67 68 69
static char *emacs_program;

/* The option we tell the session manager to start Emacs with when
70
   restarting Emacs.  The client_id is appended.  */
71 72 73 74

#define SMID_OPT "--smid="


75
/* The option to start Emacs without the splash screen when
76
   restarting Emacs.  */
77

78
static char NOSPLASH_OPT[] = "--no-splash";
79

80 81 82 83
/* The option to make Emacs start in the given directory.  */

#define CHDIR_OPT "--chdir="

84
static void
85
ice_connection_closed (void)
86 87
{
  if (ice_fd >= 0)
88
    delete_read_fd (ice_fd);
89 90 91
  ice_fd = -1;
}

92

93
/* Handle any messages from the session manager.  If no connection is
94
   open to a session manager, just return.  */
95

96
static void
97
x_session_check_input (int fd, void *data)
98
{
99
  int ret;
Juanma Barranquero's avatar
Juanma Barranquero committed
100

101
  if (ice_fd == -1) return;
Juanma Barranquero's avatar
Juanma Barranquero committed
102

103 104
  /* Reset this so wo can check kind after callbacks have been called by
     IceProcessMessages.  The smc_interact_CB sets the kind to
Pavel Janík's avatar
Pavel Janík committed
105
     SAVE_SESSION_EVENT, but we don't know beforehand if that callback
106
     will be called.  */
Pavel Janík's avatar
Pavel Janík committed
107
  emacs_event.kind = NO_EVENT;
108

Paul Eggert's avatar
Paul Eggert committed
109
  ret = IceProcessMessages (SmcGetIceConnection (smc_conn), 0, 0);
110
  if (ret != IceProcessMessagesSuccess)
111
    {
112 113 114 115
      /* Either IO error or Connection closed.  */
      if (ret == IceProcessMessagesIOError)
        IceCloseConnection (SmcGetIceConnection (smc_conn));

116 117
      ice_connection_closed ();
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
118

119
  /* Check if smc_interact_CB was called and we shall generate a
120
     SAVE_SESSION_EVENT.  */
121
  if (emacs_event.kind != NO_EVENT)
122
    kbd_buffer_store_event (&emacs_event);
123 124
}

Paul Eggert's avatar
Paul Eggert committed
125
/* Return true if we have a connection to a session manager.  */
126

Paul Eggert's avatar
Paul Eggert committed
127
bool
128
x_session_have_connection (void)
129 130 131 132 133
{
  return ice_fd != -1;
}

/* This is called when the session manager says it is OK to interact with the
Pavel Janík's avatar
Pavel Janík committed
134
   user.  Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
135 136
   Then lisp code can interact with the user.  */

137
static void
138
smc_interact_CB (SmcConn smcConn, SmPointer clientData)
139
{
Paul Eggert's avatar
Paul Eggert committed
140
  doing_interact = true;
Pavel Janík's avatar
Pavel Janík committed
141
  emacs_event.kind = SAVE_SESSION_EVENT;
142
  emacs_event.arg = Qnil;
143 144
}

Juanma Barranquero's avatar
Juanma Barranquero committed
145
/* This is called when the session manager tells us to save ourselves.
146 147 148 149 150
   We set the required properties so the session manager can restart us,
   plus the current working directory property (not mandatory) so we
   are started in the correct directory.

   If this is a shutdown and we can request to interact with the user,
151 152
   we do so, because we don't know what the lisp code might do.  */

153
static void
154 155 156 157 158 159
smc_save_yourself_CB (SmcConn smcConn,
		      SmPointer clientData,
		      int saveType,
		      Bool shutdown,
		      int interactStyle,
		      Bool fast)
160 161
{
#define NR_PROPS 5
Juanma Barranquero's avatar
Juanma Barranquero committed
162

163 164
  SmProp *props[NR_PROPS];
  SmProp prop_ptr[NR_PROPS];
Juanma Barranquero's avatar
Juanma Barranquero committed
165

166 167
  SmPropValue values[20], *vp;
  int val_idx = 0, vp_idx = 0;
168
  int props_idx = 0;
169
  int i;
170
  char *smid_opt, *chdir_opt = NULL;
Jan D's avatar
Jan D committed
171 172
  Lisp_Object user_login_name = Fuser_login_name (Qnil);

173
  /* Must have these.  */
Jan D's avatar
Jan D committed
174 175
  if (! STRINGP (Vinvocation_name) || ! STRINGP (user_login_name))
    return;
176

177
  /* How to start a new instance of Emacs.  */
178
  props[props_idx] = &prop_ptr[props_idx];
179 180
  props[props_idx]->name = xstrdup (SmCloneCommand);
  props[props_idx]->type = xstrdup (SmLISTofARRAY8);
181 182 183 184 185 186
  props[props_idx]->num_vals = 1;
  props[props_idx]->vals = &values[val_idx++];
  props[props_idx]->vals[0].length = strlen (emacs_program);
  props[props_idx]->vals[0].value = emacs_program;
  ++props_idx;

Jan D's avatar
Jan D committed
187 188 189 190 191 192 193 194 195
  /* The name of the program.  */
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = xstrdup (SmProgram);
  props[props_idx]->type = xstrdup (SmARRAY8);
  props[props_idx]->num_vals = 1;
  props[props_idx]->vals = &values[val_idx++];
  props[props_idx]->vals[0].length = SBYTES (Vinvocation_name);
  props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
  ++props_idx;
Juanma Barranquero's avatar
Juanma Barranquero committed
196

197
  /* User id.  */
Jan D's avatar
Jan D committed
198 199 200 201 202 203 204 205
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = xstrdup (SmUserID);
  props[props_idx]->type = xstrdup (SmARRAY8);
  props[props_idx]->num_vals = 1;
  props[props_idx]->vals = &values[val_idx++];
  props[props_idx]->vals[0].length = SBYTES (user_login_name);
  props[props_idx]->vals[0].value = SDATA (user_login_name);
  ++props_idx;
206

207
  char *cwd = emacs_get_current_dir_name ();
208
  if (cwd)
209 210
    {
      props[props_idx] = &prop_ptr[props_idx];
211 212
      props[props_idx]->name = xstrdup (SmCurrentDirectory);
      props[props_idx]->type = xstrdup (SmARRAY8);
213 214 215 216 217 218
      props[props_idx]->num_vals = 1;
      props[props_idx]->vals = &values[val_idx++];
      props[props_idx]->vals[0].length = strlen (cwd);
      props[props_idx]->vals[0].value = cwd;
      ++props_idx;
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
219 220


221 222 223 224 225
  /* How to restart Emacs.  */
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = xstrdup (SmRestartCommand);
  props[props_idx]->type = xstrdup (SmLISTofARRAY8);
  /* /path/to/emacs, --smid=xxx --no-splash --chdir=dir ... */
226
  if (INT_ADD_WRAPV (initial_argc, 3, &i))
227
    memory_full (SIZE_MAX);
228
  props[props_idx]->num_vals = i;
229
  vp = xnmalloc (i, sizeof *vp);
230 231 232 233 234
  props[props_idx]->vals = vp;
  props[props_idx]->vals[vp_idx].length = strlen (emacs_program);
  props[props_idx]->vals[vp_idx++].value = emacs_program;

  smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
Paul Eggert's avatar
Paul Eggert committed
235
  strcpy (stpcpy (smid_opt, SMID_OPT), client_id);
236 237 238 239 240 241 242 243 244 245

  props[props_idx]->vals[vp_idx].length = strlen (smid_opt);
  props[props_idx]->vals[vp_idx++].value = smid_opt;

  props[props_idx]->vals[vp_idx].length = strlen (NOSPLASH_OPT);
  props[props_idx]->vals[vp_idx++].value = NOSPLASH_OPT;

  if (cwd)
    {
      chdir_opt = xmalloc (strlen (CHDIR_OPT) + strlen (cwd) + 1);
Paul Eggert's avatar
Paul Eggert committed
246
      strcpy (stpcpy (chdir_opt, CHDIR_OPT), cwd);
247 248 249 250 251

      props[props_idx]->vals[vp_idx].length = strlen (chdir_opt);
      props[props_idx]->vals[vp_idx++].value = chdir_opt;
    }

252
  for (i = 1; i < initial_argc; ++i)
253 254 255 256 257 258 259
    {
      props[props_idx]->vals[vp_idx].length = strlen (initial_argv[i]);
      props[props_idx]->vals[vp_idx++].value = initial_argv[i];
    }

  ++props_idx;

260 261 262
  SmcSetProperties (smcConn, props_idx, props);

  xfree (smid_opt);
263
  xfree (chdir_opt);
264 265
  xfree (cwd);
  xfree (vp);
266

267 268 269 270 271
  for (i = 0; i < props_idx; ++i)
    {
      xfree (props[i]->type);
      xfree (props[i]->name);
    }
272

273
  /* See if we maybe shall interact with the user.  */
274 275 276 277 278
  if (interactStyle != SmInteractStyleAny
      || ! shutdown
      || saveType == SmSaveLocal
      || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
    {
279
      /* No interaction, we are done saving ourself.  */
280 281 282 283
      SmcSaveYourselfDone (smcConn, True);
    }
}

284 285
/* According to the SM specification, this shall close the connection.  */

286
static void
287
smc_die_CB (SmcConn smcConn, SmPointer clientData)
288
{
289 290
  emacs_event.kind = SAVE_SESSION_EVENT;
  emacs_event.arg = Qt;
291 292 293 294 295 296
}

/* We don't use the next two but they are mandatory, leave them empty.
   According to the SM specification, we should not interact with the
   user between smc_save_yourself_CB is called and until smc_save_complete_CB
   is called.  It seems like a lot of job to implement this and it doesn't
297 298
   even seem necessary.  */

299
static void
300
smc_save_complete_CB (SmcConn smcConn, SmPointer clientData)
301 302 303 304 305
{
  /* Empty */
}

static void
306
smc_shutdown_cancelled_CB (SmcConn smcConn, SmPointer clientData)
307 308 309 310
{
  /* Empty */
}

Juanma Barranquero's avatar
Juanma Barranquero committed
311
/* Error handlers for SM and ICE.  We don't want to exit Emacs just
312 313
   because there is some error in the session management.  */

314
static void
315 316 317 318 319 320 321
smc_error_handler (SmcConn smcConn,
		   Bool swap,
		   int offendingMinorOpcode,
		   unsigned long offendingSequence,
		   int errorClass,
		   int severity,
		   SmPointer values)
322
{
323
  /* Empty  */
324 325 326
}

static void
327 328 329 330 331 332 333
ice_error_handler (IceConn iceConn,
		   Bool swap,
		   int offendingMinorOpcode,
		   unsigned long offendingSequence,
		   int errorClass,
		   int severity,
		   IcePointer values)
334
{
335
  /* Empty  */
336 337 338 339
}


static void
340
ice_io_error_handler (IceConn iceConn)
341
{
342
  /* Connection probably gone.  */
343
  ice_connection_closed ();
344 345 346
}

/* This is called when the ICE connection is created or closed.  The SM library
347 348
   uses ICE as it transport protocol.  */

349
static void
350 351
ice_conn_watch_CB (IceConn iceConn, IcePointer clientData,
                   int opening, IcePointer *watchData)
352 353 354
{
  if (! opening)
    {
355
      ice_connection_closed ();
356 357
      return;
    }
Juanma Barranquero's avatar
Juanma Barranquero committed
358

359
  ice_fd = IceConnectionNumber (iceConn);
360
  add_read_fd (ice_fd, x_session_check_input, NULL);
361 362
}

363
/* Create the client leader window.  */
364

365
#ifndef USE_GTK
366
static void
367
create_client_leader_window (struct x_display_info *dpyinfo, char *client_ID)
368 369 370 371 372 373 374 375 376
{
  Window w;
  XClassHint class_hints;

  w = XCreateSimpleWindow (dpyinfo->display,
                           dpyinfo->root_window,
                           -1, -1, 1, 1,
                           CopyFromParent, CopyFromParent, CopyFromParent);

377
  validate_x_resource_name ();
378 379
  class_hints.res_name = SSDATA (Vx_resource_name);
  class_hints.res_class = SSDATA (Vx_resource_class);
380 381 382
  XSetClassHint (dpyinfo->display, w, &class_hints);
  XStoreName (dpyinfo->display, w, class_hints.res_name);

383 384
  XChangeProperty (dpyinfo->display, w, dpyinfo->Xatom_SM_CLIENT_ID,
                   XA_STRING, 8, PropModeReplace,
385
                   (unsigned char *) client_ID, strlen (client_ID));
386 387 388

  dpyinfo->client_leader_window = w;
}
389 390
#endif /* ! USE_GTK */

391

392 393
/* Try to open a connection to the session manager.  */

394
void
395
x_session_initialize (struct x_display_info *dpyinfo)
396 397 398
{
#define SM_ERRORSTRING_LEN 512
  char errorstring[SM_ERRORSTRING_LEN];
399
  char *previous_id = NULL;
400
  SmcCallbacks callbacks;
401
  ptrdiff_t name_len = 0;
Juanma Barranquero's avatar
Juanma Barranquero committed
402

403
  /* libSM seems to crash if pwd is missing - see bug#18851.  */
404 405
  char *pwd = emacs_get_current_dir_name ();
  if (!pwd)
406 407 408 409 410
    {
      fprintf (stderr, "Disabling session management due to pwd error: %s\n",
               emacs_strerror (errno));
      return;
    }
411
  xfree (pwd);
412

413
  ice_fd = -1;
Paul Eggert's avatar
Paul Eggert committed
414
  doing_interact = false;
415

416
  /* Check if we where started by the session manager.  If so, we will
417
     have a previous id.  */
418
  if (STRINGP (Vx_session_previous_id))
419
    previous_id = SSDATA (Vx_session_previous_id);
420

421
  /* Construct the path to the Emacs program.  */
422
  if (STRINGP (Vinvocation_directory))
423
    name_len += SBYTES (Vinvocation_directory);
424 425
  if (STRINGP (Vinvocation_name))
    name_len += SBYTES (Vinvocation_name);
426 427

  /* This malloc will not be freed, but it is only done once, and hopefully
428
     not very large   */
429
  emacs_program = xmalloc (name_len + 1);
430
  char *z = emacs_program;
431

432
  if (STRINGP (Vinvocation_directory))
433
    z = lispstpcpy (z, Vinvocation_directory);
434 435
  if (STRINGP (Vinvocation_name))
    lispstpcpy (z, Vinvocation_name);
Juanma Barranquero's avatar
Juanma Barranquero committed
436

437
  /* The SM protocol says all callbacks are mandatory, so set up all
438
     here and in the mask passed to SmcOpenConnection.  */
439 440 441 442 443 444 445 446 447
  callbacks.save_yourself.callback = smc_save_yourself_CB;
  callbacks.save_yourself.client_data = 0;
  callbacks.die.callback = smc_die_CB;
  callbacks.die.client_data = 0;
  callbacks.save_complete.callback = smc_save_complete_CB;
  callbacks.save_complete.client_data = 0;
  callbacks.shutdown_cancelled.callback = smc_shutdown_cancelled_CB;
  callbacks.shutdown_cancelled.client_data = 0;

448
  /* Set error handlers.  */
449 450 451 452
  SmcSetErrorHandler (smc_error_handler);
  IceSetErrorHandler (ice_error_handler);
  IceSetIOErrorHandler (ice_io_error_handler);

453
  /* Install callback for when connection status changes.  */
454 455 456
  IceAddConnectionWatch (ice_conn_watch_CB, 0);

  /* Open the connection to the session manager.  A failure is not
Juanma Barranquero's avatar
Juanma Barranquero committed
457
     critical, it usually means that no session manager is running.
458
     The errorstring is here for debugging.  */
459 460 461 462 463 464 465 466 467 468 469 470
  smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
                                (SmcSaveYourselfProcMask|
                                 SmcDieProcMask|
                                 SmcSaveCompleteProcMask|
                                 SmcShutdownCancelledProcMask),
                                &callbacks,
                                previous_id,
                                &client_id,
                                SM_ERRORSTRING_LEN,
                                errorstring);

  if (smc_conn != 0)
471
    {
472
      Vx_session_id = build_string (client_id);
473 474

#ifdef USE_GTK
Paul Eggert's avatar
Paul Eggert committed
475
      /* GTK creates a leader window by itself, but we need to tell
476
         it about our client_id.  */
477
      gdk_x11_set_sm_client_id (client_id);
478 479 480 481
#else
      create_client_leader_window (dpyinfo, client_id);
#endif
    }
482 483
}

484 485 486
/* Ensure that the session manager is not contacted again. */

void
487
x_session_close (void)
488
{
489
  ice_connection_closed ();
490 491
}

492 493 494 495

DEFUN ("handle-save-session", Fhandle_save_session,
       Shandle_save_session, 1, 1, "e",
       doc: /* Handle the save_yourself event from a session manager.
Juanma Barranquero's avatar
Juanma Barranquero committed
496
A session manager can tell Emacs that the window system is shutting down
497 498 499 500 501 502 503 504
by sending Emacs a save_yourself message.  Emacs executes this function when
such an event occurs.  This function then executes `emacs-session-save'.
After that, this function informs the session manager that it can continue
or abort shutting down the window system depending on the return value
from `emacs-session-save'  If the return value is non-nil the session manager
is told to abort the window system shutdown.

Do not call this function yourself. */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
505
  (Lisp_Object event)
506
{
Paul Eggert's avatar
Paul Eggert committed
507 508
  bool kill_emacs = (CONSP (event) && CONSP (XCDR (event))
		     && EQ (Qt, XCAR (XCDR (event))));
509

510 511
  /* Check doing_interact so that we don't do anything if someone called
     this at the wrong time. */
512
  if (doing_interact && ! kill_emacs)
513
    {
Paul Eggert's avatar
Paul Eggert committed
514
      bool cancel_shutdown = ! NILP (call0 (intern ("emacs-session-save")));
515 516 517 518

      SmcInteractDone (smc_conn, cancel_shutdown);
      SmcSaveYourselfDone (smc_conn, True);

Paul Eggert's avatar
Paul Eggert committed
519
      doing_interact = false;
520
    }
521 522 523 524 525
  else if (kill_emacs)
    {
      /* We should not do user interaction here, but it is not easy to
         prevent.  Fix this in next version.  */
      Fkill_emacs (Qnil);
526

Paul Eggert's avatar
Paul Eggert committed
527
#if false
528 529 530
      /* This will not be reached, but we want kill-emacs-hook to be run.  */
      SmcCloseConnection (smc_conn, 0, 0);
      ice_connection_closed ();
Paul Eggert's avatar
Paul Eggert committed
531
#endif
532
    }
533

534
  return Qnil;
535
}
536

537 538 539 540 541 542


/***********************************************************************
			    Initialization
 ***********************************************************************/
void
543
syms_of_xsmfns (void)
544
{
545
  DEFVAR_LISP ("x-session-id", Vx_session_id,
546 547 548 549
    doc: /* The session id Emacs got from the session manager for this session.
Changing the value does not change the session id used by Emacs.
The value is nil if no session manager is running.
See also `x-session-previous-id', `emacs-save-session-functions',
550
`emacs-session-save' and `emacs-session-restore'.  */);
551 552
  Vx_session_id = Qnil;

553
  DEFVAR_LISP ("x-session-previous-id", Vx_session_previous_id,
554
    doc: /* The previous session id Emacs got from session manager.
Juanma Barranquero's avatar
Juanma Barranquero committed
555
If Emacs is running on a window system that has a session manager, the
556
session manager gives Emacs a session id.  It is feasible for Emacs Lisp
Juanma Barranquero's avatar
Juanma Barranquero committed
557 558 559
code to use the session id to save configuration in, for example, a file
with a file name based on the session id.  If Emacs is running when the
window system is shut down, the session manager remembers that Emacs was
560 561
running and saves the session id Emacs had.

Juanma Barranquero's avatar
Juanma Barranquero committed
562 563 564 565
When the window system is started again, the session manager restarts
Emacs and hands Emacs the session id it had the last time it was
running.  This is now the previous session id and the value of this
variable.  If configuration was saved in a file as stated above, the
566 567
previous session id shall be used to reconstruct the file name.

Juanma Barranquero's avatar
Juanma Barranquero committed
568
The session id Emacs has while it is running is in the variable
569 570 571 572
`x-session-id'.  The value of this variable and `x-session-id' may be the
same, depending on how the session manager works.

See also `emacs-save-session-functions', `emacs-session-save' and
573
`emacs-session-restore'.  */);
574
  Vx_session_previous_id = Qnil;
Juanma Barranquero's avatar
Juanma Barranquero committed
575

576 577 578 579
  defsubr (&Shandle_save_session);
}

#endif /* HAVE_X_SM */