/*
 * EasyChem
 * A program for creating and editing molecular formulas.
 *
 * Copyright (C) 2003, 2004, 2005 François-Xavier Coudert
 * 
 * Distributed under the General Public Licence (GPL).
 * See file COPYING in the source distribution for more details.
 *
 */

#define SPIN_BUTTON_WITH_DEFAULT(s,min,max,step,def,digits) { \
  s = gtk_spin_button_new_with_range (min, max, step); \
  gtk_spin_button_set_digits (GTK_SPIN_BUTTON (s), digits); \
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (s), def); \
  gtk_spin_button_set_update_policy (GTK_SPIN_BUTTON (s), \
                                     GTK_UPDATE_IF_VALID);}

#include <stdio.h>
#include <string.h>
#include <gtk/gtk.h>

#include "common.h"
#include "bonds.h"

#include "graph/text_center.c"
#include "graph/text_left.c"
#include "graph/text_right.c"
#include "graph/arrowhead_right.c"
#include "graph/nohead_right.c"
#include "graph/semihead_right1.c"
#include "graph/semihead_right2.c"
#include "graph/arrowhead_left.c"
#include "graph/nohead_left.c"
#include "graph/semihead_left1.c"
#include "graph/semihead_left2.c"

static gint
color_button_expose (GtkWidget * rect, G_GNUC_UNUSED GdkEventExpose *event,
                     GdkColor * color)
{
  GdkGC * gc;

  gc = gdk_gc_new (rect->window);
  gdk_gc_set_rgb_fg_color (gc, color);
  
  gdk_draw_rectangle (rect->window, gc, TRUE, 0, 0,
	              rect->allocation.width, rect->allocation.height);

  return FALSE;
}


/* Dialog used to edit a color... */
void
edit_color (GtkWidget * widget, G_GNUC_UNUSED GdkEventButton * event,
	    GdkColor * color)
{
  GtkWidget *win, *colsel;
  int response;

  win = gtk_dialog_new_with_buttons (_("Color selection"),
      		                     NULL,
				     GTK_DIALOG_DESTROY_WITH_PARENT |
				     GTK_DIALOG_MODAL |
				     GTK_DIALOG_NO_SEPARATOR,
				     GTK_STOCK_OK, 1,
				     GTK_STOCK_CANCEL, 0, NULL);
  gtk_container_set_border_width (GTK_CONTAINER (win), 20);
  colsel = gtk_color_selection_new ();
  gtk_color_selection_set_current_color (GTK_COLOR_SELECTION (colsel), color);
  gtk_color_selection_set_has_opacity_control (GTK_COLOR_SELECTION (colsel),
					       FALSE);
  gtk_color_selection_set_has_palette (GTK_COLOR_SELECTION (colsel), TRUE);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (win)->vbox),
		      colsel, TRUE, TRUE, 10);
  gtk_widget_show_all (win);
  response = gtk_dialog_run (GTK_DIALOG (win));
  if (response == 1)
    gtk_color_selection_get_current_color (GTK_COLOR_SELECTION (colsel),
					   color);

  gtk_widget_destroy (win);
  gtk_widget_queue_draw (widget);
}


/* Help text of the following function */
void
edit_text_help (GtkWidget * parent)
{
  GtkTextBuffer *txt;
  GtkWidget *textview, *window, *sw;
  GtkTextIter iter;

  window = gtk_dialog_new_with_buttons (_("Richtext help"),
					GTK_WINDOW (parent),
					GTK_DIALOG_DESTROY_WITH_PARENT |
					GTK_DIALOG_MODAL |
					GTK_DIALOG_NO_SEPARATOR,
					GTK_STOCK_OK, 0, NULL);
  sw = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_NEVER,
				  GTK_POLICY_AUTOMATIC);
  gtk_container_add (GTK_CONTAINER (GTK_DIALOG (window)->vbox), sw);
  textview = gtk_text_view_new ();
  gtk_widget_set_size_request (textview, 270, 300);
  gtk_container_add (GTK_CONTAINER (sw), textview);
  txt = gtk_text_view_get_buffer (GTK_TEXT_VIEW (textview));
  gtk_text_view_set_editable (GTK_TEXT_VIEW (textview), FALSE);
  gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (textview), FALSE);
  gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW (textview), GTK_WRAP_WORD);
  gtk_text_buffer_create_tag (txt, "italic", "style", PANGO_STYLE_ITALIC,
			      NULL);
  gtk_text_buffer_create_tag (txt, "bold", "weight", PANGO_WEIGHT_BOLD, NULL);
  gtk_text_buffer_create_tag (txt, "superscript", "rise", 5 * PANGO_SCALE,
			      "size", 8 * PANGO_SCALE, NULL);
  gtk_text_buffer_create_tag (txt, "subscript", "rise", -5 * PANGO_SCALE,
			      "size", 8 * PANGO_SCALE, NULL);
  gtk_text_buffer_create_tag (txt, "tt", "family", "monospace",
			      "foreground", "blue", NULL);
  gtk_text_buffer_get_iter_at_offset (txt, &iter, 0);

