view src/xsmfns.c @ 94414:d86cb59eea9f

2008-04-27 Carsten Dominik <dominik@science.uva.nl> * org/org.el (org-html-level-start): Always have id's in HTML (org-export-as-html): Use `org-link-protocols' to retrieve the export form of the link. (org-add-link-type): Final parameter renamed from PUBLISH. Better documentation of how it is to be used. Avoid double entries for the same link type. (org-add-link-props): New function. (org-modules-loaded): New variable. (org-load-modules-maybe, org-set-modules): New function. (org-modules): New option. (org-mode, org-cycle, orgstruct-mode, org-run-like-in-org-mode) (orgtbl-mode, org-store-link, org-insert-link-global) (org-open-at-point): Call `org-load-modules-maybe'. (org-search-view): Add more text properties. (org-agenda-schedule, org-agenda-deadline): Allow also in search-type agendas. (org-search-view): Order of arguments has been changed. Interpret prefix-arg as TODO-ONLY. (org-agenda, org-run-agenda-series, org-agenda-manipulate-query): Take new argument order of `org-search-view' into account. (org-todo-only): New variable. (org-search-syntax-table): New variable and function. (org-search-view): Do the search with the special syntax table. (define-obsolete-function-alias): Make work with XEmacs. (org-add-planning-info): Use old date as default when modifying an existing deadline or scheduled item. (org-agenda-compute-time-span): Make argument N optional. (org-agenda-format-date-aligned): Require `cal-iso'. (org-agenda-list): Include week into into agenda heading, don't list it at each date (only on Mondays). (org-read-date-analyze): Define local variable `iso-date'. (org-agenda-format-date-aligned): Remove dependency on `calendar-time-from-absolute'. (org-remember-apply-template, org-go-to-remember-target): Interpret filenames relative to `org-directory'. (org-complete): Silently fail when trying to complete keywords that don't have a default value. (org-get-current-options): Added a #+DATE: option. (org-additional-option-like-keywords): Removed "DATE:" from the list of additional keywords. (org-export-as-html): Removed (current-time) as unnecessary second argument of `format-time-string'. (org-clock-find-position): Handle special case at end of buffer. (org-agenda-day-view): New argument DAY-OF-YEAR, pass it on to `org-agenda-change-time-span'. (org-agenda-week-view): New argument ISO-WEEK, pass it on to `org-agenda-change-time-span'. (org-agenda-month-view): New argument MONTH, pass it on to `org-agenda-change-time-span'. (org-agenda-year-view): New argument YEAR, pass it on to `org-agenda-change-time-span'. (org-agenda-change-time-span): New optional argument N, pass it on to `org-agenda-compute-time-span'. (org-agenda-compute-time-span): New argument N, interpret it by changing the starting day. (org-small-year-to-year): New function. (org-scheduled-past-days): Respect `org-scheduled-past-days'. (org-auto-repeat-maybe): Make sure that repeating dates are pushed into the future, and that the shift is at least one interval, never 0. (org-update-checkbox-count): Fix bug with checkbox counting. (org-add-note): New command. (org-add-log-setup): Renamed from `org-add-log-maybe'. (org-log-note-headings): New entry for plain notes (i.e. notes not related to state changes or clocking). (org-get-org-file): Check for availability of `remember-data-file'. (org-cached-entry-get): Allow a regexp value for `org-use-property-inheritance'. (org-use-property-inheritance): Allow regexp value. Fix bug in customization type. (org-use-tag-inheritance): Allow a list and a regexp value for this variable. (org-scan-tags, org-get-tags-at): Implement selective tag inheritance. (org-entry-get): Respect value `selective' for the INHERIT argument. (org-tag-inherit-p, org-property-inherit-p): New functions. (org-agenda-format-date-aligned): Allow 10 characters for weekday, to acomodate German locale. (org-add-archive-files): New function. (org-agenda-files): New argument `ext', to get archive files as well. (org-tbl-menu): Protect the use of variables that are only available when org-table.el gets loaded. (org-read-agenda-file-list): Error if `org-agenda-files' is a single directory. (org-open-file): Allow a batch process to trigger waiting after executing a system command. (org-store-link): Link to headline when there is not target and no region in an org-mode buffer when creating a link. (org-link-types-re): New variable. (org-make-link-regexps): Compute `org-link-types-re'. (org-make-link-description-function): New option. (org-agenda-date, org-agenda-date-weekend): New faces. (org-archive-sibling-heading): New option. (org-archive-to-archive-sibling): New function. (org-iswitchb): New command. (org-buffer-list): New function. (org-agenda-columns): Also try the #+COLUMNS line in the buffer associated with the entry at point (or with the first entry in the agenda view). (org-modules): Add entry for org-bibtex.el. (org-completion-fallback-command): Moved into `org-completion' group. (org-clock-heading-function): Moved to `org-progress' group. (org-auto-repeat-maybe): Make sure that a note can be enforces if `org-log-repeat' is `note'. (org-modules): Allow additional symbols for external packages. (org-ctrl-c-ctrl-c): Allow for `org-clock-overlays' to be undefined. (org-clock-goto): Hide drawers after showing an entry with `org-clock-goto.' (org-shiftup, org-shiftdown, org-shiftright, org-shiftleft): Try also a clocktable block shift. (org-clocktable-try-shift): New function. (org-columns-hscoll-title): New function. (org-columns-previous-hscroll): New variable. (org-columns-full-header-line-format): New variable. (org-columns-display-here-title, org-columns-remove-overlays): Install `org-columns-hscoll-title' in post-command-hook. * org/org.el: Split into many small files. * org/org-agenda.el: New file, split off from org.el. * org/org-archive.el: New file, split off from org.el. * org/org-bbdb.el: New file. * org/org-bibtex.el: New file, split off from org.el. * org/org-clock.el: New file, split off from org.el. * org/org-colview.el: New file, split off from org.el. * org/org-compat.el: New file, split off from org.el. * org/org-exp.el: New file, split off from org.el. * org/org-faces.el: New file, split off from org.el. * org/org-gnus.el: New file, split off from org.el. * org/org-info.el: New file, split off from org.el. * org/org-infojs.el: New file. * org/org-irc.el: New file. * org/org-macs.el: New file, split off from org.el. * org/org-mew.el: New file. * org/org-mhe.el: New file, split off from org.el. * org/org-publish.el: New file, split off from org.el. * org/org-remember.el: New file, split off from org.el. * org/org-rmail.el: New file, split off from org.el. * org/org-table.el: New file, split off from org.el. * org/org-vm.el: New file, split off from org.el. * org/org-wl.el: New file, split off from org.el. 2008-04-27 Jason Riedy <jason@acm.org> * lisp/org-table.el (orgtbl-to-generic): Add a :remove-nil-lines parameter that supresses lines that evaluate to NIL. (orgtbl-get-fmt): New inline function for picking apart formats that may be lists. (orgtbl-apply-fmt): New inline function for applying formats that may be functions. (orgtbl-eval-str): New inline function for strings that may be functions. (orgtbl-format-line, orgtbl-to-generic): Use and document. (orgtbl-to-latex, orgtbl-to-texinfo): Document. (*orgtbl-llfmt*, *orgtbl-llstart*) (*orgtbl-llend*): Dynamic variables for last-line formatting. (orgtbl-format-section): Shift formatting to support detecting the last line and formatting it specially. (orgtbl-to-generic): Document :ll* formats. Set to the non-ll formats unless overridden. (orgtbl-to-latex): Suggest using :llend to suppress the final \\. (*orgtbl-table*, *orgtbl-rtn*): Dynamically bound variables to hold the input collection of lines and output formatted text. (*orgtbl-hline*, *orgtbl-sep*, *orgtbl-fmt*, *orgtbl-efmt*, (*orgtbl-lfmt*, *orgtbl-lstart*, *orgtbl-lend*): Dynamically bound format parameters. (orgtbl-format-line): New function encapsulating formatting for a single line. (orgtbl-format-section): Similar for each section. Rebinding the dynamic vars customizes the formatting for each section. (orgtbl-to-generic): Use orgtbl-format-line and orgtbl-format-section. (org-get-param): Now unused, so delete. (orgtbl-gather-send-defs): New function to gather all the SEND definitions before a table. (orgtbl-send-replace-tbl): New function to find the RECEIVE corresponding to the current name. (orgtbl-send-table): Use the previous two functions and implement multiple destinations for each table. * doc/org.texi (A LaTeX example): Note that fmt may be a one-argument function, and efmt may be a two-argument function. (Radio tables): Document multiple destinations. 2008-04-27 Carsten Dominik <dominik@science.uva.nl> * org/org-agenda.el (org-add-to-diary-list): New function. (org-prefix-has-effort): New variable. (org-sort-agenda-noeffort-is-high): New option. (org-agenda-columns-show-summaries) (org-agenda-columns-compute-summary-properties): New options. (org-format-agenda-item): Compute the duration of the item. (org-agenda-weekend-days): New variable. (org-agenda-list, org-timeline): Use the proper faces for dates in the agenda and timeline buffers. (org-agenda-archive-to-archive-sibling): New command. (org-agenda-start-with-clockreport-mode): New option. (org-agenda-clockreport-parameter-plist): New option. (org-agenda-clocktable-mode): New variable. (org-agenda-deadline-leaders): Allow a function value for the deadline leader. (org-agenda-get-deadlines): Deal with new function value. * lisp/org-clock.el (org-clock): New customization group. (org-clock-into-drawer, org-clock-out-when-done) (org-clock-in-switch-to-state, org-clock-heading-function): Moved into the new group. (org-clock-out-remove-zero-time-clocks): New option. (org-clock-out): Use `org-clock-out-remove-zero-time-clocks'. (org-dblock-write:clocktable): Allow a Lisp form for the scope parameter. (org-dblock-write:clocktable): Fixed bug with total time calculation. (org-dblock-write:clocktable): Request the unrestricted list of files. (org-get-clocktable): New function. (org-dblock-write:clocktable): Make sure :tstart and :tend can not only be strings but also integers (an absolute day number) and lists (m d y). * org/org-colview.el (org-columns-next-allowed-value) (org-columns-edit-value): Limit the effort for updatig in the agenda to recomputing a single file. (org-columns-compute): Only write property value if it has changed. This avoids raising the buffer-change-flag unnecessarily. (org-agenda-colview-summarize) (org-agenda-colview-compute): New functions. (org-agenda-columns): Call `org-agenda-colview-summarize'. * org/org-exp.el (org-export-run-in-background): New option. (org-export-icalendar): Allow a batch process to trigger waiting after executing a system command. (org-export-preprocess-string): Renamed-from `org-cleaned-string-for-export'. (org-export-html-style): Made target class look like normal text. (org-export-as-html): Make use of the better proprocessing in `org-cleaned-string-for-export'. (org-cleaned-string-for-export): Better treatment of heuristic targets, many more internal links will now work in HTML export. (org-get-current-options): Incorporate LINK_UP, LINK_HOME, and INFOJS. (org-export-inbuffer-options-extra): New variable. (org-export-options-filters): New hook. (org-infile-export-plist): Find also the settings keywords in `org-export-inbuffer-options-extra'. (org-infile-export-plist): Allow multiple #+OPTIONS lines and multiple #+INFOJS_OPT lines. (org-export-html-handle-js-options): New function. (org-export-html-infojs-setup): New option. (org-export-as-html): Call `org-export-html-handle-js-options'. Add autoload to all entry points. (org-skip-comments): Function removed. * org/org-table.el (org-table-make-reference): Extra parenthesis around single fields, to make sure that algebraic formulas get correctly interpreted by calc. (org-table-current-column): No longer interactive. * org/org-export-latex.el (org-export-latex-preprocess): Renamed from `org-export-latex-cleaned-string'. 2008-04-27 Bastien Guerry <bzg@altern.org> * org/org-publish.el (org-publish-get-base-files-1): New function. (org-publish-get-base-files): Use it. (org-publish-temp-files): New variable. Don't require 'dired-aux anymore. (org-publish-initial-buffer): New variable. (org-publish-org-to, org-publish): Use it. (org-publish-get-base-files-1): Bug fix: get the proper list of files when recursing thru a directory. (org-publish-get-base-files): Use the :exclude property to skip both files and directories.
author Carsten Dominik <dominik@science.uva.nl>
date Sun, 27 Apr 2008 18:33:39 +0000
parents b7a5a89054dc
children 8971ddf55736
line wrap: on
line source

