
#include <gtk/gtk.h>

#include "t1fonts.h"

#include "gw_pannel.h"
#include "gw_choice.h"
#include "gw_list.h"

#include "gg_gtkinc.h"
#include "gg_protos.h"

#include "gg_glyph_choice.h"

static Gw_pannel **glyph_pannel = NULL;

/********************* G L Y P H   C H O I C E **********************/
/**

 * T1_SetChar(...): Generate the bitmap for a character 
 *
 */

/**
 *   Create or update a 16 x 16 = 256 elements pannel for glyphs
 */
void gg_glyph_pannel_update (int font)
{
  GtkWidget *pannel_button;
  T1_TMATRIX UNITY_MATRIX = {1.0, 0.0, 0.0, 1.0};
  float fsize = 0.8 * 24;
  GLYPH *glyph,*glyph_b;
  int n ,width ,height;
  Gw_pannel *pannel;
  char *label;
  if (glyph_pannel[font] == NULL) {
    label = get_fontalias (font);
    glyph_pannel[font] = GW_PANNEL (gw_pannel_new (label ,16 ,16 ,gg_get_win ()));
    pannel             = glyph_pannel[font];
    gw_pannel_set_bitmaps_defaults (pannel ,gg_get_depth () ,TRUE);
    gw_pannel_numbering            (pannel ,FALSE);  
    gw_pannel_set_row_first        (pannel ,FALSE);
    /* create the elements in pannel */
    for (n = 0; n < 256; n++) {
      glyph  = T1_SetChar (font ,n ,fsize ,&UNITY_MATRIX);
      if (glyph && glyph->bits) {
	width  = glyph->metrics.rightSideBearing - glyph->metrics.leftSideBearing;
	height = glyph->metrics.ascent           - glyph->metrics.descent;
	glyph_b = T1_CopyGlyph (glyph);
	pannel_button = gtk_toggle_button_new ();
	gw_pannel_bitmap_button_attach (pannel ,pannel_button ,n
					,(unsigned char *)(glyph_b->bits) ,width ,height);
	// g_free (glyph_b); //16 on devrait pouvoir liberer ce qui n'est pas bits: A ESSAYER
      } else {
	pannel->buttons[n] = NULL;
      }
    }
  }
}

/**
 *  Creates the button to popup a glyph choice pannel
 *  and returns the Gw_choice widget created
 */
GtkWidget *gg_glyph_new (GtkWidget *parent ,char *label)
{
  GtkWidget *choix;
  Gw_pannel *pannel;
  int nfonts = number_of_fonts();
  if (glyph_pannel == NULL) {
    glyph_pannel = g_malloc0 (nfonts * sizeof(Gw_pannel *));
  }
  gg_glyph_pannel_update (0);
  pannel = glyph_pannel[0];
  choix  = gw_choice_new (label ,pannel ,nfonts);
  gtk_widget_show_all (choix);
  gg_frame_attach (parent ,choix);
  return (choix);
}


/**
 *  Called when font is changed to change the pannel displayed,
 *  create it if necessary and update the choice button
 */
void gg_update_glyph_choice (Gw_choice *wc ,int font)
{
  Gw_pannel *pannel;
  gtk_widget_hide_all (GTK_WIDGET (wc));
  gg_glyph_pannel_update (font);
  pannel           = glyph_pannel[font];
  wc->pannel[font] = pannel;
  gw_choice_pan_set (wc ,pannel ,font);
  if (pannel->mask[wc->value] != NULL) {
    gw_pannel_bitmap_button_set (pannel ,wc->button ,wc->value);
  }
  gtk_widget_show_all (GTK_WIDGET (wc));
}