/* The help message itself */
  gtk_text_buffer_insert (txt, &iter,
_("This is the help message for text editing. I will help you to deal with the possibilities offered by EasyChem for rich text. The syntax offered is very similar to TeX (and LaTeX).\n\nThe text must be composed of regular characters (from the latin1 character set), and can include \\commands. There are 2 kinds of commands, with argument and without argument. Arguments are specified between brackets ("), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "\\textbf{bold}", -1, "tt", NULL);
  gtk_text_buffer_insert (txt, &iter,
_(" is a typical example). Commands without arguments need to be separated from the next character by a space (like in "), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "c\\oe ur", -1, "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, ", ", -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "\\oe", -1, "tt", NULL);
  gtk_text_buffer_insert (txt, &iter,
_(" being a command producing a non-latin1 character). Just like in LaTeX, if you want a space just after a command, you have to protect it ("), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter,
_("it costs 10 \\euro\\ per unit"), -1, "tt", NULL);
  gtk_text_buffer_insert (txt, &iter,
_(", for an example).\n\n\nEnough small talk, what are the commands available?\n\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "\\textbf{foo}", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" produces "), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "foo", -1,
					    "bold", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" (bold).\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "\\emph{foo}", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" produces "), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "foo", -1,
					    "italic", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" (italic).\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "CO_2H", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" produces "), -1);
  gtk_text_buffer_insert (txt, &iter, "CO", -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "2", -1,
					    "subscript", NULL);
  gtk_text_buffer_insert (txt, &iter, "H", -1);
  gtk_text_buffer_insert (txt, &iter, _("(subscript).\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "H_{text}", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" produces "), -1);
  gtk_text_buffer_insert (txt, &iter, "H", -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "text", -1,
					    "subscript", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" (subscript).\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "x^2", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" produces "), -1);
  gtk_text_buffer_insert (txt, &iter, "x", -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "2", -1,
					    "superscript", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" (superscript).\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "Mg^{2+}", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" produces "), -1);
  gtk_text_buffer_insert (txt, &iter, "Mg", -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "2+", -1,
					    "superscript", NULL);
  gtk_text_buffer_insert (txt, &iter, _(" (superscript).\n\n\n"), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "\\alpha", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter,
_(" produces α (greek letter) and the same is true for all greek letters. "), -1);
  gtk_text_buffer_insert_with_tags_by_name (txt, &iter, "\\Omega", -1,
					    "tt", NULL);
  gtk_text_buffer_insert (txt, &iter,
_(" produces Ω (capital greek letter)."), -1);
/* End of the help message */

  gtk_text_buffer_get_iter_at_offset (txt, &iter, 0);
  gtk_text_view_scroll_to_iter (GTK_TEXT_VIEW (textview), &iter, 0.0, FALSE,
				0.0, 0.0);
  gtk_widget_show_all (sw);
  gtk_dialog_run (GTK_DIALOG (window));
  gtk_widget_destroy (window);
}


/* The dialog used to edit text... */
gchar *
edit_text (const gchar * text, unsigned int * type, double * size,
           GdkColor * color, GtkWindow * parent)
{
  char *new;
  int response;
  GtkWidget *entry, *dialog, *label, *hbox, *help, *rect, *frame;
  GtkWidget *radioA, *radioL, *radioR, *gA, *gL, *gR, *size_spin;
  GdkPixbuf *graphA, *graphL, *graphR;

  dialog = gtk_dialog_new_with_buttons (_("Edit atom or group"), parent,
					GTK_DIALOG_MODAL |
					GTK_DIALOG_NO_SEPARATOR,
					GTK_STOCK_OK, 1,
					GTK_STOCK_CANCEL, 0, NULL);
  gtk_container_set_border_width (GTK_CONTAINER (dialog), 20);
  label = gtk_label_new (_("Enter the text here:"));
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      label, TRUE, TRUE, 0);
  entry = gtk_entry_new ();
  if (text != NULL)
    gtk_entry_set_text (GTK_ENTRY (entry), text);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), entry,
		      TRUE, TRUE, 0);
  help = gtk_button_new_from_stock (GTK_STOCK_HELP);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      help, TRUE, TRUE, 0);

/* Size controller */
  hbox = gtk_hbox_new (FALSE, 0);
  label = gtk_label_new ("Relative size:");
  SPIN_BUTTON_WITH_DEFAULT (size_spin, 0.1, 5.0, 0.05, *size, 2);
  gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX (hbox), size_spin, TRUE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      hbox, TRUE, TRUE, 20);

/* Color controller */
  frame = gtk_frame_new (NULL);
  gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
  rect = gtk_drawing_area_new ();
  g_signal_connect (G_OBJECT (rect), "expose_event",
                    G_CALLBACK (color_button_expose), color);
  g_signal_connect (G_OBJECT (rect), "button_press_event",
                    G_CALLBACK (edit_color), color);
  gtk_widget_set_events (rect, gtk_widget_get_events (rect)
                         | GDK_BUTTON_PRESS_MASK);
  gtk_widget_set_size_request (rect, 40, 20);
  gtk_container_add (GTK_CONTAINER (frame), rect);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), frame,
                      TRUE, TRUE, 0);      

  label = gtk_label_new ("");
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      label, TRUE, TRUE, 10);
  label = gtk_label_new (_("Type of atom or group:"));
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      label, TRUE, TRUE, 10);
  graphA = gdk_pixbuf_new_from_inline (-1, graph_text_center, FALSE, NULL);
  graphL = gdk_pixbuf_new_from_inline (-1, graph_text_left, FALSE, NULL);
  graphR = gdk_pixbuf_new_from_inline (-1, graph_text_right, FALSE, NULL);
  radioA = gtk_radio_button_new (NULL);
  radioL = gtk_radio_button_new_from_widget (GTK_RADIO_BUTTON (radioA));
  radioR = gtk_radio_button_new_from_widget (GTK_RADIO_BUTTON (radioA));
  gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (radioA), FALSE);
  gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (radioL), FALSE);
  gtk_toggle_button_set_mode (GTK_TOGGLE_BUTTON (radioR), FALSE);
  gA = gtk_image_new_from_pixbuf (graphA);
  gR = gtk_image_new_from_pixbuf (graphR);
  gL = gtk_image_new_from_pixbuf (graphL);
  gtk_container_add (GTK_CONTAINER (radioA), gA);
  gtk_container_add (GTK_CONTAINER (radioR), gR);
  gtk_container_add (GTK_CONTAINER (radioL), gL);
  hbox = gtk_hbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (hbox), radioA, TRUE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX (hbox), radioR, TRUE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX (hbox), radioL, TRUE, TRUE, 0);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      hbox, TRUE, TRUE, 0);
  label = gtk_label_new ("");
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox),
		      label, TRUE, TRUE, 0);
  g_signal_connect_swapped (G_OBJECT (help), "clicked",
			    G_CALLBACK (edit_text_help), dialog);

  if (*type == BOND_ATOM)
    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (radioA), TRUE);
  if (*type == BOND_GROUP_L)
    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (radioL), TRUE);
  if (*type == BOND_GROUP_R)
    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (radioR), TRUE);
  gtk_widget_show_all (dialog);

  response = gtk_dialog_run (GTK_DIALOG (dialog));
  if (response == 1)
    {
      new = g_strdup (gtk_entry_get_text (GTK_ENTRY (entry)));
      if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (radioA)))
	*type = BOND_ATOM;
      if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (radioL)))
	*type = BOND_GROUP_L;
      if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (radioR)))
	*type = BOND_GROUP_R;
      *size = gtk_spin_button_get_value (GTK_SPIN_BUTTON (size_spin));
    }
  else
    new = g_strdup (text);

  gtk_widget_destroy (dialog);
  return new;
}


