/* Generic glyph/image implementation + display tables
   Copyright (C) 1994, 1995 Board of Trustees, University of Illinois
   Copyright (C) 1995 Tinker Systems
   Copyright (C) 1995 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, 675 Mass Ave, Cambridge, MA 02139, USA.  */

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

/* Written by Chuck Thompson and Ben Wing */

#include <config.h>
#include "lisp.h"

#include "buffer.h"
#include "device.h"
#include "faces.h"
#include "frame.h"
#include "glyphs-x.h" /* #### Should be glyphs.h.  Need to abstract. */
#include "redisplay.h"
#include "window.h"

Lisp_Object Qglyphp, Qimage, Qcontrib_p, Qbaseline;

#ifdef HAVE_X_WINDOWS
Lisp_Object Vx_image_conversion_list;
#endif
Lisp_Object Vtty_image_conversion_list;
Lisp_Object Vstream_image_conversion_list;

/* Qstring is defined in data.c */
Lisp_Object Qformatted_string, Qnothing;
Lisp_Object Qautodetect;

Lisp_Object Vcurrent_display_table;

Lisp_Object Vtruncation_glyph, Vcontinuation_glyph, Voctal_escape_glyph;
Lisp_Object Vcontrol_arrow_glyph, Vinvisible_text_glyph, Vhscroll_glyph;
Lisp_Object Vxemacs_logo;

Lisp_Object Vthe_nothing_vector;

Lisp_Object Q_file, Q_data;

static int image_validate (Lisp_Object instantiator, int no_error);


/****************************************************************************
 *                         Image Specifier Object                           *
 ****************************************************************************/

DEFINE_SPECIFIER_OBJECT (image);

static Lisp_Object *
get_image_type_list (Lisp_Object device_type)
{
  if (!valid_device_type_p (device_type))
    signal_simple_error ("Invalid device type", device_type);
#ifdef HAVE_X_WINDOWS
  if (EQ (device_type, Qx))
    return &Vx_image_conversion_list;
#endif
  if (EQ (device_type, Qtty))
    return &Vtty_image_conversion_list;
  if (EQ (device_type, Qstream))
    return &Vstream_image_conversion_list;
  abort (); /* oops. */
  return &Qnil;
}

/* Process an string instantiator according to the image-conversion-list for
   DEVICE_TYPE.  Returns a vector. */

Lisp_Object
process_image_string_instantiator (Lisp_Object data, Lisp_Object device_type,
				   int no_errors_or_quit)
{
  Lisp_Object tail;

  LIST_LOOP (tail, *get_image_type_list (device_type))
    {
      Lisp_Object mapping = XCAR (tail);
      Lisp_Object exp = XCAR (mapping);
      Lisp_Object typevec = XCAR (XCDR (mapping));
      
      if (fast_string_match (exp, string_data (XSTRING (data)),
			     string_length (XSTRING (data)),
			     no_errors_or_quit) >= 0)
	{
	  if (!NILP (XCDR (XCDR (mapping))))
	    {
	      int pos = XINT (XCAR (XCDR (XCDR (mapping))));
	      Lisp_Object newvec = Fcopy_sequence (typevec);
	      vector_data (XVECTOR (newvec))[pos] = data;
	      return newvec;
	    }
	  else
	    return typevec;
	}
    }

  /* Oh well. */
  return Qnil;
}

DEFUN ("set-device-type-image-conversion-list",
       Fset_device_type_image_conversion_list,
       Sset_device_type_image_conversion_list, 2, 2, 0,
       "Set the image-conversion-list for devices of the given TYPE.\n\
The image-conversion-list specifies how image instantiators that\n\
are strings should be interpreted.  Each element of the list should be\n\
a list of two elements (a regular expression string and a vector) or\n\
a list of three elements (the preceding two plus an integer index into\n\
the vector).  The string is converted to the vector associated with the\n\
first matching regular expression.  If a vector index is specified, the\n\
string itself is substituted into that position in the vector.\n\
\n\
Note: The conversion above is applied when the image instantiator is\n\
added to an image specifier, not when the specifier is actually\n\
instantiated.  Therefore, changing the image-conversion-list only affects\n\
newly-added instantiators.  Existing instantiators in glyphs and image\n\
specifiers will not be affected.")
     (device_type, list)
     Lisp_Object device_type, list;
{
  Lisp_Object tail;
  Lisp_Object *imlist = get_image_type_list (device_type);

  /* Check the list to make sure that it only has valid entries. */

  EXTERNAL_LIST_LOOP (tail, list)
    {
      Lisp_Object mapping = XCAR (tail);

      /* Mapping form should be (STRING VECTOR) or (STRING VECTOR INTEGER) */
      if (!CONSP (mapping) ||
	  !CONSP (XCDR (mapping)) ||
	  (!NILP (XCDR (XCDR (mapping))) &&
	   (!CONSP (XCDR (XCDR (mapping))) ||
	    !NILP (XCDR (XCDR (XCDR (mapping)))))))
	signal_simple_error ("Invalid mapping form", mapping);
      else
	{
	  Lisp_Object exp = XCAR (mapping);
	  Lisp_Object typevec = XCAR (XCDR (mapping));
	  Lisp_Object pos = Qnil;
	  Lisp_Object newvec;
	  struct gcpro gcpro1;

	  CHECK_STRING (exp, 0);
	  CHECK_VECTOR (typevec, 1);
	  if (!NILP (XCDR (XCDR (mapping))))
	    {
	      pos = XCAR (XCDR (XCDR (mapping)));
	      CHECK_INT (pos, 0);
	      if (XINT (pos) < 0 ||
		  XINT (pos) >= vector_length (XVECTOR (typevec)))
		args_out_of_range_3
		  (pos, Qzero, make_number
		   (vector_length (XVECTOR (typevec)) - 1));
	    }
	  
	  newvec = Fcopy_sequence (typevec);
	  if (INTP (pos))
	    vector_data (XVECTOR (newvec))[XINT (pos)] = exp;
	  GCPRO1 (newvec);
	  if (!image_validate (newvec, 0))
	    signal_simple_error ("Invalid image-conversion-list vector",
				 typevec);
	  UNGCPRO;
	}
    }

  *imlist = Fcopy_tree (list, Qt);
  return list;
}

