view src/select-msw.c @ 872:79c6ff3eef26

[xemacs-hg @ 2002-06-20 21:18:01 by ben] font changes etc.; some 21.4 changes mule/mule-msw-init-late.el: Specify charset->windows-registry conversion. mule/mule-x-init.el: Delete extra mule font additions here. Put them in faces.c. cl-macs.el: Document better. font-lock.el: Move Lisp function regexp to lisp-mode.el. lisp-mode.el: Various indentation fixes: Handle flet functions better. Handle argument lists in defuns and flets. Handle quoted lists, e.g. property lists -- don't indent like function calls. Distinguish between lambdas and other lists. lisp-mode.el: Handle this form. faces.el, font-menu.el, font.el, gtk-faces.el, msw-faces.el, msw-font-menu.el, x-faces.el, x-init.el: Major overhaul of face-handling code: -- Fix lots of bogus code in msw-faces.el, msw-font-menu.el, font-menu.el that was "truenaming" font specs -- i.e. in the process of frobbing a particular field in a general user-specified font spec with wildcarded fields, sticking in particular values for all the remaining wildcarded fields. This bug was rampant everywhere except in x-faces.el (the oldest and only correctly written code). This also means that we need to work with font names at all times and not font instances, because a font instance is essentially a truenamed font. -- Total rewrite of extremely junky code in msw-faces.el. Work with names as well as font instances, and return names; stop truenaming when canonicalizing and frobbing; fix handling of the combined style field, i.e. weight/slant (also fixed in font.el). -- Totally rewrite the frobbing functions in faces.el. This time, we frob all the instantiators rather than just computing a single instance value and working backwards. That way, e.g., `bold' will work for all charsets that have bold available, rather than only for whatever charset was part of the computed font instance (another example of the truename virus). Also fix up code to look at the fallbacks (all of them) when no global value present, so we don't need to put something in the global value. Intelligently handle a request to frob a buffer locale, rather than signalling an error. When frobbing instantiators, try hard to figure out what device type is associated with them, and frob each according to its own proper device type. Correctly handle inheritance vectors given as instantiators. Preserve existing tags when putting back frobbed instantiators. Extract out general specifier-frobbing code into specifier.el. Document everything cleanly. Do lots of other things better, etc. -- Don't duplicatively set a global specification for the default font -- it's already in the fallback and we no longer need a default global specification present. Delete various code in x-faces.el and msw-faces.el that duplicated the lists of fonts in faces.c. -- init-global-faces was not being called at all under MS Windows! Major bogosity. That caused device-specific values to get stuck into all the fonts, making it very hard to change them -- setting global specs caused nothing to happen. -- Correct weight names in font.el. -- Lots more font fixups in objects*.c. Printer.el: Warning fix. specifier.el: Add more args to map-specifier. Add various "heuristic" specifier functions to aid in creation of specifier-munging code such as in faces.el. subr.el: New functions. lwlib.c: Fix warning. config.inc.samp: Clean up, add args to control fastcall (not yet supported! the changes needed are in another ws of mine), profile support, vc6 support, union-type. xemacs.dsp, xemacs.mak: Semi-major overhaul. Fix bug where dump-id was always getting recomputed, forcing a redump even when nothing changed. Add support for fastcall. Support edit-and-continue (on by default) with vc6. Use incremental linking when doing a debug compilation. Add support for profiling. Consolidate the various debug flags. Partial support for "batch-compiling" -- compiling many files on a single invocation of the compiler. Doesn't seem to help that much for me, so it's not finished or enabled by default. Remove HAVE_MSW_C_DIRED, we always do. Correct some sloppy use of directories. s/cygwin32.h: Allow pdump to work under Cygwin (mmap is broken, so need to undefine HAVE_MMAP). s/win32-common.h, s/windowsnt.h: Support for fastcall. Add WIN32_ANY for identifying all Win32 variants (Cygwin, native, MinGW). Both of these are properly used in another ws. alloc.c, balloon-x.c, buffer.c, bytecode.c, callint.c, cm.c, cmdloop.c, cmds.c, console-gtk.c, console-gtk.h, console-msw.c, console-msw.h, console-stream.c, console-stream.h, console-tty.c, console-tty.h, console-x.c, console-x.h, console.c, console.h, device-gtk.c, device-msw.c, device-tty.c, device-x.c, device.c, device.h, devslots.h, dialog-gtk.c, dialog-msw.c, dialog-x.c, dialog.c, dired-msw.c, editfns.c, emacs.c, event-Xt.c, event-gtk.c, event-msw.c, event-stream.c, event-tty.c, event-unixoid.c, events.c, extents.c, extents.h, faces.c, fileio.c, fns.c, frame-gtk.c, frame-msw.c, frame-tty.c, frame-x.c, frame.c, frame.h, glyphs-eimage.c, glyphs-gtk.c, glyphs-msw.c, glyphs-widget.c, glyphs-x.c, glyphs.c, glyphs.h, gui-gtk.c, gui-msw.c, gui-x.c, gui.c, gutter.c, input-method-xlib.c, intl-encap-win32.c, intl-win32.c, keymap.c, lisp.h, macros.c, menubar-gtk.c, menubar-msw.c, menubar-x.c, menubar.c, menubar.h, minibuf.c, mule-charset.c, nt.c, objects-gtk.c, objects-gtk.h, objects-msw.c, objects-msw.h, objects-tty.c, objects-tty.h, objects-x.c, objects-x.h, objects.c, objects.h, postgresql.c, print.c, process.h, redisplay-gtk.c, redisplay-msw.c, redisplay-output.c, redisplay-tty.c, redisplay-x.c, redisplay.c, redisplay.h, scrollbar-gtk.c, scrollbar-msw.c, scrollbar-x.c, scrollbar.c, select-gtk.c, select-msw.c, select-x.c, select.c, signal.c, sound.c, specifier.c, symbols.c, syntax.c, sysdep.c, syssignal.h, syswindows.h, toolbar-common.c, toolbar-gtk.c, toolbar-msw.c, toolbar-x.c, toolbar.c, unicode.c, window.c, window.h: The following are the major changes made: (1) Separation of various header files into an external and an internal version, similar to the existing separation of process.h and procimpl.h. Eventually this should be done for all Lisp objects. The external version has the same name as currently; the internal adds -impl. The external file has XFOO() macros for objects, but the structure is opaque and defined only in the internal file. It's now reasonable to move all prototypes in lisp.h into the appropriate external file, and this should be done. Currently, separation has been done on extents.h, objects*.h, console.h, device.h, frame.h, and window.h. For c/d/f/w, the most basic properties are available in the external header file, with the macros resolving to functions. In the internal header file, the macros are redefined to directly access the structure. Also, the global MARK_FOO_CHANGED macros have been made into functions so that they can be accessed without needing to include lots of -impl headers -- they are used in almost exclusively in non-time-critical functions, and take up enough time that the function overhead will be negligible. Similarly, the function overhead from making the basic properties mentioned above into functions is negligible, and code that does heavy accessing of c/d/f/w structures inevitably ends up needing the internal header files, anyway. (2) More face changes. -- Major rewrite of objects-msw.c. Now handles wildcard specs properly, rather than "truenaming" (or even worse, signalling an error, which previously happened with some of the fallbacks if you tried to use them in make-font-instance!). -- Split charset matching of fonts into two stages -- one to find a font specifically designed for a particular charset (by examining its registry), the second to find a Unicode font that can support the charset. This needs to proceed as two complete, separate instantiations in order to work properly (otherwise many of the fonts in the HELLO page look wrong). This should also make it easy to support iso10646 (Unicode) fonts under X. -- All default values for fonts are now completely specified in the fallbacks. Stuff from mule-x-init.el has all been moved here, merged with the existing specs, and totally rethought so you get sensible results. (HELLO now looks much better!). -- Generalize the "default X/GTK device" stuff into a per-device-type "default device". -- Add mswindows-{set-}charset-registry. In time, charset<->code-page conversion functions will be removed. -- Wrap protective code around calls to compute device specifier tags, and do this computation before calling the face initialization code because the latter may need these tags to be correctly updated. (3) Other changes. EmacsFrame.c, glyphs-msw.c, eval.c, gui-x.c, intl-encap-win32.c, search.c, signal.c, toolbar-msw.c, unicode.c: Warning fixes. config.h.in: #undefs meant to be frobbed by configure *MUST* go inside of #ifndef WIN32_NO_CONFIGURE, and everything else *MUST* go outside! eval.c: Let detailed backtraces be detailed. specifier.c: Don't override user's print-string-length/print-length settings. glyphs.c: New function image-instance-instantiator. config.h.in, sysdep.c: Changes for fastcall. sysdep.c, nt.c: Fix up a previous botched patch that tried to add support for both EEXIST and EACCES. IF THE BOTCHED PATCH WENT INTO 21.4, THIS FIXUP NEEDS TO GO IN, TOO. search.c: Fix *evil* crash due to incorrect synching of syntax-cache code with 21.1. THIS SHOULD GO INTO 21.4.
author ben
date Thu, 20 Jun 2002 21:19:10 +0000
parents e7ee5f8bde58
children a8d8f419b459
line wrap: on
line source