struct edit_bond_param
{
  int type;
  GtkWidget * menu_bond_l;
  GtkWidget * menu_bond;
  GtkWidget * frame_l;
  GtkWidget * frame;
  GtkWidget * width_l;
  GtkWidget * width;
  GtkWidget * arrow_size_l;
  GtkWidget * arrow_size;
  GtkWidget * head1;
  GtkWidget * head1_l;
  GtkWidget * head2;
  GtkWidget * head2_l;
};


void
edit_bond_update_menu (struct edit_bond_param * p)
{
  int pos = gtk_option_menu_get_history (GTK_OPTION_MENU (p->menu_bond));
  
  switch (p->type)
  {
    case BOND_SIMPLE:
    case BOND_DOUBLE:
    case BOND_TRIPLE:
    case BOND_UP:
    case BOND_DOWN:
    case BOND_DASHED:
    case BOND_ARROW:
      pos += BOND_SIMPLE;
      break;

    case BOND_ARC:
      pos += BOND_ARC;
      break;

    case BOND_CIRCLE:
      pos += BOND_CIRCLE;
      break;
  }

  if ((pos == BOND_SIMPLE) || (pos == BOND_DASHED) || (pos == BOND_ARC)
      || (pos == BOND_CIRCLE))
  { 
    gtk_widget_hide (p->width);
    gtk_widget_hide (p->width_l);
  }
  else
  {
    gtk_widget_show (p->width);
    gtk_widget_show (p->width_l);
  }

  if (pos == BOND_ARROW || pos == BOND_ARC)
  {
    gtk_widget_show (p->head1);
    gtk_widget_show (p->head1_l);
    gtk_widget_show (p->head2);
    gtk_widget_show (p->head2_l);
    gtk_widget_show (p->arrow_size);
    gtk_widget_show (p->arrow_size_l);
    gtk_widget_hide (p->width);
    gtk_widget_hide (p->width_l);
  }
  else
  {
    gtk_widget_hide (p->head1);
    gtk_widget_hide (p->head1_l);
    gtk_widget_hide (p->head2);
    gtk_widget_hide (p->head2_l);
    gtk_widget_hide (p->arrow_size);
    gtk_widget_hide (p->arrow_size_l);
  }
}


