--- loncom/xml/lontable.pm	2008/11/25 12:27:34	1.2
+++ loncom/xml/lontable.pm	2009/01/20 12:01:01	1.8
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 #  Generating TeX tables.
 #
-# $Id: lontable.pm,v 1.2 2008/11/25 12:27:34 foxr Exp $
+# $Id: lontable.pm,v 1.8 2009/01/20 12:01:01 foxr Exp $
 # 
 #
 # Copyright Michigan State University Board of Trustees
@@ -39,7 +39,7 @@
 
 # This module is a support packkage that helps londefdef generate
 # LaTeX tables using the LaTeX::Table package.  A prerequisite is that
-# the print generator must have added the following to the LaTeX header:
+# the print generator must have added the following to the LaTeX 
 #
 #  \usepackage{xtab}
 #  \usepackage{booktabs}
@@ -56,7 +56,9 @@
 package Apache::lontable;
 use strict;
 use LaTeX::Table;
+use Apache::lonnet;		# for trace logging.
 
+my $tracing = 0;		# Set to 1 to enable log tracing. 2 for local sub tracing.
 
 =pod
 
@@ -77,11 +79,6 @@ Opens a new table row.
 
 Closes a table row.
 
-=item start_header
-
-Starts a new row that has the header attribute (e.g. <th> tagged row).
-header rows are ended with an end_row just like any ordinary row.
-
 =item configure_row
 
 Modifies a configuration item in the currently open row.
@@ -94,6 +91,10 @@ Returns the generated table string.
 
 Configures a table's global configuration.
 
+=item add_cell
+
+Add and configure a cell to the current row.6
+
 =back
 
 =cut
@@ -109,6 +110,7 @@ modified by this.  These configuration i
 
 =over3
 
+
 =item alignment
 
 Table alignment.  Some table styles support this but not all.
@@ -133,6 +135,13 @@ to the LaTeX::Table package, and they wi
 not error checked.  Any use of a non-existent theme is reported by the LaTeX::Table package
 when the table text is generated.
 
+=item width
+
+The width of the table.   in any
+TeX unit measure e.g.  10.8cm  This forces the table to the
+tabularx environment.  It also forces the declarations for
+cells to be paragraph mode which supports more internal formatting.
+
 =back
 
 =head3 Member data
@@ -165,6 +174,11 @@ Table caption (configurable).
 
 Theme desired (configurable).
 