/* mswindows selection processing for XEmacs
   Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
   Copyright (C) 2000, 2001, 2002 Ben Wing.

This file is part of XEmacs.

XEmacs 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 2, or (at your option) any
later version.

XEmacs 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 XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Synched up with: Not synched with FSF. */

/* This file Mule-ized 7-00??  Needs some Unicode review. --ben */

/* Authorship:

   Written by Kevin Gallo for FSF Emacs.
   Rewritten for mswindows by Jonathan Harris, December 1997 for 21.0.
   Rewritten April 2000 by Ben Wing -- support device methods, Mule-ize.
   Hacked by Alastair Houghton, July 2000 for enhanced clipboard support.
*/

#include <config.h>
#include "lisp.h"
#include "buffer.h"
#include "frame-impl.h"
#include "select.h"
#include "opaque.h"
#include "file-coding.h"

#include "console-msw-impl.h"

static int in_own_selection;

/* A list of handles that we must release. Not accessible from Lisp. */
static Lisp_Object Vhandle_alist;

void
mswindows_handle_destroyclipboard (void)
{
  /* We also receive a destroy message when we call EmptyClipboard() and
     we already own it.  In this case we don't want to call
     handle_selection_clear() because it will remove what we're trying
     to add! */
  if (!in_own_selection)
    {
      /* We own the clipboard and someone else wants it.  Delete our
	 cached copy of the clipboard contents so we'll ask for it from
	 Windows again when someone does a paste, and destroy any memory
         objects we hold on the clipboard that are not in the list of types
         that Windows will delete itself. */
      mswindows_destroy_selection (QCLIPBOARD);
      handle_selection_clear (QCLIPBOARD);
    }
}