DEFUN ("device-type-image-conversion-list", Fdevice_type_image_conversion_list,
       Sdevice_type_image_conversion_list, 1, 1, 0,
       "Return the image-conversion-list for devices of the given TYPE.\n\
The image-conversion-list specifies how to interpret image string\n\
instantiators for the specified device type.  See\n\
`set-device-type-image-conversion-list' for a description of its syntax.")
     (device_type)
     Lisp_Object device_type;
{
  return Fcopy_tree (*get_image_type_list (device_type), Qt);
}


/* Given a specification for an image, return an instance of
   the image which matches the given instantiator and which can be
   displayed in the given domain. */

static Lisp_Object
image_instantiate_1 (Lisp_Object instantiator, Lisp_Object device,
		     int no_errors_or_quit)
{
  Lisp_Object *elt;
  int vec_len;

  elt = vector_data (XVECTOR (instantiator));
  vec_len = vector_length (XVECTOR (instantiator));

  if (EQ (elt[0], Qnothing))
    return instantiator;

  if (EQ (elt[0], Qstring) || EQ (elt[0], Qformatted_string))
    /* #### implement formatted-string; strings should be
       image-instances */
    return elt[2];

#ifdef HAVE_X_WINDOWS
  if (DEVICE_IS_X (XDEVICE (device)))
    return Fmake_image_instance (instantiator, device, Qnil, Qt);
  else
#endif
    if (EQ (elt[0], Qautodetect))
    /* #### strings should be image-instances */
      return elt[2];

  return Qnil;
}

static Lisp_Object
image_instantiate (Lisp_Object specifier, Lisp_Object domain,
		   Lisp_Object instantiator, int no_errors_or_quit)
{
  Lisp_Object device = DFW_DEVICE (domain);
  struct device *d = XDEVICE (device);
  Lisp_Object instance;

  /* First look in the hash table. */
  instance = Fgethash (instantiator, d->image_instance_cache, Qunbound);
  if (EQ (instance, Qunbound))
    {
      instance = image_instantiate_1 (instantiator, device,
				      no_errors_or_quit);
      Fputhash (instantiator, instance, d->image_instance_cache);
    }

  return (NILP (instance) ? Qunbound : instance);
}

/* Validate an image instantiator. */

static int
image_validate (Lisp_Object instantiator, int no_error)
{
  if (STRINGP (instantiator))
    return 1;
  else if (VECTORP (instantiator))
    {
      Lisp_Object *elt = vector_data (XVECTOR (instantiator));
      int instantiator_len = XVECTOR (instantiator)->size;

      if (instantiator_len == 1 &&
	  EQ (elt[0], Qnothing))
	return 1;

      if (instantiator_len == 3 &&
	  (EQ (elt[0], Qstring) ||
	   EQ (elt[0], Qformatted_string) ||
	   EQ (elt[0], Qautodetect)))
	{
	  if (!EQ (elt[1], Q_data))
	    {
	      if (!no_error)
		signal_simple_error ("Must be :data", elt[1]);
	      return 0;
	    }

	  if (!STRINGP (elt[2]))
	    {
	      if (!no_error)
		CHECK_STRING (elt[2], 0);
	      return 0;
	    }
	  return 1;
	}

#ifndef HAVE_X_WINDOWS
      if (!no_error)
	{
	  if (instantiator_len != 1 && instantiator_len != 3)
	    signal_simple_error ("Vector length must be 1 or 3",
				 instantiator);
	  else if (instantiator_len == 3)
	    signal_simple_error
	      ("Must be 'string, 'formatted-string, or 'autodetect",
	       elt[0]);
	  else
	    signal_simple_error ("Must be 'nothing", elt[0]);
	}
      return 0;
#else /* HAVE_X_WINDOWS */
      return x_valid_image_instantiator_p (instantiator, no_error);
#endif
    }
  else if (!no_error)
    signal_simple_error ("Must be string, vector, or 'nothing",
			 instantiator);

  return 0;
}