/* Session management module for systems which understand the X Session
   management protocol.
   Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
     Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.

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
along with GNU Emacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.  */

#include <config.h>

#ifdef HAVE_X_SM

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

#ifdef HAVE_STRING_H
#include <string.h>
#else
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#endif

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#include <sys/param.h>
#include <stdio.h>

#include "lisp.h"
#include "systime.h"
#include "sysselect.h"
#include "frame.h"
#include "termhooks.h"
#include "termopts.h"
#include "xterm.h"

/* The user login name.  */

extern Lisp_Object Vuser_login_name;

/* This is the event used when SAVE_SESSION_EVENT occurs.  */

static struct input_event emacs_event;

/* The descriptor that we use to check for data from the session manager.  */

static int ice_fd = -1;

/* A flag that says if we are in shutdown interactions or not.  */

static int doing_interact = False;

/* The session manager object for the session manager connection.  */

static SmcConn smc_conn;

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

static char *client_id;

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

static char *emacs_program;

/* The client session id for this session as a lisp object.  */

Lisp_Object Vx_session_id;

/* The id we had the previous session.  This is only available if we
   have been started by the session manager with SMID_OPT.  */

Lisp_Object Vx_session_previous_id;

/* The option we tell the session manager to start Emacs with when
   restarting Emacs.  The client_id is appended.  */