static int
mswindows_empty_clipboard (void)
{
  int retval;

  in_own_selection = 1;
  retval = EmptyClipboard ();
  in_own_selection = 0;
  return retval;
}

/* Test if this is an X symbol that we understand */
static int
x_sym_p (Lisp_Object value)
{
  if (NILP (value) || INTP (value))
    return 0;

  /* Check for some of the X symbols */
  if (EQ (value, QSTRING))		return 1;
  if (EQ (value, QTEXT))		return 1;
  if (EQ (value, QCOMPOUND_TEXT))	return 1;

  return 0;
}

/* This converts a Lisp symbol to an MS-Windows clipboard format.
   We have symbols for all predefined clipboard formats, but that
   doesn't mean we support them all ;-)
   The name of this function is actually a lie - it also knows about
   integers and strings... */
static UINT
symbol_to_ms_cf (Lisp_Object value)
{
  /* If it's NIL, we're in trouble. */
  if (NILP (value))			return 0;

  /* If it's an integer, assume it's a format ID */
  if (INTP (value))			return (UINT) (XINT (value));

  /* If it's a string, register the format(!) */
  if (STRINGP (value))
    {
      Extbyte *valext;
      LISP_STRING_TO_TSTR (value, valext);
      return qxeRegisterClipboardFormat (valext);
    }

  /* Check for Windows clipboard format symbols */
  if (EQ (value, QCF_TEXT))		return CF_TEXT;
  if (EQ (value, QCF_BITMAP))		return CF_BITMAP;
  if (EQ (value, QCF_METAFILEPICT))	return CF_METAFILEPICT;
  if (EQ (value, QCF_SYLK))		return CF_SYLK;
  if (EQ (value, QCF_DIF))		return CF_DIF;
  if (EQ (value, QCF_TIFF))		return CF_TIFF;
  if (EQ (value, QCF_OEMTEXT))		return CF_OEMTEXT;
  if (EQ (value, QCF_DIB))		return CF_DIB;
#ifdef CF_DIBV5
  if (EQ (value, QCF_DIBV5))		return CF_DIBV5;
#endif
  if (EQ (value, QCF_PALETTE))		return CF_PALETTE;
  if (EQ (value, QCF_PENDATA))		return CF_PENDATA;
  if (EQ (value, QCF_RIFF))		return CF_RIFF;
  if (EQ (value, QCF_WAVE))		return CF_WAVE;
  if (EQ (value, QCF_UNICODETEXT))	return CF_UNICODETEXT;
  if (EQ (value, QCF_ENHMETAFILE))	return CF_ENHMETAFILE;
  if (EQ (value, QCF_HDROP))		return CF_HDROP;
  if (EQ (value, QCF_LOCALE))		return CF_LOCALE;
  if (EQ (value, QCF_OWNERDISPLAY))	return CF_OWNERDISPLAY;
  if (EQ (value, QCF_DSPTEXT))		return CF_DSPTEXT;
  if (EQ (value, QCF_DSPBITMAP))	return CF_DSPBITMAP;
  if (EQ (value, QCF_DSPMETAFILEPICT))	return CF_DSPMETAFILEPICT;
  if (EQ (value, QCF_DSPENHMETAFILE))	return CF_DSPENHMETAFILE;

  return 0;
}

