#include<LEDA/graphwin.h>
#include<LEDA/graph_alg.h>

// ------------------------------------------------------------- //
//                    GraphWin interface                         //
// ------------------------------------------------------------- //



void fix_node(GraphWin& gw, const point&)
{ // position no used
  node v = gw.get_found_node();
  if (gw.get_color(v) != red) 
     gw.set_color(v,red);
  else
     gw.set_color(v,yellow);
 }


void update_drawing(GraphWin& GW, const graph& G)
// redraw the graph according to the positions of the red nodes
{
  // get fixed nodes
  node v;
  list<node> fixed_nodes;
  forall_nodes(v,G) if(GW.get_color(v) == red) fixed_nodes.append(v);

  node_array<point> pos(G);
  node_array<double> xpos(G);
  node_array<double> ypos(G);
  forall(v,fixed_nodes) 
  { point p = GW.get_position(v);
    xpos[v] = p.xcoord();
    ypos[v] = p.ycoord();
   }

  if (TUTTE_EMBEDDING(G,fixed_nodes,xpos,ypos)) 
              GW.set_position(xpos,ypos);
}


// --------------------- handler ------------------------------ //


void move_node_handler(GraphWin& GW, node v)
{
  if(GW.get_color(v) != red) return;
  const graph& G = GW.get_graph();
  update_drawing(GW,G);
}

void del_node_handler(GraphWin& GW)
{
  const graph& G = GW.get_graph();
  update_drawing(GW,G);
}

void new_edge_handler(GraphWin& GW, edge e)
{
  const graph& G = GW.get_graph();
  update_drawing(GW,G);
}

void del_edge_handler(GraphWin& GW)
{
  const graph& G = GW.get_graph();
  update_drawing(GW,G);
}

main()
{
  graph G;
  GraphWin GW("Tutte Demo");;
  GW.set_action(A_LEFT|A_NODE|A_CTRL,fix_node);
  GW.display();
  GW.set_animation_steps(0);

  panel P("Usage");
  P.text_item("This program demonstrates the TUTTE_DRAWING procedure.");
  P.text_item("Some designated nodes of the graph have fixed positions,");
  P.text_item("and all other nodes are drawn in the center of gravity");
  P.text_item("of their neighbors.");
  P.text_item("Edit a graph and select some nodes by clicking with the left");
  P.text_item("mouse button while simultaneously holding down the CTRL key.");
  P.text_item("The selected nodes will become red and be the fixed nodes as");
  P.text_item("described above. Now, move the red nodes or change the graph.");
  P.text_item("");
  P.text_item("You get the best results for planar triangulated graphs");
  P.button("ok");

  P.open(GW.get_window());

  GW.set_move_node_handler(move_node_handler);
  GW.set_del_node_handler(del_node_handler);
  GW.set_new_edge_handler(new_edge_handler);
  GW.set_del_edge_handler(del_edge_handler);

  return GW.edit();
}