#define SMID_OPT "--smid="


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

#define NOSPLASH_OPT "--no-splash"


/* Handle any messages from the session manager.  If no connection is
   open to a session manager, just return 0.
   Otherwise returns 1 if SAVE_SESSION_EVENT is stored in buffer BUFP.  */

int
x_session_check_input (bufp)
     struct input_event *bufp;
{
  SELECT_TYPE read_fds;
  EMACS_TIME tmout;

  if (ice_fd == -1) return 0;

  FD_ZERO (&read_fds);
  FD_SET (ice_fd, &read_fds);

  tmout.tv_sec = 0;
  tmout.tv_usec = 0;

  /* Reset this so wo can check kind after callbacks have been called by
     IceProcessMessages.  The smc_interact_CB sets the kind to
     SAVE_SESSION_EVENT, but we don't know beforehand if that callback
     will be called.  */
  emacs_event.kind = NO_EVENT;

  if (select (ice_fd+1, &read_fds,
              (SELECT_TYPE *)0, (SELECT_TYPE *)0, &tmout) < 0)
    {
      ice_fd = -1;
      return 0;
    }


  if (FD_ISSET (ice_fd, &read_fds))
    IceProcessMessages (SmcGetIceConnection (smc_conn),
                        (IceReplyWaitInfo *)0, (Bool *)0);