static Lisp_Object
image_going_to_add (Lisp_Object specifier, Lisp_Object locale,
		    Lisp_Object tag_set, Lisp_Object instantiator)
{
  int is_stream, is_tty;
#ifdef HAVE_X_WINDOWS
  int is_x;
#endif
  int sum = 0;
  Lisp_Object retlist = Qnil;
  struct gcpro gcpro1;

  is_stream = !NILP (memq_no_quit (Qstream, tag_set));
  sum += is_stream;
  is_tty = !NILP (memq_no_quit (Qtty, tag_set));
  sum += is_tty;
#ifdef HAVE_X_WINDOWS
  is_x = !NILP (memq_no_quit (Qx, tag_set));
  sum += is_x;
#endif

  if (sum > 1)
    /* two conflicting device types specified */
    return Qnil;

  GCPRO1 (retlist);
  if (sum == 0 || is_stream)
    {
      Lisp_Object newinst;

      if (STRINGP (instantiator))
	newinst =
	  process_image_string_instantiator (instantiator, Qstream, 1);
      else
	newinst = instantiator;
      
      if (!NILP (newinst))
	{
	  Lisp_Object newtag = tag_set;
	  if (!is_stream)
	    newtag = Fcons (Qstream, tag_set);
	  retlist = Fcons (Fcons (newtag, newinst), retlist);
	}
    }

  if (sum == 0 || is_tty)
    {
      Lisp_Object newinst;

      if (STRINGP (instantiator))
	newinst =
	  process_image_string_instantiator (instantiator, Qtty, 1);
      else
	newinst = instantiator;

      if (!NILP (newinst))
	{
	  Lisp_Object newtag = tag_set;
	  if (!is_tty)
	    newtag = Fcons (Qtty, tag_set);
	  retlist = Fcons (Fcons (newtag, newinst), retlist);
	}
    }

#ifdef HAVE_X_WINDOWS
  if (sum == 0 || is_x)
    {
      Lisp_Object newinst;

      if (STRINGP (instantiator))
	newinst =
	  process_image_string_instantiator (instantiator, Qx, 1);
      else
	newinst = instantiator;

      if (!NILP (newinst))
	{
	  /* We have to always store the actual pixmap data and not the
	     filename even though this is a potential memory pig.  We have to
	     do this because it is quite possible that we will need to
	     instantiate a new instance of the pixmap and the file will no
	     longer exist (e.g. w3 pixmaps are almost always from temporary
	     files). */
	  newinst = x_normalize_image_instantiator (newinst);
	  if (!NILP (newinst))
	    {
	      Lisp_Object newtag = tag_set;
	      if (!is_x)
		newtag = Fcons (Qx, tag_set);
	      retlist = Fcons (Fcons (newtag, newinst), retlist);
	    }
	}
    }
#endif

  return retlist;
}

DEFUN ("image-specifier-p", Fimage_specifier_p, Simage_specifier_p, 1, 1, 0,
       "Return non-nil if OBJECT is an image specifier.\n\
\n\
An image specifier is used for images (pixmaps and the like).  It is used\n\
to describe the actual image in a glyph.  It is instanced as an image-\n\
instance. (#### In 19.12, string images are instantiated as strings and\n\
[nothing] is instantiated as [nothing]; this will change in 19.13, where\n\
everything will instantiate to an image-instance.)\n\
\n\
An image instantiator should be a string or a vector of the form\n\
\n\
 [TYPE :KEYWORD VALUE ...]\n\
\n\
i.e. a type symbol followed by zero or more alternating keyword-value\n\
pairs.  TYPE should be one of\n\
\n\
'nothing\n\
  (Don't display anything; no keywords are valid for this.)\n\
'string\n\
  (Display this image as a text string.)\n\
'formatted-string\n\
  (Display this image as a text string, with replaceable fields;\n\
  #### not implemented in 19.12.)\n\
'xbm\n\
  (An X bitmap; only if X support was compiled into this XEmacs.)\n\
'xpm\n\
  (An XPM pixmap; only if XPM support was compiled into this XEmacs.)\n\
'xface\n\
  (An X-Face bitmap, used to encode people's faces in e-mail messages;\n\
  only if X-Face support was compiled into this XEmacs.)\n\
'autodetect\n\
  (XEmacs tries to guess what format the data is in.  If X support\n\
  exists, the data string will be checked to see if it names a filename.\n\
  If so, and this filename contains XBM or XPM data, the appropriate\n\
  sort of pixmap will be created.  Otherwise, the image will be displayed\n\
  as a string.  If no X support exists, the image will always be displayed\n\
  as a string.)\n\
\n\
The valid keywords are:\n\
\n\
:data\n\
  (Inline data.  For most formats above, this should be a string.  For\n\
  XBM images, this should be a cons of three elements: width, height, and\n\
  a string of bit data.)\n\
:file\n\
  (Data is contained in a file.  The value is the name of this file.\n\
  If both :data and :file are specified, the image is created from\n\
  what is specified in :data and the string in :file becomes the\n\
  value of the `image-instance-file-name' function when applied to\n\
  the resulting image-instance.)\n\
:mask-data\n\
  (Only for XBM images.  This specifies a mask to be used with the\n\
  bitmap.  The format is a cons of width, height, and bits, like for\n\
  :data.)\n\
:mask-file\n\
  (Only for XBM images.  This specifies a file containing the mask data.)\n\
:color-symbols\n\
  (Only for XPM images.  This specifies an alist that maps strings\n\
  that specify symbolic color names to the actual color to be used\n\
  for that symbolic color (in the form of a string or a color-specifier\n\
  object).  If this is not specified, the contents of `xpm-color-symbols'\n\
  are used to generate the alist.)\n\
\n\
If instead of a vector, the instantiator is a string, it will be looked\n\
up according to the specs in the `device-type-image-conversion-list' (q.v.)\n\
for the device type of the domain over which the image is being\n\
instantiated.\n\
\n\
If the instantiator is a string, it will be converted specifies a filename, the data will be read in at\n\
the time that the instantiator is added to the image, and the instantiator\n\
will be converted into one of the [FILENAME ...] forms.  This implies\n\
that the file must exist when the instantiator is added to the image,\n\
but does not need to exist at any other time (e.g. it may be a temporary\n\
file).")
     (object)
     Lisp_Object object;
{
  return (IMAGE_SPECIFIERP (object) ? Qt : Qnil);
}