/* Dialog used to edit a bond... */
void
edit_bond (struct Bond *bond, GtkWindow * parent)
{
  struct edit_bond_param p;
  GtkWidget *win, *menu, *menu1, *menu2, *menu_item, *rect, *table, *img;
  GdkPixbuf * g;
  GdkColor color = bond->color;
  int response;
  unsigned int row = 0;

  if (bond->type == BOND_GROUP)
    {
      win = gtk_message_dialog_new
	(parent, GTK_DIALOG_DESTROY_WITH_PARENT,
	 GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
	 _("You cannot edit a group. You need to ungroup its components and edit them."));
      gtk_dialog_run (GTK_DIALOG (win));
      gtk_widget_destroy (win);
      return;
    }

  win = gtk_dialog_new_with_buttons (_("Edit a bond"), GTK_WINDOW (parent),
				     GTK_DIALOG_DESTROY_WITH_PARENT |
				     GTK_DIALOG_MODAL,
				     GTK_STOCK_OK, 1,
				     GTK_STOCK_CANCEL, 0, NULL);
  gtk_container_set_border_width (GTK_CONTAINER (win), 20);
  table = gtk_table_new (5, 2, TRUE);
  gtk_table_set_row_spacings (GTK_TABLE (table), 5);
  gtk_table_set_col_spacings (GTK_TABLE (table), 10);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (win)->vbox), table, TRUE, TRUE, 20);
  p.type = bond->type;

#define ADD_ROW(S,l,w) { \
  l = gtk_label_new (S); \
  gtk_misc_set_alignment (GTK_MISC (l), 1.0, 0.5); \
  gtk_table_attach_defaults (GTK_TABLE (table), l, 0, 1, row, row + 1); \
  gtk_table_attach_defaults (GTK_TABLE (table), w, 1, 2, row, row + 1); \
  row ++; }
  
  menu = gtk_menu_new ();
  p.menu_bond = gtk_option_menu_new ();
  gtk_option_menu_set_menu (GTK_OPTION_MENU (p.menu_bond), menu);

#define ADD_MENU_ITEM(STR) { \
  menu_item = gtk_menu_item_new_with_label (STR); \
  gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item); }

  switch (bond->type)
    {
    case BOND_SIMPLE:
    case BOND_DOUBLE:
    case BOND_TRIPLE:
    case BOND_UP:
    case BOND_DOWN:
    case BOND_DASHED:
    case BOND_ARROW:
      ADD_MENU_ITEM (_("Simple"));
      ADD_MENU_ITEM (_("Double"));
      ADD_MENU_ITEM (_("Triple"));
      ADD_MENU_ITEM (_("Going up"));
      ADD_MENU_ITEM (_("Going down"));
      ADD_MENU_ITEM (_("Dashed"));
      ADD_MENU_ITEM (_("Arrow"));
      gtk_option_menu_set_history (GTK_OPTION_MENU (p.menu_bond),
				   (unsigned) (bond->type - BOND_SIMPLE));
      break;

    case BOND_ARC:
      ADD_MENU_ITEM (_("Arc"));
      gtk_option_menu_set_history (GTK_OPTION_MENU (p.menu_bond),
				   (unsigned) (bond->type - BOND_ARC));
      break;

    case BOND_CIRCLE:
      ADD_MENU_ITEM (_("Circle"));
      gtk_option_menu_set_history (GTK_OPTION_MENU (p.menu_bond), 0);
      break;

    case BOND_ATOM:
    case BOND_GROUP_L:
    case BOND_GROUP_R:
      ADD_MENU_ITEM (_("Atom/Group"));
      gtk_option_menu_set_history (GTK_OPTION_MENU (p.menu_bond), 0);
      break;
    }

#undef ADD_MENU_ITEM

  g_signal_connect_swapped (G_OBJECT (p.menu_bond), "changed",
                            G_CALLBACK (edit_bond_update_menu), &p);
  ADD_ROW (_("Type of the bond:"), p.menu_bond_l, p.menu_bond);

  p.frame = gtk_frame_new (NULL);
  gtk_frame_set_shadow_type (GTK_FRAME (p.frame), GTK_SHADOW_IN);
  rect = gtk_drawing_area_new ();
  g_signal_connect (G_OBJECT (rect), "expose_event",
                    G_CALLBACK (color_button_expose), &color);
  g_signal_connect (G_OBJECT (rect), "button_press_event",
                    G_CALLBACK (edit_color), &color);
  gtk_widget_set_events (rect, gtk_widget_get_events (rect)
                         | GDK_BUTTON_PRESS_MASK);
  gtk_widget_set_size_request (rect, 40, 20);
  gtk_container_add (GTK_CONTAINER (p.frame), rect);
  ADD_ROW (_("Color:"), p.frame_l, p.frame);

  SPIN_BUTTON_WITH_DEFAULT (p.width, 0., 5., .05, bond->width, 2);
  ADD_ROW (_("Relative width:"), p.width_l, p.width);

  SPIN_BUTTON_WITH_DEFAULT (p.arrow_size, 0., 3., .1, bond->width, 2);
  row--;
  ADD_ROW (_("Arrow size:"), p.arrow_size_l, p.arrow_size);

  menu1 = gtk_menu_new ();
  menu2 = gtk_menu_new ();
  p.head1 = gtk_option_menu_new ();
  p.head2 = gtk_option_menu_new ();
  gtk_option_menu_set_menu (GTK_OPTION_MENU (p.head1), menu1);
  gtk_option_menu_set_menu (GTK_OPTION_MENU (p.head2), menu2);