  /* Check if smc_interact_CB was called and we shall generate a
     SAVE_SESSION_EVENT.  */
  if (emacs_event.kind == NO_EVENT)
    return 0;

  bcopy (&emacs_event, bufp, sizeof (struct input_event));
  return 1;
}

/* Return non-zero if we have a connection to a session manager.  */

int
x_session_have_connection ()
{
  return ice_fd != -1;
}

/* This is called when the session manager says it is OK to interact with the
   user.  Here we set the kind to SAVE_SESSION_EVENT so an event is generated.
   Then lisp code can interact with the user.  */

static void
smc_interact_CB (smcConn, clientData)
     SmcConn smcConn;
     SmPointer clientData;
{
  doing_interact = True;
  emacs_event.kind = SAVE_SESSION_EVENT;
}

/* This is called when the session manager tells us to save ourselves.
   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,
   we do so, because we don't know what the lisp code might do.  */

static void
smc_save_yourself_CB (smcConn,
                      clientData,
                      saveType,
                      shutdown,
                      interactStyle,
                      fast)
     SmcConn smcConn;
     SmPointer clientData;
     int saveType;
     Bool shutdown;
     int interactStyle;
     Bool fast;
{
#define NR_PROPS 5

  SmProp *props[NR_PROPS];
  SmProp prop_ptr[NR_PROPS];

  SmPropValue values[20];
  int val_idx = 0;
  int props_idx = 0;

  char *cwd = NULL;
  char *smid_opt;

  /* How to start a new instance of Emacs.  */
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = SmCloneCommand;
  props[props_idx]->type = SmLISTofARRAY8;
  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;

  /* The name of the program.  */
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = SmProgram;
  props[props_idx]->type = SmARRAY8;
  props[props_idx]->num_vals = 1;
  props[props_idx]->vals = &values[val_idx++];
  props[props_idx]->vals[0].length = strlen (SDATA (Vinvocation_name));
  props[props_idx]->vals[0].value = SDATA (Vinvocation_name);
  ++props_idx;

  /* How to restart Emacs (i.e.: /path/to/emacs --smid=xxxx --no-splash).  */
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = SmRestartCommand;
  props[props_idx]->type = SmLISTofARRAY8;
  props[props_idx]->num_vals = 3; /* /path/to/emacs, --smid=xxx --no-splash  */
  props[props_idx]->vals = &values[val_idx];
  props[props_idx]->vals[0].length = strlen (emacs_program);
  props[props_idx]->vals[0].value = emacs_program;

  smid_opt = xmalloc (strlen (SMID_OPT) + strlen (client_id) + 1);
  strcpy (smid_opt, SMID_OPT);
  strcat (smid_opt, client_id);

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

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

  /* User id.  */
  props[props_idx] = &prop_ptr[props_idx];
  props[props_idx]->name = SmUserID;
  props[props_idx]->type = SmARRAY8;
  props[props_idx]->num_vals = 1;
  props[props_idx]->vals = &values[val_idx++];
  props[props_idx]->vals[0].length = strlen (SDATA (Vuser_login_name));
  props[props_idx]->vals[0].value = SDATA (Vuser_login_name);
  ++props_idx;

  cwd = get_current_dir_name ();

  if (cwd)
    {
      props[props_idx] = &prop_ptr[props_idx];
      props[props_idx]->name = SmCurrentDirectory;
      props[props_idx]->type = SmARRAY8;
      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;
    }


  SmcSetProperties (smcConn, props_idx, props);

  xfree (smid_opt);

  if (cwd)
    free (cwd);

  /* See if we maybe shall interact with the user.  */
  if (interactStyle != SmInteractStyleAny
      || ! shutdown
      || saveType == SmSaveLocal
      || ! SmcInteractRequest (smcConn, SmDialogNormal, smc_interact_CB, 0))
    {
      /* No interaction, we are done saving ourself.  */
      SmcSaveYourselfDone (smcConn, True);
    }
}

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