/* This converts an MS-Windows clipboard format to its corresponding
   Lisp symbol, or a Lisp integer otherwise. */
static Lisp_Object
ms_cf_to_symbol (UINT format)
{
  switch (format)
    {
    case CF_TEXT:		return QCF_TEXT;
    case CF_BITMAP:		return QCF_BITMAP;
    case CF_METAFILEPICT:	return QCF_METAFILEPICT;
    case CF_SYLK:		return QCF_SYLK;
    case CF_DIF:		return QCF_DIF;
    case CF_TIFF:		return QCF_TIFF;
    case CF_OEMTEXT:		return QCF_OEMTEXT;
    case CF_DIB:		return QCF_DIB;
#ifdef CF_DIBV5
    case CF_DIBV5:		return QCF_DIBV5;
#endif
    case CF_PALETTE:		return QCF_PALETTE;
    case CF_PENDATA:		return QCF_PENDATA;
    case CF_RIFF:		return QCF_RIFF;
    case CF_WAVE:		return QCF_WAVE;
    case CF_UNICODETEXT:	return QCF_UNICODETEXT;
    case CF_ENHMETAFILE:	return QCF_ENHMETAFILE;
    case CF_HDROP:		return QCF_HDROP;
    case CF_LOCALE:		return QCF_LOCALE;
    case CF_OWNERDISPLAY:	return QCF_OWNERDISPLAY;
    case CF_DSPTEXT:		return QCF_DSPTEXT;
    case CF_DSPBITMAP:		return QCF_DSPBITMAP;
    case CF_DSPMETAFILEPICT:	return QCF_DSPMETAFILEPICT;
    case CF_DSPENHMETAFILE:	return QCF_DSPENHMETAFILE;
    default:			return make_int ((int) format);
    }
}

/* Test if the specified clipboard format is auto-released by the OS. If
   not, we must remember the handle on Vhandle_alist, and free it if
   the clipboard is emptied or if we set data with the same format. */
static int
cf_is_autofreed (UINT format)
{
  switch (format)
    {
      /* This list comes from the SDK documentation */
    case CF_DSPENHMETAFILE:
    case CF_DSPMETAFILEPICT:
    case CF_ENHMETAFILE:
    case CF_METAFILEPICT:
    case CF_BITMAP:
    case CF_DSPBITMAP:
    case CF_PALETTE:
    case CF_DIB:
#ifdef CF_DIBV5
    case CF_DIBV5:
#endif
    case CF_DSPTEXT:
    case CF_OEMTEXT:
    case CF_TEXT:
    case CF_UNICODETEXT:
      return TRUE;

    default:
      return FALSE;
    }
}