#define ADD_MENU_ITEM(X,M) { \
  g = gdk_pixbuf_new_from_inline (-1, X, FALSE, NULL); \
  img = gtk_image_new_from_pixbuf (g); \
  menu_item = gtk_menu_item_new (); \
  gtk_container_add (GTK_CONTAINER(menu_item), img); \
  gtk_menu_shell_append (GTK_MENU_SHELL (M), menu_item); }

  ADD_MENU_ITEM (graph_nohead_right, menu1);
  ADD_MENU_ITEM (graph_arrowhead_right, menu1);
  ADD_MENU_ITEM (graph_semihead_right1, menu1);
  ADD_MENU_ITEM (graph_semihead_right2, menu1);
  ADD_MENU_ITEM (graph_nohead_left, menu2);
  ADD_MENU_ITEM (graph_arrowhead_left, menu2);
  ADD_MENU_ITEM (graph_semihead_left2, menu2);
  ADD_MENU_ITEM (graph_semihead_left1, menu2);

#undef ADD_MENU_ITEM

  ADD_ROW (_("Beginning arrowhead:"), p.head1_l, p.head1);
  ADD_ROW (_("Ending arrowhead:"), p.head2_l, p.head2);

  if (bond->type == BOND_ARROW || bond->type == BOND_ARC)
    gtk_option_menu_set_history (GTK_OPTION_MENU (p.head1), bond->x4);
  else
    gtk_option_menu_set_history (GTK_OPTION_MENU (p.head1), 0);
  if (bond->type == BOND_ARROW || bond->type == BOND_ARC)
    gtk_option_menu_set_history (GTK_OPTION_MENU (p.head2), bond->y4);
  else
    gtk_option_menu_set_history (GTK_OPTION_MENU (p.head2), 0);

#undef ADD_ROW

  gtk_widget_show_all (win);
  edit_bond_update_menu (&p);
  response = gtk_dialog_run (GTK_DIALOG (win));
  if (response == 1)
    {
      switch (bond->type)
	{
	case BOND_SIMPLE:
	case BOND_DOUBLE:
	case BOND_TRIPLE:
	case BOND_UP:
	case BOND_DOWN:
	case BOND_DASHED:
	case BOND_ARROW:
	  bond->type =
	    gtk_option_menu_get_history (GTK_OPTION_MENU (p.menu_bond)) +
	    BOND_SIMPLE;
	  break;

	case BOND_ARC:
	  bond->type =
	    gtk_option_menu_get_history (GTK_OPTION_MENU (p.menu_bond)) +
	    BOND_ARC;
	  break;
	}
      bond->color = color;
      if (bond->type == BOND_ARROW || bond->type == BOND_ARC)
	bond->width = gtk_spin_button_get_value
	                (GTK_SPIN_BUTTON (p.arrow_size));
      else
        bond->width = gtk_spin_button_get_value (GTK_SPIN_BUTTON (p.width));
      if (bond->type == BOND_ARROW || bond->type == BOND_ARC)
      {
	bond->x4 = gtk_option_menu_get_history (GTK_OPTION_MENU (p.head1));
	bond->y4 = gtk_option_menu_get_history (GTK_OPTION_MENU (p.head2));
      }
    }

  gtk_widget_destroy (win);
}

gint
expose_preview (GtkWidget * widget, G_GNUC_UNUSED GdkEventExpose * event,
                GdkPixmap * pix)
{
  gdk_draw_pixmap (widget->window,
                   widget->style->fg_gc[GTK_WIDGET_STATE (widget)], pix,
		   event->area.x, event->area.y,
                   event->area.x, event->area.y,
                   event->area.width, event->area.height);
  return FALSE;

/* The following is used to keep a white preview area */
/*  gdk_draw_rectangle (widget->window,
	              widget->style->white_gc,
	              TRUE, 0, 0,
	              widget->allocation.width, widget->allocation.height);
  return TRUE;*/
}


#define MAX_ORNS 10
struct orn_pages 
{ 
  GtkWidget * page;
  GtkWidget * number;
  GtkWidget * size;
  GtkWidget * distance;
  GtkWidget * spacing;
  GtkWidget * angle;
  GtkWidget * type;
};

static struct orn_pages pages[MAX_ORNS];
static struct Ornament orns[MAX_ORNS];
static unsigned int num_orns;
static GtkWidget *nb;


void
set_orn_page_from_ornament (struct orn_pages * page, struct Ornament * orn)
{
  gtk_option_menu_set_history (GTK_OPTION_MENU (page->type), orn->type);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (page->number), orn->number);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (page->size), orn->size);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (page->angle), orn->angle);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (page->distance), orn->dist);
  gtk_spin_button_set_value (GTK_SPIN_BUTTON (page->spacing), orn->spacing);
}