static void
smc_die_CB (smcConn, clientData)
     SmcConn smcConn;
     SmPointer clientData;
{
  SmcCloseConnection (smcConn, 0, 0);
  ice_fd = -1;
}

/* 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
   even seem necessary.  */

static void
smc_save_complete_CB (smcConn, clientData)
     SmcConn smcConn;
     SmPointer clientData;
{
  /* Empty */
}

static void
smc_shutdown_cancelled_CB (smcConn, clientData)
     SmcConn smcConn;
     SmPointer clientData;
{
  /* Empty */
}

/* Error handlers for SM and ICE.  We don't want to exit Emacs just
   because there is some error in the session management.  */

static void
smc_error_handler (smcConn,
                   swap,
                   offendingMinorOpcode,
                   offendingSequence,
                   errorClass,
                   severity,
                   values)
     SmcConn smcConn;
     Bool swap;
     int offendingMinorOpcode;
     unsigned long offendingSequence;
     int errorClass;
     int severity;
     SmPointer values;
{
  /* Empty  */
}

static void
ice_error_handler (iceConn,
                   swap,
                   offendingMinorOpcode,
                   offendingSequence,
                   errorClass,
                   severity,
                   values)
     IceConn iceConn;
     Bool swap;
     int offendingMinorOpcode;
     unsigned long offendingSequence;
     int errorClass;
     int severity;
     IcePointer values;
{
  /* Empty  */
}


static void
ice_io_error_handler (iceConn)
     IceConn iceConn;
{
  /* Connection probably gone.  */
  ice_fd = -1;
}

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

static void
ice_conn_watch_CB (iceConn, clientData, opening, watchData)
     IceConn iceConn;
     IcePointer clientData;
     Bool opening;
     IcePointer *watchData;
{
  if (! opening)
    {
      ice_fd = -1;
      return;
    }

  ice_fd = IceConnectionNumber (iceConn);
#ifdef F_SETOWN
  fcntl (ice_fd, F_SETOWN, getpid ());
#endif /* ! defined (F_SETOWN) */

#ifdef SIGIO
  if (interrupt_input)
    init_sigio (ice_fd);
#endif /* ! defined (SIGIO) */
}

/* Create the client leader window.  */

static void
create_client_leader_window (dpyinfo, client_id)
     struct x_display_info *dpyinfo;
     char *client_id;
{
  Window w;
  XClassHint class_hints;
  Atom sm_id;

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

  class_hints.res_name = (char *) SDATA (Vx_resource_name);
  class_hints.res_class = (char *) SDATA (Vx_resource_class);
  XSetClassHint (dpyinfo->display, w, &class_hints);
  XStoreName (dpyinfo->display, w, class_hints.res_name);

  sm_id = XInternAtom (dpyinfo->display, "SM_CLIENT_ID", False);
  XChangeProperty (dpyinfo->display, w, sm_id, XA_STRING, 8, PropModeReplace,
                   client_id, strlen (client_id));

  dpyinfo->client_leader_window = w;
}

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