/* ####
   ####

   Need an image_after_change function */


/****************************************************************************
 *                             Glyph Object                                 *
 ****************************************************************************/

static Lisp_Object mark_glyph (Lisp_Object, void (*) (Lisp_Object));
static void print_glyph (Lisp_Object, Lisp_Object, int);
static int glyph_equal (Lisp_Object, Lisp_Object, int depth);
static unsigned long glyph_hash (Lisp_Object obj, int depth);
static int glyph_getprop (Lisp_Object obj, Lisp_Object prop,
			 Lisp_Object *value_out);
static int glyph_putprop (Lisp_Object obj, Lisp_Object prop,
			  Lisp_Object value);
static int glyph_remprop (Lisp_Object obj, Lisp_Object prop);
static Lisp_Object glyph_props (Lisp_Object obj);
DEFINE_LRECORD_IMPLEMENTATION_WITH_PROPS ("glyph", glyph,
					  mark_glyph, print_glyph, 0,
					  glyph_equal, glyph_hash,
					  glyph_getprop, glyph_putprop,
					  glyph_remprop, glyph_props,
					  struct Lisp_Glyph);

static Lisp_Object
mark_glyph (Lisp_Object obj, void (*markobj) (Lisp_Object))
{
  struct Lisp_Glyph *glyph =  XGLYPH (obj);

  ((markobj) (glyph->image));
  ((markobj) (glyph->contrib_p));
  ((markobj) (glyph->baseline));
  ((markobj) (glyph->face));

  return (glyph->plist);
}

