//<copyright>
//
// Copyright (c) 1995
// Institute for Information Processing and Computer Supported New Media (IICM),
// Graz University of Technology, Austria.
//
//</copyright>



//<file>
//
//
// Name:             table.C
//
// Purpose:          Implementation of class TableGlyph
//
// Created:          22 May 95   Bernhard Marschall
// Modified:         22 May 95   Bernhard Marschall
//
//
// Description:
//
//</file>


#include "table.h"

#include <InterViews/align.h>
#include <InterViews/layout.h>
#include <InterViews/superpose.h>
#include <InterViews/tile.h>


//---------- Table ------------------------------------------------------

TableGlyph::TableGlyph(int columns, int rows,
                       Coord hnatural, Coord hstretch, Coord hshrink)
: Box(
    new Superpose(
      new Tile(Dimension_X),
      new Align(Dimension_Y)
    ),
    rows
  )
{
  rows_ = 0;
  cols_ = columns;
  hnatural_ = hnatural;
  hstretch_ = hstretch;
  hshrink_ = hshrink;

  // set up vboxes (Table is a hbox of vboxes)
  const LayoutKit& layout = *LayoutKit::instance();
  for (int i=0; i<2*columns-1; i++) {
    append(layout.vbox());
  }
}

TableGlyph::~TableGlyph()
{
}

//-----------------------------------------------------------------------

void TableGlyph::insertRow(GlyphIndex gi, PolyGlyph* g)
{
  Resource::ref (g);
  const LayoutKit& layout = *LayoutKit::instance();

  // insert glyphs
  Coord vsize = height(g);
  int i;  // gcc keeps loop-vars local
  for (i = 0;  i < cols_;  i++)
  {
    Glyph* gl = g->component (i);
    Glyph* g;
    if (gl)
      g = layout.vfixed (gl, vsize);
    else
      g = layout.vfixed (layout.hglue(0), vsize);
    component (2*i)->insert (gi, g);
  }

  // insert horizontal space
  GlyphIndex num;
  if (g->count() > cols_)
    num = 2 * cols_ - 1;
  else
    num = 2 * g->count () - 1;
  for (i = 1;  i < num;  i += 2)
    component (i)->insert (gi, layout.hglue (hnatural_, hstretch_, hshrink_));

  rows_++;
  Resource::unref (g);
}


void TableGlyph::removeRow(GlyphIndex gi)
{
  // remove glyph
  for (int i=0; i<2*cols_-1; i++) {
    Glyph* vbox = component(i);
    if (vbox->component(gi)) vbox->remove(gi);
  }
}

//-----------------------------------------------------------------------

Coord TableGlyph::height(PolyGlyph* pGlyph) const
{
  Coord max = 0;
  Requisition req;
  Coord comp;
  for (GlyphIndex i=0; i<pGlyph->count(); i++) {
    if (pGlyph->component(i)) {
      pGlyph->component(i)->request(req);
      comp = req.y_requirement().natural();
      if (max < comp) max = comp;
    }
  }

  return max;
}