void
x_session_initialize (dpyinfo)
     struct x_display_info *dpyinfo;
{
#define SM_ERRORSTRING_LEN 512
  char errorstring[SM_ERRORSTRING_LEN];
  char* previous_id = NULL;
  SmcCallbacks callbacks;
  int  name_len = 0;

  /* Check if we where started by the session manager.  If so, we will
     have a previous id.  */
  if (! EQ (Vx_session_previous_id, Qnil) && STRINGP (Vx_session_previous_id))
    previous_id = SDATA (Vx_session_previous_id);

  /* Construct the path to the Emacs program.  */
  if (! EQ (Vinvocation_directory, Qnil))
    name_len += strlen (SDATA (Vinvocation_directory));
  name_len += strlen (SDATA (Vinvocation_name));

  /* This malloc will not be freed, but it is only done once, and hopefully
     not very large   */
  emacs_program = xmalloc (name_len + 1);
  emacs_program[0] = '\0';

  if (! EQ (Vinvocation_directory, Qnil))
    strcpy (emacs_program, SDATA (Vinvocation_directory));
  strcat (emacs_program, SDATA (Vinvocation_name));

  /* The SM protocol says all callbacks are mandatory, so set up all
     here and in the mask passed to SmcOpenConnection.  */
  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;

  /* Set error handlers.  */
  SmcSetErrorHandler (smc_error_handler);
  IceSetErrorHandler (ice_error_handler);
  IceSetIOErrorHandler (ice_io_error_handler);

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

  /* Open the connection to the session manager.  A failure is not
     critical, it usually means that no session manager is running.
     The errorstring is here for debugging.  */
  smc_conn = SmcOpenConnection (NULL, NULL, 1, 0,
                                (SmcSaveYourselfProcMask|
                                 SmcDieProcMask|
                                 SmcSaveCompleteProcMask|
                                 SmcShutdownCancelledProcMask),
                                &callbacks,
                                previous_id,
                                &client_id,
                                SM_ERRORSTRING_LEN,
                                errorstring);

  if (smc_conn != 0)
    {
      Vx_session_id = make_string (client_id, strlen (client_id));

#ifdef USE_GTK
      /* GTK creats a leader window by itself, but we need to tell
         it about our client_id.  */
      gdk_set_sm_client_id (client_id);
#else
      create_client_leader_window (dpyinfo, client_id);
#endif
    }
}

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

void
x_session_close ()
{
  ice_fd = -1;
}


DEFUN ("handle-save-session", Fhandle_save_session,
       Shandle_save_session, 1, 1, "e",
       doc: /* Handle the save_yourself event from a session manager.
A session manager can tell Emacs that the window system is shutting down
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. */)
     (event)
     Lisp_Object event;
{
  /* Check doing_interact so that we don't do anything if someone called
     this at the wrong time. */
  if (doing_interact)
    {
      Bool cancel_shutdown = False;

      cancel_shutdown = ! EQ (call0 (intern ("emacs-session-save")), Qnil);

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

      doing_interact = False;
    }

  return Qnil;
}


/***********************************************************************
			    Initialization
 ***********************************************************************/
void
syms_of_xsmfns ()
{
  DEFVAR_LISP ("x-session-id", &Vx_session_id,
    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',
`emacs-session-save' and `emacs-session-restore'." */);
  Vx_session_id = Qnil;

  DEFVAR_LISP ("x-session-previous-id", &Vx_session_previous_id,
    doc: /* The previous session id Emacs got from session manager.
If Emacs is running on a window system that has a session manager, the
session manager gives Emacs a session id.  It is feasible for Emacs Lisp
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
running and saves the session id Emacs had.

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
previous session id shall be used to reconstruct the file name.

The session id Emacs has while it is running is in the variable
`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
`emacs-session-restore'." */);
  Vx_session_previous_id = Qnil;

  defsubr (&Shandle_save_session);
}

#endif /* HAVE_X_SM */

/* arch-tag: 56a2c58c-adfa-430a-b772-130abd29fd2e
   (do not change this comment) */