| 1 |
package tablewriter |
| 2 |
|
| 3 |
import ( |
| 4 |
"math" |
| 5 |
|
| 6 |
"github.com/olekukonko/errors" |
| 7 |
"github.com/olekukonko/tablewriter/pkg/twwidth" |
| 8 |
"github.com/olekukonko/tablewriter/tw" |
| 9 |
) |
| 10 |
|
| 11 |
// Close finalizes the table stream. |
| 12 |
// It requires the stream to be started (by calling NewStreamTable). |
| 13 |
// It calls the renderer's Close method to render final elements (like the bottom border) and close the stream. |
| 14 |
func (t *Table) Close() error { |
| 15 |
t.logger.Debug("Close() called. Finalizing stream.") |
| 16 |
|
| 17 |
// Ensure stream was actually started and enabled |
| 18 |
if !t.config.Stream.Enable || !t.hasPrinted { |
| 19 |
t.logger.Warn("Close() called but streaming not enabled or not started. Ignoring Close() actions.") |
| 20 |
// If renderer has a Close method that should always be called, consider that. |
| 21 |
// For Blueprint, Close is a no-op, so returning early is fine. |
| 22 |
// If we always call renderer.Close(), ensure it's safe if renderer.Start() wasn't called. |
| 23 |
// Let's only call renderer.Close if stream was started. |
| 24 |
if t.hasPrinted && t.renderer != nil { // Check if renderer is not nil for safety |
| 25 |
t.renderer.Close() // Still call renderer's close for cleanup |
| 26 |
} |
| 27 |
t.hasPrinted = false // Reset flag |
| 28 |
return nil |
| 29 |
} |
| 30 |
|
| 31 |
// Render stored footer if any |
| 32 |
if len(t.streamFooterLines) > 0 { |
| 33 |
t.logger.Debug("Close(): Rendering stored footer.") |
| 34 |
if err := t.streamRenderFooter(t.streamFooterLines); err != nil { |
| 35 |
t.logger.Errorf("Close(): Failed to render stream footer: %v", err) |
| 36 |
// Continue to try and close renderer and render bottom border |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
// Render the final table bottom border |
| 41 |
t.logger.Debug("Close(): Rendering stream bottom border.") |
| 42 |
if err := t.streamRenderBottomBorder(); err != nil { |
| 43 |
t.logger.Errorf("Close(): Failed to render stream bottom border: %v", err) |
| 44 |
// Continue to try and close renderer |
| 45 |
} |
| 46 |
|
| 47 |
// Call the underlying renderer's Close method |
| 48 |
err := t.renderer.Close() |
| 49 |
if err != nil { |
| 50 |
t.logger.Errorf("Renderer.Close() failed: %v", err) |
| 51 |
} |
| 52 |
|
| 53 |
// Reset streaming state |
| 54 |
t.hasPrinted = false |
| 55 |
t.headerRendered = false |
| 56 |
t.firstRowRendered = false |
| 57 |
t.lastRenderedLineContent = nil |
| 58 |
t.lastRenderedMergeState = nil |
| 59 |
t.lastRenderedPosition = "" |
| 60 |
t.streamFooterLines = nil |
| 61 |
// t.streamWidths should persist if we want to make multiple Start/Close calls on same config? |
| 62 |
// For now, let's assume Start re-evaluates. If widths are from StreamConfig, they'd be reused. |
| 63 |
// If derived, they'd be re-derived. Let's clear for true reset. |
| 64 |
t.streamWidths = tw.NewMapper[int, int]() |
| 65 |
t.streamNumCols = 0 |
| 66 |
// t.streamRowCounter = 0 // Removed this field |
| 67 |
|
| 68 |
t.logger.Debug("Stream ended. hasPrinted = false.") |
| 69 |
return err // Return error from renderer.Close or other significant errors |
| 70 |
} |
| 71 |
|
| 72 |
// Start initializes the table stream. |
| 73 |
// In this streaming model, renderer.Start() is primarily called in NewStreamTable. |
| 74 |
// This method serves as a safeguard or point for adding pre-rendering logic. |
| 75 |
// Start initializes the table stream. |
| 76 |
// It is the entry point for streaming mode. |
| 77 |
// Requires t.config.Stream.Enable to be true. |
| 78 |
// Returns an error if streaming is disabled or the renderer does not support streaming, |
| 79 |
// or if called multiple times on the same stream. |
| 80 |
func (t *Table) Start() error { |
| 81 |
t.ensureInitialized() // Ensures basic setup like loggers |
| 82 |
|
| 83 |
if !t.config.Stream.Enable { |
| 84 |
// Start() should only be called when streaming is explicitly enabled. |
| 85 |
// Otherwise, the user should call Render() for batch mode. |
| 86 |
t.logger.Warn("Start() called but streaming is disabled. Call Render() instead for batch mode.") |
| 87 |
return errors.New("start() called but streaming is disabled") |
| 88 |
} |
| 89 |
|
| 90 |
if !t.renderer.Config().Streaming { |
| 91 |
// Check if the configured renderer actually supports streaming. |
| 92 |
t.logger.Error("Configured renderer does not support streaming.") |
| 93 |
return errors.Newf("renderer does not support streaming") |
| 94 |
} |
| 95 |
|
| 96 |
// t.renderer.Start(t.writer) |
| 97 |
// t.renderer.Logger(t.logger) |
| 98 |
|
| 99 |
if t.hasPrinted { |
| 100 |
// Prevent calling Start() multiple times on the same stream instance. |
| 101 |
t.logger.Warn("Start() called multiple times for the same table stream. Ignoring subsequent calls.") |
| 102 |
return nil |
| 103 |
} |
| 104 |
|
| 105 |
t.logger.Debug("Starting table stream.") |
| 106 |
|
| 107 |
// Initialize/reset streaming state flags and buffers |
| 108 |
t.headerRendered = false |
| 109 |
t.firstRowRendered = false |
| 110 |
t.lastRenderedLineContent = nil |
| 111 |
t.lastRenderedPosition = "" // Reset last rendered position |
| 112 |
t.streamFooterLines = nil // Reset footer buffer |
| 113 |
t.streamNumCols = 0 // Reset derived column count |
| 114 |
|
| 115 |
// Calculate initial fixed widths if provided in StreamConfig.Widths |
| 116 |
// These widths will be used for all subsequent rendering in streaming mode. |
| 117 |
if t.config.Widths.PerColumn != nil && t.config.Widths.PerColumn.Len() > 0 { |
| 118 |
// Use per-column stream widths if set |
| 119 |
t.logger.Debugf("Using per-column stream widths from StreamConfig: %v", t.config.Widths.PerColumn) |
| 120 |
t.streamWidths = t.config.Widths.PerColumn.Clone() |
| 121 |
// Determine numCols from the highest index in PerColumn map |
| 122 |
maxColIdx := -1 |
| 123 |
t.streamWidths.Each(func(col, width int) { |
| 124 |
if col > maxColIdx { |
| 125 |
maxColIdx = col |
| 126 |
} |
| 127 |
// Ensure configured widths are reasonable (>0 becomes >=1, <0 becomes 0) |
| 128 |
if width > 0 && width < 1 { |
| 129 |
t.streamWidths.Set(col, 1) |
| 130 |
} else if width < 0 { |
| 131 |
t.streamWidths.Set(col, 0) // Negative width means hide column |
| 132 |
} |
| 133 |
}) |
| 134 |
if maxColIdx >= 0 { |
| 135 |
t.streamNumCols = maxColIdx + 1 |
| 136 |
t.logger.Debugf("Derived streamNumCols from PerColumn widths: %d", t.streamNumCols) |
| 137 |
} else { |
| 138 |
// PerColumn map exists but is empty? Or all negative widths? Assume 0 columns for now. |
| 139 |
t.streamNumCols = 0 |
| 140 |
t.logger.Debugf("PerColumn widths map is effectively empty or contains only negative values, streamNumCols = 0.") |
| 141 |
} |
| 142 |
|
| 143 |
} else if t.config.Widths.Global > 0 { |
| 144 |
// Global width is set, but we don't know the number of columns yet. |
| 145 |
// Defer applying global width until the first data (Header or first Row) arrives. |
| 146 |
// Store a placeholder or flag indicating global width should be used. |
| 147 |
// The simple way for now: Keep streamWidths empty, signal the global width preference. |
| 148 |
// The width calculation function called later will need to check StreamConfig.Widths.Global |
| 149 |
// if streamWidths is empty. |
| 150 |
t.logger.Debugf("Global stream width %d set in StreamConfig. Will derive numCols from first data.", t.config.Widths.Global) |
| 151 |
t.streamWidths = tw.NewMapper[int, int]() // Initialize as empty, will be populated later |
| 152 |
// Note: No need to store Global width value here, it's available in t.config.Stream.Widths.Global |
| 153 |
|
| 154 |
} else { |
| 155 |
// No explicit stream widths in config. They will be calculated from the first data (Header or first Row). |
| 156 |
t.logger.Debug("No explicit stream widths configured in StreamConfig. Will derive from first data.") |
| 157 |
t.streamWidths = tw.NewMapper[int, int]() // Initialize as empty, will be populated later |
| 158 |
t.streamNumCols = 0 // NumCols will be determined by first data |
| 159 |
} |
| 160 |
|
| 161 |
// Log warnings if incompatible features are enabled in streaming config |
| 162 |
// Vertical/Hierarchical merges require processing all rows together. |
| 163 |
if t.config.Header.Formatting.MergeMode&(tw.MergeVertical|tw.MergeHierarchical) != 0 { |
| 164 |
t.logger.Warnf("Vertical or Hierarchical merge modes enabled on Header config (%d) but are unsupported in streaming mode. Only Horizontal merge will be considered.", t.config.Header.Formatting.MergeMode) |
| 165 |
} |
| 166 |
if t.config.Row.Formatting.MergeMode&(tw.MergeVertical|tw.MergeHierarchical) != 0 { |
| 167 |
t.logger.Warnf("Vertical or Hierarchical merge modes enabled on Row config (%d) but are unsupported in streaming mode. Only Horizontal merge will be considered.", t.config.Row.Formatting.MergeMode) |
| 168 |
} |
| 169 |
if t.config.Footer.Formatting.MergeMode&(tw.MergeVertical|tw.MergeHierarchical) != 0 { |
| 170 |
t.logger.Warnf("Vertical or Hierarchical merge modes enabled on Footer config (%d) but are unsupported in streaming mode. Only Horizontal merge will be considered.", t.config.Footer.Formatting.MergeMode) |
| 171 |
} |
| 172 |
// AutoHide requires processing all row data to find empty columns. |
| 173 |
if t.config.Behavior.AutoHide.Enabled() { |
| 174 |
t.logger.Warn("AutoHide is enabled in config but is ignored in streaming mode.") |
| 175 |
} |
| 176 |
|
| 177 |
// Call the renderer's start method for the stream. |
| 178 |
err := t.renderer.Start(t.writer) |
| 179 |
if err == nil { |
| 180 |
t.hasPrinted = true // Mark as started successfully only if renderer.Start works |
| 181 |
t.logger.Debug("Renderer.Start() succeeded. Table stream initiated.") |
| 182 |
} else { |
| 183 |
// Reset state if renderer.Start fails |
| 184 |
t.hasPrinted = false |
| 185 |
t.headerRendered = false |
| 186 |
t.firstRowRendered = false |
| 187 |
t.lastRenderedLineContent = nil |
| 188 |
t.lastRenderedPosition = "" |
| 189 |
t.streamFooterLines = nil |
| 190 |
t.streamWidths = tw.NewMapper[int, int]() // Clear any widths that might have been set |
| 191 |
t.streamNumCols = 0 |
| 192 |
t.logger.Errorf("Renderer.Start() failed: %v. Streaming initialization failed.", err) |
| 193 |
} |
| 194 |
return err |
| 195 |
} |
| 196 |
|
| 197 |
// streamAppendRow processes and renders a single row in streaming mode. |
| 198 |
// It calculates/uses fixed stream widths, processes content, renders separators and lines, |
| 199 |
// and updates streaming state. |
| 200 |
// It assumes Start() has already been called and t.hasPrinted is true. |
| 201 |
func (t *Table) streamAppendRow(row interface{}) error { |
| 202 |
t.logger.Debugf("streamAppendRow called with row: %v (type: %T)", row, row) |
| 203 |
|
| 204 |
if !t.config.Stream.Enable { |
| 205 |
return errors.New("streaming mode is disabled") |
| 206 |
} |
| 207 |
|
| 208 |
rawCellsSlice, err := t.convertCellsToStrings(row, t.config.Row) |
| 209 |
if err != nil { |
| 210 |
t.logger.Errorf("streamAppendRow: Failed to convert row to strings: %v", err) |
| 211 |
return errors.Newf("failed to convert row to strings").Wrap(err) |
| 212 |
} |
| 213 |
|
| 214 |
if len(rawCellsSlice) == 0 { |
| 215 |
t.logger.Debug("streamAppendRow: No raw cells after conversion, skipping row rendering.") |
| 216 |
if !t.firstRowRendered { |
| 217 |
t.firstRowRendered = true |
| 218 |
t.logger.Debug("streamAppendRow: Marked first row rendered (empty content after processing).") |
| 219 |
} |
| 220 |
return nil |
| 221 |
} |
| 222 |
|
| 223 |
if err := t.ensureStreamWidthsCalculated(rawCellsSlice, t.config.Row); err != nil { |
| 224 |
return errors.New("failed to establish stream column count/widths").Wrap(err) |
| 225 |
} |
| 226 |
|
| 227 |
// Now, check for column mismatch if a column count has been established. |
| 228 |
if t.streamNumCols > 0 { |
| 229 |
if len(rawCellsSlice) != t.streamNumCols { |
| 230 |
if t.config.Stream.StrictColumns { |
| 231 |
err := errors.Newf("input row column count (%d) does not match established stream column count (%d) and StrictColumns is enabled", len(rawCellsSlice), t.streamNumCols) |
| 232 |
t.logger.Error(err.Error()) |
| 233 |
return err |
| 234 |
} |
| 235 |
// If not strict, retain the old lenient behavior (warn and pad/truncate) |
| 236 |
t.logger.Warnf("streamAppendRow: Input row column count (%d) != stream column count (%d). Padding/Truncating (StrictColumns is false).", len(rawCellsSlice), t.streamNumCols) |
| 237 |
if len(rawCellsSlice) < t.streamNumCols { |
| 238 |
paddedCells := make([]string, t.streamNumCols) |
| 239 |
copy(paddedCells, rawCellsSlice) |
| 240 |
for i := len(rawCellsSlice); i < t.streamNumCols; i++ { |
| 241 |
paddedCells[i] = tw.Empty |
| 242 |
} |
| 243 |
rawCellsSlice = paddedCells |
| 244 |
} else { |
| 245 |
rawCellsSlice = rawCellsSlice[:t.streamNumCols] |
| 246 |
} |
| 247 |
} |
| 248 |
} else if len(rawCellsSlice) > 0 && t.config.Stream.StrictColumns { |
| 249 |
err := errors.Newf("failed to establish stream column count from first data row (%d cells) and StrictColumns is enabled", len(rawCellsSlice)) |
| 250 |
t.logger.Error(err.Error()) |
| 251 |
return err |
| 252 |
} |
| 253 |
|
| 254 |
if t.streamNumCols == 0 { |
| 255 |
t.logger.Warn("streamAppendRow: streamNumCols is 0. Cannot render row.") |
| 256 |
return errors.New("cannot render row, column count is zero and could not be determined") |
| 257 |
} |
| 258 |
|
| 259 |
_, rowMerges, _ := t.prepareWithMerges([][]string{rawCellsSlice}, t.config.Row, tw.Row) |
| 260 |
processedRowLines := t.prepareContent(rawCellsSlice, t.config.Row) |
| 261 |
t.logger.Debugf("streamAppendRow: Processed row lines: %d lines", len(processedRowLines)) |
| 262 |
|
| 263 |
f := t.renderer |
| 264 |
cfg := t.renderer.Config() |
| 265 |
|
| 266 |
if !t.headerRendered && !t.firstRowRendered && t.lastRenderedPosition == "" { |
| 267 |
if cfg.Borders.Top.Enabled() && cfg.Settings.Lines.ShowTop.Enabled() { |
| 268 |
t.logger.Debug("streamAppendRow: Rendering table top border (first element is a row).") |
| 269 |
var nextCellsCtx map[int]tw.CellContext |
| 270 |
if len(processedRowLines) > 0 { |
| 271 |
firstRowLineResp := t.streamBuildCellContexts( |
| 272 |
tw.Row, 0, 0, processedRowLines, rowMerges, t.config.Row, |
| 273 |
) |
| 274 |
nextCellsCtx = firstRowLineResp.cells |
| 275 |
} |
| 276 |
f.Line(tw.Formatting{ |
| 277 |
Row: tw.RowContext{ |
| 278 |
Widths: t.streamWidths, |
| 279 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 280 |
Next: nextCellsCtx, |
| 281 |
Position: tw.Row, |
| 282 |
Location: tw.LocationFirst, |
| 283 |
}, |
| 284 |
Level: tw.LevelHeader, |
| 285 |
IsSubRow: false, |
| 286 |
|
| 287 |
NormalizedWidths: t.streamWidths, |
| 288 |
}) |
| 289 |
t.logger.Debug("streamAppendRow: Top border rendered.") |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
shouldDrawHeaderRowSeparator := t.headerRendered && !t.firstRowRendered && cfg.Settings.Lines.ShowHeaderLine.Enabled() |
| 294 |
shouldDrawRowRowSeparator := t.firstRowRendered && cfg.Settings.Separators.BetweenRows.Enabled() |
| 295 |
|
| 296 |
firstCellForLog := "" |
| 297 |
if len(rawCellsSlice) > 0 { |
| 298 |
firstCellForLog = rawCellsSlice[0] |
| 299 |
} |
| 300 |
t.logger.Debugf("streamAppendRow: Separator Pre-Check for row starting with '%s': headerRendered=%v, firstRowRendered=%v, ShowHeaderLine=%v, BetweenRows=%v, lastRenderedPos=%q", |
| 301 |
firstCellForLog, t.headerRendered, t.firstRowRendered, cfg.Settings.Lines.ShowHeaderLine.Enabled(), |
| 302 |
cfg.Settings.Separators.BetweenRows.Enabled(), t.lastRenderedPosition) |
| 303 |
t.logger.Debugf("streamAppendRow: Separator Decision Flags for row starting with '%s': shouldDrawHeaderRowSeparator=%v, shouldDrawRowRowSeparator=%v", |
| 304 |
firstCellForLog, shouldDrawHeaderRowSeparator, shouldDrawRowRowSeparator) |
| 305 |
|
| 306 |
if (shouldDrawHeaderRowSeparator || shouldDrawRowRowSeparator) && t.lastRenderedPosition != tw.Position("separator") { |
| 307 |
t.logger.Debugf("streamAppendRow: Rendering separator line for row starting with '%s'.", firstCellForLog) |
| 308 |
prevCellsCtx := t.streamRenderedMergeState(t.lastRenderedLineContent, t.lastRenderedMergeState) |
| 309 |
var nextCellsCtx map[int]tw.CellContext |
| 310 |
if len(processedRowLines) > 0 { |
| 311 |
firstRowLineResp := t.streamBuildCellContexts(tw.Row, 0, 0, processedRowLines, rowMerges, t.config.Row) |
| 312 |
nextCellsCtx = firstRowLineResp.cells |
| 313 |
} |
| 314 |
f.Line(tw.Formatting{ |
| 315 |
Row: tw.RowContext{ |
| 316 |
Widths: t.streamWidths, |
| 317 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 318 |
Current: prevCellsCtx, |
| 319 |
Previous: nil, |
| 320 |
Next: nextCellsCtx, |
| 321 |
Position: tw.Row, |
| 322 |
Location: tw.LocationMiddle, |
| 323 |
}, |
| 324 |
Level: tw.LevelBody, |
| 325 |
IsSubRow: false, |
| 326 |
|
| 327 |
NormalizedWidths: t.streamWidths, |
| 328 |
}) |
| 329 |
t.lastRenderedPosition = tw.Position("separator") |
| 330 |
t.lastRenderedLineContent = nil |
| 331 |
t.lastRenderedMergeState = nil |
| 332 |
t.logger.Debug("streamAppendRow: Separator line rendered. Updated lastRenderedPosition to 'separator'.") |
| 333 |
} else { |
| 334 |
details := "" |
| 335 |
if !shouldDrawHeaderRowSeparator && !shouldDrawRowRowSeparator { |
| 336 |
details = "neither header/row nor row/row separator was flagged true" |
| 337 |
} else if t.lastRenderedPosition == tw.Position("separator") { |
| 338 |
details = "lastRenderedPosition is already 'separator'" |
| 339 |
} else { |
| 340 |
details = "an unexpected combination of conditions" |
| 341 |
} |
| 342 |
t.logger.Debugf("streamAppendRow: Separator not drawn for row '%s' because %s.", firstCellForLog, details) |
| 343 |
} |
| 344 |
|
| 345 |
if len(processedRowLines) == 0 { |
| 346 |
t.logger.Debugf("streamAppendRow: No processed row lines to render for row starting with '%s'.", firstCellForLog) |
| 347 |
if !t.firstRowRendered { |
| 348 |
t.firstRowRendered = true |
| 349 |
t.logger.Debugf("streamAppendRow: Marked first row rendered (empty content after processing).") |
| 350 |
} |
| 351 |
return nil |
| 352 |
} |
| 353 |
|
| 354 |
totalRowLines := len(processedRowLines) |
| 355 |
for i := 0; i < totalRowLines; i++ { |
| 356 |
resp := t.streamBuildCellContexts(tw.Row, 0, i, processedRowLines, rowMerges, t.config.Row) |
| 357 |
t.logger.Debug("streamAppendRow: Rendering row line %d/%d with location %v for row starting with '%s'.", i, totalRowLines, resp.location, firstCellForLog) |
| 358 |
f.Row(resp.cellsContent, tw.Formatting{ |
| 359 |
Row: tw.RowContext{ |
| 360 |
Widths: t.streamWidths, |
| 361 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 362 |
Current: resp.cells, |
| 363 |
Previous: resp.prevCells, |
| 364 |
Next: resp.nextCells, |
| 365 |
Position: tw.Row, |
| 366 |
Location: resp.location, |
| 367 |
}, |
| 368 |
Level: tw.LevelBody, |
| 369 |
IsSubRow: i > 0, |
| 370 |
|
| 371 |
NormalizedWidths: t.streamWidths, |
| 372 |
HasFooter: len(t.streamFooterLines) > 0, |
| 373 |
}) |
| 374 |
t.lastRenderedLineContent = resp.cellsContent |
| 375 |
t.lastRenderedMergeState = make(map[int]tw.MergeState) |
| 376 |
for colIdx, cellCtx := range resp.cells { |
| 377 |
t.lastRenderedMergeState[colIdx] = cellCtx.Merge |
| 378 |
} |
| 379 |
t.lastRenderedPosition = tw.Row |
| 380 |
} |
| 381 |
|
| 382 |
if !t.firstRowRendered { |
| 383 |
t.firstRowRendered = true |
| 384 |
t.logger.Debug("streamAppendRow: Marked first row rendered (after processing content).") |
| 385 |
} |
| 386 |
|
| 387 |
t.logger.Debug("streamAppendRow: Row processing completed for row starting with '%s'.", firstCellForLog) |
| 388 |
return nil |
| 389 |
} |
| 390 |
|
| 391 |
// streamBuildCellContexts creates CellContext objects for a given line in streaming mode. |
| 392 |
// Parameters: |
| 393 |
// - position: The section being processed (Header, Row, Footer). |
| 394 |
// - rowIdx: The row index within its section (always 0 for Header/Footer, row number for Row). |
| 395 |
// - lineIdx: The line index within the processed lines for this block. |
| 396 |
// - processedLines: All multi-lines for the current row/header/footer block. |
| 397 |
// - sectionMerges: Merge states for the section or row (map[int]tw.MergeState). |
| 398 |
// - sectionConfig: The CellConfig for this section (Header, Row, Footer). |
| 399 |
// Returns a renderMergeResponse with Current, Previous, Next cells, cellsContent, and the determined Location. |
| 400 |
func (t *Table) streamBuildCellContexts( |
| 401 |
position tw.Position, |
| 402 |
rowIdx, lineIdx int, |
| 403 |
processedLines [][]string, |
| 404 |
sectionMerges map[int]tw.MergeState, |
| 405 |
sectionConfig tw.CellConfig, |
| 406 |
) renderMergeResponse { |
| 407 |
t.logger.Debug("streamBuildCellContexts: Building contexts for position=%s, rowIdx=%d, lineIdx=%d", position, rowIdx, lineIdx) |
| 408 |
resp := renderMergeResponse{ |
| 409 |
cells: make(map[int]tw.CellContext), |
| 410 |
prevCells: nil, |
| 411 |
nextCells: nil, |
| 412 |
cellsContent: make([]string, t.streamNumCols), |
| 413 |
location: tw.LocationMiddle, |
| 414 |
} |
| 415 |
|
| 416 |
if t.streamWidths == nil || t.streamWidths.Len() == 0 || t.streamNumCols == 0 { |
| 417 |
t.logger.Warn("streamBuildCellContexts: streamWidths is not set or streamNumCols is 0. Returning empty contexts.") |
| 418 |
return resp |
| 419 |
} |
| 420 |
|
| 421 |
currentLineContent := make([]string, t.streamNumCols) |
| 422 |
if lineIdx >= 0 && lineIdx < len(processedLines) { |
| 423 |
currentLineContent = padLine(processedLines[lineIdx], t.streamNumCols) |
| 424 |
} else { |
| 425 |
t.logger.Warnf("streamBuildCellContexts: lineIdx %d out of bounds for processedLines (len %d) at position %s, rowIdx %d. Using empty line.", lineIdx, len(processedLines), position, rowIdx) |
| 426 |
for j := range currentLineContent { |
| 427 |
currentLineContent[j] = tw.Empty |
| 428 |
} |
| 429 |
} |
| 430 |
resp.cellsContent = currentLineContent |
| 431 |
|
| 432 |
colAligns := t.buildAligns(sectionConfig) |
| 433 |
colPadding := t.buildPadding(sectionConfig.Padding) |
| 434 |
resp.cells = t.buildCoreCellContexts(currentLineContent, sectionMerges, t.streamWidths, colAligns, colPadding, t.streamNumCols) |
| 435 |
|
| 436 |
if t.lastRenderedLineContent != nil && t.lastRenderedPosition.Validate() == nil { |
| 437 |
resp.prevCells = t.streamRenderedMergeState(t.lastRenderedLineContent, t.lastRenderedMergeState) |
| 438 |
} |
| 439 |
|
| 440 |
totalLinesInBlock := len(processedLines) |
| 441 |
if lineIdx < totalLinesInBlock-1 { |
| 442 |
resp.nextCells = make(map[int]tw.CellContext) |
| 443 |
nextLineContent := padLine(processedLines[lineIdx+1], t.streamNumCols) |
| 444 |
nextCells := t.buildCoreCellContexts(nextLineContent, sectionMerges, t.streamWidths, colAligns, colPadding, t.streamNumCols) |
| 445 |
for j := 0; j < t.streamNumCols; j++ { |
| 446 |
resp.nextCells[j] = nextCells[j] |
| 447 |
} |
| 448 |
} |
| 449 |
|
| 450 |
isFirstLineOfBlock := (lineIdx == 0) |
| 451 |
if isFirstLineOfBlock && (t.lastRenderedLineContent == nil || t.lastRenderedPosition != position) { |
| 452 |
resp.location = tw.LocationFirst |
| 453 |
} |
| 454 |
|
| 455 |
t.logger.Debug("streamBuildCellContexts: Position %s, Row %d, Line %d/%d. Location: %v. Prev Pos: %v. Has Prev: %v.", |
| 456 |
position, rowIdx, lineIdx, totalLinesInBlock, resp.location, t.lastRenderedPosition, t.lastRenderedLineContent != nil) |
| 457 |
return resp |
| 458 |
} |
| 459 |
|
| 460 |
// streamCalculateWidths determines the fixed column widths for streaming mode. |
| 461 |
// It prioritizes widths from StreamConfig.Widths.PerColumn, then StreamConfig.Widths.Global, |
| 462 |
// then derives from the provided sample data lines. |
| 463 |
// It populates t.streamWidths and t.streamNumCols if they are currently empty. |
| 464 |
// The sampleDataLines should be the *raw* input lines (e.g., []string for Header/Footer, or the first row's []string cells for Row). |
| 465 |
// The paddingConfig should be the CellPadding config relevant to the sample data (Header/Row/Footer). |
| 466 |
// Returns the determined number of columns. |
| 467 |
// This function should only be called when t.streamWidths is currently empty. |
| 468 |
func (t *Table) streamCalculateWidths(sampling []string, config tw.CellConfig) int { |
| 469 |
if t.streamWidths != nil && t.streamWidths.Len() > 0 { |
| 470 |
t.logger.Debug("streamCalculateWidths: Called when streaming widths are already set (%d columns). Reusing existing.", t.streamNumCols) |
| 471 |
return t.streamNumCols |
| 472 |
} |
| 473 |
|
| 474 |
t.logger.Debug("streamCalculateWidths: Calculating streaming widths. Sample data cells: %d. Using section config: %+v", len(sampling), config.Formatting) |
| 475 |
|
| 476 |
determinedNumCols := 0 |
| 477 |
if t.config.Widths.PerColumn != nil && t.config.Widths.PerColumn.Len() > 0 { |
| 478 |
maxColIdx := -1 |
| 479 |
t.config.Widths.PerColumn.Each(func(col, width int) { |
| 480 |
if col > maxColIdx { |
| 481 |
maxColIdx = col |
| 482 |
} |
| 483 |
}) |
| 484 |
determinedNumCols = maxColIdx + 1 |
| 485 |
t.logger.Debug("streamCalculateWidths: Determined numCols (%d) from StreamConfig.Widths.PerColumn", determinedNumCols) |
| 486 |
} else if len(sampling) > 0 { |
| 487 |
determinedNumCols = len(sampling) |
| 488 |
t.logger.Debug("streamCalculateWidths: Determined numCols (%d) from sample data length", determinedNumCols) |
| 489 |
} else { |
| 490 |
t.logger.Debug("streamCalculateWidths: Cannot determine numCols (no PerColumn config, no sample data)") |
| 491 |
t.streamNumCols = 0 |
| 492 |
t.streamWidths = tw.NewMapper[int, int]() |
| 493 |
return 0 |
| 494 |
} |
| 495 |
|
| 496 |
t.streamNumCols = determinedNumCols |
| 497 |
t.streamWidths = tw.NewMapper[int, int]() |
| 498 |
|
| 499 |
// Use padding and autowrap from the provided config |
| 500 |
paddingForWidthCalc := config.Padding |
| 501 |
autoWrapForWidthCalc := config.Formatting.AutoWrap |
| 502 |
|
| 503 |
if t.config.Widths.PerColumn != nil && t.config.Widths.PerColumn.Len() > 0 { |
| 504 |
t.logger.Debug("streamCalculateWidths: Using widths from StreamConfig.Widths.PerColumn") |
| 505 |
for i := 0; i < t.streamNumCols; i++ { |
| 506 |
width, ok := t.config.Widths.PerColumn.OK(i) |
| 507 |
if !ok { |
| 508 |
width = 0 |
| 509 |
} |
| 510 |
if width > 0 && width < 1 { |
| 511 |
width = 1 |
| 512 |
} else if width < 0 { |
| 513 |
width = 0 |
| 514 |
} |
| 515 |
t.streamWidths.Set(i, width) |
| 516 |
} |
| 517 |
} else { |
| 518 |
// No PerColumn config, derive from sampling intelligently |
| 519 |
t.logger.Debug("streamCalculateWidths: Intelligently deriving widths from sample data content and padding.") |
| 520 |
tempRequiredWidths := tw.NewMapper[int, int]() // Widths from updateWidths (content + padding) |
| 521 |
if len(sampling) > 0 { |
| 522 |
// updateWidths calculates: DisplayWidth(content) + padLeft + padRight |
| 523 |
t.updateWidths(sampling, tempRequiredWidths, paddingForWidthCalc) |
| 524 |
} |
| 525 |
|
| 526 |
ellipsisWidthBuffer := 0 |
| 527 |
if autoWrapForWidthCalc == tw.WrapTruncate { |
| 528 |
ellipsisWidthBuffer = twwidth.Width(tw.CharEllipsis) |
| 529 |
} |
| 530 |
varianceBuffer := 2 // Your suggested variance |
| 531 |
minTotalColWidth := tw.MinimumColumnWidth |
| 532 |
// Example: if t.config.Stream.MinAutoColumnWidth > 0 { minTotalColWidth = t.config.Stream.MinAutoColumnWidth } |
| 533 |
|
| 534 |
for i := 0; i < t.streamNumCols; i++ { |
| 535 |
// baseCellWidth (content_width + padding_width) comes from tempRequiredWidths.Get(i) |
| 536 |
// We need to deconstruct it to apply logic to content_width first. |
| 537 |
|
| 538 |
sampleContent := "" |
| 539 |
if i < len(sampling) { |
| 540 |
sampleContent = t.Trimmer(sampling[i]) |
| 541 |
} |
| 542 |
sampleContentDisplayWidth := twwidth.Width(sampleContent) |
| 543 |
|
| 544 |
colPad := paddingForWidthCalc.Global |
| 545 |
if i < len(paddingForWidthCalc.PerColumn) && paddingForWidthCalc.PerColumn[i].Paddable() { |
| 546 |
colPad = paddingForWidthCalc.PerColumn[i] |
| 547 |
} |
| 548 |
currentPadLWidth := twwidth.Width(colPad.Left) |
| 549 |
currentPadRWidth := twwidth.Width(colPad.Right) |
| 550 |
currentTotalPaddingWidth := currentPadLWidth + currentPadRWidth |
| 551 |
|
| 552 |
// Start with the target content width logic |
| 553 |
targetContentWidth := sampleContentDisplayWidth |
| 554 |
if autoWrapForWidthCalc == tw.WrapTruncate { |
| 555 |
// If content is short, ensure it's at least wide enough for an ellipsis |
| 556 |
if targetContentWidth < ellipsisWidthBuffer { |
| 557 |
targetContentWidth = ellipsisWidthBuffer |
| 558 |
} |
| 559 |
} |
| 560 |
targetContentWidth += varianceBuffer // Add variance |
| 561 |
|
| 562 |
// Now calculate the total cell width based on this buffered content target + padding |
| 563 |
calculatedWidth := targetContentWidth + currentTotalPaddingWidth |
| 564 |
|
| 565 |
// Apply an absolute minimum total column width |
| 566 |
if calculatedWidth > 0 && calculatedWidth < minTotalColWidth { |
| 567 |
t.logger.Debug("streamCalculateWidths: Col %d, InitialCalcW=%d (ContentTarget=%d + Pad=%d) is less than MinTotalW=%d. Adjusting to MinTotalW.", |
| 568 |
i, calculatedWidth, targetContentWidth, currentTotalPaddingWidth, minTotalColWidth) |
| 569 |
calculatedWidth = minTotalColWidth |
| 570 |
} else if calculatedWidth <= 0 && sampleContentDisplayWidth > 0 { // If content exists but calc width is 0 (e.g. large negative variance) |
| 571 |
// Ensure at least min width or content + padding + buffers |
| 572 |
fallbackWidth := sampleContentDisplayWidth + currentTotalPaddingWidth |
| 573 |
if autoWrapForWidthCalc == tw.WrapTruncate { |
| 574 |
fallbackWidth += ellipsisWidthBuffer |
| 575 |
} |
| 576 |
fallbackWidth += varianceBuffer |
| 577 |
calculatedWidth = tw.Max(minTotalColWidth, fallbackWidth) |
| 578 |
if calculatedWidth <= 0 && (currentTotalPaddingWidth+1) > 0 { // last resort if all else is zero |
| 579 |
calculatedWidth = currentTotalPaddingWidth + 1 |
| 580 |
} else if calculatedWidth <= 0 { |
| 581 |
calculatedWidth = 1 // absolute last resort |
| 582 |
} |
| 583 |
|
| 584 |
t.logger.Debug("streamCalculateWidths: Col %d, CalculatedW was <=0 despite content. Adjusted to %d.", i, calculatedWidth) |
| 585 |
} else if calculatedWidth <= 0 && sampleContentDisplayWidth == 0 { |
| 586 |
// Column is truly empty in sample and buffers didn't make it positive, or minTotalColWidth is 0. |
| 587 |
// Keep width 0 (it will be hidden by renderer if all content is empty for this col) |
| 588 |
// Or, if we want empty columns to have a minimum presence (even if just padding): |
| 589 |
// calculatedWidth = currentTotalPaddingWidth // This would make it just wide enough for padding |
| 590 |
// For now, let truly empty sample + no min width result in 0. |
| 591 |
calculatedWidth = 0 // Explicitly set to 0 if it ended up non-positive and no content |
| 592 |
} |
| 593 |
|
| 594 |
t.streamWidths.Set(i, calculatedWidth) |
| 595 |
t.logger.Debug("streamCalculateWidths: Col %d, SampleContentW=%d, PadW=%d, EllipsisBufIfTruncate=%d, VarianceBuf=%d -> FinalTotalColW=%d", |
| 596 |
i, sampleContentDisplayWidth, currentTotalPaddingWidth, ellipsisWidthBuffer, varianceBuffer, calculatedWidth) |
| 597 |
} |
| 598 |
} |
| 599 |
|
| 600 |
// Apply Global Constraint (if t.config.Stream.Widths.Global > 0) |
| 601 |
if t.config.Widths.Global > 0 && t.streamNumCols > 0 { |
| 602 |
t.logger.Debug("streamCalculateWidths: Applying global stream width constraint %d", t.config.Widths.Global) |
| 603 |
currentTotalColumnWidthsSum := 0 |
| 604 |
t.streamWidths.Each(func(_, w int) { |
| 605 |
currentTotalColumnWidthsSum += w |
| 606 |
}) |
| 607 |
|
| 608 |
separatorWidth := 0 |
| 609 |
if t.renderer != nil { |
| 610 |
rendererConfig := t.renderer.Config() |
| 611 |
if rendererConfig.Settings.Separators.BetweenColumns.Enabled() { |
| 612 |
separatorWidth = twwidth.Width(rendererConfig.Symbols.Column()) |
| 613 |
} |
| 614 |
} else { |
| 615 |
separatorWidth = 1 // Default if renderer not available yet |
| 616 |
} |
| 617 |
|
| 618 |
totalWidthIncludingSeparators := currentTotalColumnWidthsSum |
| 619 |
if t.streamNumCols > 1 { |
| 620 |
totalWidthIncludingSeparators += (t.streamNumCols - 1) * separatorWidth |
| 621 |
} |
| 622 |
|
| 623 |
if t.config.Widths.Global < totalWidthIncludingSeparators && totalWidthIncludingSeparators > 0 { // Added check for total > 0 |
| 624 |
t.logger.Debug("streamCalculateWidths: Total calculated width (%d incl separators) exceeds global stream width (%d). Shrinking.", totalWidthIncludingSeparators, t.config.Widths.Global) |
| 625 |
|
| 626 |
// Target sum for column widths only (global limit - total separator width) |
| 627 |
targetSumForColumnWidths := t.config.Widths.Global |
| 628 |
if t.streamNumCols > 1 { |
| 629 |
targetSumForColumnWidths -= (t.streamNumCols - 1) * separatorWidth |
| 630 |
} |
| 631 |
if targetSumForColumnWidths < t.streamNumCols && t.streamNumCols > 0 { // Ensure at least 1 per column if possible |
| 632 |
targetSumForColumnWidths = t.streamNumCols |
| 633 |
} else if targetSumForColumnWidths < 0 { |
| 634 |
targetSumForColumnWidths = 0 |
| 635 |
} |
| 636 |
|
| 637 |
scaleFactor := float64(targetSumForColumnWidths) / float64(currentTotalColumnWidthsSum) |
| 638 |
if currentTotalColumnWidthsSum <= 0 { |
| 639 |
scaleFactor = 0 |
| 640 |
} // Avoid division by zero or negative scale |
| 641 |
|
| 642 |
adjustedSum := 0 |
| 643 |
for i := 0; i < t.streamNumCols; i++ { |
| 644 |
originalColWidth := t.streamWidths.Get(i) |
| 645 |
if originalColWidth == 0 { |
| 646 |
continue |
| 647 |
} // Don't scale hidden columns |
| 648 |
|
| 649 |
scaledWidth := 0 |
| 650 |
if scaleFactor > 0 { |
| 651 |
scaledWidth = int(math.Round(float64(originalColWidth) * scaleFactor)) |
| 652 |
} |
| 653 |
|
| 654 |
if scaledWidth < 1 && originalColWidth > 0 { // Ensure at least 1 if original had width and scaling made it too small |
| 655 |
scaledWidth = 1 |
| 656 |
} else if scaledWidth < 0 { // Should not happen with math.Round on positive*positive |
| 657 |
scaledWidth = 0 |
| 658 |
} |
| 659 |
t.streamWidths.Set(i, scaledWidth) |
| 660 |
adjustedSum += scaledWidth |
| 661 |
} |
| 662 |
|
| 663 |
// Distribute rounding errors to meet targetSumForColumnWidths |
| 664 |
remainingSpace := targetSumForColumnWidths - adjustedSum |
| 665 |
t.logger.Debug("streamCalculateWidths: Scaling complete. TargetSum=%d, AchievedSum=%d, RemSpace=%d", targetSumForColumnWidths, adjustedSum, remainingSpace) |
| 666 |
// Distribute remainingSpace (positive or negative) among non-zero width columns |
| 667 |
if remainingSpace != 0 && t.streamNumCols > 0 { |
| 668 |
colsToAdjust := []int{} |
| 669 |
t.streamWidths.Each(func(col, w int) { |
| 670 |
if w > 0 { // Only consider columns that currently have width |
| 671 |
colsToAdjust = append(colsToAdjust, col) |
| 672 |
} |
| 673 |
}) |
| 674 |
if len(colsToAdjust) > 0 { |
| 675 |
for i := 0; i < int(math.Abs(float64(remainingSpace))); i++ { |
| 676 |
if remainingSpace > 0 { |
| 677 |
colIdx := colsToAdjust[i%len(colsToAdjust)] |
| 678 |
currentColWidth := t.streamWidths.Get(colIdx) |
| 679 |
t.streamWidths.Set(colIdx, currentColWidth+1) |
| 680 |
} else { |
| 681 |
// Find next column that can be reduced (skip columns already at minimum width) |
| 682 |
reduced := false |
| 683 |
for j := 0; j < len(colsToAdjust); j++ { |
| 684 |
colIdx := colsToAdjust[(i+j)%len(colsToAdjust)] |
| 685 |
if t.streamWidths.Get(colIdx) > 1 { |
| 686 |
t.streamWidths.Set(colIdx, t.streamWidths.Get(colIdx)-1) |
| 687 |
reduced = true |
| 688 |
break |
| 689 |
} |
| 690 |
} |
| 691 |
if !reduced { |
| 692 |
break // All columns at minimum width, no further reduction possible |
| 693 |
} |
| 694 |
} |
| 695 |
} |
| 696 |
} |
| 697 |
} |
| 698 |
t.logger.Debug("streamCalculateWidths: Widths after scaling and distribution: %v", t.streamWidths) |
| 699 |
} else { |
| 700 |
t.logger.Debug("streamCalculateWidths: Total calculated width (%d) fits global stream width (%d). No scaling needed.", totalWidthIncludingSeparators, t.config.Widths.Global) |
| 701 |
} |
| 702 |
} |
| 703 |
|
| 704 |
// Final sanitization |
| 705 |
t.streamWidths.Each(func(col, width int) { |
| 706 |
if width < 0 { |
| 707 |
t.streamWidths.Set(col, 0) |
| 708 |
} |
| 709 |
}) |
| 710 |
|
| 711 |
t.logger.Debug("streamCalculateWidths: Final derived stream widths after all adjustments (%d columns): %v", t.streamNumCols, t.streamWidths) |
| 712 |
return t.streamNumCols |
| 713 |
} |
| 714 |
|
| 715 |
// streamRenderBottomBorder renders the bottom border of the table in streaming mode. |
| 716 |
// It uses the fixed streamWidths and the last rendered content to create the border context. |
| 717 |
// It assumes Start() has been called and t.hasPrinted is true. |
| 718 |
// Returns an error if rendering fails. |
| 719 |
func (t *Table) streamRenderBottomBorder() error { |
| 720 |
if t.streamWidths == nil || t.streamWidths.Len() == 0 { |
| 721 |
t.logger.Debug("streamRenderBottomBorder: No stream widths available, skipping bottom border.") |
| 722 |
return nil |
| 723 |
} |
| 724 |
|
| 725 |
cfg := t.renderer.Config() |
| 726 |
if !cfg.Borders.Bottom.Enabled() || !cfg.Settings.Lines.ShowBottom.Enabled() { |
| 727 |
t.logger.Debug("streamRenderBottomBorder: Bottom border disabled in config, skipping.") |
| 728 |
return nil |
| 729 |
} |
| 730 |
|
| 731 |
// The bottom border's "Current" context is the last rendered content line |
| 732 |
currentCells := make(map[int]tw.CellContext) |
| 733 |
if t.lastRenderedLineContent != nil { |
| 734 |
// Use a helper to convert last rendered state to cell contexts |
| 735 |
currentCells = t.streamRenderedMergeState(t.lastRenderedLineContent, t.lastRenderedMergeState) |
| 736 |
} else { |
| 737 |
// No content was ever rendered, but we might still want a bottom border if a top border was drawn. |
| 738 |
// Create empty cell contexts. |
| 739 |
for i := 0; i < t.streamNumCols; i++ { |
| 740 |
currentCells[i] = tw.CellContext{Width: t.streamWidths.Get(i)} |
| 741 |
} |
| 742 |
t.logger.Debug("streamRenderBottomBorder: No previous content line, creating empty context for bottom border.") |
| 743 |
} |
| 744 |
|
| 745 |
f := t.renderer |
| 746 |
f.Line(tw.Formatting{ |
| 747 |
Row: tw.RowContext{ |
| 748 |
Widths: t.streamWidths, |
| 749 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 750 |
Current: currentCells, // Context of the line *above* the bottom border |
| 751 |
Previous: nil, // No line before this, relative to the border itself (or use lastRendered's previous?) |
| 752 |
Next: nil, // No line after the bottom border |
| 753 |
Position: t.lastRenderedPosition, // Position of the content above the border (Row or Footer) |
| 754 |
Location: tw.LocationEnd, // This is the absolute end |
| 755 |
}, |
| 756 |
Level: tw.LevelFooter, // Bottom border is LevelFooter |
| 757 |
IsSubRow: false, |
| 758 |
|
| 759 |
NormalizedWidths: t.streamWidths, |
| 760 |
}) |
| 761 |
t.logger.Debug("streamRenderBottomBorder: Bottom border rendered.") |
| 762 |
return nil |
| 763 |
} |
| 764 |
|
| 765 |
// streamRenderFooter renders the stored footer lines in streaming mode. |
| 766 |
// It's called by Close(). It renders the Row/Footer separator line first. |
| 767 |
// It assumes Start() has been called and t.hasPrinted is true. |
| 768 |
// Returns an error if rendering fails. |
| 769 |
func (t *Table) streamRenderFooter(processedFooterLines [][]string) error { |
| 770 |
t.logger.Debug("streamRenderFooter: Rendering %d processed footer lines.", len(processedFooterLines)) |
| 771 |
|
| 772 |
if t.streamWidths == nil || t.streamWidths.Len() == 0 || t.streamNumCols == 0 { |
| 773 |
t.logger.Warn("streamRenderFooter: No stream widths or columns defined. Cannot render footer.") |
| 774 |
return errors.New("cannot render stream footer without defined column widths") |
| 775 |
} |
| 776 |
|
| 777 |
if len(processedFooterLines) == 0 { |
| 778 |
t.logger.Debug("streamRenderFooter: No footer lines to render.") |
| 779 |
return nil |
| 780 |
} |
| 781 |
|
| 782 |
f := t.renderer |
| 783 |
cfg := t.renderer.Config() |
| 784 |
|
| 785 |
// Render Row/Footer or Header/Footer Separator Line |
| 786 |
// This separator is drawn if ShowFooterLine is enabled AND there was content before the footer. |
| 787 |
// The last rendered position (t.lastRenderedPosition) should be Row or Header or "separator". |
| 788 |
if (t.lastRenderedPosition == tw.Row || t.lastRenderedPosition == tw.Header || t.lastRenderedPosition == tw.Position("separator")) && |
| 789 |
cfg.Settings.Lines.ShowFooterLine.Enabled() { |
| 790 |
|
| 791 |
t.logger.Debug("streamRenderFooter: Rendering Row/Footer or Header/Footer separator line.") |
| 792 |
|
| 793 |
// Previous context is the last line rendered before this footer |
| 794 |
prevCells := t.streamRenderedMergeState(t.lastRenderedLineContent, t.lastRenderedMergeState) |
| 795 |
|
| 796 |
// Next context is the first line of this footer |
| 797 |
var nextCells map[int]tw.CellContext = nil |
| 798 |
if len(processedFooterLines) > 0 { |
| 799 |
// Need merge states for the footer section. |
| 800 |
// Since footer is processed once and stored, detect merges on its raw input once. |
| 801 |
// This requires access to the *original* raw footer strings passed to Footer(). |
| 802 |
// For simplicity now, assume no complex horizontal merges in footer for this separator line context. |
| 803 |
// A better approach: streamStoreFooter should also calculate and store footerMerges. |
| 804 |
// For now, create nextCells without specific merge info for the separator line. |
| 805 |
// Or, call prepareWithMerges on the *stored processed* lines, which might be okay for simple cases. |
| 806 |
// Let's pass nil for sectionMerges to streamBuildCellContexts for this specific Next context. |
| 807 |
// It will result in default (no-merge) states. |
| 808 |
|
| 809 |
// For now, let's build nextCells manually for the separator line context |
| 810 |
nextCells = make(map[int]tw.CellContext) |
| 811 |
firstFooterLineContent := padLine(processedFooterLines[0], t.streamNumCols) |
| 812 |
// Footer merges should be calculated in streamStoreFooter and stored if needed. |
| 813 |
// For now, assume no merges for this 'Next' context. |
| 814 |
for j := 0; j < t.streamNumCols; j++ { |
| 815 |
nextCells[j] = tw.CellContext{Data: firstFooterLineContent[j], Width: t.streamWidths.Get(j)} |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
separatorLevel := tw.LevelFooter // Line before footer section is LevelFooter |
| 820 |
separatorPosition := tw.Footer // Positioned relative to the footer it precedes |
| 821 |
separatorLocation := tw.LocationMiddle |
| 822 |
|
| 823 |
f.Line(tw.Formatting{ |
| 824 |
Row: tw.RowContext{ |
| 825 |
Widths: t.streamWidths, |
| 826 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 827 |
Current: prevCells, // Context of line above separator |
| 828 |
Previous: nil, // No line before Current in this specific context |
| 829 |
Next: nextCells, // Context of line below separator (first footer line) |
| 830 |
Position: separatorPosition, |
| 831 |
Location: separatorLocation, |
| 832 |
}, |
| 833 |
Level: separatorLevel, |
| 834 |
IsSubRow: false, |
| 835 |
|
| 836 |
NormalizedWidths: t.streamWidths, |
| 837 |
}) |
| 838 |
t.lastRenderedPosition = tw.Position("separator") // Update state |
| 839 |
t.lastRenderedLineContent = nil |
| 840 |
t.lastRenderedMergeState = nil |
| 841 |
t.logger.Debug("streamRenderFooter: Footer separator line rendered.") |
| 842 |
} |
| 843 |
// End Render Separator Line |
| 844 |
|
| 845 |
// Detect horizontal merges for the footer section based on its (assumed stored) raw input. |
| 846 |
// This is tricky because streamStoreFooter gets []string, but prepareWithMerges expects [][]string. |
| 847 |
// For simplicity, if complex merges are needed in footer, streamStoreFooter should |
| 848 |
// have received raw data, called prepareWithMerges, and stored those merges. |
| 849 |
// For now, assume no complex horizontal merges in footer or pass nil for sectionMerges. |
| 850 |
// Let's assume footerMerges were calculated and stored as `t.streamFooterMerges map[int]tw.MergeState` |
| 851 |
// by `streamStoreFooter`. For this example, we'll pass nil, meaning no merges. |
| 852 |
var footerMerges map[int]tw.MergeState = nil // Placeholder |
| 853 |
|
| 854 |
totalFooterLines := len(processedFooterLines) |
| 855 |
for i := 0; i < totalFooterLines; i++ { |
| 856 |
resp := t.streamBuildCellContexts( |
| 857 |
tw.Footer, |
| 858 |
0, // Row index within Footer (always 0) |
| 859 |
i, // Line index |
| 860 |
processedFooterLines, |
| 861 |
footerMerges, // Pass footer-specific merges if calculated and stored |
| 862 |
t.config.Footer, |
| 863 |
) |
| 864 |
|
| 865 |
// Special Location logic for the *very last line* of the table if this footer line is it. |
| 866 |
// This is complex because bottom border might follow. |
| 867 |
// Let streamBuildCellContexts handle LocationFirst/Middle for now. |
| 868 |
// streamRenderBottomBorder will handle the final LocationEnd for its line. |
| 869 |
// If this footer line is the last content and no bottom border, *it* should be LocationEnd. |
| 870 |
|
| 871 |
// If this is the last line of the last content block (footer), and no bottom border will be drawn, |
| 872 |
// its Location should be End. |
| 873 |
isLastLineOfTableContent := (i == totalFooterLines-1) && |
| 874 |
(!cfg.Borders.Bottom.Enabled() || !cfg.Settings.Lines.ShowBottom.Enabled()) |
| 875 |
if isLastLineOfTableContent { |
| 876 |
resp.location = tw.LocationEnd |
| 877 |
t.logger.Debug("streamRenderFooter: Setting LocationEnd for last footer line as no bottom border will follow.") |
| 878 |
} |
| 879 |
|
| 880 |
f.Footer([][]string{resp.cellsContent}, tw.Formatting{ |
| 881 |
Row: tw.RowContext{ |
| 882 |
Widths: t.streamWidths, |
| 883 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 884 |
Current: resp.cells, |
| 885 |
Previous: resp.prevCells, |
| 886 |
Next: resp.nextCells, // Next is nil if last line of footer block |
| 887 |
Position: tw.Footer, |
| 888 |
Location: resp.location, |
| 889 |
}, |
| 890 |
Level: tw.LevelFooter, |
| 891 |
IsSubRow: (i > 0), |
| 892 |
|
| 893 |
NormalizedWidths: t.streamWidths, |
| 894 |
}) |
| 895 |
|
| 896 |
t.lastRenderedLineContent = resp.cellsContent |
| 897 |
t.lastRenderedMergeState = make(map[int]tw.MergeState) |
| 898 |
for colIdx, cellCtx := range resp.cells { |
| 899 |
t.lastRenderedMergeState[colIdx] = cellCtx.Merge |
| 900 |
} |
| 901 |
t.lastRenderedPosition = tw.Footer |
| 902 |
} |
| 903 |
|
| 904 |
t.logger.Debug("streamRenderFooter: Footer content rendering completed.") |
| 905 |
return nil |
| 906 |
} |
| 907 |
|
| 908 |
// streamRenderHeader processes and renders the header section in streaming mode. |
| 909 |
// It calculates/uses fixed stream widths, processes content, renders borders/lines, |
| 910 |
// and updates streaming state. |
| 911 |
// It assumes Start() has already been called and t.hasPrinted is true. |
| 912 |
func (t *Table) streamRenderHeader(headers []string) error { |
| 913 |
t.logger.Debug("streamRenderHeader called with headers: %v", headers) |
| 914 |
|
| 915 |
if !t.config.Stream.Enable { |
| 916 |
return errors.New("streaming mode is disabled") |
| 917 |
} |
| 918 |
|
| 919 |
if t.headerRendered { |
| 920 |
t.logger.Warn("streamRenderHeader called but header already rendered. Ignoring.") |
| 921 |
return nil |
| 922 |
} |
| 923 |
|
| 924 |
if err := t.ensureStreamWidthsCalculated(headers, t.config.Header); err != nil { |
| 925 |
return err |
| 926 |
} |
| 927 |
|
| 928 |
_, headerMerges, _ := t.prepareWithMerges([][]string{headers}, t.config.Header, tw.Header) |
| 929 |
processedHeaderLines := t.prepareContent(headers, t.config.Header) |
| 930 |
t.logger.Debug("streamRenderHeader: Processed header lines: %d", len(processedHeaderLines)) |
| 931 |
|
| 932 |
if t.streamNumCols > 0 { |
| 933 |
t.headerRendered = true |
| 934 |
} |
| 935 |
if len(processedHeaderLines) == 0 && t.streamNumCols == 0 { |
| 936 |
t.logger.Debug("streamRenderHeader: No header content and no columns determined.") |
| 937 |
return nil |
| 938 |
} |
| 939 |
|
| 940 |
f := t.renderer |
| 941 |
cfg := t.renderer.Config() |
| 942 |
|
| 943 |
if t.lastRenderedPosition == "" && cfg.Borders.Top.Enabled() && cfg.Settings.Lines.ShowTop.Enabled() { |
| 944 |
t.logger.Debug("streamRenderHeader: Rendering table top border.") |
| 945 |
var nextCellsCtx map[int]tw.CellContext |
| 946 |
if len(processedHeaderLines) > 0 { |
| 947 |
firstHeaderLineResp := t.streamBuildCellContexts( |
| 948 |
tw.Header, 0, 0, processedHeaderLines, headerMerges, t.config.Header, |
| 949 |
) |
| 950 |
nextCellsCtx = firstHeaderLineResp.cells |
| 951 |
} |
| 952 |
f.Line(tw.Formatting{ |
| 953 |
Row: tw.RowContext{ |
| 954 |
Widths: t.streamWidths, |
| 955 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 956 |
Next: nextCellsCtx, |
| 957 |
Position: tw.Header, |
| 958 |
Location: tw.LocationFirst, |
| 959 |
}, |
| 960 |
Level: tw.LevelHeader, |
| 961 |
IsSubRow: false, |
| 962 |
|
| 963 |
NormalizedWidths: t.streamWidths, |
| 964 |
}) |
| 965 |
t.logger.Debug("streamRenderHeader: Top border rendered.") |
| 966 |
} |
| 967 |
|
| 968 |
hasTopPadding := t.config.Header.Padding.Global.Top != tw.Empty |
| 969 |
if hasTopPadding { |
| 970 |
resp := t.streamBuildCellContexts(tw.Header, 0, -1, nil, headerMerges, t.config.Header) |
| 971 |
resp.cellsContent = t.buildPaddingLineContents(t.config.Header.Padding.Global.Top, t.streamWidths, t.streamNumCols, headerMerges) |
| 972 |
resp.location = tw.LocationFirst |
| 973 |
t.logger.Debug("streamRenderHeader: Rendering header top padding line: %v (loc: %v)", resp.cellsContent, resp.location) |
| 974 |
f.Header([][]string{resp.cellsContent}, tw.Formatting{ |
| 975 |
Row: tw.RowContext{ |
| 976 |
Widths: t.streamWidths, |
| 977 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 978 |
Current: resp.cells, |
| 979 |
Previous: resp.prevCells, |
| 980 |
Next: resp.nextCells, |
| 981 |
Position: tw.Header, |
| 982 |
Location: resp.location, |
| 983 |
}, |
| 984 |
Level: tw.LevelHeader, |
| 985 |
IsSubRow: true, |
| 986 |
|
| 987 |
NormalizedWidths: t.streamWidths, |
| 988 |
}) |
| 989 |
t.lastRenderedLineContent = resp.cellsContent |
| 990 |
t.lastRenderedMergeState = make(map[int]tw.MergeState) |
| 991 |
for colIdx, cellCtx := range resp.cells { |
| 992 |
t.lastRenderedMergeState[colIdx] = cellCtx.Merge |
| 993 |
} |
| 994 |
t.lastRenderedPosition = tw.Header |
| 995 |
} |
| 996 |
|
| 997 |
totalHeaderLines := len(processedHeaderLines) |
| 998 |
for i := 0; i < totalHeaderLines; i++ { |
| 999 |
resp := t.streamBuildCellContexts(tw.Header, 0, i, processedHeaderLines, headerMerges, t.config.Header) |
| 1000 |
t.logger.Debug("streamRenderHeader: Rendering header content line %d/%d with location %v", i, totalHeaderLines, resp.location) |
| 1001 |
f.Header([][]string{resp.cellsContent}, tw.Formatting{ |
| 1002 |
Row: tw.RowContext{ |
| 1003 |
Widths: t.streamWidths, |
| 1004 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 1005 |
Current: resp.cells, |
| 1006 |
Previous: resp.prevCells, |
| 1007 |
Next: resp.nextCells, |
| 1008 |
Position: tw.Header, |
| 1009 |
Location: resp.location, |
| 1010 |
}, |
| 1011 |
Level: tw.LevelHeader, |
| 1012 |
IsSubRow: i > 0, |
| 1013 |
|
| 1014 |
NormalizedWidths: t.streamWidths, |
| 1015 |
}) |
| 1016 |
t.lastRenderedLineContent = resp.cellsContent |
| 1017 |
t.lastRenderedMergeState = make(map[int]tw.MergeState) |
| 1018 |
for colIdx, cellCtx := range resp.cells { |
| 1019 |
t.lastRenderedMergeState[colIdx] = cellCtx.Merge |
| 1020 |
} |
| 1021 |
t.lastRenderedPosition = tw.Header |
| 1022 |
} |
| 1023 |
|
| 1024 |
hasBottomPadding := t.config.Header.Padding.Global.Bottom != tw.Empty |
| 1025 |
if hasBottomPadding { |
| 1026 |
resp := t.streamBuildCellContexts(tw.Header, 0, totalHeaderLines, nil, headerMerges, t.config.Header) |
| 1027 |
resp.cellsContent = t.buildPaddingLineContents(t.config.Header.Padding.Global.Bottom, t.streamWidths, t.streamNumCols, headerMerges) |
| 1028 |
resp.location = tw.LocationEnd |
| 1029 |
t.logger.Debug("streamRenderHeader: Rendering header bottom padding line: %v (loc: %v)", resp.cellsContent, resp.location) |
| 1030 |
f.Header([][]string{resp.cellsContent}, tw.Formatting{ |
| 1031 |
Row: tw.RowContext{ |
| 1032 |
Widths: t.streamWidths, |
| 1033 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 1034 |
Current: resp.cells, |
| 1035 |
Previous: resp.prevCells, |
| 1036 |
Next: resp.nextCells, |
| 1037 |
Position: tw.Header, |
| 1038 |
Location: resp.location, |
| 1039 |
}, |
| 1040 |
Level: tw.LevelHeader, |
| 1041 |
IsSubRow: true, |
| 1042 |
|
| 1043 |
NormalizedWidths: t.streamWidths, |
| 1044 |
}) |
| 1045 |
t.lastRenderedLineContent = resp.cellsContent |
| 1046 |
t.lastRenderedMergeState = make(map[int]tw.MergeState) |
| 1047 |
for colIdx, cellCtx := range resp.cells { |
| 1048 |
t.lastRenderedMergeState[colIdx] = cellCtx.Merge |
| 1049 |
} |
| 1050 |
t.lastRenderedPosition = tw.Header |
| 1051 |
} |
| 1052 |
|
| 1053 |
if cfg.Settings.Lines.ShowHeaderLine.Enabled() && (t.firstRowRendered || len(t.streamFooterLines) > 0) { |
| 1054 |
t.logger.Debug("streamRenderHeader: Rendering header separator line.") |
| 1055 |
resp := t.streamBuildCellContexts(tw.Header, 0, totalHeaderLines-1, processedHeaderLines, headerMerges, t.config.Header) |
| 1056 |
f.Line(tw.Formatting{ |
| 1057 |
Row: tw.RowContext{ |
| 1058 |
Widths: t.streamWidths, |
| 1059 |
ColMaxWidths: tw.CellWidth{PerColumn: t.streamWidths}, |
| 1060 |
Current: resp.cells, |
| 1061 |
Previous: resp.prevCells, |
| 1062 |
Next: nil, |
| 1063 |
Position: tw.Header, |
| 1064 |
Location: tw.LocationMiddle, |
| 1065 |
}, |
| 1066 |
Level: tw.LevelBody, |
| 1067 |
IsSubRow: false, |
| 1068 |
|
| 1069 |
NormalizedWidths: t.streamWidths, |
| 1070 |
}) |
| 1071 |
t.lastRenderedPosition = tw.Position("separator") |
| 1072 |
t.lastRenderedLineContent = nil |
| 1073 |
t.lastRenderedMergeState = nil |
| 1074 |
} |
| 1075 |
|
| 1076 |
t.logger.Debug("streamRenderHeader: Header content rendering completed.") |
| 1077 |
return nil |
| 1078 |
} |
| 1079 |
|
| 1080 |
// streamRenderedMergeState converts the stored last rendered line content |
| 1081 |
// and its merge states into a map of CellContext, suitable for providing |
| 1082 |
// context (e.g., "Current" or "Previous") to the renderer. |
| 1083 |
// It uses the fixed streamWidths. |
| 1084 |
func (t *Table) streamRenderedMergeState( |
| 1085 |
lineContent []string, |
| 1086 |
lineMergeStates map[int]tw.MergeState, |
| 1087 |
) map[int]tw.CellContext { |
| 1088 |
cells := make(map[int]tw.CellContext) |
| 1089 |
if t.streamWidths == nil || t.streamWidths.Len() == 0 || t.streamNumCols == 0 { |
| 1090 |
t.logger.Warn("streamRenderedMergeState: streamWidths not set or streamNumCols is 0. Returning empty cell contexts.") |
| 1091 |
return cells |
| 1092 |
} |
| 1093 |
|
| 1094 |
// Ensure lineContent is padded to streamNumCols if it's not nil |
| 1095 |
var paddedLineContent []string |
| 1096 |
if lineContent != nil { |
| 1097 |
paddedLineContent = padLine(lineContent, t.streamNumCols) |
| 1098 |
} else { |
| 1099 |
// If lineContent is nil (e.g. after a separator), create an empty padded line |
| 1100 |
paddedLineContent = make([]string, t.streamNumCols) |
| 1101 |
for i := range paddedLineContent { |
| 1102 |
paddedLineContent[i] = tw.Empty |
| 1103 |
} |
| 1104 |
} |
| 1105 |
|
| 1106 |
for j := 0; j < t.streamNumCols; j++ { |
| 1107 |
cellData := paddedLineContent[j] |
| 1108 |
colWidth := t.streamWidths.Get(j) |
| 1109 |
mergeState := tw.MergeState{} // Default to no merge |
| 1110 |
|
| 1111 |
if lineMergeStates != nil { |
| 1112 |
if state, ok := lineMergeStates[j]; ok { |
| 1113 |
mergeState = state |
| 1114 |
} |
| 1115 |
} |
| 1116 |
|
| 1117 |
// For context purposes (like Previous or Current for a border line), |
| 1118 |
// Align and Padding are often less critical than Data, Width, and Merge. |
| 1119 |
// We can use default/empty Align and Padding here. |
| 1120 |
cells[j] = tw.CellContext{ |
| 1121 |
Data: cellData, |
| 1122 |
Align: tw.AlignDefault, // Or tw.AlignNone if preferred for context-only cells |
| 1123 |
Padding: tw.Padding{}, // Empty padding |
| 1124 |
Width: colWidth, |
| 1125 |
Merge: mergeState, |
| 1126 |
} |
| 1127 |
} |
| 1128 |
return cells |
| 1129 |
} |
| 1130 |
|
| 1131 |
// streamStoreFooter processes the footer content and stores it for later rendering by Close() |
| 1132 |
// in streaming mode. It ensures stream widths are calculated if not already set. |
| 1133 |
func (t *Table) streamStoreFooter(footers []string) error { |
| 1134 |
t.logger.Debug("streamStoreFooter called with footers: %v", footers) |
| 1135 |
|
| 1136 |
if !t.config.Stream.Enable { |
| 1137 |
return errors.New("streaming mode is disabled") |
| 1138 |
} |
| 1139 |
|
| 1140 |
if len(footers) == 0 { |
| 1141 |
t.logger.Debug("streamStoreFooter: Empty footer cells, storing empty footer lines.") |
| 1142 |
t.streamFooterLines = [][]string{} |
| 1143 |
return nil |
| 1144 |
} |
| 1145 |
|
| 1146 |
if err := t.ensureStreamWidthsCalculated(footers, t.config.Footer); err != nil { |
| 1147 |
t.logger.Warnf("streamStoreFooter: Failed to determine column count from footer data: %v", err) |
| 1148 |
t.streamFooterLines = [][]string{} |
| 1149 |
return nil |
| 1150 |
} |
| 1151 |
|
| 1152 |
if t.streamNumCols > 0 && len(footers) != t.streamNumCols { |
| 1153 |
t.logger.Warnf("streamStoreFooter: Input footer column count (%d) does not match fixed stream column count (%d). Padding/Truncating input footers.", len(footers), t.streamNumCols) |
| 1154 |
if len(footers) < t.streamNumCols { |
| 1155 |
paddedFooters := make([]string, t.streamNumCols) |
| 1156 |
copy(paddedFooters, footers) |
| 1157 |
for i := len(footers); i < t.streamNumCols; i++ { |
| 1158 |
paddedFooters[i] = tw.Empty |
| 1159 |
} |
| 1160 |
footers = paddedFooters |
| 1161 |
} else { |
| 1162 |
footers = footers[:t.streamNumCols] |
| 1163 |
} |
| 1164 |
} |
| 1165 |
|
| 1166 |
if t.streamNumCols == 0 { |
| 1167 |
t.logger.Warn("streamStoreFooter: streamNumCols is 0, cannot process/store footer lines meaningfully.") |
| 1168 |
t.streamFooterLines = [][]string{} |
| 1169 |
return nil |
| 1170 |
} |
| 1171 |
|
| 1172 |
t.streamFooterLines = t.prepareContent(footers, t.config.Footer) |
| 1173 |
t.logger.Debug("streamStoreFooter: Processed and stored footer lines: %d lines. Content: %v", len(t.streamFooterLines), t.streamFooterLines) |
| 1174 |
|
| 1175 |
return nil |
| 1176 |
} |