static void
print_glyph (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
{
  struct Lisp_Glyph *glyph = XGLYPH (obj);

  if (print_readably)
    error ("printing unreadable object #<glyph %d>", glyph->header.uid);

  write_c_string ("#<glyph ", printcharfun);
  print_internal (glyph->image, printcharfun, 1);
  write_c_string (">", printcharfun);
}

/* Glyphs are equal if all of their display attributes are equal.  We
   don't compare names or doc-strings, because that would make equal
   be eq.

   This isn't concerned with "unspecified" attributes, that's what
   #'glyph-differs-from-default-p is for. */
static int
glyph_equal (Lisp_Object o1, Lisp_Object o2, int depth)
{
  struct Lisp_Glyph *g1 = XGLYPH (o1);
  struct Lisp_Glyph *g2 = XGLYPH (o2);

  depth++;

  if (!internal_equal (g1->image, g2->image, depth) ||
      !internal_equal (g1->contrib_p, g2->contrib_p, depth) ||
      !internal_equal (g1->baseline, g2->baseline, depth) ||
      !internal_equal (g1->face, g2->face, depth) ||
      plists_differ (g1->plist, g2->plist, depth + 1))
    return 0;

  return 1;
}

static unsigned long
glyph_hash (Lisp_Object obj, int depth)
{
  struct Lisp_Glyph *g = XGLYPH (obj);

  depth++;

  /* No need to hash all of the elements; that would take too long.
     Just hash the most common ones. */
  return HASH2 (internal_hash (g->image, depth),
		internal_hash (g->face, depth));
}

static int
glyph_getprop (Lisp_Object obj, Lisp_Object prop, Lisp_Object *value_out)
{
  struct Lisp_Glyph *g = XGLYPH (obj);

#define FROB(propprop) 							\
do {									\
  if (EQ (prop, Q##propprop))						\
    {									\
      *value_out = g->propprop;						\
      return 1;								\
    }									\
} while (0)

  FROB (image);
  FROB (contrib_p);
  FROB (baseline);
  FROB (face);

#undef FROB

  return internal_getf (g->plist, prop, value_out);
}

static int
glyph_putprop (Lisp_Object obj, Lisp_Object prop, Lisp_Object value)
{
  struct Lisp_Glyph *g = XGLYPH (obj);

#define FROB(propprop) 							\
do {									\
  if (EQ (prop, Q##propprop))						\
    return 0;								\
} while (0)

  FROB (image);
  FROB (contrib_p);
  FROB (baseline);

#undef FROB

  if (EQ (prop, Qface))
    {
      value = Fget_face (value);
      g->face = value;
      return 1;
    }

  internal_putf (&g->plist, prop, value);
  return 1;
}

static int
glyph_remprop (Lisp_Object obj, Lisp_Object prop)
{
  struct Lisp_Glyph *g = XGLYPH (obj);

#define FROB(propprop) 							\
do {									\
  if (EQ (prop, Q##propprop))						\
    return -1;								\
} while (0)

  FROB (image);
  FROB (contrib_p);
  FROB (baseline);

  if (EQ (prop, Qface))
    {
      g->face = Qnil;
      return 1;
    }

#undef FROB
  return internal_remprop (&g->plist, prop);
}

static Lisp_Object
glyph_props (Lisp_Object obj)
{
  struct Lisp_Glyph *g = XGLYPH (obj);
  Lisp_Object result = Qnil;

#define FROB(propprop) 							\
do {									\
  result = Fcons (g->propprop, Fcons (Q##propprop, result));		\
} while (0)

  /* backwards order; we reverse it below */
  FROB (face);
  FROB (baseline);
  FROB (contrib_p);
  FROB (image);

#undef FROB
  return nconc2 (Fnreverse (result), Fcopy_sequence (g->plist));
}

static Lisp_Object
make_glyph (void)
{
  Lisp_Object obj = Qnil;
  struct Lisp_Glyph *g =
    alloc_lcrecord (sizeof (struct Lisp_Glyph), lrecord_glyph);
  
  g->image = Fmake_specifier (Qimage);
  set_specifier_fallback (g->image, list1 (Fcons (Qnil, Vthe_nothing_vector)));
  g->contrib_p = Fmake_specifier (Qboolean);
  set_specifier_fallback (g->contrib_p, list1 (Fcons (Qnil, Qt)));
  /* #### should have a specifier for the following */
  g->baseline = Fmake_specifier (Qgeneric);
  set_specifier_fallback (g->baseline, list1 (Fcons (Qnil, Qnil)));
  g->face = Qnil;
  g->plist = Qnil;

  XSETGLYPH (obj, g);
  return obj;
}

DEFUN ("make-glyph-internal", Fmake_glyph_internal, Smake_glyph_internal,
       0, 0, 0,
       "Create a new, uninitialized glyph.")
     ()
{
  return make_glyph ();
}

DEFUN ("glyphp", Fglyphp, Sglyphp, 1, 1, 0,
       "Return non-nil if OBJECT is a glyph.\n\
\n\
A glyph is an object used for pixmaps and the like.  It is used\n\
in begin-glyphs and end-glyphs attached to extents, in marginal and textual\n\
annotations, in overlay arrows (overlay-arrow-* variables), in toolbar\n\
buttons, and the like.  Its image is described using an image specifier --\n\
see `image-specifier-p'.")
     (object)
     Lisp_Object object;
{
  return GLYPHP (object) ? Qt : Qnil;
}

/*****************************************************************************
 glyph_width

 Return the width of the given GLYPH on the given WINDOW.  If the
 instance is a string then the width is calculated using the font of
 the given FACE.
 ****************************************************************************/
unsigned short
glyph_width (Lisp_Object glyph, face_index findex, int framep,
	     Lisp_Object window)
{
  Lisp_Object instance;
  Lisp_Object frame = XWINDOW (window)->frame;

  /* #### We somehow need to distinguish between the user causing this
     error condition and a bug causing it. */
  if (!GLYPHP (glyph))
    return 0;
  else
    instance = glyph_image_instance (glyph, window, 1);

  if (NILP (instance))
    return 0;
  else if (STRINGP (instance))
    {
      struct device *d = XDEVICE (XFRAME (frame)->device);
      struct Lisp_String *str = XSTRING (instance);
      Lisp_Object font;

      /* #### more lossage.  See add_glyph_rune(). */
#ifdef MULE
      lose; /* !!#### */
#else
      int i;
      int len = string_length (str);
      Emchar *bogobogo = (Emchar *) alloca (len * sizeof (Emchar));
      for (i = 0; i < len; i++)
	bogobogo[i] = (Emchar) string_byte (str, i);

      if (framep)
	font = FACE_FONT (Vdefault_face, frame);
      else
	font = FACE_CACHE_ELEMENT_FONT (XWINDOW (window), findex);

      return (DEVMETH (d, text_width,
		       (XWINDOW (window), font, bogobogo, len)));
#endif

    }
#ifdef HAVE_X_WINDOWS
  else if (IMAGE_INSTANCEP (instance))
    {
      return XIMAGE_INSTANCE (instance)->width;
    }
#endif /* HAVE_X_WINDOWS */
  else
    {
      /* #### Still need to handle other types. */
      return 0;
    }
}

DEFUN ("glyph-width", Fglyph_width, Sglyph_width, 1, 2, 0,
       "Return the width of GLYPH on WINDOW.\n\
This may not be exact as it does not take into account all of the context\n\
that redisplay will.")
     (glyph, window)
     Lisp_Object glyph, window;
{
  XSETWINDOW (window, decode_window (window));
  CHECK_GLYPH (glyph, 0);

  return (make_number (glyph_width (glyph, DEFAULT_INDEX, 0, window)));
}

#define RETURN_ASCENT	0
#define RETURN_DESCENT	1
#define RETURN_HEIGHT	2

Lisp_Object
glyph_image_instance (Lisp_Object glyph, Lisp_Object domain,
		      int no_errors_or_quit)
{
  Lisp_Object specifier = GLYPH_IMAGE (XGLYPH (glyph));

  /* This can never return Qunbound.  All glyphs have 'nothing as
     a fallback. */
  return specifier_instance (specifier, domain, no_errors_or_quit, 0);
}

static unsigned short
glyph_height_internal (Lisp_Object glyph, face_index findex, int framep,
		       Lisp_Object window, int function)
{
  Lisp_Object instance;
  Lisp_Object frame = XWINDOW (window)->frame;

  if (!GLYPHP (glyph))
    return 0;
  else
    instance = glyph_image_instance (glyph, window, 1);

  if (NILP (instance))
    return 0;
  else if (STRINGP (instance))
    {
      struct device *d = XDEVICE (XFRAME (frame)->device);
      struct font_metric_info fm;
      Lisp_Object font;

      if (framep)
	font = FACE_FONT (Vdefault_face, frame);
      else
	font = FACE_CACHE_ELEMENT_FONT (XWINDOW (window), findex);

      DEVMETH (d, font_metric_info, (d, font, &fm));

      if (function == RETURN_ASCENT)
	return fm.ascent;
      else if (function == RETURN_DESCENT)
	return fm.descent;
      else if (function == RETURN_HEIGHT)
	return fm.ascent + fm.descent;
      else
	abort ();
    }
#ifdef HAVE_X_WINDOWS
  else if (IMAGE_INSTANCEP (instance))
    {
      /* #### Ugh ugh ugh -- temporary crap */
      if (function == RETURN_ASCENT || function == RETURN_HEIGHT)
	return XIMAGE_INSTANCE (instance)->height;
      else
	return 0;
    }
#endif /* HAVE_X_WINDOWS */
  /* else */
      /* #### Still need to handle other types. */
  return 0;
}

unsigned short
glyph_ascent (Lisp_Object glyph, face_index findex, int framep,
	      Lisp_Object window)
{
  return glyph_height_internal (glyph, findex, framep, window, RETURN_ASCENT);
}

unsigned short
glyph_descent (Lisp_Object glyph, face_index findex, int framep,
	       Lisp_Object window)
{
  return glyph_height_internal (glyph, findex, framep, window, RETURN_DESCENT);
}

/* strictly a convenience function. */
unsigned short
glyph_height (Lisp_Object glyph, face_index findex, int framep,
	      Lisp_Object window)
{
  return glyph_height_internal (glyph, findex, framep, window, RETURN_HEIGHT);
}

DEFUN ("glyph-ascent", Fglyph_ascent, Sglyph_ascent, 1, 2, 0,
       "Return the ascent value of GLYPH on WINDOW.\n\
This may not be exact as it does not take into account all of the context\n\
that redisplay will.")
     (glyph, window)
     Lisp_Object glyph, window;
{
  XSETWINDOW (window, decode_window (window));
  CHECK_GLYPH (glyph, 0);

  return (make_number (glyph_ascent (glyph, DEFAULT_INDEX, 0, window)));
}

DEFUN ("glyph-descent", Fglyph_descent, Sglyph_descent, 1, 2, 0,
       "Return the descent value of GLYPH on WINDOW.\n\
This may not be exact as it does not take into account all of the context\n\
that redisplay will.")
     (glyph, window)
     Lisp_Object glyph, window;
{
  XSETWINDOW (window, decode_window (window));
  CHECK_GLYPH (glyph, 0);

  return (make_number (glyph_descent (glyph, DEFAULT_INDEX, 0, window)));
}

/* This is redundant but I bet a lot of people expect it to exist. */
DEFUN ("glyph-height", Fglyph_height, Sglyph_height, 1, 2, 0,
       "Return the height of GLYPH on WINDOW.\n\
This may not be exact as it does not take into account all of the context\n\
that redisplay will.")
     (glyph, window)
     Lisp_Object glyph, window;
{
  XSETWINDOW (window, decode_window (window));
  CHECK_GLYPH (glyph, 0);

  return (make_number (glyph_height (glyph, DEFAULT_INDEX, 0, window)));
}

#undef RETURN_ASCENT
#undef RETURN_DESCENT
#undef RETURN_HEIGHT

/* #### do we need to cache this info to speed things up? */

Lisp_Object
glyph_baseline (Lisp_Object glyph, Lisp_Object domain)
{
  if (!GLYPHP (glyph))
    return Qnil;
  else
    {
      Lisp_Object retval =
	specifier_instance_no_quit (GLYPH_BASELINE (XGLYPH (glyph)),
				    domain, 0);
      if (!NILP (retval) && !INTP (retval))
	retval = Qnil;
      else if (INTP (retval))
	{
	  if (XINT (retval) < 0)
	    retval = Qzero;
	  if (XINT (retval) > 100)
	    retval = make_number (100);
	}
      return retval;
    }
}

Lisp_Object
glyph_face (Lisp_Object glyph, Lisp_Object domain)
{
  /* #### Domain parameter not currently used but it will be */
  if (!GLYPHP (glyph))
    return Qnil;
  else
    return GLYPH_FACE (XGLYPH (glyph));
}

int
glyph_contrib_p (Lisp_Object glyph, Lisp_Object domain)
{
  if (!GLYPHP (glyph))
    return 0;
  else
    return (!NILP (specifier_instance_no_quit
		   (GLYPH_CONTRIB_P (XGLYPH (glyph)), domain, 0)));
}


/*****************************************************************************
 *                     glyph cache element functions                         *
 *****************************************************************************/

/*
 #### All of this is 95% copied from face cache elements.
      Consider consolidating.
 #### We need to add a dirty flag to the glyphs.
 */

void
mark_glyph_cache_elements (glyph_cache_element_dynarr *elements,
			   void (*markobj) (Lisp_Object))
{
  int elt;

  if (!elements)
    return;

  for (elt = 0; elt < Dynarr_length (elements); elt++)
    {
      struct glyph_cache_element *inst = Dynarr_atp (elements, elt);
      ((markobj) (inst->glyph));
    }
}

static void
update_glyph_cache_element_data (struct window *w, Lisp_Object glyph,
				 struct glyph_cache_element *inst)
{
  /* #### This should be || !inst->updated */
  if (NILP (inst->glyph) || !EQ (inst->glyph, glyph))
    {
      Lisp_Object window = Qnil;

      XSETWINDOW (window, w);
      inst->glyph = glyph;

#define FROB(field)							\
  do {									\
    unsigned short new_val = glyph_##field (glyph, DEFAULT_INDEX, 0, window); \
    if (inst->field != new_val)						\
      inst->field = new_val;						\
  } while (0)

    /* #### This could be sped up if we redid things to grab the glyph
       instantiation and passed it to the size functions. */
      FROB (width);
      FROB (ascent);
      FROB (descent);
#undef FROB

    }

  inst->updated = 1;
}

static void
add_glyph_cache_element (struct window *w, Lisp_Object glyph)
{
  struct glyph_cache_element new_inst;

  memset (&new_inst, 0, sizeof (struct glyph_cache_element));
  new_inst.glyph = Qnil;

  update_glyph_cache_element_data (w, glyph, &new_inst);
  Dynarr_add (w->glyph_cache_elements, new_inst);
}

static glyph_index
get_glyph_cache_element_index (struct window *w, Lisp_Object glyph)
{
  int elt;

  if (noninteractive)
    return 0;

  for (elt = 0; elt < Dynarr_length (w->glyph_cache_elements); elt++)
    {
      struct glyph_cache_element *inst =
	Dynarr_atp (w->glyph_cache_elements, elt);

      if (EQ (inst->glyph, glyph))
	{
	  if (!inst->updated)
	    update_glyph_cache_element_data (w, glyph, inst);
	  return elt;
	}
    }

  /* If we didn't find the glyph, add it and then return its index. */
  add_glyph_cache_element (w, glyph);
  return elt;
}

void
reset_glyph_cache_elements (struct window *w)
{
  Dynarr_reset (w->glyph_cache_elements);
  get_glyph_cache_element_index (w, Vcontinuation_glyph);
  get_glyph_cache_element_index (w, Vtruncation_glyph);
  get_glyph_cache_element_index (w, Vhscroll_glyph);
  get_glyph_cache_element_index (w, Vcontrol_arrow_glyph);
  get_glyph_cache_element_index (w, Voctal_escape_glyph);
  get_glyph_cache_element_index (w, Vinvisible_text_glyph);
}

void
mark_glyph_cache_elements_as_not_updated (struct window *w)
{
  int elt;

  /* We need to have a dirty flag to tell if the glyph has changed.
     We can check to see if each glyph variable is actually a
     completely different glyph, though. */
#define FROB(glyph_obj, gindex)						\
  update_glyph_cache_element_data (w, glyph_obj,			\
			      Dynarr_atp (w->glyph_cache_elements, gindex))

  FROB (Vcontinuation_glyph, CONT_GLYPH_INDEX);
  FROB (Vtruncation_glyph, TRUN_GLYPH_INDEX);
  FROB (Vhscroll_glyph, HSCROLL_GLYPH_INDEX);
  FROB (Vcontrol_arrow_glyph, CONTROL_GLYPH_INDEX);
  FROB (Voctal_escape_glyph, OCT_ESC_GLYPH_INDEX);
  FROB (Vinvisible_text_glyph, INVIS_GLYPH_INDEX);
#undef FROB

  for (elt = 0; elt < Dynarr_length (w->glyph_cache_elements); elt++)
    Dynarr_atp (w->glyph_cache_elements, elt)->updated = 0;
}


/*****************************************************************************
 *                              display tables                               *
 *****************************************************************************/

/* Get the display table for use currently on window W with face FACE.
   Precedence:

   -- FACE's display table
   -- W's display table (comes from specifier `current-display-table')

   Ignore the specified tables if they are not valid;
   if no valid table is specified, return 0.  */

struct Lisp_Vector *
get_display_table (struct window *w, face_index findex)
{
  Lisp_Object tem = Qnil;

  tem = FACE_CACHE_ELEMENT_DISPLAY_TABLE (w, findex);
  if (VECTORP (tem) && XVECTOR (tem)->size == DISP_TABLE_SIZE)
    return XVECTOR (tem);

  tem = w->display_table;
  if (VECTORP (tem) && XVECTOR (tem)->size == DISP_TABLE_SIZE)
    return XVECTOR (tem);

  return 0;
}

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

void
init_glyphs_once (void)
{
#ifdef HAVE_X_WINDOWS
  staticpro (&Vx_image_conversion_list);
  Vx_image_conversion_list = Qnil;
#endif
  staticpro (&Vtty_image_conversion_list);
  Vtty_image_conversion_list = Qnil;
  staticpro (&Vstream_image_conversion_list);
  Vstream_image_conversion_list = Qnil;

  defsymbol (&Q_file, ":file");
    Fset (Q_file, Q_file);
  defsymbol (&Q_data, ":data");
    Fset (Q_data, Q_data);

  defsymbol (&Qformatted_string, "formatted-string");
  defsymbol (&Qnothing, "nothing");
  defsymbol (&Qautodetect, "autodetect");

  defsymbol (&Qimage, "image");
  INITIALIZE_SPECIFIER_OBJECT (image, "image", "imagep");

  SPECIFIER_HAS_METHOD (image, instantiate);
  SPECIFIER_HAS_METHOD (image, validate);
  SPECIFIER_HAS_METHOD (image, going_to_add);

  Vthe_nothing_vector = vector1 (Qnothing);
  staticpro (&Vthe_nothing_vector);

  /* Partially initialized in glyphs-x.c, glyphs.el */
  DEFVAR_LISP ("truncation-glyph", &Vtruncation_glyph,
    "What to display at the end of truncated lines.");
  Vtruncation_glyph = Fmake_glyph_internal ();

  /* Partially initialized in glyphs-x.c, glyphs.el */
  DEFVAR_LISP ("continuation-glyph", &Vcontinuation_glyph,
    "What to display at the end of wrapped lines.");
  Vcontinuation_glyph = Fmake_glyph_internal ();

  /* Partially initialized in glyphs-x.c, glyphs.el */
  DEFVAR_LISP ("xemacs-logo", &Vxemacs_logo,
    "The glyph used to display the XEmacs logo at startup.");
  Vxemacs_logo = Fmake_glyph_internal ();
}

void
syms_of_glyphs (void)
{
  defsubr (&Sglyphp);
  defsubr (&Smake_glyph_internal);

  defsubr (&Sglyph_width);
  defsubr (&Sglyph_ascent);
  defsubr (&Sglyph_descent);
  defsubr (&Sglyph_height);
  defsubr (&Sset_device_type_image_conversion_list);
  defsubr (&Sdevice_type_image_conversion_list);

  defsubr (&Simage_specifier_p);

  defsymbol (&Qglyphp, "glyphp");
  defsymbol (&Qcontrib_p, "contrib-p");
  defsymbol (&Qbaseline, "baseline");

  /* The octal-escape glyph, control-arrow-glyph and
     invisible-text-glyph are completely initialized in glyphs.el */

  DEFVAR_LISP ("octal-escape-glyph", &Voctal_escape_glyph,
    "What to prefix character codes displayed in octal with.");
  Voctal_escape_glyph = Qnil;

  DEFVAR_LISP ("control-arrow-glyph", &Vcontrol_arrow_glyph,
    "What to use as an arrow for control characters.");
  Vcontrol_arrow_glyph = Qnil;

  DEFVAR_LISP ("invisible-text-glyph", &Vinvisible_text_glyph,
    "What to use to indicate the presence of invisible text.");
  Vinvisible_text_glyph = Qnil;

  /* Partially initialized in glyphs.el */
  DEFVAR_LISP ("hscroll-glyph", &Vhscroll_glyph,
    "What to display at the beginning of horizontally scrolled lines.");
  Vhscroll_glyph = Qnil;

  DEFVAR_SPECIFIER ("current-display-table", &Vcurrent_display_table,
    "*The display table currently in use.\n\
This is a specifier; use `set-specifier' to change it.\n\
The display table is a vector created with `make-display-table'.\n\
The 256 elements control how to display each possible text character.\n\
Each value should be a string, a glyph, a vector or nil.\n\
If a value is a vector it must be composed only of strings and glyphs.\n\
nil means display the character in the default fashion.\n\
Faces can have their own, overriding display table.");
  Vcurrent_display_table = Fmake_specifier (Qgeneric);
  set_specifier_fallback (Vcurrent_display_table,
			  list1 (Fcons (Qnil, Qnil)));
  set_specifier_caching (Vcurrent_display_table,
			 slot_offset (struct window,
				      display_table),
			 some_window_value_changed,
			 0, 0);
}