/* Do protocol to assert ourself as a selection owner.

   Under mswindows, we:

   * Only set the clipboard if (eq selection-name 'CLIPBOARD)

   * Check if an X atom name has been passed. If so, convert to CF_TEXT
     (or CF_UNICODETEXT) remembering to perform LF -> CR-LF conversion.

   * Otherwise assume the data is formatted appropriately for the data type
     that was passed.

   Then set the clipboard as necessary.
*/
static Lisp_Object
mswindows_own_selection (Lisp_Object selection_name,
			 Lisp_Object selection_value,
			 Lisp_Object how_to_add,
			 Lisp_Object selection_type,
			 int owned_p /* Not used */)
{
  HGLOBAL 	hValue = NULL;
  UINT		cfType;
  int		is_X_type = FALSE;
  Lisp_Object	cfObject;
  Lisp_Object	data = Qnil;
  int		size;
  void		*src, *dst;
  struct frame  *f = NULL;

  /* Only continue if we're trying to set the clipboard - mswindows doesn't
     use the same selection model as X */
  if (!EQ (selection_name, QCLIPBOARD))
    return Qnil;

  /* If this is one of the X-style atom name symbols, or NIL, convert it
     as appropriate */
  if (NILP (selection_type) || x_sym_p (selection_type))
    {
      /* Should COMPOUND_TEXT map to CF_UNICODETEXT? */
      if (XEUNICODE_P)
	{
	  cfType = CF_UNICODETEXT;
	  cfObject = QCF_UNICODETEXT;
	}
      else
	{
	  cfType = CF_TEXT;
	  cfObject = QCF_TEXT;
	}
      is_X_type = TRUE;
    }
  else
    {
      cfType = symbol_to_ms_cf (selection_type);

      /* Only continue if we can figure out a clipboard type */
      if (!cfType)
	return Qnil;

      cfObject = selection_type;
    }

  /* Convert things appropriately */
  data = select_convert_out (selection_name,
			     cfObject,
			     selection_value);

  if (NILP (data))
    return Qnil;

  if (CONSP (data))
    {
      if (!EQ (XCAR (data), cfObject))
	cfType = symbol_to_ms_cf (XCAR (data));

      if (!cfType)
	return Qnil;

      data = XCDR (data);
    }

  /* We support opaque or string values, but we only mention string
     values for now...
     #### where do the opaque objects come from?  currently they're not
     allowed to be exported to the lisp level! */
  if (!OPAQUEP (data)
      && !STRINGP (data))
    return Qnil;

  /* Find the frame */
  f = selected_frame ();

  /* Open the clipboard */
  if (!OpenClipboard (FRAME_MSWINDOWS_HANDLE (f)))
    return Qnil;

  /* Obtain the data */
  if (OPAQUEP (data))
    {
      src = XOPAQUE_DATA (data);
      size = XOPAQUE_SIZE (data);
    }
  else
    /* we do NOT append a zero byte.  we don't know whether we're dealing
       with regular text, unicode text, binary data, etc. */
    TO_EXTERNAL_FORMAT (LISP_STRING, data, MALLOC, (src, size),
			Qbinary);

  /* Allocate memory */
  hValue = GlobalAlloc (GMEM_DDESHARE | GMEM_MOVEABLE, size);

  if (!hValue)
    {
      CloseClipboard ();

      xfree (src);
      return Qnil;
    }

  dst = GlobalLock (hValue);

  if (!dst)
    {
      GlobalFree (hValue);
      CloseClipboard ();

      xfree (src);
      return Qnil;
    }

  memcpy (dst, src, size);
  xfree (src);

  GlobalUnlock (hValue);

  /* Empty the clipboard if we're replacing everything */
  if (NILP (how_to_add) || EQ (how_to_add, Qreplace_all))
    {
      if (!mswindows_empty_clipboard ())
	{
	  CloseClipboard ();
	  GlobalFree (hValue);

	  return Qnil;
	}
    }

  /* Append is currently handled in select.el; perhaps this should change,
     but it only really makes sense for ordinary text in any case... */

  SetClipboardData (cfType, hValue);

  if (!cf_is_autofreed (cfType))
    {
      Lisp_Object alist_elt = Qnil, rest;
      Lisp_Object cfType_int = make_int (cfType);

      /* First check if there's an element in the alist for this type
	 already. */
      alist_elt = assq_no_quit (cfType_int, Vhandle_alist);

      /* Add an element to the alist */
      Vhandle_alist = Fcons (Fcons (cfType_int, make_opaque_ptr (hValue)),
			     Vhandle_alist);

      if (!NILP (alist_elt))
	{
	  /* Free the original handle */
	  GlobalFree ((HGLOBAL) get_opaque_ptr (XCDR (alist_elt)));

	  /* Remove the original one (adding first makes life easier,
	     because we don't have to special case this being the
	     first element)  */
	  for (rest = Vhandle_alist; !NILP (rest); rest = Fcdr (rest))
	    if (EQ (cfType_int, Fcar (XCDR (rest))))
	      {
		XCDR (rest) = Fcdr (XCDR (rest));
		break;
	      }
	}
    }

  CloseClipboard ();

  /* #### Should really return a time, though this is because of the
     X model (by the looks of things) */
  return Qnil;
}

