//<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;

  // 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());
  }

  hglue_ = layout.hglue(hnatural, hstretch, hshrink);
  Resource::ref(hglue_);
}

TableGlyph::~TableGlyph()
{
  Resource::unref(hglue_);
}

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

void TableGlyph::insertRow(GlyphIndex gi, PolyGlyph* 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* gl2;
    if (gl)
      gl2 = layout.vfixed(gl, vsize);
    else
      gl2 = layout.vfixed(layout.hglue(0), vsize);
    component(2*i)->insert(gi, gl2);
  }

  // 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, hglue_);

  rows_++;
}


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;
}