+=item width
+
+If defined, the width of the table (should be supplied
+in fraction of column width e.g. .75 for 75%.
+
 =item row_open 
 
 True if a row is open and not yet closed.
@@ -181,21 +195,20 @@ Each row of table data is an element of
 
 =over 3
 
-=item is_header
-
-True if the user wants to format this row like a header.  This row will be used to generate
-the table header.  All header rows will be gathered together into the table header.  If there
-are multiple table headers interspersed with non table header data, this can lead to some 
-surprises.
 
 =item default_halign 
-
+0
 Default horizontal alignment for cells in this row.
 
 =item default_valign
 
 Default vertical alignment for cells in this row (may be ignored).
 
+=item cell_width
+ 
+The width of the row in cells.  This is the sum of the column spans 
+of the cells in the row.
+
 =item cells
 
 Array of hashes where each element represents the data for a cell.
@@ -203,6 +216,11 @@ The contents of each element of this has
 
 =over 3
 
+=item header
+
+If present, the row is a 'header' that is it was made via the
+<th> tag.
+
 =item halign
 
 If present, overrides the row default horizontal alignment.
@@ -220,6 +238,10 @@ If present, indicates the number of rows
 If present indicates the number of columns this cell spans.
 Note that a cell can span both rows and columns.
 
+=item start_col
+
+The starting column of the cell in the table grid.
+
 =item contents
 
 The contents of the cell.
@@ -233,6 +255,8 @@ The contents of the cell.
 sub new {
     my ($class, $configuration) = @_;
 
+    if($tracing) {&Apache::lonnet::logthis("new table object");}
+
     #  Initialize the object member data with the default values
     #  then override with any stuff in $configuration.
 
@@ -256,6 +280,7 @@ sub new {
     return $self;
 }
 
+
 #-------------------------------------------------------------------------
 #
 #  Methods that get/set table global configuration.
@@ -278,10 +303,12 @@ Regardless, the current alignment is use
 sub alignment {
     my ($self, $new_value) = @_;
 
+    if ($tracing) {&Apache::lonnet::logthis("alignment = $new_value");}
+
     if (defined($new_value)) {
-	$self->{alignment} = $new_value;
+	$self->{'alignment'} = $new_value;
     }
-    return $self->{alignment};
+    return $self->{'alignment'};
 }
 
 =pod
@@ -303,10 +330,12 @@ the final value of the outer_border requ
 sub table_border {
     my ($self, $new_value) = @_;
 
+    if ($tracing) {&Apache::lonnet::logthis("table_border $new_value");}
+
     if (defined($new_value)) {
-	$self->{outer_border} = $new_value;
+	$self->{'outer_border'} = $new_value;
     }
-    return $self->{outer_border};
+    return $self->{'outer_border'};
 }
 
 
@@ -321,18 +350,18 @@ value of that configuration parameter is
 
 =head3 Examples:
 
- my $cell_borders = $table->cell_border(); # ask if cell borders are requested.
+ my $cell_border = $table->cell_border(); # ask if cell borders are requested.
  $table->cell_border(1);	# Request cell borders.
 
 =cut
 
-sub cell_borders {
+sub cell_border {
     my ($self, $new_value) = @_;
-
+    if($tracing) {&Apache::lonnet::logthis("cell_border: $new_value"); }
     if (defined($new_value)) {
-	$self->{inner_border} = $new_value;
+	$self->{'inner_border'} = $new_value;
     }
-    reurn $self->{inner_border};
+    return $self->{'inner_border'};
 }
 
 =pod
@@ -353,11 +382,12 @@ the table.  If a parameter is supplied i
 sub caption {
     my ($self, $new_value) = @_;
 
+    if($tracing) {&Apache::lonnet::logthis("caption: $new_value"); }
     if (defined($new_value)) {
-	$self->catpion = $new_value;
+	$self->{'caption'} = $new_value;
     }
 
-    return $self->caption;
+    return $self->{'caption'};
 }
 
 =pod
@@ -377,11 +407,32 @@ will be the new theme selection.
 
 sub theme {
     my ($self, $new_value) = @_;
+    if($tracing) {&Apache::lonnet::logthis("theme $new_value"); }
+    if (defined($new_value)) {
+	$self->{'theme'} = $new_value;
+    }
+    return $self->{'theme'};
+}
+
+=pod
+
+=head 2 width
+
+Gets and optionally sets the width of the table.
+
+=head 3 Examples:
+
+ my $newwidth = $table->width("10cm");   # 10cm width returns "10cm".
+
+=cut
+sub width {
+    my ($self, $new_value) = @_;
+    if($tracing) {&Apache::lonnet::logthis("width = $new_value"); }
 
     if (defined($new_value)) {
-	$self->theme = $new_value;
+	$self->{'width'} = $new_value;
     }
-    return $self->theme;
+    return $self->{'width'}; 	# Could be undef.
 }
 
 =pod
@@ -413,30 +464,31 @@ The default vertical alignment of the ro
 =cut
 
 sub start_row {
-    my ($self, %config) = @_;
-
-    if ($self->row_open) { 
-	$self->end_row;
+    my ($self, $config) = @_;
+    if($tracing) {&Apache::lonnet::logthis("start_row"); }
+    if ($self->{'row_open'}) { 
+	$self->end_row();
     }
     my $row_hash = {
-	is_header      =>  0,
 	default_halign => "left",
 	default_valign => "top",
+	cell_width     =>  0,
 	cells          => []
     };
 
     # Override the defaults if the config hash is present:
 
-    if (defined(%config)) {
-	foreach my $key  (keys %config) {
-	    $row_hash->{$key} = $config{$key};
+    if (defined($config)) {
+	foreach my $key  (keys %$config) {
+	    $row_hash->{$key} = $config->{$key};
 	}
     }
+
     
-    my $rows = $self->{rows};
+    my $rows = $self->{'rows'};
     push(@$rows, $row_hash);
 
-    $self->row_open = 1;	# Row is now open and ready for business.
+    $self->{"row_open"} = 1;	# Row is now open and ready for business.
 }
 
 =pod
@@ -447,50 +499,408 @@ Closes off a row.  Once closed, cells ca
 
 =head3 Examples:
 
-   $table->close_row();
+   $table->end_row();
 
 
 =cut
 
-sub close_row {
+sub end_row {
     my ($self) = @_;
-
-    if ($self->row_open) {
+    if($tracing) {&Apache::lonnet::logthis("end_row"); }
+    if ($self->{'row_open'}) {
 	
 	# Mostly we need to determine if this row has the maximum
 	# cell count of any row in existence in the table:
 
-	my $row        = $self->{rows}[-1];
-	my $cells      = $row->{cells};
-	my $cell_count = scalar(@$cells);
-	if ($cell_count > $self->{column_count}) {
-	    $self->{column_count} = $cell_count;
+	my $row        = $self->{'rows'}->[-1];
+	my $cells      = $row->{'cells'};
+
+	if ($row->{'cell_width'} > $self->{'column_count'}) {
+	    $self->{'column_count'} = $row->{'cell_width'};
+	}
+
+	$self->{'row_open'} = 0;;
+    }
+}
+
+=pod
+
+=head2 configure_row
+
+Modify the configuration of a row.   If a row is not open, a new one will be opened.
+
+=head3 Parameters:
+
+config_hash - A hash that contains new values for the set of row confiuguration 
+items to be modified.  There is currently no check/penalty for items that are not in
+the set of defined configuration properties which are:
+
+=over 2
+
+=item default_halign
+
+The default horizontal alignment for text in  cells in the row.  This can be any of:
+"left", "right" or "center".
+
+=item default_valign
+
+The default vertical alignment for text in cells in the row.  This can be any of:
+
+"top", "bottom" or "center"
+
+=back 
+
+=cut
+
+sub configure_row {
+    my ($self, $config) = @_;
+    if($tracing) {&Apache::lonnet::logthis("configure_row");}
+    if (!$self->{'row_open'}) {
+	$self->start_row();
+    }
+    
+    my $row = $self->{'rows'}[-1];
+    foreach my $config_item (keys %$config) {
+	$row->{$config_item} = $config->{$config_item};
+    }
+}
+
+
+=pod
+
+=head2 add_cell
+
+Add a new cell to a row.  If there is a row above us, we need to 
+watch out for row spans that may force additional blank cell entries
+to fill in the span. 
+
+=head3 Parameters:
+
+=over 2
+
+=item text
+
+Text to put in the cell.
+
+=item cell_config
+
+Hash of configuration options that override the defaults.   The recognized options,
+and their defaults are:
+
+=over 2
+
+=item halign 
+
+If nonblank overrides the row's default for the cell's horizontal alignment.
+
+=item valign
+
+If nonblank, overrides the row's default for the cdell's vertical alignment.
+
+=item rowspan
+
+Number of rows the cell spans.
+
+=item colspan
+
+Number of columns the cell spans.
+
+=back
+
+=cut
+
+sub add_cell {
+    my ($self, $text, $config) = @_;
+
+    if($tracing) {&Apache::lonnet::logthis("add_cell : $text"); }
+
+    # If a row is not open, we must open it:
+
+    if (!$self->{'row_open'}) {
+	$self->start_row();
+    }
+    my $rows          = $self->{'rows'};
+    my $current_row   = $rows->[-1];
+    my $current_cells = $current_row->{'cells'}; 
+    my $last_coord    = $current_row->{'cell_width'};
+
+    #  We have to worry about row spans if there is a prior row:
+
+    if (scalar(@$rows) > 1) {
+
+	my $last_row = $rows->[-2];
+	if ($last_coord < $last_row->{'cell_width'}) {
+	    my $prior_coord       = 0;
+	    my $prior_cell_index  = 0;
+	    while ($prior_coord <= $last_coord) {
+		
+		# Pull a cell down if it's coord matches our start coord
+		# And there's a row span > 1.
+		# Having done so, we adjust our $last_coord to match the
+		# end point of the pulled down cell.
+
+		my $prior_cell = $last_row->{'cells'}->[$prior_cell_index];
+		if (!defined($prior_cell)) {
+		    last;
+		}
+		if (($prior_cell->{'start_col'} == $last_coord) &&
+		    ($prior_cell->{'rowspan'}  > 1)) {
+		    
+		    #  Need to drop the cell down
+
+		    my %dropped_down_cell = %$prior_cell;
+		    $dropped_down_cell{'rowspan'}--;
+		    $dropped_down_cell{'contents'} = '';
+
+		    push(@$current_cells, \%dropped_down_cell);
+		    $last_coord += $dropped_down_cell{'colspan'};
+		    $current_row->{'cell_width'} = $last_coord;
+		    
+		}
+		$prior_coord += $prior_cell->{'colspan'};
+		$prior_cell_index++;
+	    }
 	}
 
-	$self->row_closed;
     }
+
+    #
+    # Now we're ready to build up our cell:
+
+    my $cell = {
+	rowspan    => 1,
+	colspan    => 1,
+	start_col  => $last_coord,
+	contents   => $text
+    };
+    
+    if (defined($config)) {
+	foreach my $key (keys(%$config)) {
+	    $cell->{$key} = $config->{$key};
+	}
+    }
+    $current_row->{'cell_width'} += $cell->{'colspan'};
+
+    push(@$current_cells, $cell);
+
+    if ($tracing) { &Apache::lonnet::logthis("add_cell done"); }
 }
 
+
 =pod
 
-=head2 start_header
+=head2  append_cell_text
+
+Sometimes it's necessary to create/configure the cell and then later add text to it.
+This sub allows text to be appended to the most recently created cell.
 
-Starts a row that is a header.  This is the same as start_row,but the is_header flag
-is set to true.
+=head3 Parameters
 
+The text to add to the cell.
 
 =cut
+sub append_cell_text {
+    my ($this, $text) = @_;
 
-sub start_header {
-    my ($self, %config) = @_;
+    if($tracing) {&Apache::lonnet::logthis("append_cell_text: $text"); }
+    my $rows         = $this->{'rows'};
+    my $current_row  = $rows->[-1];
+    my $cells        = $current_row->{'cells'};
+    my $current_cell = $cells->[-1];
+    $current_cell->{'contents'} .= $text;
+    
+}
+
+
+=pod
+
+=head2 generate
+
+Call this when the structures for the table have been built.
+This will generate and return the table object that can be used
+to generate the table.  Returning the table object allows for
+a certain amount of testing to be done on the generated table.
+The caller can then ask the table object to generate LaTeX.
+
+=cut
+sub generate {
+    my ($this) = @_;
+    my $useP   = 0;
+    my $colwidth;
+    my $colunits;
+
+    if($tracing) {&Apache::lonnet::logthis("generate"); }
+    my $table = LaTeX::Table->new();
+    $table->set_center(0);	# loncapa tables don't float.
+    $table->set_environment(0);
+
+
+    # Add the caption if supplied.
+
+    if ($this->{'caption'} ne "") {
+	$table->set_caption($this->caption);
+    }
+    
+    # Set the width if defined:
+
+    if (defined ($this->{'width'})) {
+#	$table->set_width($this->{'width'});
+#	$table->set_width_environment('tabularx');
+	$useP = 1;
+	($colwidth, $colunits) = split(/ /, $this->{'width'});
+	$colwidth = $colwidth/$this->{'column_count'};
+
+    }
+
+    # Build up the data:
+
+    my @data;
+    my $rows      = $this->{'rows'};
+    my $row_count = scalar(@$rows);
+    my $inner_border = $this->{'inner_border'};
+    my $outer_border = $this->{'outer_border'};
+    my $column_count = $this->{'column_count'};
+
+    for (my $row = 0; $row < $row_count; $row++) {
+	my @row;
+	my $cells      = $rows->[$row]->{'cells'};
+	my $def_halign = $rows->[$row]->{'default_halign'};
+	my $cell_count = scalar(@$cells);
+	my $startcol   = 1;
+	my @underlines;		# Array of \cline cells if cellborder on.
+
+
+	for (my $cell  = 0; $cell < $cell_count; $cell++) {
+	    my $contents = $cells->[$cell]->{'contents'};
+
+	    #
+	    #  Cell alignment is the default alignment unless
+	    #  explicitly specified in the cell.
+	    #  NOTE: at this point I don't know how to do vert alignment.
+	    #
+
+	    my $halign   = $def_halign;
+	    if (defined ($cells->[$cell]->{'halign'})) {
+		$halign = $cells->[$cell]->{'halign'};
+	    }
+
+	    # Create the horizontal alignment character:
+
+	    my $col_align = 'l';
+	    my $embeddedAlignStart = "";
+	    my $embeddedAlignEnd   = "";
+
+	    if ($halign eq 'right') {
+		$col_align = 'r';
+		$embeddedAlignStart = '\begin{flushright} ';
+		$embeddedAlignEnd   = ' \end{flushright}';
+	    }
+	    if ($halign eq 'center') {
+		$col_align = 'c';
+		$embeddedAlignStart = '\begin{center}';
+		$embeddedAlignEnd   = '\end{center}';
+	    }
+
+	    # If the width has been specified, turn these into
+	    # para mode; and wrap the contents in the start/stop stuff:
+
+	    if ($useP) {
+		my $cw = $colwidth * $cells->[$cell]->{'colspan'};
+		$col_align = "p{$cw $colunits}";
+		$contents = $embeddedAlignStart . $contents .  $embeddedAlignEnd;
+	    }
+
+	    if ($inner_border || ($outer_border && ($cell == 0))) {
+		$col_align = '|'.$col_align;
+	    }
+	    if ($inner_border || ($outer_border && ($cell == ($cell_count -1)))) {
+		$col_align = $col_align.'|';
+	    }
+
+	    #factor in spans:
+
+	    my $cspan    = $cells->[$cell]->{'colspan'};
+	    my $nextcol  = $startcol + $cspan;
+
+	    # If we can avoid the \multicolumn directive that's best as
+	    # that makes some things like \parpic invalid in LaTeX which
+            # screws everything up.
+
+	    if (($cspan > 1) || !($col_align =~ /l/)) {
+
+		$contents = '\multicolumn{'.$cspan.'}{'.$col_align.'}{'.$contents.'}';
+
+		# A nasty edge case.  If there's only one cell, the software will assume
+		# we're in complete control of the row so we need to end the row ourselves.
+		
+		if ($cell_count == 1) {
+		    $contents .= '  \\\\';
+		}
+	    }
+	    if ($inner_border && ($cells->[$cell]->{'rowspan'} == 1)) {
+		my $lastcol = $nextcol -1;
+		push(@underlines, "\\cline{$startcol-$lastcol}");
+	    }
+	    $startcol = $nextcol;
+	    # Rowspans should take care of themselves.
+	    
+	    push(@row, $contents);
+
+	}
+	push(@data, \@row);
+	if ($inner_border) {
+	    for (my $i =0; $i < scalar(@underlines); $i++) {
+		push(@data, [$underlines[$i]]);
+	    }
+	}
+
+    }
+    $table->set_data(\@data);
+    
+    my $coldef = "";
+    if ($outer_border || $inner_border) {
+	$coldef .= '|';
+    }
+    for (my $i =0; $i < $column_count; $i++) {
+	if ($useP) {
+	    $coldef .= "p{$colwidth $colunits}";
+	} else {
+	    $coldef .= 'l';
+	}
+	if ($inner_border || 
+	    ($outer_border && ($i == $column_count-1))) {
+	    $coldef .= '|';
+	}
+    }
+    $table->{'coldef'} = $coldef;
+
+    # Return the table:
+
+    if ($tracing) { &Apache::lonnet::logthis("Leaving generate"); }
+
+    return $table;
 
-    $self->start_row(%config);
-    $self->{rows}[-1]->is_header = 1;
 }
+#----------------------------------------------------------------------------
+# The following methods allow for testability.
 
 
+sub get_object_attribute {
+    my ($self, $attribute) = @_;
+    if ($tracing > 1) { &Apache::lonnet::logthis("get_object_attribute: $attribute"); }
+    return $self->{$attribute};
+}
+
+sub get_row {
+    my ($self, $row) = @_;
+    if ($tracing > 1) { &Apache::lonnet::logthis("get_row"); }
 
+    my $rows = $self->{'rows'};	  # ref to an array....
+    return $rows->[$row];         # ref to the row hash for the selected row.
+}
 #   Mandatory initialization.
+BEGIN{
+}
 
 1;
 __END__