static Lisp_Object
mswindows_available_selection_types (Lisp_Object selection_name)
{
  Lisp_Object	types = Qnil;
  UINT		format = 0;
  struct frame  *f = NULL;

  if (!EQ (selection_name, QCLIPBOARD))
    return Qnil;

  /* Find the frame */
  f = selected_frame ();

  /* Open the clipboard */
  if (!OpenClipboard (FRAME_MSWINDOWS_HANDLE (f)))
    return Qnil;

  /* [[ ajh - Should there be an unwind-protect handler around this?
     It could (well it probably won't, but it's always better to
     be safe) run out of memory and leave the clipboard open... ]]
     -- xemacs in general makes no provisions for out-of-memory errors;
     we will probably just crash.  fixing this is a huge amount of work,
     so don't bother protecting in this case. --ben */

  while ((format = EnumClipboardFormats (format)))
    types = Fcons (ms_cf_to_symbol (format), types);

  /* Close it */
  CloseClipboard ();

  return types;
}

static Lisp_Object
mswindows_register_selection_data_type (Lisp_Object type_name)
{
  /* Type already checked in select.c */
  Extbyte *nameext;
  UINT format;

  LISP_STRING_TO_TSTR (type_name, nameext);
  format = qxeRegisterClipboardFormat (nameext);

  if (format)
    return make_int ((int) format);
  else
    return Qnil;
}

static Lisp_Object
mswindows_selection_data_type_name (Lisp_Object type_id)
{
  UINT format;
  Extbyte *namebuf;
  int numchars;

  /* If it's an integer, convert to a symbol if appropriate */
  if (INTP (type_id))
    type_id = ms_cf_to_symbol (XINT (type_id));

  /* If this is a symbol, return it */
  if (SYMBOLP (type_id))
    return type_id;

  /* Find the format code */
  format = symbol_to_ms_cf (type_id);

  if (!format)
    return Qnil;

  /* Microsoft, stupid Microsoft */
  {
    int size = 64;
    do
      {
	size *= 2;
	namebuf = alloca_extbytes (size * XETCHAR_SIZE);
	numchars = qxeGetClipboardFormatName (format, namebuf, size);
      }
    while (numchars >= size - 1);
  }

  if (numchars)
    return build_tstr_string (namebuf);

  return Qnil;
}