void
set_ornament_from_orn_page (struct Ornament * orn, struct orn_pages * page)
{
  orn->type = gtk_option_menu_get_history (GTK_OPTION_MENU (page->type));
  orn->number = gtk_spin_button_get_value_as_int
      (GTK_SPIN_BUTTON (page->number));
  orn->angle = gtk_spin_button_get_value_as_int
      (GTK_SPIN_BUTTON (page->angle));
  orn->spacing = gtk_spin_button_get_value_as_int
      (GTK_SPIN_BUTTON (page->spacing));
  orn->size = gtk_spin_button_get_value (GTK_SPIN_BUTTON (page->size));
  orn->dist = gtk_spin_button_get_value (GTK_SPIN_BUTTON (page->distance));
}

gint
remove_orn_page_click (void)
{
  unsigned int page, i;
  gchar *s;
  struct orn_pages old_page;

  if (num_orns == 0)
    return TRUE;
  
  page = gtk_notebook_get_current_page (GTK_NOTEBOOK (nb));

/* First, we push the selected page so that it is the last one. */
  gtk_notebook_reorder_child (GTK_NOTEBOOK (nb), pages[page].page,
	                      num_orns - 1);
  old_page = pages[page];
  if (page < num_orns)
    for (i = page; i < num_orns - 1; i++)
    {
      orns[i] = orns[i + 1];
      pages[i] = pages[i + 1];
    }
  pages[num_orns - 1] = old_page;

/* Then we hide it. */
  gtk_widget_hide (pages[num_orns - 1].page);
  num_orns --;

/* And we take care of the numbering. */
  for (i = 0; i < num_orns; i++)
  {
    s = g_strdup_printf ("%d", i + 1);
    gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (nb),
	                             pages[i].page, s);
    g_free (s);
  }

  gtk_notebook_set_current_page (GTK_NOTEBOOK (nb), page);
  return TRUE;
}

gint
add_orn_page_click (void)
{
  gchar *s;
  
  if (num_orns >= MAX_ORNS)
    return TRUE;

  orns[num_orns].type = 0;
  orns[num_orns].number = 1;
  orns[num_orns].size = 1.0;
  orns[num_orns].angle = 0;
  orns[num_orns].spacing = 90;
  orns[num_orns].dist = 1.0;

  s = g_strdup_printf ("%d", num_orns + 1);
  gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (nb), pages[num_orns].page, s);
  g_free (s);

  set_orn_page_from_ornament (&(pages[num_orns]), &(orns[num_orns]));
  gtk_widget_show (pages[num_orns].page);

  gtk_notebook_set_current_page (GTK_NOTEBOOK (nb), num_orns);

  num_orns ++;
  return TRUE;
}


#define PREVIEW_SIZE 120
void
edit_ornaments (struct Bond *list, struct Bond *bond, const unsigned int end,
        	GtkWindow * parent)
{
  char *s;
  unsigned int row = 0, i;
  int response;
  LLINT x, y;
  GtkWidget *win, *hbox, *vbox, *table, *preview, *add, *remove,
            *l, *frame, *menu, *menu_item;
  GdkPixmap *preview_pixmap = NULL;
  struct Bond * attach;
  struct Ornament *old, *new;

  
/* Here we gather all ornaments from 'list' into the 'orns' array. */
  num_orns = 0;
  if (end == 0)
  {
    if (BOND_HAS_TEXT (bond))
    {
	x = bond->x3;
	y = bond->y3;
    } else {
	x = bond->x1;
	y = bond->y1;
    }
  } else { /* end == 1 */
      x = bond->x2;
      y = bond->y2;
  }

  num_orns = gather_ornaments_on_point (list, orns, MAX_ORNS, x, y);

/* If there is none, we add one. */
  if (num_orns == 0)
  {
    num_orns = 1;
    orns[0].type = 0;
    orns[0].number = 1;
    orns[0].size = 1.0;
    orns[0].angle = 0;
    orns[0].spacing = 90;
    orns[0].dist = 1.0;
  }

/* We create the dialog itself. */
  win = gtk_dialog_new_with_buttons (_("Edit ornaments"), GTK_WINDOW (parent),
				     GTK_DIALOG_DESTROY_WITH_PARENT |
				     GTK_DIALOG_MODAL,
				     GTK_STOCK_OK, 1,
				     GTK_STOCK_CANCEL, 0, NULL);
  gtk_container_set_border_width (GTK_CONTAINER (win), 10);
  
  hbox = gtk_hbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (win)->vbox), hbox, TRUE, TRUE, 20);

  nb = gtk_notebook_new ();
  gtk_box_pack_start (GTK_BOX (hbox), nb, TRUE, TRUE, 10);

  for (i = 0; i < MAX_ORNS; i++)
  {
    pages[i].page = gtk_frame_new (NULL);

    table = gtk_table_new (7, 2, TRUE);
    gtk_container_set_border_width (GTK_CONTAINER (table), 10);
    gtk_table_set_row_spacings (GTK_TABLE (table), 5);
    gtk_table_set_col_spacings (GTK_TABLE (table), 10);
    gtk_table_set_homogeneous (GTK_TABLE (table), FALSE);
    gtk_container_add (GTK_CONTAINER (pages[i].page), table);
    row = 0;

#define ADD_ROW(S,w) { \
  l = gtk_label_new (S); \
  gtk_misc_set_alignment (GTK_MISC (l), 1.0, 0.5); \
  gtk_table_attach_defaults (GTK_TABLE (table), l, 0, 1, row, row + 1); \
 gtk_table_attach_defaults (GTK_TABLE (table), w, 1, 2, row, row + 1); \
  row ++; }

