home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / lucid / lemacs-19.6 / src / xselect.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-29  |  59.0 KB  |  1,956 lines

  1. /* X Selection processing for emacs
  2.    Copyright (C) 1990-1993 Free Software Foundation.
  3.  
  4. This file is part of GNU Emacs.
  5.  
  6. GNU Emacs is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU Emacs is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU Emacs; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* Rewritten by jwz */
  21.  
  22. #include "config.h"
  23. #include "lisp.h"
  24. #include "xterm.h"    /* for all of the X includes */
  25. #include "dispextern.h"    /* screen.h seems to want this */
  26. #include "screen.h"    /* Need this to get the X window of selected_screen */
  27.  
  28. #ifdef LWLIB_USES_MOTIF
  29. # define MOTIF_CLIPBOARDS
  30. #endif
  31.  
  32. #ifdef MOTIF_CLIPBOARDS
  33. # include <Xm/CutPaste.h>
  34. #endif
  35.  
  36. #define CUT_BUFFER_SUPPORT
  37.  
  38. static Atom Xatom_CLIPBOARD, Xatom_TIMESTAMP, Xatom_TEXT, Xatom_DELETE,
  39.   Xatom_MULTIPLE, Xatom_INCR, Xatom_EMACS_TMP, Xatom_TARGETS, Xatom_NULL,
  40.   Xatom_ATOM_PAIR;
  41.  
  42. Lisp_Object QPRIMARY, QSECONDARY, QSTRING, QINTEGER, QCLIPBOARD, QTIMESTAMP,
  43.   QTEXT, QDELETE, QMULTIPLE, QINCR, QEMACS_TMP, QTARGETS, QATOM, QNULL,
  44.   QATOM_PAIR;
  45.  
  46. #ifdef CUT_BUFFER_SUPPORT
  47. Lisp_Object QCUT_BUFFER0, QCUT_BUFFER1, QCUT_BUFFER2, QCUT_BUFFER3,
  48.   QCUT_BUFFER4, QCUT_BUFFER5, QCUT_BUFFER6, QCUT_BUFFER7;
  49. #endif
  50.  
  51. Lisp_Object Vx_lost_selection_hooks;
  52. Lisp_Object Vx_sent_selection_hooks;
  53.  
  54. /* If this is a smaller number than the max-request-size of the display,
  55.    emacs will use INCR selection transfer when the selection is larger
  56.    than this.  The max-request-size is usually around 64k, so if you want
  57.    emacs to use incremental selection transfers when the selection is 
  58.    smaller than that, set this.  I added this mostly for debugging the
  59.    incremental transfer stuff, but it might improve server performance.
  60.  */
  61. #define MAX_SELECTION_QUANTUM 0xFFFFFF
  62.  
  63. #define SELECTION_QUANTUM(dpy) ((XMaxRequestSize (dpy) << 2) - 100)
  64.  
  65.  
  66. /* The time of the last-read mouse or keyboard event. 
  67.    For selection purposes, we use this as a sleazy way of knowing what the
  68.    current time is in server-time.  This assumes that the most recently read
  69.    mouse or keyboard event has something to do with the assertion of the
  70.    selection, which is probably true.
  71.  */
  72. extern Time mouse_timestamp;
  73.  
  74.  
  75. /* This is an association list whose elements are of the form
  76.      ( selection-name selection-value selection-timestamp )
  77.    selection-name is a lisp symbol, whose name is the name of an X Atom.
  78.    selection-value is the value that emacs owns for that selection.
  79.      It may be any kind of Lisp object.
  80.    selection-timestamp is the time at which emacs began owning this selection,
  81.      as a cons of two 16-bit numbers (making a 32 bit time.)
  82.    If there is an entry in this alist, then it can be assumed that emacs owns
  83.     that selection.
  84.    The only (eq) parts of this list that are visible from elisp are the
  85.     selection-values.
  86.  */
  87. Lisp_Object Vselection_alist;
  88.  
  89. /* This is an alist whose CARs are selection-types (whose names are the same
  90.    as the names of X Atoms) and whose CDRs are the names of Lisp functions to
  91.    call to convert the given Emacs selection value to a string representing 
  92.    the given selection type.  This is for elisp-level extension of the emacs
  93.    selection handling.
  94.  */
  95. Lisp_Object Vselection_converter_alist;
  96.  
  97. /* If the selection owner takes too long to reply to a selection request,
  98.    we give up on it.  This is in seconds (0 = no timeout.)
  99.  */
  100. int x_selection_timeout;
  101.  
  102.  
  103. /* Utility functions */
  104.  
  105. static void lisp_data_to_selection_data ();
  106. static Lisp_Object selection_data_to_lisp_data ();
  107. static Lisp_Object x_get_window_property_as_lisp_data ();
  108.  
  109. static int expect_property_change ();
  110. static void wait_for_property_change ();
  111. static void unexpect_property_change ();
  112. static int waiting_for_other_props_on_window ();
  113.  
  114. /* This converts a Lisp symbol to a server Atom, avoiding a server 
  115.    roundtrip whenever possible.
  116.  */
  117. static Atom
  118. symbol_to_x_atom (display, sym)
  119.      Display *display;
  120.      Lisp_Object sym;
  121. {
  122.   Atom val;
  123.   if (NILP (sym))        return 0;
  124.   if (EQ (sym, QPRIMARY))   return XA_PRIMARY;
  125.   if (EQ (sym, QSECONDARY)) return XA_SECONDARY;
  126.   if (EQ (sym, QSTRING))    return XA_STRING;
  127.   if (EQ (sym, QINTEGER))   return XA_INTEGER;
  128.   if (EQ (sym, QATOM))        return XA_ATOM;
  129.   if (EQ (sym, QCLIPBOARD)) return Xatom_CLIPBOARD;
  130.   if (EQ (sym, QTIMESTAMP)) return Xatom_TIMESTAMP;
  131.   if (EQ (sym, QTEXT))        return Xatom_TEXT;
  132.   if (EQ (sym, QDELETE))    return Xatom_DELETE;
  133.   if (EQ (sym, QMULTIPLE))  return Xatom_MULTIPLE;
  134.   if (EQ (sym, QINCR))        return Xatom_INCR;
  135.   if (EQ (sym, QEMACS_TMP)) return Xatom_EMACS_TMP;
  136.   if (EQ (sym, QTARGETS))   return Xatom_TARGETS;
  137.   if (EQ (sym, QNULL))        return Xatom_NULL;
  138. #ifdef CUT_BUFFER_SUPPORT
  139.   if (EQ (sym, QCUT_BUFFER0)) return XA_CUT_BUFFER0;
  140.   if (EQ (sym, QCUT_BUFFER1)) return XA_CUT_BUFFER1;
  141.   if (EQ (sym, QCUT_BUFFER2)) return XA_CUT_BUFFER2;
  142.   if (EQ (sym, QCUT_BUFFER3)) return XA_CUT_BUFFER3;
  143.   if (EQ (sym, QCUT_BUFFER4)) return XA_CUT_BUFFER4;
  144.   if (EQ (sym, QCUT_BUFFER5)) return XA_CUT_BUFFER5;
  145.   if (EQ (sym, QCUT_BUFFER6)) return XA_CUT_BUFFER6;
  146.   if (EQ (sym, QCUT_BUFFER7)) return XA_CUT_BUFFER7;
  147. #endif
  148.   if (!SYMBOLP (sym)) abort ();
  149.  
  150.   BLOCK_INPUT;
  151.   val = XInternAtom (display, (char *) XSYMBOL (sym)->name->data, False);
  152.   UNBLOCK_INPUT;
  153.   return val;
  154. }
  155.  
  156.  
  157. /* This converts a server Atom to a Lisp symbol, avoiding server roundtrips
  158.    and calls to intern whenever possible.
  159.  */
  160. static Lisp_Object
  161. x_atom_to_symbol (display, atom)
  162.      Display *display;
  163.      Atom atom;
  164. {
  165.   char *str;
  166.   Lisp_Object val;
  167.   if (! atom) return Qnil;
  168.   if (atom == XA_PRIMARY)      return QPRIMARY;
  169.   if (atom == XA_SECONDARY)    return QSECONDARY;
  170.   if (atom == XA_STRING)       return QSTRING;
  171.   if (atom == XA_INTEGER)      return QINTEGER;
  172.   if (atom == XA_ATOM)           return QATOM;
  173.   if (atom == Xatom_CLIPBOARD) return QCLIPBOARD;
  174.   if (atom == Xatom_TIMESTAMP) return QTIMESTAMP;
  175.   if (atom == Xatom_TEXT)      return QTEXT;
  176.   if (atom == Xatom_DELETE)    return QDELETE;
  177.   if (atom == Xatom_MULTIPLE)  return QMULTIPLE;
  178.   if (atom == Xatom_INCR)      return QINCR;
  179.   if (atom == Xatom_EMACS_TMP) return QEMACS_TMP;
  180.   if (atom == Xatom_TARGETS)   return QTARGETS;
  181.   if (atom == Xatom_NULL)      return QNULL;
  182. #ifdef CUT_BUFFER_SUPPORT
  183.   if (atom == XA_CUT_BUFFER0) return QCUT_BUFFER0;
  184.   if (atom == XA_CUT_BUFFER1) return QCUT_BUFFER1;
  185.   if (atom == XA_CUT_BUFFER2) return QCUT_BUFFER2;
  186.   if (atom == XA_CUT_BUFFER3) return QCUT_BUFFER3;
  187.   if (atom == XA_CUT_BUFFER4) return QCUT_BUFFER4;
  188.   if (atom == XA_CUT_BUFFER5) return QCUT_BUFFER5;
  189.   if (atom == XA_CUT_BUFFER6) return QCUT_BUFFER6;
  190.   if (atom == XA_CUT_BUFFER7) return QCUT_BUFFER7;
  191. #endif
  192.  
  193.   BLOCK_INPUT;
  194.   str = XGetAtomName (display, atom);
  195.   UNBLOCK_INPUT;
  196.   if (! str) return Qnil;
  197.   val = intern (str);
  198.   BLOCK_INPUT;
  199.   XFree (str);
  200.   UNBLOCK_INPUT;
  201.   return val;
  202. }
  203.  
  204.  
  205. static Lisp_Object
  206. long_to_cons (i)
  207.      unsigned long i;
  208. {
  209.   unsigned int top = i >> 16;
  210.   unsigned int bot = i & 0xFFFF;
  211.   if (top == 0) return make_number (bot);
  212.   if (top == 0xFFFF) return Fcons (make_number (-1), make_number (bot));
  213.   return Fcons (make_number (top), make_number (bot));
  214. }
  215.  
  216. static unsigned long
  217. cons_to_long (c)
  218.      Lisp_Object c;
  219. {
  220.   int top, bot;
  221.   if (FIXNUMP (c)) return XINT (c);
  222.   top = XCONS (c)->car;
  223.   bot = XCONS (c)->cdr;
  224.   if (CONSP (bot)) bot = XCONS (bot)->car;
  225.   return ((XINT (top) << 16) | XINT (bot));
  226. }
  227.  
  228.  
  229.  
  230. /* Do protocol to assert ourself as a selection owner.
  231.    Update the Vselection_alist so that we can reply to later requests for 
  232.    our selection.
  233.  */
  234. static void
  235. x_own_selection (selection_name, selection_value)
  236.      Lisp_Object selection_name, selection_value;
  237. {
  238.   Display *display = x_current_display;
  239.   Window selecting_window = XtWindow (selected_screen->display.x->edit_widget);
  240.   Time time = mouse_timestamp;
  241.   Atom selection_atom;
  242.  
  243.   CHECK_SYMBOL (selection_name, 0);
  244.   selection_atom = symbol_to_x_atom (display, selection_name);
  245.  
  246.   BLOCK_INPUT;
  247.   XSetSelectionOwner (display, selection_atom, selecting_window, time);
  248.   UNBLOCK_INPUT;
  249.  
  250.   /* Now update the local cache */
  251.   {
  252.     Lisp_Object selection_time = long_to_cons ((unsigned long) time);
  253.     Lisp_Object selection_data = Fcons (selection_name,
  254.                     Fcons (selection_value,
  255.                            Fcons (selection_time, Qnil)));
  256.     Lisp_Object prev_value = assq_no_quit (selection_name, Vselection_alist);
  257.     Vselection_alist = Fcons (selection_data, Vselection_alist);
  258.  
  259.     /* If we already owned the selection, remove the old selection data.
  260.        Perhaps we should destructively modify it instead.
  261.        Don't use Fdelq() as that may QUIT;.
  262.      */
  263.     if (!NILP (prev_value))
  264.       {
  265.     Lisp_Object rest;    /* we know it's not the CAR, so it's easy. */
  266.     for (rest = Vselection_alist; !NILP (rest); rest = Fcdr (rest))
  267.       if (EQ (prev_value, Fcar (XCONS (rest)->cdr)))
  268.         {
  269.           XCONS (rest)->cdr = Fcdr (XCONS (rest)->cdr);
  270.           break;
  271.         }
  272.       }
  273.   }
  274.  
  275. #ifdef MOTIF_CLIPBOARDS
  276.   /* Those Motif wankers can't be bothered to follow the ICCCM, and do
  277.      their own non-Xlib non-Xt clipboard processing.  So we have to do
  278.      this so that linked-in Motif widgets don't get themselves wedged.
  279.    */
  280.   if (selection_atom == Xatom_CLIPBOARD &&
  281.       STRINGP (selection_value))
  282.     {
  283.       Widget widget = selected_screen->display.x->edit_widget;
  284.       int result;
  285.       long itemid;
  286.       int dataid;
  287.       XmString fmh;
  288.       BLOCK_INPUT;
  289.       fmh = XmStringCreateLtoR ("Clipboard", XmSTRING_DEFAULT_CHARSET);
  290.       while (ClipboardSuccess !=
  291.          XmClipboardStartCopy (display, selecting_window, fmh, time,
  292.                    widget, NULL, &itemid))
  293.     ;
  294.       XmStringFree (fmh);
  295.       while (ClipboardSuccess !=
  296.          XmClipboardCopy (display, selecting_window, itemid, "STRING",
  297.                   (char *) XSTRING (selection_value)->data,
  298.                   XSTRING (selection_value)->size + 1,
  299.                   0, &dataid))
  300.     ;
  301.       while (ClipboardSuccess !=
  302.          XmClipboardEndCopy (display, selecting_window, itemid))
  303.     ;
  304.       UNBLOCK_INPUT;
  305.     }
  306. #endif /* MOTIF_CLIPBOARDS */
  307. }
  308.  
  309.  
  310. /* Given a selection-name and desired type, this looks up our local copy of
  311.    the selection value and converts it to the type.  It returns nil or a
  312.    string.  This calls random elisp code, and may signal or gc.
  313.  */
  314. static Lisp_Object
  315. x_get_local_selection (selection_symbol, target_type)
  316.      Lisp_Object selection_symbol, target_type;
  317. {
  318.   Lisp_Object local_value = assq_no_quit (selection_symbol, Vselection_alist);
  319.   Lisp_Object handler_fn, value, check;
  320.  
  321.   if (NILP (local_value)) return Qnil;
  322.  
  323.   /* TIMESTAMP and MULTIPLE are special cases 'cause that's easiest. */
  324.   if (EQ (target_type, QTIMESTAMP))
  325.     {
  326.       handler_fn = Qnil;
  327.       value = XCONS (XCONS (XCONS (local_value)->cdr)->cdr)->car;
  328.     }
  329.  
  330. #if 0 /* #### MULTIPLE doesn't work yet */
  331.   else if (CONSP (target_type) &&
  332.        XCONS (target_type)->car == QMULTIPLE)
  333.     {
  334.       Lisp_Object pairs = XCONS (target_type)->cdr;
  335.       int size = XVECTOR (pairs)->size;
  336.       int i;
  337.       /* If the target is MULTIPLE, then target_type looks like
  338.       (MULTIPLE . [[SELECTION1 TARGET1] [SELECTION2 TARGET2] ... ])
  339.      We modify the second element of each pair in the vector and
  340.      return it as [[SELECTION1 <value1>] [SELECTION2 <value2>] ... ]
  341.        */
  342.       for (i = 0; i < size; i++)
  343.     {
  344.       Lisp_Object pair = XVECTOR (pairs)->contents [i];
  345.       XVECTOR (pair)->contents [1] =
  346.         x_get_local_selection (XVECTOR (pair)->contents [0],
  347.                    XVECTOR (pair)->contents [1]);
  348.     }
  349.       return pairs;
  350.     }
  351. #endif
  352.   else
  353.     {
  354.       CHECK_SYMBOL (target_type, 0);
  355.       handler_fn = Fcdr (Fassq (target_type, Vselection_converter_alist));
  356.       if (NILP (handler_fn)) return Qnil;
  357.       value = call3 (handler_fn,
  358.              selection_symbol, target_type,
  359.              XCONS (XCONS (local_value)->cdr)->car);
  360.     }
  361.  
  362.   /* This lets the selection function to return (TYPE . VALUE).  For example,
  363.      when the selected type is LINE_NUMBER, the returned type is SPAN, not
  364.      INTEGER.
  365.    */
  366.   check = value;
  367.   if (CONSP (value) && SYMBOLP (XCONS (value)->car))
  368.     check = XCONS (value)->cdr;
  369.   
  370.   /* Strings, vectors, and symbols are converted to selection data format in
  371.      the obvious way.  Integers are converted to 16 bit quantities if they're
  372.      small enough, otherwise 32 bits are used.
  373.    */
  374.   if (STRINGP (check) ||
  375.       VECTORP (check) ||
  376.       SYMBOLP (check) ||
  377.       FIXNUMP (check) ||
  378.       NILP (value))
  379.     return value;
  380.  
  381.   /* (N . M) or (N M) get turned into a 32 bit quantity.  So if you want to
  382.      always return a small quantity as 32 bits, your converter routine needs
  383.      to return a cons.
  384.    */
  385.   else if (CONSP (check) &&
  386.        FIXNUMP (XCONS (check)->car) &&
  387.        (FIXNUMP (XCONS (check)->cdr) ||
  388.         (CONSP (XCONS (check)->cdr) &&
  389.          FIXNUMP (XCONS (XCONS (check)->cdr)->car) &&
  390.          NILP (XCONS (XCONS (check)->cdr)->cdr))))
  391.     return value;
  392.   /* Otherwise the lisp converter function returned something unrecognised. 
  393.    */
  394.   else
  395.     return
  396.       Fsignal (Qerror,
  397.            Fcons (build_string ("unrecognised selection-conversion type"),
  398.               Fcons (handler_fn, Fcons (value, Qnil))));
  399. }
  400.  
  401.  
  402.  
  403. /* Send a SelectionNotify event to the requestor with property=None, meaning
  404.    we were unable to do what they wanted.
  405.  */
  406. static void
  407. x_decline_selection_request (event)
  408.      XSelectionRequestEvent *event;
  409. {
  410.   XSelectionEvent reply;
  411.   reply.type = SelectionNotify;
  412.   reply.display = event->display;
  413.   reply.requestor = event->requestor;
  414.   reply.selection = event->selection;
  415.   reply.time = event->time;
  416.   reply.target = event->target;
  417.   reply.property = None;
  418.  
  419.   BLOCK_INPUT;
  420.   (void) XSendEvent (reply.display, reply.requestor, False, 0L,
  421.              (XEvent *) &reply);
  422.   UNBLOCK_INPUT;
  423. }
  424.  
  425.  
  426. /* Used as an unwind-protect clause so that, if a selection-converter signals
  427.    an error, we tell the requestor that we were unable to do what they wanted
  428.    before we throw to top-level or go into the debugger or whatever.
  429.  */
  430. static Lisp_Object
  431. x_selection_request_lisp_error (closure)
  432.      Lisp_Object closure;
  433. {
  434.   /* Sleazy! */
  435.   XSelectionRequestEvent *event = (XSelectionRequestEvent *) closure;
  436.   
  437.   if (event->type == 0) /* we set this to mean "completed normally" */
  438.     return Qnil;
  439.   x_decline_selection_request (event);
  440.   return Qnil;
  441. }
  442.  
  443.  
  444. /* Convert our selection to the requested type, and put that data where the
  445.    requestor wants it.  Then tell them whether we've succeeded.
  446.  */
  447. static void
  448. x_reply_selection_request (event, format, data, size, type)
  449.      XSelectionRequestEvent *event;
  450.      int format, size;
  451.      unsigned char *data;
  452.      Atom type;
  453. {
  454.   XSelectionEvent reply;
  455.   Display *display = event->display;
  456.   Window window = event->requestor;
  457.   int bytes_remaining;
  458.   int format_bytes = format/8;
  459.   int max_bytes = SELECTION_QUANTUM (display);
  460.   if (max_bytes > MAX_SELECTION_QUANTUM) max_bytes = MAX_SELECTION_QUANTUM;
  461.  
  462.   reply.type = SelectionNotify;
  463.   reply.display = display;
  464.   reply.requestor = window;
  465.   reply.selection = event->selection;
  466.   reply.time = event->time;
  467.   reply.target = event->target;
  468.   reply.property = (event->property == None ? event->target : event->property);
  469.  
  470.   /* #### XChangeProperty can generate BadAlloc, and we must handle it! */
  471.  
  472.   BLOCK_INPUT;
  473.   /* Store the data on the requested property.
  474.      If the selection is large, only store the first N bytes of it.
  475.    */
  476.   bytes_remaining = size * format_bytes;
  477.   if (bytes_remaining <= max_bytes)
  478.     {
  479.       /* Send all the data at once, with minimal handshaking. */
  480. #if 0
  481.       fprintf(stderr,"\nStoring all %d\n", bytes_remaining);
  482. #endif
  483.       XChangeProperty (display, window, reply.property, type, format,
  484.                PropModeReplace, data, size);
  485.       /* At this point, the selection was successfully stored; ack it. */
  486.       (void) XSendEvent (display, window, False, 0L, (XEvent *) &reply);
  487.     }
  488.   else
  489.     {
  490.       /* Send an INCR selection. */
  491.       int prop_id;
  492.  
  493.       if (x_window_to_screen (window)) /* #### debug */
  494.     error ("attempt to transfer an INCR to ourself!");
  495. #if 0
  496.       fprintf(stderr, "\nINCR %d\n", bytes_remaining);
  497. #endif
  498.       prop_id = expect_property_change (display, window, reply.property,
  499.                     PropertyDelete);
  500.  
  501.       XChangeProperty (display, window, reply.property, Xatom_INCR,
  502.                32, PropModeReplace, (unsigned char *)
  503.                &bytes_remaining, 1);
  504.       XSelectInput (display, window, PropertyChangeMask);
  505.       /* Tell 'em the INCR data is there... */
  506.       (void) XSendEvent (display, window, False, 0L, (XEvent *) &reply);
  507.  
  508.       /* First, wait for the requestor to ack by deleting the property.
  509.      This can run random lisp code (process handlers) or signal.
  510.        */
  511.       wait_for_property_change (prop_id);
  512.  
  513.       while (bytes_remaining)
  514.     {
  515.       int i = ((bytes_remaining < max_bytes)
  516.            ? bytes_remaining
  517.            : max_bytes);
  518.       prop_id = expect_property_change (display, window, reply.property,
  519.                         PropertyDelete);
  520. #if 0
  521.       fprintf (stderr,"  INCR adding %d\n", i);
  522. #endif
  523.       /* Append the next chunk of data to the property. */
  524.       XChangeProperty (display, window, reply.property, type, format,
  525.                PropModeAppend, data, i / format_bytes);
  526.       bytes_remaining -= i;
  527.       data += i;
  528.  
  529.       /* Now wait for the requestor to ack this chunk by deleting the
  530.          property.     This can run random lisp code or signal.
  531.        */
  532.       wait_for_property_change (prop_id);
  533.     }
  534.       /* Now write a zero-length chunk to the property to tell the requestor
  535.      that we're done. */
  536. #if 0
  537.       fprintf (stderr,"  INCR done\n");
  538. #endif
  539.       if (! waiting_for_other_props_on_window (display, window))
  540.     XSelectInput (display, window, 0L);
  541.  
  542.       XChangeProperty (display, window, reply.property, type, format,
  543.                PropModeReplace, data, 0);
  544.     }
  545.   UNBLOCK_INPUT;
  546. }
  547.  
  548.  
  549.  
  550. /* Called from the event-loop in response to a SelectionRequest event.
  551.  */
  552. void
  553. x_handle_selection_request (event)
  554.      XSelectionRequestEvent *event;
  555. {
  556.   struct gcpro gcpro1, gcpro2, gcpro3;
  557.   XSelectionEvent reply;
  558.   Lisp_Object local_selection_data = Qnil;
  559.   Lisp_Object selection_symbol;
  560.   Lisp_Object target_symbol = Qnil;
  561.   Lisp_Object converted_selection = Qnil;
  562.   Time local_selection_time;
  563.   Lisp_Object successful_p = Qnil;
  564.   int count;
  565.  
  566.   GCPRO3 (local_selection_data, converted_selection, target_symbol);
  567.  
  568.   reply.type = SelectionNotify;        /* Construct the reply event */
  569.   reply.display = event->display;
  570.   reply.requestor = event->requestor;
  571.   reply.selection = event->selection;
  572.   reply.time = event->time;
  573.   reply.target = event->target;
  574.   reply.property = (event->property == None ? event->target : event->property);
  575.  
  576.   selection_symbol = x_atom_to_symbol (reply.display, event->selection);
  577.  
  578.   local_selection_data = assq_no_quit (selection_symbol, Vselection_alist);
  579.   
  580. #if 0
  581. # define CDR(x) (XCONS(x)->cdr)
  582. # define CAR(x) (XCONS(x)->car)
  583.   /* This list isn't user-visible, so it can't "go bad." */
  584.   if (!CONSP (local_selection_data)) abort ();
  585.   if (!CONSP (CDR (local_selection_data))) abort ();
  586.   if (!CONSP (CDR (CDR (local_selection_data)))) abort ();
  587.   if (!NILP (CDR (CDR (CDR (local_selection_data))))) abort ();
  588.   if (!CONSP (CAR (CDR (CDR (local_selection_data))))) abort ();
  589.   if (!FIXNUMP (CAR (CAR (CDR (CDR (local_selection_data)))))) abort ();
  590.   if (!FIXNUMP (CDR (CAR (CDR (CDR (local_selection_data)))))) abort ();
  591. # undef CAR
  592. # undef CDR
  593. #endif
  594.  
  595.   if (NILP (local_selection_data))
  596.     {
  597.       /* Someone asked for the selection, but we don't have it any more.
  598.        */
  599.       x_decline_selection_request (event);
  600.       goto DONE;
  601.     }
  602.  
  603.   local_selection_time = (Time)
  604.     cons_to_long (XCONS (XCONS (XCONS (local_selection_data)->cdr)->cdr)->car);
  605.  
  606.   if (event->time != CurrentTime &&
  607.       local_selection_time > event->time)
  608.     {
  609.       /* Someone asked for the selection, and we have one, but not the one
  610.      they're looking for.
  611.        */
  612.       x_decline_selection_request (event);
  613.       goto DONE;
  614.     }
  615.  
  616.   count = specpdl_ptr - specpdl;
  617.   record_unwind_protect (x_selection_request_lisp_error,
  618.              (Lisp_Object) event);    /* #### dangerous cast */
  619.   target_symbol = x_atom_to_symbol (reply.display, event->target);
  620.  
  621. #if 0 /* #### MULTIPLE doesn't work yet */
  622.   if (EQ (target_symbol, QMULTIPLE))
  623.     target_symbol = fetch_multiple_target (event);
  624. #endif
  625.   
  626.   /* Convert lisp objects back into binary data */
  627.   
  628.   converted_selection =
  629.     x_get_local_selection (selection_symbol, target_symbol);
  630.   
  631.   if (! NILP (converted_selection))
  632.     {
  633.       unsigned char *data;
  634.       unsigned int size;
  635.       int format;
  636.       Atom type;
  637.       lisp_data_to_selection_data (reply.display, converted_selection,
  638.                    &data, &type, &size, &format);
  639.       
  640.       x_reply_selection_request (event, format, data, size, type);
  641.       successful_p = Qt;
  642.       /* Tell x_selection_request_lisp_error() it's cool. */
  643.       event->type = 0;
  644.       xfree (data);
  645.     }
  646.   unbind_to (count, Qnil);
  647.  
  648.  DONE:
  649.  
  650.   UNGCPRO;
  651.  
  652.   /* Let random lisp code notice that the selection has been asked for.
  653.    */
  654.   {
  655.     Lisp_Object rest;
  656.     Lisp_Object val = Vx_sent_selection_hooks;
  657.     if (!EQ (val, Qunbound) && !NILP (val))
  658.       {
  659.     if (CONSP (val) && !EQ (XCONS (val)->car, Qlambda))
  660.       for (rest = val; !NILP (rest); rest = Fcdr (rest))
  661.         call3 (Fcar(rest), selection_symbol, target_symbol, successful_p);
  662.     else
  663.       call3 (val, selection_symbol, target_symbol, successful_p);
  664.       }
  665.   }
  666. }
  667.  
  668.  
  669. /* Called from the event-loop in response to a SelectionClear event.
  670.  */
  671. void
  672. x_handle_selection_clear (event)
  673.      XSelectionClearEvent *event;
  674. {
  675.   Display *display = event->display;
  676.   Atom selection = event->selection;
  677.   Time changed_owner_time = event->time;
  678.   
  679.   Lisp_Object selection_symbol, local_selection_data;
  680.   Time local_selection_time;
  681.  
  682.   selection_symbol = x_atom_to_symbol (display, selection);
  683.  
  684.   local_selection_data = assq_no_quit (selection_symbol, Vselection_alist);
  685.  
  686.   /* Well, we already believe that we don't own it, so that's just fine. */
  687.   if (NILP (local_selection_data)) return;
  688.  
  689.   local_selection_time = (Time)
  690.     cons_to_long (XCONS (XCONS (XCONS (local_selection_data)->cdr)->cdr)->car);
  691.  
  692.   /* This SelectionClear is for a selection that we no longer own, so we can
  693.      disregard it.  (That is, we have reasserted the selection since this
  694.      request was generated.)
  695.    */
  696.   if (changed_owner_time != CurrentTime &&
  697.       local_selection_time > changed_owner_time)
  698.     return;
  699.  
  700.   /* Otherwise, we're really honest and truly being told to drop it.
  701.      Don't use Fdelq() as that may QUIT;.
  702.    */
  703.   if (EQ (local_selection_data, Fcar (Vselection_alist)))
  704.     Vselection_alist = Fcdr (Vselection_alist);
  705.   else
  706.     {
  707.       Lisp_Object rest;
  708.       for (rest = Vselection_alist; !NILP (rest); rest = Fcdr (rest))
  709.     if (EQ (local_selection_data, Fcar (XCONS (rest)->cdr)))
  710.       {
  711.         XCONS (rest)->cdr = Fcdr (XCONS (rest)->cdr);
  712.         break;
  713.       }
  714.     }
  715.  
  716.   /* Let random lisp code notice that the selection has been stolen.
  717.    */
  718.   {
  719.     Lisp_Object rest;
  720.     Lisp_Object val = Vx_lost_selection_hooks;
  721.     if (!EQ (val, Qunbound) && !NILP (val))
  722.       {
  723.     if (CONSP (val) && !EQ (XCONS (val)->car, Qlambda))
  724.       for (rest = val; !NILP (rest); rest = Fcdr (rest))
  725.         call1 (Fcar (rest), selection_symbol);
  726.     else
  727.       call1 (val, selection_symbol);
  728.       }
  729.   }
  730. }
  731.  
  732.  
  733. /* This stuff is so that INCR selections are reentrant (that is, so we can
  734.    be servicing multiple INCR selection requests simultaniously.)  I haven't
  735.    actually tested that yet.
  736.  */
  737.  
  738. static int prop_location_tick;
  739.  
  740. static struct prop_location {
  741.   int tick;
  742.   Display *display;
  743.   Window window;
  744.   Atom property;
  745.   int desired_state;
  746.   struct prop_location *next;
  747. } *for_whom_the_bell_tolls;
  748.  
  749.  
  750. static int
  751. property_deleted_p (tick)
  752.      void *tick;
  753. {
  754.   struct prop_location *rest = for_whom_the_bell_tolls;
  755.   while (rest)
  756.     if (rest->tick == (int) tick)
  757.       return 0;
  758.     else
  759.       rest = rest->next;
  760.   return 1;
  761. }
  762.  
  763. static int
  764. waiting_for_other_props_on_window (display, window)
  765.      Display *display;
  766.      Window window;
  767. {
  768.   struct prop_location *rest = for_whom_the_bell_tolls;
  769.   while (rest)
  770.     if (rest->display == display && rest->window == window)
  771.       return 1;
  772.     else
  773.       rest = rest->next;
  774.   return 0;
  775. }
  776.  
  777.  
  778. static int
  779. expect_property_change (display, window, property, state)
  780.      Display *display;
  781.      Window window;
  782.      Lisp_Object property;
  783.      int state;
  784. {
  785.   struct prop_location *pl = (struct prop_location *)
  786.     xmalloc (sizeof (struct prop_location));
  787.   pl->tick = ++prop_location_tick;
  788.   pl->display = display;
  789.   pl->window = window;
  790.   pl->property = property;
  791.   pl->desired_state = state;
  792.   pl->next = for_whom_the_bell_tolls;
  793.   for_whom_the_bell_tolls = pl;
  794.   return pl->tick;
  795. }
  796.  
  797. static void
  798. unexpect_property_change (tick)
  799.      int tick;
  800. {
  801.   struct prop_location *prev = 0, *rest = for_whom_the_bell_tolls;
  802.   while (rest)
  803.     {
  804.       if (rest->tick == tick)
  805.     {
  806.       if (prev)
  807.         prev->next = rest->next;
  808.       else
  809.         for_whom_the_bell_tolls = rest->next;
  810.       xfree (rest);
  811.       return;
  812.     }
  813.       prev = rest;
  814.       rest = rest->next;
  815.     }
  816. }
  817.  
  818. static void
  819. wait_for_property_change (tick)
  820.      int tick;
  821. {
  822.   wait_delaying_user_input (property_deleted_p, (void *) tick);
  823. }
  824.  
  825.  
  826. /* Called from the event-loop in response to a PropertyNotify event.
  827.  */
  828. void
  829. x_handle_property_notify (event)
  830.      XPropertyEvent *event;
  831. {
  832.   struct prop_location *prev = 0, *rest = for_whom_the_bell_tolls;
  833.   while (rest)
  834.     {
  835.       if (rest->property == event->atom &&
  836.       rest->window == event->window &&
  837.       rest->display == event->display &&
  838.       rest->desired_state == event->state)
  839.     {
  840. #if 0
  841.       fprintf (stderr, "Saw expected prop-%s on %s\n",
  842.            (event->state == PropertyDelete ? "delete" : "change"),
  843.            (char *) XSYMBOL (x_atom_to_symbol (event->display,
  844.                                event->atom))
  845.            ->name->data);
  846. #endif
  847.       if (prev)
  848.         prev->next = rest->next;
  849.       else
  850.         for_whom_the_bell_tolls = rest->next;
  851.       xfree (rest);
  852.       return;
  853.     }
  854.       prev = rest;
  855.       rest = rest->next;
  856.     }
  857. #if 0
  858.   fprintf (stderr, "Saw UNexpected prop-%s on %s\n",
  859.        (event->state == PropertyDelete ? "delete" : "change"),
  860.        (char *) XSYMBOL (x_atom_to_symbol (event->display, event->atom))
  861.        ->name->data);
  862. #endif
  863. }
  864.  
  865.  
  866.  
  867. #if 0 /* #### MULTIPLE doesn't work yet */
  868.  
  869. static Lisp_Object
  870. fetch_multiple_target (event)
  871.      XSelectionRequestEvent *event;
  872. {
  873.   Display *display = event->display;
  874.   Window window = event->requestor;
  875.   Atom target = event->target;
  876.   Atom selection_atom = event->selection;
  877.   int result;
  878.  
  879.   return
  880.     Fcons (QMULTIPLE,
  881.        x_get_window_property_as_lisp_data (display, window, target,
  882.                            QMULTIPLE, selection_atom));
  883. }
  884.  
  885. static Lisp_Object
  886. copy_multiple_data (obj)
  887.      Lisp_Object obj;
  888. {
  889.   Lisp_Object vec;
  890.   int i;
  891.   int size;
  892.   if (CONSP (obj))
  893.     return Fcons (XCONS (obj)->car, copy_multiple_data (XCONS (obj)->cdr));
  894.     
  895.   CHECK_VECTOR (obj, 0);
  896.   vec = Fmake_vector (size = XVECTOR (obj)->size, Qnil);
  897.   for (i = 0; i < size; i++)
  898.     {
  899.       Lisp_Object vec2 = XVECTOR (obj)->contents [i];
  900.       CHECK_VECTOR (vec2, 0);
  901.       if (XVECTOR (vec2)->size != 2)
  902.     Fsignal (Qerror, Fcons (build_string ("vectors must be of length 2"),
  903.                 Fcons (vec2, Qnil)));
  904.       XVECTOR (vec)->contents [i] = Fmake_vector (2, Qnil);
  905.       XVECTOR (XVECTOR (vec)->contents [i])->contents [0] =
  906.     XVECTOR (vec2)->contents [0];
  907.       XVECTOR (XVECTOR (vec)->contents [i])->contents [1] =
  908.     XVECTOR (vec2)->contents [1];
  909.     }
  910.   return vec;
  911. }
  912.  
  913. #endif
  914.  
  915.  
  916. static int reading_selection_reply;
  917. static Atom reading_which_selection;
  918. static int selection_reply_timed_out;
  919.  
  920. static int
  921. selection_reply_done (ignore)
  922.      void *ignore;
  923. {
  924.   return !reading_selection_reply;
  925. }
  926.  
  927. static Lisp_Object Qx_selection_reply_timeout_internal;
  928.  
  929. DEFUN ("x-selection-reply-timeout-internal",
  930.        Fx_selection_reply_timeout_internal,
  931.        Sx_selection_reply_timeout_internal, 1, 1, 0, "")
  932.      (arg)
  933.      Lisp_Object arg;
  934. {
  935.   selection_reply_timed_out = 1;
  936.   reading_selection_reply = 0;
  937.   return Qnil;
  938. }
  939.  
  940.  
  941. /* Do protocol to read selection-data from the server.
  942.    Converts this to lisp data and returns it.
  943.  */
  944. static Lisp_Object
  945. x_get_foreign_selection (selection_symbol, target_type)
  946.      Lisp_Object selection_symbol, target_type;
  947. {
  948.   Display *display = x_current_display;
  949.   Window requestor_window = XtWindow (selected_screen->display.x->edit_widget);
  950.   Time requestor_time = mouse_timestamp;
  951.   Atom target_property = Xatom_EMACS_TMP;
  952.   Atom selection_atom = symbol_to_x_atom (display, selection_symbol);
  953.   Atom type_atom;
  954.   int count;
  955.  
  956.   if (CONSP (target_type))
  957.     type_atom = symbol_to_x_atom (display, XCONS (target_type)->car);
  958.   else
  959.     type_atom = symbol_to_x_atom (display, target_type);
  960.  
  961.   BLOCK_INPUT;
  962.   XConvertSelection (display, selection_atom, type_atom, target_property,
  963.              requestor_window, requestor_time);
  964.   UNBLOCK_INPUT;
  965.  
  966.   /* Block until the reply has been read. */
  967.   reading_selection_reply = (int) requestor_window;
  968.   reading_which_selection = selection_atom;
  969.   selection_reply_timed_out = 0;
  970.  
  971.   count = specpdl_ptr - specpdl;
  972.  
  973.   /* add a timeout handler */
  974.   if (x_selection_timeout > 0)
  975.     {
  976.       Lisp_Object id = Fadd_timeout (make_number (x_selection_timeout),
  977.                      Qx_selection_reply_timeout_internal,
  978.                      Qnil, Qnil);
  979.       record_unwind_protect (Fdisable_timeout, id);
  980.     }
  981.  
  982.   /* This is ^Gable */
  983.   wait_delaying_user_input (selection_reply_done, 0);
  984.  
  985.   if (selection_reply_timed_out)
  986.     error ("timed out waiting for reply from selection owner");
  987.  
  988.   unbind_to (count, Qnil);
  989.  
  990.   /* otherwise, the selection is waiting for us on the requested property. */
  991.   return
  992.     x_get_window_property_as_lisp_data (display, requestor_window,
  993.                     target_property, target_type,
  994.                     selection_atom);
  995. }
  996.  
  997.  
  998. static void
  999. x_get_window_property (display, window, property, data_ret, bytes_ret,
  1000.                actual_type_ret, actual_format_ret, actual_size_ret,
  1001.                delete_p)
  1002.      Display *display;
  1003.      Window window;
  1004.      Atom property;
  1005.      unsigned char **data_ret;
  1006.      int *bytes_ret;
  1007.      Atom *actual_type_ret;
  1008.      int *actual_format_ret;
  1009.      unsigned long *actual_size_ret;
  1010.      int delete_p;
  1011. {
  1012.   int total_size;
  1013.   unsigned long bytes_remaining;
  1014.   int offset = 0;
  1015.   unsigned char *tmp_data = 0;
  1016.   int result;
  1017.   int buffer_size = SELECTION_QUANTUM (display);
  1018.   if (buffer_size > MAX_SELECTION_QUANTUM) buffer_size = MAX_SELECTION_QUANTUM;
  1019.   
  1020.   BLOCK_INPUT;
  1021.   /* First probe the thing to find out how big it is. */
  1022.   result = XGetWindowProperty (display, window, property,
  1023.                    0, 0, False, AnyPropertyType,
  1024.                    actual_type_ret, actual_format_ret,
  1025.                    actual_size_ret,
  1026.                    &bytes_remaining, &tmp_data);
  1027.   UNBLOCK_INPUT;
  1028.   if (result != Success)
  1029.     {
  1030.       *data_ret = 0;
  1031.       *bytes_ret = 0;
  1032.       return;
  1033.     }
  1034.   BLOCK_INPUT;
  1035.   XFree ((char *) tmp_data);
  1036.   UNBLOCK_INPUT;
  1037.   
  1038.   if (*actual_type_ret == None || *actual_format_ret == 0)
  1039.     {
  1040.       if (delete_p) XDeleteProperty (display, window, property);
  1041.       return;
  1042.     }
  1043.  
  1044.   total_size = bytes_remaining + 1;
  1045.   *data_ret = (unsigned char *) xmalloc (total_size);
  1046.   
  1047.   /* Now read, until weve gotten it all. */
  1048.   BLOCK_INPUT;
  1049.   while (bytes_remaining)
  1050.     {
  1051. #if 0
  1052.       int last = bytes_remaining;
  1053. #endif
  1054.       result =
  1055.     XGetWindowProperty (display, window, property,
  1056.                 offset/4, buffer_size/4,
  1057.                 (delete_p ? True : False),
  1058.                 AnyPropertyType,
  1059.                 actual_type_ret, actual_format_ret,
  1060.                 actual_size_ret, &bytes_remaining, &tmp_data);
  1061. #if 0
  1062.       fprintf (stderr, "<< read %d\n", last-bytes_remaining);
  1063. #endif
  1064.       /* If this doesn't return Success at this point, it means that
  1065.      some clod deleted the selection while we were in the midst of
  1066.      reading it.  Deal with that, I guess....
  1067.        */
  1068.       if (result != Success) break;
  1069.       *actual_size_ret *= *actual_format_ret / 8;
  1070.       memcpy ((*data_ret) + offset, tmp_data, *actual_size_ret);
  1071.       offset += *actual_size_ret;
  1072.       XFree ((char *) tmp_data);
  1073.     }
  1074.   UNBLOCK_INPUT;
  1075.   *bytes_ret = offset;
  1076. }
  1077.  
  1078.  
  1079. static void
  1080. receive_incremental_selection (display, window, property, target_type,
  1081.                    min_size_bytes, data_ret, size_bytes_ret,
  1082.                    type_ret, format_ret, size_ret)
  1083.      Display *display;
  1084.      Window window;
  1085.      Atom property;
  1086.      Lisp_Object target_type; /* for error messages only */
  1087.      unsigned int min_size_bytes;
  1088.      unsigned char **data_ret;
  1089.      int *size_bytes_ret;
  1090.      Atom *type_ret;
  1091.      unsigned long *size_ret;
  1092.      int *format_ret;
  1093. {
  1094.   int offset = 0;
  1095.   int prop_id;
  1096.   *size_bytes_ret = min_size_bytes;
  1097.   *data_ret = (unsigned char *) xmalloc (*size_bytes_ret);
  1098. #if 0
  1099.   fprintf (stderr, "\nread INCR %d\n", min_size_bytes);
  1100. #endif
  1101.   /* At this point, we have read an INCR property, and deleted it (which
  1102.      is how we ack its receipt: the sending window will be selecting
  1103.      PropertyNotify events on our window to notice this.)
  1104.  
  1105.      Now, we must loop, waiting for the sending window to put a value on
  1106.      that property, then reading the property, then deleting it to ack.
  1107.      We are done when the sender places a property of length 0.
  1108.    */
  1109.   prop_id = expect_property_change (display, window, property,
  1110.                     PropertyNewValue);
  1111.   while (1)
  1112.     {
  1113.       unsigned char *tmp_data;
  1114.       int tmp_size_bytes;
  1115.       wait_for_property_change (prop_id);
  1116.       /* expect it again immediately, because x_get_window_property may
  1117.      .. no it wont, I dont get it.
  1118.      .. Ok, I get it now, the Xt code that implements INCR is broken.
  1119.        */
  1120.       prop_id = expect_property_change (display, window, property,
  1121.                     PropertyNewValue);
  1122.       x_get_window_property (display, window, property,
  1123.                  &tmp_data, &tmp_size_bytes,
  1124.                  type_ret, format_ret, size_ret, 1);
  1125.  
  1126.       if (tmp_size_bytes == 0) /* we're done */
  1127.     {
  1128. #if 0
  1129.       fprintf (stderr, "  read INCR done\n");
  1130. #endif
  1131.       unexpect_property_change (prop_id);
  1132.       if (tmp_data) xfree (tmp_data);
  1133.       break;
  1134.     }
  1135. #if 0
  1136.       fprintf (stderr, "  read INCR %d\n", tmp_size_bytes);
  1137. #endif
  1138.       if (*size_bytes_ret < offset + tmp_size_bytes)
  1139.     {
  1140. #if 0
  1141.       fprintf (stderr, "  read INCR realloc %d -> %d\n",
  1142.            *size_bytes_ret, offset + tmp_size_bytes);
  1143. #endif
  1144.       *size_bytes_ret = offset + tmp_size_bytes;
  1145.       *data_ret = (unsigned char *) xrealloc (*data_ret, *size_bytes_ret);
  1146.     }
  1147.       memcpy ((*data_ret) + offset, tmp_data, tmp_size_bytes);
  1148.       offset += tmp_size_bytes;
  1149.       xfree (tmp_data);
  1150.     }
  1151. }
  1152.  
  1153.  
  1154. static Lisp_Object
  1155. x_get_window_property_as_lisp_data (display, window, property, target_type,
  1156.                     selection_atom)
  1157.      Display *display;
  1158.      Window window;
  1159.      Atom property;
  1160.      Lisp_Object target_type;    /* for error messages only */
  1161.      Atom selection_atom;    /* for error messages only */
  1162. {
  1163.   Atom actual_type;
  1164.   int actual_format;
  1165.   unsigned long actual_size;
  1166.   unsigned char *data = 0;
  1167.   int bytes = 0;
  1168.   Lisp_Object val;
  1169.  
  1170.   x_get_window_property (display, window, property, &data, &bytes,
  1171.              &actual_type, &actual_format, &actual_size, 1);
  1172.   if (! data)
  1173.     {
  1174.       int there_is_a_selection_owner;
  1175.       BLOCK_INPUT;
  1176.       there_is_a_selection_owner =
  1177.     XGetSelectionOwner (display, selection_atom);
  1178.       UNBLOCK_INPUT;
  1179.       while (1) /* don't let debugger return here */
  1180.     Fsignal (Qerror,
  1181.          there_is_a_selection_owner ?
  1182.          Fcons (build_string ("selection owner couldn't convert"),
  1183.             actual_type
  1184.             ? Fcons (target_type,
  1185.                  Fcons (x_atom_to_symbol (display, actual_type),
  1186.                     Qnil))
  1187.             : Fcons (target_type, Qnil))
  1188.          : Fcons (build_string ("no selection"),
  1189.               Fcons (x_atom_to_symbol (display, selection_atom),
  1190.                  Qnil)));
  1191.     }
  1192.   
  1193.   if (actual_type == Xatom_INCR)
  1194.     {
  1195.       /* Ok, that data wasnt *the* data, it was just the beginning. */
  1196.  
  1197.       unsigned int min_size_bytes = * ((unsigned int *) data);
  1198.       BLOCK_INPUT;
  1199.       XFree ((char *) data);
  1200.       UNBLOCK_INPUT;
  1201.       receive_incremental_selection (display, window, property, target_type,
  1202.                      min_size_bytes, &data, &bytes,
  1203.                      &actual_type, &actual_format,
  1204.                      &actual_size);
  1205.     }
  1206.  
  1207.   /* It's been read.  Now convert it to a lisp object in some semi-rational
  1208.      manner.
  1209.    */
  1210.   val = selection_data_to_lisp_data (display, data, bytes,
  1211.                      actual_type, actual_format);
  1212.   
  1213.   xfree ((char *) data);
  1214.   return val;
  1215. }
  1216.  
  1217. /* These functions convert from the selection data read from the server into
  1218.    something that we can use from elisp, and vice versa.
  1219.  
  1220.     Type:    Format:    Size:        Elisp Type:
  1221.     -----    -------    -----        -----------
  1222.     *    8    *        String
  1223.     ATOM    32    1        Symbol
  1224.     ATOM    32    > 1        Vector of Symbols
  1225.     *    16    1        Integer
  1226.     *    16    > 1        Vector of Integers
  1227.     *    32    1        if <=16 bits: Integer
  1228.                     if > 16 bits: Cons of top16, bot16
  1229.     *    32    > 1        Vector of the above
  1230.  
  1231.    When converting a Lisp number to C, it is assumed to be of format 16 if
  1232.    it is an integer, and of format 32 if it is a cons of two integers.
  1233.  
  1234.    When converting a vector of numbers from Elisp to C, it is assumed to be
  1235.    of format 16 if every element in the vector is an integer, and is assumed
  1236.    to be of format 32 if any element is a cons of two integers.
  1237.  
  1238.    When converting an object to C, it may be of the form (SYMBOL . <data>)
  1239.    where SYMBOL is what we should claim that the type is.  Format and
  1240.    representation are as above.
  1241.  */
  1242.  
  1243.  
  1244. static Lisp_Object
  1245. selection_data_to_lisp_data (display, data, size, type, format)
  1246.      Display *display;
  1247.      unsigned char *data;
  1248.      Atom type;
  1249.      int size, format;
  1250. {
  1251.  
  1252.   if (type == Xatom_NULL)
  1253.     return QNULL;
  1254.  
  1255.   /* Convert any 8-bit data to a string, for compactness. */
  1256.   else if (format == 8)
  1257.     return make_string ((char *) data, size);
  1258.  
  1259.   /* Convert a single atom to a Lisp_Symbol.  Convert a set of atoms to
  1260.      a vector of symbols.
  1261.    */
  1262.   else if (type == XA_ATOM)
  1263.     {
  1264.       int i;
  1265.       if (size == sizeof (Atom))
  1266.     return x_atom_to_symbol (display, *((Atom *) data));
  1267.       else
  1268.     {
  1269.       Lisp_Object v = Fmake_vector (size / sizeof (Atom), 0);
  1270.       for (i = 0; i < size / sizeof (Atom); i++)
  1271.         Faset (v, i, x_atom_to_symbol (display, ((Atom *) data) [i]));
  1272.       return v;
  1273.     }
  1274.     }
  1275.  
  1276.   /* Convert a single 16 or small 32 bit number to a Lisp_Int.
  1277.      If the number is > 16 bits, convert it to a cons of integers,
  1278.      16 bits in each half.
  1279.    */
  1280.   else if (format == 32 && size == sizeof (long))
  1281.     return long_to_cons (((unsigned long *) data) [0]);
  1282.   else if (format == 16 && size == sizeof (short))
  1283.     return make_number ((int) (((unsigned short *) data) [0]));
  1284.  
  1285.   /* Convert any other kind of data to a vector of numbers, represented
  1286.      as above (as an integer, or a cons of two 16 bit integers.)
  1287.  
  1288.      #### Perhaps we should return the actual type to lisp as well.
  1289.  
  1290.     (x-get-selection-internal 'PRIMARY 'LINE_NUMBER)
  1291.     ==> [4 4]
  1292.  
  1293.      and perhaps it should be
  1294.  
  1295.     (x-get-selection-internal 'PRIMARY 'LINE_NUMBER)
  1296.     ==> (SPAN . [4 4])
  1297.  
  1298.      Right now the fact that the return type was SPAN is discarded before
  1299.      lisp code gets to see it.
  1300.    */
  1301.   else if (format == 16)
  1302.     {
  1303.       int i;
  1304.       Lisp_Object v = Fmake_vector (size / 4, 0);
  1305.       for (i = 0; i < size / 4; i++)
  1306.     {
  1307.       int j = (int) ((unsigned short *) data) [i];
  1308.       Faset (v, i, make_number (j));
  1309.     }
  1310.       return v;
  1311.     }
  1312.   else
  1313.     {
  1314.       int i;
  1315.       Lisp_Object v = Fmake_vector (size / 4, 0);
  1316.       for (i = 0; i < size / 4; i++)
  1317.     {
  1318.       unsigned long j = ((unsigned long *) data) [i];
  1319.       Faset (v, i, long_to_cons (j));
  1320.     }
  1321.       return v;
  1322.     }
  1323. }
  1324.  
  1325.  
  1326. static void
  1327. lisp_data_to_selection_data (display, obj,
  1328.                  data_ret, type_ret, size_ret, format_ret)
  1329.      Display *display;
  1330.      Lisp_Object obj;
  1331.      unsigned char **data_ret;
  1332.      Atom *type_ret;
  1333.      unsigned int *size_ret;
  1334.      int *format_ret;
  1335. {
  1336.   Lisp_Object type = Qnil;
  1337.   if (CONSP (obj) && SYMBOLP (XCONS (obj)->car))
  1338.     {
  1339.       type = XCONS (obj)->car;
  1340.       obj = XCONS (obj)->cdr;
  1341.       if (CONSP (obj) && NILP (XCONS (obj)->cdr))
  1342.     obj = XCONS (obj)->car;
  1343.     }
  1344.  
  1345.   if (EQ (obj, QNULL) || (EQ (type, QNULL)))
  1346.     {                /* This is not the same as declining */
  1347.       *format_ret = 32;
  1348.       *size_ret = 0;
  1349.       *data_ret = 0;
  1350.       type = QNULL;
  1351.     }
  1352.   else if (STRINGP (obj))
  1353.     {
  1354.       *format_ret = 8;
  1355.       *size_ret = XSTRING (obj)->size;
  1356.       *data_ret = (unsigned char *) xmalloc (*size_ret);
  1357.       memcpy (*data_ret, (char *) XSTRING (obj)->data, *size_ret);
  1358.       if (NILP (type)) type = QSTRING;
  1359.     }
  1360.   else if (SYMBOLP (obj))
  1361.     {
  1362.       *format_ret = 32;
  1363.       *size_ret = 1;
  1364.       *data_ret = (unsigned char *) xmalloc (sizeof (Atom) + 1);
  1365.       (*data_ret) [sizeof (Atom)] = 0;
  1366.       (*(Atom **) data_ret) [0] = symbol_to_x_atom (display, obj);
  1367.       if (NILP (type)) type = QATOM;
  1368.     }
  1369.   else if (FIXNUMP (obj) &&
  1370.        XINT (obj) < 0xFFFF &&
  1371.        XINT (obj) > -0xFFFF)
  1372.     {
  1373.       *format_ret = 16;
  1374.       *size_ret = 1;
  1375.       *data_ret = (unsigned char *) xmalloc (sizeof (short) + 1);
  1376.       (*data_ret) [sizeof (short)] = 0;
  1377.       (*(short **) data_ret) [0] = (short) XINT (obj);
  1378.       if (NILP (type)) type = QINTEGER;
  1379.     }
  1380.   else if (FIXNUMP (obj) || CONSP (obj))
  1381.     {
  1382.       *format_ret = 32;
  1383.       *size_ret = 1;
  1384.       *data_ret = (unsigned char *) xmalloc (sizeof (long) + 1);
  1385.       (*data_ret) [sizeof (long)] = 0;
  1386.       (*(unsigned long **) data_ret) [0] = cons_to_long (obj);
  1387.       if (NILP (type)) type = QINTEGER;
  1388.     }
  1389.   else if (VECTORP (obj))
  1390.     {
  1391.       /* Lisp_Vectors may represent a set of ATOMs;
  1392.      a set of 16 or 32 bit INTEGERs;
  1393.      or a set of ATOM_PAIRs (represented as [[A1 A2] [A3 A4] ...]
  1394.        */
  1395.       int i;
  1396.  
  1397.       if (SYMBOLP (XVECTOR (obj)->contents [0]))
  1398.     /* This vector is an ATOM set */
  1399.     {
  1400.       if (NILP (type)) type = QATOM;
  1401.       *size_ret = XVECTOR (obj)->size;
  1402.       *format_ret = 32;
  1403.       *data_ret = (unsigned char *) xmalloc ((*size_ret) * sizeof (Atom));
  1404.       for (i = 0; i < *size_ret; i++)
  1405.         if (SYMBOLP (XVECTOR (obj)->contents [i]))
  1406.           (*(Atom **) data_ret) [i] =
  1407.         symbol_to_x_atom (display, XVECTOR (obj)->contents [i]);
  1408.         else
  1409.           Fsignal (Qerror, /* Qselection_error */
  1410.                Fcons (build_string
  1411.            ("all elements of the vector must be of the same type"),
  1412.                   Fcons (obj, Qnil)));
  1413.     }
  1414. #if 0 /* #### MULTIPLE doesn't work yet */
  1415.       else if (VECTORP (XVECTOR (obj)->contents [0]))
  1416.     /* This vector is an ATOM_PAIR set */
  1417.     {
  1418.       if (NILP (type)) type = QATOM_PAIR;
  1419.       *size_ret = XVECTOR (obj)->size;
  1420.       *format_ret = 32;
  1421.       *data_ret = (unsigned char *)
  1422.         xmalloc ((*size_ret) * sizeof (Atom) * 2);
  1423.       for (i = 0; i < *size_ret; i++)
  1424.         if (VECTORP (XVECTOR (obj)->contents [i]))
  1425.           {
  1426.         Lisp_Object pair = XVECTOR (obj)->contents [i];
  1427.         if (XVECTOR (pair)->size != 2)
  1428.           Fsignal (Qerror,
  1429.                Fcons (build_string 
  1430.        ("elements of the vector must be vectors of exactly two elements"),
  1431.                   Fcons (pair, Qnil)));
  1432.         
  1433.         (*(Atom **) data_ret) [i * 2] =
  1434.           symbol_to_x_atom (display, XVECTOR (pair)->contents [0]);
  1435.         (*(Atom **) data_ret) [(i * 2) + 1] =
  1436.           symbol_to_x_atom (display, XVECTOR (pair)->contents [1]);
  1437.           }
  1438.         else
  1439.           Fsignal (Qerror,
  1440.                Fcons (build_string
  1441.            ("all elements of the vector must be of the same type"),
  1442.                   Fcons (obj, Qnil)));
  1443.       
  1444.     }
  1445. #endif
  1446.       else
  1447.     /* This vector is an INTEGER set, or something like it */
  1448.     {
  1449.       *size_ret = XVECTOR (obj)->size;
  1450.       if (NILP (type)) type = QINTEGER;
  1451.       *format_ret = 16;
  1452.       for (i = 0; i < *size_ret; i++)
  1453.         if (CONSP (XVECTOR (obj)->contents [i]))
  1454.           *format_ret = 32;
  1455.         else if (!FIXNUMP (XVECTOR (obj)->contents [i]))
  1456.           Fsignal (Qerror, /* Qselection_error */
  1457.                Fcons (build_string
  1458.     ("all elements of the vector must be integers or conses of integers"),
  1459.                   Fcons (obj, Qnil)));
  1460.  
  1461.       *data_ret = (unsigned char *) xmalloc (*size_ret * (*format_ret/8));
  1462.       for (i = 0; i < *size_ret; i++)
  1463.         if (*format_ret == 32)
  1464.           (*((unsigned long **) data_ret)) [i] =
  1465.         cons_to_long (XVECTOR (obj)->contents [i]);
  1466.         else
  1467.           (*((unsigned short **) data_ret)) [i] =
  1468.         (unsigned short) cons_to_long (XVECTOR (obj)->contents [i]);
  1469.     }
  1470.     }
  1471.   else
  1472.     Fsignal (Qerror, /* Qselection_error */
  1473.          Fcons (build_string ("unrecognised selection data"),
  1474.             Fcons (obj, Qnil)));
  1475.  
  1476.   *type_ret = symbol_to_x_atom (display, type);
  1477. }
  1478.  
  1479. static Lisp_Object
  1480. clean_local_selection_data (obj)
  1481.      Lisp_Object obj;
  1482. {
  1483.   if (CONSP (obj) &&
  1484.       FIXNUMP (XCONS (obj)->car) &&
  1485.       CONSP (XCONS (obj)->cdr) &&
  1486.       FIXNUMP (XCONS (XCONS (obj)->cdr)->car) &&
  1487.       NILP (XCONS (XCONS (obj)->cdr)->cdr))
  1488.     obj = Fcons (XCONS (obj)->car, XCONS (obj)->cdr);
  1489.  
  1490.   if (CONSP (obj) &&
  1491.       FIXNUMP (XCONS (obj)->car) &&
  1492.       FIXNUMP (XCONS (obj)->cdr))
  1493.     {
  1494.       if (XINT (XCONS (obj)->car) == 0)
  1495.     return XCONS (obj)->cdr;
  1496.       if (XINT (XCONS (obj)->car) == -1)
  1497.     return make_number (- XINT (XCONS (obj)->cdr));
  1498.     }
  1499.   if (VECTORP (obj))
  1500.     {
  1501.       int i;
  1502.       int size = XVECTOR (obj)->size;
  1503.       Lisp_Object copy;
  1504.       if (size == 1)
  1505.     return clean_local_selection_data (XVECTOR (obj)->contents [0]);
  1506.       copy = Fmake_vector (size, Qnil);
  1507.       for (i = 0; i < size; i++)
  1508.     XVECTOR (copy)->contents [i] =
  1509.       clean_local_selection_data (XVECTOR (obj)->contents [i]);
  1510.       return copy;
  1511.     }
  1512.   return obj;
  1513. }
  1514.  
  1515.  
  1516. /* Called from the event loop to handle SelectionNotify events.
  1517.    I don't think this needs to be reentrant.
  1518.  */
  1519. void
  1520. x_handle_selection_notify (event)
  1521.      XSelectionEvent *event;
  1522. {
  1523.   if (! reading_selection_reply)
  1524.     {
  1525.       message ("received an unexpected SelectionNotify event");
  1526.       return;
  1527.     }
  1528.   if (event->requestor != reading_selection_reply)
  1529.     {
  1530.       message ("received a SelectionNotify event for the wrong window");
  1531.       return;
  1532.     }
  1533.   if (event->selection != reading_which_selection)
  1534.     {
  1535.       message ("received the wrong selection type in SelectionNotify!");
  1536.       return;
  1537.     }
  1538.  
  1539.   reading_selection_reply = 0; /* we're done now. */
  1540. }
  1541.  
  1542.  
  1543. DEFUN ("x-own-selection-internal",
  1544.        Fx_own_selection_internal, Sx_own_selection_internal,
  1545.   2, 2, 0,
  1546.   "Assert an X selection of the given TYPE with the given VALUE.\n\
  1547. TYPE is a symbol, typically PRIMARY, SECONDARY, or CLIPBOARD.\n\
  1548. VALUE is typically a string, or a cons of two markers, but may be\n\
  1549. anything that the functions on selection-converter-alist know about.")
  1550.   (selection_name, selection_value)
  1551.      Lisp_Object selection_name, selection_value;
  1552. {
  1553.   CHECK_SYMBOL (selection_name, 0);
  1554.   if (NILP (selection_value)) error ("selection-value may not be nil.");
  1555.   x_own_selection (selection_name, selection_value);
  1556.   return selection_value;
  1557. }
  1558.  
  1559.  
  1560. /* Request the selection value from the owner.  If we are the owner,
  1561.    simply return our selection value.  If we are not the owner, this
  1562.    will block until all of the data has arrived.
  1563.  */
  1564. DEFUN ("x-get-selection-internal",
  1565.        Fx_get_selection_internal, Sx_get_selection_internal, 2, 2, 0,
  1566.   "Return text selected from some X window.\n\
  1567. SELECTION is a symbol, typically PRIMARY, SECONDARY, or CLIPBOARD.\n\
  1568. TYPE is the type of data desired, typically STRING.")
  1569.   (selection_symbol, target_type)
  1570.      Lisp_Object selection_symbol, target_type;
  1571. {
  1572.   Lisp_Object val = Qnil;
  1573.   struct gcpro gcpro1, gcpro2;
  1574.   GCPRO2 (target_type, val); /* we store newly consed data into these */
  1575.   CHECK_SYMBOL (selection_symbol, 0);
  1576.  
  1577. #if 0 /* #### MULTIPLE doesn't work yet */
  1578.   if (CONSP (target_type) &&
  1579.       XCONS (target_type)->car == QMULTIPLE)
  1580.     {
  1581.       CHECK_VECTOR (XCONS (target_type)->cdr, 0);
  1582.       /* So we don't destructively modify this... */
  1583.       target_type = copy_multiple_data (target_type);
  1584.     }
  1585.   else
  1586. #endif
  1587.     CHECK_SYMBOL (target_type, 0);
  1588.  
  1589.   val = x_get_local_selection (selection_symbol, target_type);
  1590.  
  1591.   if (NILP (val))
  1592.     {
  1593.       val = x_get_foreign_selection (selection_symbol, target_type);
  1594.       goto DONE;
  1595.     }
  1596.  
  1597.   if (CONSP (val) &&
  1598.       SYMBOLP (XCONS (val)->car))
  1599.     {
  1600.       val = XCONS (val)->cdr;
  1601.       if (CONSP (val) && NILP (XCONS (val)->cdr))
  1602.     val = XCONS (val)->car;
  1603.     }
  1604.   val = clean_local_selection_data (val);
  1605.  DONE:
  1606.   UNGCPRO;
  1607.   return val;
  1608. }
  1609.  
  1610. DEFUN ("x-disown-selection-internal",
  1611.        Fx_disown_selection_internal, Sx_disown_selection_internal, 1, 2, 0,
  1612.  "If we own the named selection, then disown it (make there be no selection).")
  1613.      (selection, time)
  1614.      Lisp_Object selection;
  1615.      Lisp_Object time;
  1616. {
  1617.   Display *display = x_current_display;
  1618.   Time timestamp;
  1619.   Atom selection_atom;
  1620.   XSelectionClearEvent event;
  1621.  
  1622.   CHECK_SYMBOL (selection, 0);
  1623.   if (NILP (time))
  1624.     timestamp = mouse_timestamp;
  1625.   else
  1626.     timestamp = cons_to_long (time);
  1627.  
  1628.   if (NILP (assq_no_quit (selection, Vselection_alist)))
  1629.     return Qnil;  /* Don't disown the selection when we're not the owner. */
  1630.  
  1631.   selection_atom = symbol_to_x_atom (display, selection);
  1632.  
  1633.   BLOCK_INPUT;
  1634.   XSetSelectionOwner (display, selection_atom, None, timestamp);
  1635.   UNBLOCK_INPUT;
  1636.  
  1637.   /* It doesn't seem to be guarenteed that a SelectionClear event will be
  1638.      generated for a window which owns the selection when that window sets
  1639.      the selection owner to None.  The NCD server does, the MIT Sun4 server
  1640.      doesn't.  So we synthesize one; this means we might get two, but
  1641.      that's ok, because the second one won't have any effect.
  1642.    */
  1643.   event.display = display;
  1644.   event.selection = selection_atom;
  1645.   event.time = timestamp;
  1646.   x_handle_selection_clear (&event);
  1647.  
  1648.   return Qt;
  1649. }
  1650.  
  1651.  
  1652. DEFUN ("x-selection-owner-p",
  1653.        Fx_selection_owner_p, Sx_selection_owner_p, 0, 1, 0,
  1654.        "Whether the current emacs process owns the given X Selection.\n\
  1655. The arg should be the name of the selection in question, typically one of\n\
  1656. the symbols PRIMARY, SECONDARY, or CLIPBOARD.  (For convenience, the symbol\n\
  1657. nil is the same as PRIMARY, and t is the same as SECONDARY.)")
  1658.      (selection)
  1659.      Lisp_Object selection;
  1660. {
  1661.   CHECK_SYMBOL (selection, 0);
  1662.   if (EQ (selection, Qnil)) selection = QPRIMARY;
  1663.   if (EQ (selection, Qt)) selection = QSECONDARY;
  1664.   
  1665.   if (NILP (Fassq (selection, Vselection_alist)))
  1666.     return Qnil;
  1667.   return Qt;
  1668. }
  1669.  
  1670. DEFUN ("x-selection-exists-p",
  1671.        Fx_selection_exists_p, Sx_selection_exists_p, 0, 1, 0,
  1672.        "Whether there is an owner for the given X Selection.\n\
  1673. The arg should be the name of the selection in question, typically one of\n\
  1674. the symbols PRIMARY, SECONDARY, or CLIPBOARD.  (For convenience, the symbol\n\
  1675. nil is the same as PRIMARY, and t is the same as SECONDARY.)")
  1676.      (selection)
  1677.      Lisp_Object selection;
  1678. {
  1679.   Window owner;
  1680.   Display *dpy = x_current_display;
  1681.   CHECK_SYMBOL (selection, 0);
  1682.   if (!NILP (Fx_selection_owner_p (selection)))
  1683.     return Qt;
  1684.   BLOCK_INPUT;
  1685.   owner = XGetSelectionOwner (dpy, symbol_to_x_atom (dpy, selection));
  1686.   UNBLOCK_INPUT;
  1687.   return (owner ? Qt : Qnil);
  1688. }
  1689.  
  1690.  
  1691. #ifdef CUT_BUFFER_SUPPORT
  1692.  
  1693. static int cut_buffers_initialized; /* Whether we're sure they all exist */
  1694.  
  1695. /* Ensure that all 8 cut buffers exist.  ICCCM says we gotta... */
  1696. static void
  1697. initialize_cut_buffers (display, window)
  1698.      Display *display;
  1699.      Window window;
  1700. {
  1701.   unsigned char *data = (unsigned char *) "";
  1702.   BLOCK_INPUT;
  1703. #define FROB(atom) XChangeProperty (display, window, atom, XA_STRING, 8, \
  1704.                     PropModeAppend, data, 0)
  1705.   FROB (XA_CUT_BUFFER0);
  1706.   FROB (XA_CUT_BUFFER1);
  1707.   FROB (XA_CUT_BUFFER2);
  1708.   FROB (XA_CUT_BUFFER3);
  1709.   FROB (XA_CUT_BUFFER4);
  1710.   FROB (XA_CUT_BUFFER5);
  1711.   FROB (XA_CUT_BUFFER6);
  1712.   FROB (XA_CUT_BUFFER7);
  1713. #undef FROB
  1714.   UNBLOCK_INPUT;
  1715.   cut_buffers_initialized = 1;
  1716. }
  1717.  
  1718.  
  1719. #define CHECK_CUTBUFFER(symbol,n)                    \
  1720.   { CHECK_SYMBOL((symbol),(n));                        \
  1721.     if (!EQ((symbol),QCUT_BUFFER0) && !EQ((symbol),QCUT_BUFFER1) &&    \
  1722.     !EQ((symbol),QCUT_BUFFER2) && !EQ((symbol),QCUT_BUFFER3) &&    \
  1723.     !EQ((symbol),QCUT_BUFFER4) && !EQ((symbol),QCUT_BUFFER5) &&    \
  1724.     !EQ((symbol),QCUT_BUFFER6) && !EQ((symbol),QCUT_BUFFER7))    \
  1725.       Fsignal(Qerror, Fcons (build_string ("doesn't name a cutbuffer"),    \
  1726.                  Fcons ((symbol), Qnil)));            \
  1727.   }
  1728.  
  1729. DEFUN ("x-get-cutbuffer-internal", Fx_get_cutbuffer_internal,
  1730.        Sx_get_cutbuffer_internal, 1, 1, 0,
  1731.        "Returns the value of the named cutbuffer (typically CUT_BUFFER0).")
  1732.      (buffer)
  1733.      Lisp_Object buffer;
  1734. {
  1735.   Display *display = x_current_display;
  1736.   Window window = RootWindow (display, 0); /* Cutbuffers are on screen 0 */
  1737.   Atom buffer_atom;
  1738.   unsigned char *data;
  1739.   int bytes;
  1740.   Atom type;
  1741.   int format;
  1742.   unsigned long size;
  1743.   Lisp_Object ret;
  1744.  
  1745.   CHECK_CUTBUFFER (buffer, 0);
  1746.   buffer_atom = symbol_to_x_atom (display, buffer);
  1747.  
  1748.   x_get_window_property (display, window, buffer_atom, &data, &bytes,
  1749.              &type, &format, &size, 0);
  1750.   if (!data) return Qnil;
  1751.   
  1752.   if (format != 8 || type != XA_STRING)
  1753.     Fsignal (Qerror,
  1754.          Fcons (build_string ("cut buffer doesn't contain 8-bit data"),
  1755.             Fcons (x_atom_to_symbol (display, type),
  1756.                Fcons (make_number (format), Qnil))));
  1757.  
  1758.   ret = (bytes ? make_string ((char *) data, bytes) : Qnil);
  1759.   xfree (data);
  1760.   return ret;
  1761. }
  1762.  
  1763.  
  1764. DEFUN ("x-store-cutbuffer-internal", Fx_store_cutbuffer_internal,
  1765.        Sx_store_cutbuffer_internal, 2, 2, 0,
  1766.        "Sets the value of the named cutbuffer (typically CUT_BUFFER0).")
  1767.      (buffer, string)
  1768.      Lisp_Object buffer, string;
  1769. {
  1770.   Display *display = x_current_display;
  1771.   Window window = RootWindow (display, 0); /* Cutbuffers are on screen 0 */
  1772.   Atom buffer_atom;
  1773.   unsigned char *data;
  1774.   int bytes;
  1775.   int bytes_remaining;
  1776.   int max_bytes = SELECTION_QUANTUM (display);
  1777.   if (max_bytes > MAX_SELECTION_QUANTUM) max_bytes = MAX_SELECTION_QUANTUM;
  1778.  
  1779.   CHECK_CUTBUFFER (buffer, 0);
  1780.   CHECK_STRING (string, 0);
  1781.   buffer_atom = symbol_to_x_atom (display, buffer);
  1782.   data = (unsigned char *) XSTRING (string)->data;
  1783.   bytes = XSTRING (string)->size;
  1784.   bytes_remaining = bytes;
  1785.  
  1786.   if (! cut_buffers_initialized) initialize_cut_buffers (display, window);
  1787.  
  1788.   BLOCK_INPUT;
  1789.   while (bytes_remaining)
  1790.     {
  1791.       int chunk = (bytes_remaining < max_bytes
  1792.            ? bytes_remaining : max_bytes);
  1793.       XChangeProperty (display, window, buffer_atom, XA_STRING, 8,
  1794.                (bytes_remaining == bytes
  1795.             ? PropModeReplace
  1796.             : PropModeAppend),
  1797.                data, chunk);
  1798.       data += chunk;
  1799.       bytes_remaining -= chunk;
  1800.     }
  1801.   UNBLOCK_INPUT;
  1802.   return string;
  1803. }
  1804.  
  1805.  
  1806. DEFUN ("x-rotate-cutbuffers-internal", Fx_rotate_cutbuffers_internal,
  1807.        Sx_rotate_cutbuffers_internal, 1, 1, 0,
  1808.        "Rotate the values of the cutbuffers by the given number of steps;\n\
  1809. positive means move values forward, negative means backward.")
  1810.      (n)
  1811.      Lisp_Object n;
  1812. {
  1813.   Display *display = x_current_display;
  1814.   Window window = RootWindow (display, 0); /* Cutbuffers are on screen 0 */
  1815.   Atom props [8];
  1816.  
  1817.   CHECK_FIXNUM (n, 0);
  1818.   if (XINT (n) == 0) return n;
  1819.   if (! cut_buffers_initialized) initialize_cut_buffers (display, window);
  1820.   props[0] = XA_CUT_BUFFER0;
  1821.   props[1] = XA_CUT_BUFFER1;
  1822.   props[2] = XA_CUT_BUFFER2;
  1823.   props[3] = XA_CUT_BUFFER3;
  1824.   props[4] = XA_CUT_BUFFER4;
  1825.   props[5] = XA_CUT_BUFFER5;
  1826.   props[6] = XA_CUT_BUFFER6;
  1827.   props[7] = XA_CUT_BUFFER7;
  1828.   BLOCK_INPUT;
  1829.   XRotateWindowProperties (display, window, props, 8, XINT (n));
  1830.   UNBLOCK_INPUT;
  1831.   return n;
  1832. }
  1833.  
  1834. #endif
  1835.  
  1836.  
  1837. void
  1838. syms_of_xselect ()
  1839. {
  1840.   defsubr (&Sx_get_selection_internal);
  1841.   defsubr (&Sx_own_selection_internal);
  1842.   defsubr (&Sx_disown_selection_internal);
  1843.   defsubr (&Sx_selection_owner_p);
  1844.   defsubr (&Sx_selection_exists_p);
  1845.  
  1846. #ifdef CUT_BUFFER_SUPPORT
  1847.   defsubr (&Sx_get_cutbuffer_internal);
  1848.   defsubr (&Sx_store_cutbuffer_internal);
  1849.   defsubr (&Sx_rotate_cutbuffers_internal);
  1850.   cut_buffers_initialized = 0;
  1851. #endif
  1852.  
  1853.   reading_selection_reply = 0;
  1854.   reading_which_selection = 0;
  1855.   selection_reply_timed_out = 0;
  1856.   for_whom_the_bell_tolls = 0;
  1857.   prop_location_tick = 0;
  1858.  
  1859.   Vselection_alist = Qnil;
  1860.   staticpro (&Vselection_alist);
  1861.  
  1862.   DEFVAR_LISP ("selection-converter-alist", &Vselection_converter_alist,
  1863.   "An alist associating selection-types (such as STRING and TIMESTAMP) with\n\
  1864. functions.  These functions will be called with three args: the name of the\n\
  1865. selection (typically PRIMARY, SECONDARY, or CLIPBOARD); a desired type to\n\
  1866. which the selection should be converted; and the local selection value\n(\
  1867. whatever had been passed to `x-own-selection').  These functions should\n\
  1868. return the value to send to the X server (typically a string).  A return\n\
  1869. value of nil means that the conversion could not be done.  A return value\n\
  1870. which is the symbol NULL means that a side-effect was executed, and there\n\
  1871. is no meaningful return value.");
  1872.   Vselection_converter_alist = Qnil;
  1873.  
  1874.   DEFVAR_LISP ("x-lost-selection-hooks", &Vx_lost_selection_hooks,
  1875.   "A function or functions to be called after the X server has notified us\n\
  1876. that we have lost the selection.  The function(s) will be called with one\n\
  1877. argument, a symbol naming the selection (typically PRIMARY, SECONDARY, or\n\
  1878. CLIPBOARD.)");
  1879.   Vx_lost_selection_hooks = Qunbound;
  1880.  
  1881.   DEFVAR_LISP ("x-sent-selection-hooks", &Vx_sent_selection_hooks,
  1882.   "A function or functions to be called after we have responded to some\n\
  1883. other client's request for the value of a selection that we own.  The\n\
  1884. function(s) will be called with four arguments:\n\
  1885.   - the name of the selection (typically PRIMARY, SECONDARY, or CLIPBOARD);\n\
  1886.   - the name of the selection-type which we were requested to convert the\n\
  1887.     selection into before sending (for example, STRING or LENGTH);\n\
  1888.   - and whether we successfully transmitted the selection.\n\
  1889. We might have failed (and declined the request) for any number of reasons,\n\
  1890. including being asked for a selection that we no longer own, or being asked\n\
  1891. to convert into a type that we don't know about or that is inappropriate.\n\
  1892. This hook doesn't let you change the behavior of emacs's selection replies,\n\
  1893. it merely informs you that they have happened.");
  1894.   Vx_sent_selection_hooks = Qunbound;
  1895.  
  1896.   DEFVAR_INT ("x-selection-timeout", &x_selection_timeout,
  1897.    "If the selection owner doens't reply in this many seconds, we give up.\n\
  1898. A value of 0 means wait as long as necessary.  This is initialized from the\n\
  1899. \"*selectionTimeout\" resource (which is expressed in milliseconds).");
  1900.   x_selection_timeout = 0;
  1901.  
  1902.   /* Unfortunately, timeout handlers must be lisp functions. */
  1903.   Qx_selection_reply_timeout_internal =
  1904.     intern ("x-selection-reply-timeout-internal");
  1905.   defsubr (&Sx_selection_reply_timeout_internal);
  1906.  
  1907.   QPRIMARY   = intern ("PRIMARY");    staticpro (&QPRIMARY);
  1908.   QSECONDARY = intern ("SECONDARY");    staticpro (&QSECONDARY);
  1909.   QSTRING    = intern ("STRING");    staticpro (&QSTRING);
  1910.   QINTEGER   = intern ("INTEGER");    staticpro (&QINTEGER);
  1911.   QCLIPBOARD = intern ("CLIPBOARD");    staticpro (&QCLIPBOARD);
  1912.   QTIMESTAMP = intern ("TIMESTAMP");    staticpro (&QTIMESTAMP);
  1913.   QTEXT      = intern ("TEXT");     staticpro (&QTEXT);
  1914.   QTIMESTAMP = intern ("TIMESTAMP");    staticpro (&QTIMESTAMP);
  1915.   QDELETE    = intern ("DELETE");    staticpro (&QDELETE);
  1916.   QMULTIPLE  = intern ("MULTIPLE");    staticpro (&QMULTIPLE);
  1917.   QINCR      = intern ("INCR");        staticpro (&QINCR);
  1918.   QEMACS_TMP = intern ("_EMACS_TMP_");    staticpro (&QEMACS_TMP);
  1919.   QTARGETS   = intern ("TARGETS");    staticpro (&QTARGETS);
  1920.   QATOM         = intern ("ATOM");        staticpro (&QATOM);
  1921.   QATOM_PAIR = intern ("ATOM_PAIR");    staticpro (&QATOM_PAIR);
  1922.   QNULL         = intern ("NULL");        staticpro (&QNULL);
  1923.  
  1924. #ifdef CUT_BUFFER_SUPPORT
  1925.   QCUT_BUFFER0 = intern ("CUT_BUFFER0"); staticpro (&QCUT_BUFFER0);
  1926.   QCUT_BUFFER1 = intern ("CUT_BUFFER1"); staticpro (&QCUT_BUFFER1);
  1927.   QCUT_BUFFER2 = intern ("CUT_BUFFER2"); staticpro (&QCUT_BUFFER2);
  1928.   QCUT_BUFFER3 = intern ("CUT_BUFFER3"); staticpro (&QCUT_BUFFER3);
  1929.   QCUT_BUFFER4 = intern ("CUT_BUFFER4"); staticpro (&QCUT_BUFFER4);
  1930.   QCUT_BUFFER5 = intern ("CUT_BUFFER5"); staticpro (&QCUT_BUFFER5);
  1931.   QCUT_BUFFER6 = intern ("CUT_BUFFER6"); staticpro (&QCUT_BUFFER6);
  1932.   QCUT_BUFFER7 = intern ("CUT_BUFFER7"); staticpro (&QCUT_BUFFER7);
  1933. #endif
  1934.  
  1935. }
  1936.  
  1937. void
  1938. Xatoms_of_xselect ()
  1939. {
  1940. #define ATOM(x) XInternAtom(x_current_display, (x), False)
  1941.  
  1942.   BLOCK_INPUT;
  1943.   /* Non-predefined atoms that we might end up using a lot */
  1944.   Xatom_CLIPBOARD =    ATOM("CLIPBOARD");
  1945.   Xatom_TIMESTAMP =    ATOM("TIMESTAMP");
  1946.   Xatom_TEXT =        ATOM("TEXT");
  1947.   Xatom_DELETE =    ATOM("DELETE");
  1948.   Xatom_MULTIPLE =    ATOM("MULTIPLE");
  1949.   Xatom_INCR =        ATOM("INCR");
  1950.   Xatom_EMACS_TMP =    ATOM("_EMACS_TMP_");
  1951.   Xatom_TARGETS =    ATOM("TARGETS");
  1952.   Xatom_NULL =        ATOM("NULL");
  1953.   Xatom_ATOM_PAIR =    ATOM("ATOM_PAIR");
  1954.   UNBLOCK_INPUT;
  1955. }
  1956.