static Lisp_Object
mswindows_get_foreign_selection (Lisp_Object selection_symbol,
				 Lisp_Object target_type)
{
  HGLOBAL	hValue = NULL;
  UINT		cfType;
  Lisp_Object	cfObject = Qnil, ret = Qnil, value = Qnil;
  int		is_X_type = FALSE;
  int		size;
  void		*data;
  struct frame  *f = NULL;
  struct gcpro	gcpro1;

  /* Only continue if we're trying to read the clipboard - mswindows doesn't
     use the same selection model as X */
  if (!EQ (selection_symbol, QCLIPBOARD))
    return Qnil;

  /* If this is one of the X-style atom name symbols, or NIL, convert it
     as appropriate */
  if (NILP (target_type) || x_sym_p (target_type))
    {
      /* Should COMPOUND_TEXT map to CF_UNICODETEXT? */
      if (XEUNICODE_P)
	{
	  cfType = CF_UNICODETEXT;
	  cfObject = QCF_UNICODETEXT;
	}
      else
	{
	  cfType = CF_TEXT;
	  cfObject = QCF_TEXT;
	}
      is_X_type = TRUE;
    }
  else
    {
      cfType = symbol_to_ms_cf (target_type);

      /* Only continue if we can figure out a clipboard type */
      if (!cfType)
	return Qnil;

      cfObject = ms_cf_to_symbol (cfType);
    }

  /* Find the frame */
  f = selected_frame ();

  /* Open the clipboard */
  if (!OpenClipboard (FRAME_MSWINDOWS_HANDLE (f)))
    return Qnil;

  /* Read the clipboard */
  hValue = GetClipboardData (cfType);

  if (!hValue)
    {
      CloseClipboard ();

      return Qnil;
    }

  /* Find the data */
  size = GlobalSize (hValue);
  data = GlobalLock (hValue);

  if (!data)
    {
      CloseClipboard ();

      return Qnil;
    }

  /* Place it in a Lisp string */
  ret = make_ext_string ((Extbyte *) data, size, Qbinary);

  GlobalUnlock (data);
  CloseClipboard ();

  GCPRO1 (ret);

  /* Convert this to the appropriate type. If we can't find anything,
     then we return a cons of the form (DATA-TYPE . STRING), where the
     string contains the raw binary data. */
  value = select_convert_in (selection_symbol,
			     cfObject,
			     ret);

  UNGCPRO;

  if (NILP (value))
    return Fcons (cfObject, ret);
  else
    return value;
}

static void
mswindows_disown_selection (Lisp_Object selection, Lisp_Object timeval)
{
  if (EQ (selection, QCLIPBOARD))
    {
      BOOL success = OpenClipboard (NULL);
      if (success)
	{
	  /* the caller calls handle_selection_clear(). */
	  success = mswindows_empty_clipboard ();
	  /* Close it regardless of whether empty worked. */
	  if (!CloseClipboard ())
	    success = FALSE;
	}

      /* #### return success ? Qt : Qnil; */
    }
}

void
mswindows_destroy_selection (Lisp_Object selection)
{
  /* Do nothing if this isn't for the clipboard. */
  if (!EQ (selection, QCLIPBOARD))
    return;

  /* Right. We need to delete everything in Vhandle_alist. */
  {
    LIST_LOOP_2 (elt, Vhandle_alist)
      GlobalFree ((HGLOBAL) get_opaque_ptr (XCDR (elt)));
  }

  Vhandle_alist = Qnil;
}

static Lisp_Object
mswindows_selection_exists_p (Lisp_Object selection,
			      Lisp_Object selection_type)
{
  /* We used to be picky about the format, but now we support anything. */
  if (EQ (selection, QCLIPBOARD))
    {
      if (NILP (selection_type))
	return CountClipboardFormats () ? Qt : Qnil;
      else
	return IsClipboardFormatAvailable (symbol_to_ms_cf (selection_type))
	  ? Qt : Qnil;
    }
  else
    return Qnil;
}


/************************************************************************/
/*                            initialization                            */
/************************************************************************/

void
console_type_create_select_mswindows (void)
{
  CONSOLE_HAS_METHOD (mswindows, own_selection);
  CONSOLE_HAS_METHOD (mswindows, disown_selection);
  CONSOLE_HAS_METHOD (mswindows, selection_exists_p);
  CONSOLE_HAS_METHOD (mswindows, get_foreign_selection);
  CONSOLE_HAS_METHOD (mswindows, available_selection_types);
  CONSOLE_HAS_METHOD (mswindows, register_selection_data_type);
  CONSOLE_HAS_METHOD (mswindows, selection_data_type_name);
}

void
syms_of_select_mswindows (void)
{
}

void
vars_of_select_mswindows (void)
{
  /* Initialise Vhandle_alist */
  Vhandle_alist = Qnil;
  staticpro (&Vhandle_alist);
}

void
init_select_mswindows (void)
{
  /* Reinitialise Vhandle_alist */
  /* #### Why do we need to do this?  Somehow I added this. --ben */
  Vhandle_alist = Qnil;
}