#define ADD_MENU_ITEM(STR) { \
  menu_item = gtk_menu_item_new_with_label (STR); \
  gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item); }
      
    menu = gtk_menu_new ();

    ADD_MENU_ITEM (_("Non-bonding pair"));
    ADD_MENU_ITEM (_("Electronic gap"));
    ADD_MENU_ITEM (_("Radical"));
    ADD_MENU_ITEM (_("Electronic gap 2"));
    ADD_MENU_ITEM (_("Non-bonding pair (dots)"));
    ADD_MENU_ITEM (_("Non-bonding electron"));
    
    pages[i].type = gtk_option_menu_new ();
    gtk_option_menu_set_menu (GTK_OPTION_MENU (pages[i].type), menu);
    gtk_option_menu_set_history (GTK_OPTION_MENU (pages[i].type), 0);
    ADD_ROW (_("Type:"), pages[i].type);

#undef ADD_MENU_ITEM

    SPIN_BUTTON_WITH_DEFAULT (pages[i].size, 0.1, 5., .05, 1.0, 2);
    ADD_ROW (_("Size:"), pages[i].size);

    SPIN_BUTTON_WITH_DEFAULT (pages[i].distance, 0.1, 5., .05, 1.0, 2);
    ADD_ROW (_("Distance:"), pages[i].distance);

    SPIN_BUTTON_WITH_DEFAULT (pages[i].number, 1, 10, 1, 1, 0);
    ADD_ROW (_("Number:"), pages[i].number);

    SPIN_BUTTON_WITH_DEFAULT (pages[i].spacing, 5, 180, 1, 90, 0);
    ADD_ROW (_("Spacing:"), pages[i].spacing);
  
    SPIN_BUTTON_WITH_DEFAULT (pages[i].angle, 0, 360, 1, 0, 0);
    ADD_ROW (_("Angle\n(from 12 AM,\nclockwise):"), pages[i].angle);

#undef ADD_ROW
  }

  for (i = 0; i < MAX_ORNS; i++)
  {
    gtk_notebook_append_page (GTK_NOTEBOOK (nb), pages[i].page, NULL);
    set_orn_page_from_ornament (&(pages[i]), &(orns[i]));
    s = g_strdup_printf ("%d", i + 1);
    gtk_notebook_set_tab_label_text (GTK_NOTEBOOK (nb), pages[i].page, s);
    g_free (s);
  }

  vbox = gtk_vbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (hbox), vbox, TRUE, TRUE, 10);

  frame = gtk_frame_new (NULL);
  gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 10);
  
  preview = gtk_drawing_area_new ();
  gtk_drawing_area_size (GTK_DRAWING_AREA (preview),
                         PREVIEW_SIZE, PREVIEW_SIZE);
  gtk_container_add (GTK_CONTAINER (frame), preview);

  add = gtk_button_new_with_label (_("Add one"));
  g_signal_connect (G_OBJECT (add), "clicked",
                    G_CALLBACK (add_orn_page_click), NULL);
  gtk_box_pack_start (GTK_BOX (vbox), add, TRUE, TRUE, 10);
  remove = gtk_button_new_with_label (_("Remove current"));
  g_signal_connect (G_OBJECT (remove), "clicked",
                    G_CALLBACK (remove_orn_page_click), NULL);
  gtk_box_pack_start (GTK_BOX (vbox), remove, TRUE, TRUE, 10);
  
  gtk_widget_show_all (win);
  preview_pixmap = gdk_pixmap_new (preview->window, PREVIEW_SIZE,
      				   PREVIEW_SIZE, -1);
  gdk_draw_rectangle (preview_pixmap, preview->style->white_gc, TRUE, 0, 0,
                      PREVIEW_SIZE, PREVIEW_SIZE);
  g_signal_connect (G_OBJECT (preview), "expose_event",
                    G_CALLBACK (expose_preview), preview_pixmap);
  for (i = num_orns; i < MAX_ORNS; i++)
    gtk_widget_hide (pages[i].page);
  
  response = gtk_dialog_run (GTK_DIALOG (win));
  if (response == 1)
  {
/* Here, we clean the ornaments on the given position */
    attach = delete_ornaments_on_point (list, x, y);

    old = NULL;
    for (i = 0; i < num_orns; i++)
    {
      set_ornament_from_orn_page (&(orns[i]), &(pages[i]));
      new = g_new (struct Ornament, 1);
      *new = orns[i];
      new->next = NULL;
      if (i == 0)
	attach->ornaments[end] = new;
      else
	old->next = new;
      old = new;
    }
  }

  gtk_widget_destroy (win);
}


void
prop_dialog ()
{
#define UNITS_CM 100.0
  GtkWidget *win, *table, *entry_gs, *entry_pstoedit, *spin_width,
	    *spin_height, *l;
  GtkObject *adjust;
  gchar *s;
  int response;
  unsigned int row = 0;

  win = gtk_dialog_new_with_buttons (_("Preferences"), NULL,
          GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
	  GTK_STOCK_OK, 1, GTK_STOCK_CANCEL, 0, NULL);
  gtk_container_set_border_width (GTK_CONTAINER (win), 20);
  table = gtk_table_new (5, 2, TRUE);
  gtk_table_set_row_spacings (GTK_TABLE (table), 5);
  gtk_table_set_col_spacings (GTK_TABLE (table), 10);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (win)->vbox), table, TRUE, TRUE, 20);

#define ADD_ROW(S,w) { \
  l = gtk_label_new (S); \
  gtk_misc_set_alignment (GTK_MISC (l), 1.0, 0.5); \
  gtk_table_attach_defaults (GTK_TABLE (table), l, 0, 1, row, row + 1); \
  gtk_table_attach_defaults (GTK_TABLE (table), w, 1, 2, row, row + 1); \
  row ++; }

  entry_gs = gtk_entry_new ();
  if (prop.path_gs != NULL)
    gtk_entry_set_text (GTK_ENTRY (entry_gs), prop.path_gs);
  ADD_ROW ("Path to gs:", entry_gs);

  entry_pstoedit = gtk_entry_new ();
  if (prop.path_pstoedit != NULL)
    gtk_entry_set_text (GTK_ENTRY (entry_pstoedit), prop.path_pstoedit);
  ADD_ROW ("Path to pstoedit:", entry_pstoedit);

  adjust = gtk_adjustment_new (prop.global_width / UNITS_CM, 10000 / UNITS_CM,
                               1000000 / UNITS_CM, 10000 / UNITS_CM,
                               50000 / UNITS_CM, 0.0);
  spin_width = gtk_spin_button_new (GTK_ADJUSTMENT (adjust), 0.0, 0);
  gtk_spin_button_set_update_policy (GTK_SPIN_BUTTON (spin_width),
                                     GTK_UPDATE_IF_VALID);
  gtk_spin_button_set_numeric (GTK_SPIN_BUTTON (spin_width), TRUE);
  ADD_ROW ("Width of the drawing:", spin_width);

  adjust = gtk_adjustment_new (prop.global_height / UNITS_CM, 50000 / UNITS_CM,
                               1000000 / UNITS_CM, 50000 / UNITS_CM,
                               50000 / UNITS_CM, 0.0);
  spin_height = gtk_spin_button_new (GTK_ADJUSTMENT (adjust), 0.0, 0);
  gtk_spin_button_set_update_policy (GTK_SPIN_BUTTON (spin_height),
                                     GTK_UPDATE_IF_VALID);
  gtk_spin_button_set_numeric (GTK_SPIN_BUTTON (spin_height), TRUE);
  ADD_ROW ("Height of the drawing:", spin_height);

#undef ADD_ROW
  
  gtk_widget_show_all (win);
  response = gtk_dialog_run (GTK_DIALOG (win));
  if (response == 1)
  {
/* TODO -- test paths before accepting them */
    s = gtk_entry_get_text (GTK_ENTRY (entry_gs));
    prop.path_gs = (strlen (s) == 0 ? NULL : g_strdup (s));
    s = gtk_entry_get_text (GTK_ENTRY (entry_pstoedit));
    prop.path_pstoedit = (strlen (s) == 0 ? NULL : g_strdup (s));

    prop.global_width = UNITS_CM * gtk_spin_button_get_value
      (GTK_SPIN_BUTTON (spin_width));
    prop.global_height = UNITS_CM * gtk_spin_button_get_value
      (GTK_SPIN_BUTTON (spin_height));
  }
  gtk_widget_destroy (win);
}


#ifdef MACOSX
#include <Carbon/Carbon.h>
void
macosx_noxrunning (void)
{
  SInt16 outItemHit;
  Str255 t1, t2;
  AlertStdAlertParamRec param;
  
  CopyCStringToPascal ("No X server running", t1);
  CopyCStringToPascal ("There is no X server running (at least, none I can connect to). Please launch one (Applications, Utilities, X11) before starting EasyChem.", t2);
  param.movable = 0;
  param.helpButton = 0;
  param.filterProc = nil;
  param.defaultText = (StringPtr) -1;
  param.cancelText = nil;
  param.otherText = nil;
  param.defaultButton = kAlertStdAlertOKButton;
  param.cancelButton = 0;
  param.position = 0;
  StandardAlert (kAlertNoteAlert, t1, t2, &param, &outItemHit);
}

void
macosx_initializecarbon (void)
{
  EventRecord dummyVariable;
  
  (void) WaitNextEvent(everyEvent, &dummyVariable, 0, nil);
}
#endif
