new: table support

This commit is contained in:
daboe01 committed 2026-06-13 22:36:09 +02:00
1 parent 861c504c41
commit a0fc7723fc
3 files changed
+557 -166

No files matched your search

+131 -3
View File
@@ -23,6 +23,7 @@
@import <Foundation/CPGeometry.j>
@import "CPFontManager.j"
@import "CPParagraphStyle.j"
@import "_CPTableTextAttachment.j"
@global CPLeftTextAlignment
@global CPRightTextAlignment
@@ -34,6 +35,7 @@
@global CPForegroundColorAttributeName
@global CPBackgroundColorAttributeName
@global CPParagraphStyleAttributeName
@global CPAttachmentAttributeName
@global CPLeftTabStopType
@global CPRightTabStopType
@@ -289,7 +291,12 @@ var kRgsymRtf = {
"]" : [ "]", 0, false, kRTFParserType_char, ']'],
"{" : [ "{", 0, false, kRTFParserType_char, '{'],
"}" : [ "}", 0, false, kRTFParserType_char, '}'],
"\\" : [ "\\", 0, false, kRTFParserType_char, '\\']
"\\" : [ "\\", 0, false, kRTFParserType_char, '\\'],
"trowd" : [ "trowd", 0, false, kRTFParserType_spec, "ipfnTrowd"],
"cell" : [ "cell", 0, false, kRTFParserType_spec, "ipfnCell"],
"row" : [ "row", 0, false, kRTFParserType_spec, "ipfnRow"],
"cellx" : [ "cellx", 0, false, kRTFParserType_spec, "ipfnCellx"],
"intbl" : [ "intbl", 0, false, kRTFParserType_spec, "ipfnIntbl"]
};
@implementation _CPRTFParser : CPObject
@@ -307,6 +314,13 @@ var kRgsymRtf = {
CPArray _fontArray;
CPString _freename;
BOOL _parsingFontTable;
// Table parsing state
BOOL _inTableActive;
BOOL _waitingForNextRow;
CPMutableArray _tableRows;
CPMutableArray _currentRow;
CPString _currentCellText;
}
- (id)init
@@ -324,6 +338,12 @@ var kRgsymRtf = {
_fontArray = ['Arial']; // FIXME: should be name of system font
_freename = "";
_parsingFontTable = NO;
_inTableActive = NO;
_waitingForNextRow = NO;
_tableRows = nil;
_currentRow = nil;
_currentCellText = "";
}
return self;
@@ -420,11 +440,91 @@ var kRgsymRtf = {
_codePage = code;
_currentParseIndex--;
break;
case "ipfnTrowd":
if (_waitingForNextRow)
{
_waitingForNextRow = NO;
}
if (!_inTableActive)
{
_inTableActive = YES;
_tableRows = [CPMutableArray array];
_currentRow = [CPMutableArray array];
_currentCellText = "";
}
else
{
_currentRow = [CPMutableArray array];
}
return '';
case "ipfnIntbl":
return '';
case "ipfnCell":
if (_inTableActive)
{
if (!_currentRow)
_currentRow = [CPMutableArray array];
[_currentRow addObject:_currentCellText];
_currentCellText = "";
}
return '';
case "ipfnRow":
if (_inTableActive)
{
if (!_currentRow)
_currentRow = [CPMutableArray array];
[_tableRows addObject:_currentRow];
_waitingForNextRow = YES;
}
return '';
case "ipfnCellx":
return '';
}
return '';
}
- (void)_flushTableIfAny
{
if (_tableRows && [_tableRows count] > 0)
{
var headers = [_tableRows objectAtIndex:0];
var rows = [CPMutableArray array];
for (var idx = 1; idx < [_tableRows count]; idx++)
{
[rows addObject:[_tableRows objectAtIndex:idx]];
}
var attachment = [[_CPTableTextAttachment alloc] initWithHeaders:headers rows:rows width:500.0];
// Linear height allocation estimation
var numCols = [headers count];
var estimatedHeight = 36.0 + ([rows count] * 28.0);
var lineCount = Math.ceil(estimatedHeight / 16.0) + 1;
var newlineStr = "";
for (var nl = 0; nl < lineCount; nl++) {
newlineStr += "\n";
}
var tableAttrStr = [[CPMutableAttributedString alloc] initWithString:newlineStr];
[tableAttrStr addAttribute:@"TableAttachmentAttribute" value:attachment range:CPMakeRange(0, [tableAttrStr length])];
[tableAttrStr addAttribute:CPAttachmentAttributeName value:attachment range:CPMakeRange(0, [tableAttrStr length])];
[_result appendAttributedString:tableAttrStr];
_tableRows = nil;
_currentRow = nil;
_currentCellText = "";
_inTableActive = NO;
_waitingForNextRow = NO;
}
}
- (void)_flushCurrentRun
{
var newOffset = 0;
@@ -552,6 +652,14 @@ var kRgsymRtf = {
- (CPString)_translateKeyword:(CPString)keyword parameter:(CPString)param fParameter:(BOOL)fParam
{
if (_waitingForNextRow)
{
if (keyword !== "trowd" && keyword !== "cell" && keyword !== "row" && keyword !== "intbl" && keyword !== "cellx")
{
[self _flushTableIfAny];
}
}
if (kRgsymRtf[keyword] !== undefined)
{
var sym = kRgsymRtf[keyword];
@@ -744,9 +852,16 @@ var kRgsymRtf = {
- (void)_appendPlainString:(CPString) aString
{
[_result replaceCharactersInRange:CPMakeRange([_result length], 0) withString:aString];
if (_inTableActive)
{
_currentCellText += aString;
}
else
{
[_result replaceCharactersInRange:CPMakeRange([_result length], 0) withString:aString];
}
}
- (CPAttributedString)parseRTF:(CPString)rtf
{
rtf = rtf.replace(/\\\n/g, "\\par\n");
@@ -766,6 +881,11 @@ var kRgsymRtf = {
{
tmp = rtf.charAt(++_currentParseIndex);
if (_waitingForNextRow && tmp !== "\\" && tmp !== " " && tmp !== "\n" && tmp !== "\r" && tmp !== "\t")
{
[self _flushTableIfAny];
}
if (tmp !== "\\" && hex.length > 0)
{
[self _appendPlainString: String.fromCharCode(parseInt((hex), 16))];
@@ -788,12 +908,18 @@ var kRgsymRtf = {
break;
case "{":
if (_waitingForNextRow)
[self _flushTableIfAny];
if ([self pushState])
CPLogConsole("push");
break;
case "}":
if (_waitingForNextRow)
[self _flushTableIfAny];
if ([self popState])
CPLogConsole("pop");
@@ -863,6 +989,8 @@ var kRgsymRtf = {
}
}
[self _flushTableIfAny];
return _result;
}
+94 -163
View File
@@ -1,7 +1,7 @@
/*
_CPRTFProducer.j
Serialize CPAttributedString to an RTF String
Serialize CPAttributedString to a RTF String
Copyright (C) 2014 Daniel Boehringer
This file is based on the RTFProducer from GNUStep
@@ -27,6 +27,7 @@
@import "CPColor.j"
@import "CPGraphics.j"
@import "CPFontManager.j"
@import "_CPTableTextAttachment.j"
@global CPForegroundColorAttributeName
@global CPBackgroundColorAttributeName
@@ -43,6 +44,11 @@
@global CPJustifiedTextAlignment
@global CPNaturalTextAlignment
@global CPLeftTabStopType
@global CPRightTabStopType
@global CPCenterTabStopType
@global CPDecimalTabStopType
var PAPERSIZE = @"PaperSize",
LEFTMARGIN = @"LeftMargin",
RIGHTMARGIN = @"RightMargin",
@@ -77,30 +83,28 @@ function _points2twips(a) { return (a) * 20.0; }
#pragma mark -
#pragma mark Init methods
#pragma mark init methods
- (id)init
{
if (self = [super init])
{
// Maintain a dictionary for the used colors
// (for RTF-header generation)
// maintain a dictionary for the used colours
// (for rtf-header generation)
colorDict = [CPMutableDictionary new];
// Maintain a dictionary for the used fonts
// (for RTF-header generation)
//maintain a dictionary for the used fonts
//(for rtf-header generation)
fontDict = [CPMutableDictionary new];
fgColor = [CPColor blackColor];
bgColor = [CPColor whiteColor];
bgColor= [CPColor whiteColor];
}
return self;
}
#pragma mark -
#pragma mark Header & Formatting Support
// private stuff follows
- (CPString)fontTable
{
if (![fontDict count])
@@ -315,7 +319,7 @@ function _points2twips(a) { return (a) * 20.0; }
break;
}
// Write first line indent and left indent
// write first line indent and left indent
var twips = _points2twips([paraStyle firstLineHeadIndent]);
if (twips != 0.0)
@@ -356,163 +360,97 @@ function _points2twips(a) { return (a) * 20.0; }
switch ([tab tabStopType])
{
case CPLeftTabStopType:
// No tabkind emission needed
break;
/* case NSRightTabStopType:
case CPRightTabStopType:
headerString += @"\\tqr";
break;
case NSCenterTabStopType:
headerString += @"\\tqc";
break;
case NSDecimalTabStopType:
break;
case CPCenterTabStopType:
headerString += @"\\tqc";
break;
case CPDecimalTabStopType:
headerString += @"\\tqdec";
break;
default:
NSLog(@"Unknown tab stop type.");
*/
}
break;
}
headerString += [CPString stringWithFormat:@"\\tx%d",_points2twips([tab location])];
headerString += [CPString stringWithFormat:@"\\tx%d",_points2twips([tab location])];
}
return headerString;
}
#pragma mark -
#pragma mark Duck-Typed Table Engine
/**
* Generates a native RTF table row structure from a conforming table data object.
* This helper isolates the native RTF grid structure to ensure decoupling.
*
* @param tableObject An object implementing the dynamic getters `headers` and `rows`.
* @return A raw RTF CPString containing cell bounds, row boundaries, and escaped strings.
*/
- (CPString)rtfStringForTable:(id)tableObject
{
var headers = [tableObject headers],
rows = [tableObject rows];
var numCols = [headers count];
if (numCols == 0 && [rows count] > 0)
{
numCols = [[rows objectAtIndex:0] count];
}
if (numCols == 0)
{
return @"";
}
var rtf = @"";
// Divide printable horizontal space evenly (approx. 5.5 inches or 7920 Twips total)
var totalWidthTwips = 7920,
colWidth = Math.floor(totalWidthTwips / numCols);
var makeRowRTF = function(cells, isHeader) {
// \trowd clears existing cell definitions.
// \trleft360 applies an indent matching a standard page margin.
var rowStr = @"\\trowd\\trgaph108\\trleft360";
// 1. Declare row boundaries and configure cell border widths
var currentX = 360;
for (var c = 0; c < numCols; c++) {
currentX += colWidth;
rowStr += @"\\clbrdrt\\brdrs\\brdrw10\\clbrdrb\\brdrs\\brdrw10";
rowStr += @"\\clbrdrl\\brdrs\\brdrw10\\clbrdrr\\brdrs\\brdrw10";
rowStr += [CPString stringWithFormat:@"\\cellx%d", currentX];
}
// 2. Escape, format, and serialize cell text content
for (var c = 0; c < numCols; c++) {
var textVal = @"";
if (c < [cells count]) {
textVal = [cells objectAtIndex:c];
}
// Core RTF escaping (Backslashes escaped first to preserve subsequent tokens)
textVal = textVal.replace(/\\/g, '\\\\');
textVal = textVal.replace(/{/g, '\\{');
textVal = textVal.replace(/}/g, '\\}');
textVal = textVal.replace(/\n/g, '\\par ');
// Standard visual inline Markdown conversions for cellular parity
textVal = textVal.replace(/\*\*([^*]+)\*\*/g, '\\b $1\\b0 ');
textVal = textVal.replace(/\*([^*]+)\*/g, '\\i $1\\i0 ');
rowStr += @"\\intbl ";
if (isHeader) {
rowStr += @"\\b ";
}
rowStr += textVal;
if (isHeader) {
rowStr += @"\\b0 ";
}
rowStr += @"\\cell ";
}
rowStr += @"\\row\n";
return rowStr;
};
// Construct headers
if ([headers count] > 0) {
rtf += makeRowRTF(headers, YES);
}
// Construct content rows
for (var r = 0; r < [rows count]; r++) {
var rowData = [rows objectAtIndex:r];
rtf += makeRowRTF(rowData, NO);
}
// Explicitly restore standard paragraph attributes to escape table scope
rtf += @"\\pard\n";
return rtf;
}
#pragma mark -
#pragma mark Attribute Processing
- (CPString)runStringForString:(CPString) substring
attributes:(CPDictionary) attributes
paragraphStart:(BOOL) first
{
var tableAttachment = [attributes objectForKey:CPAttachmentAttributeName];
if (!tableAttachment)
tableAttachment = [attributes objectForKey:@"TableAttachmentAttribute"];
if (tableAttachment && [tableAttachment isKindOfClass:[_CPTableTextAttachment class]])
{
var headers = [tableAttachment headers],
rows = [tableAttachment rows];
var numCols = [headers count];
if (numCols == 0 && [rows count] > 0)
numCols = [[rows objectAtIndex:0] count];
if (numCols > 0)
{
var totalWidthTwips = 10000;
var colWidthTwips = Math.floor(totalWidthTwips / numCols);
var cellBoundaries = [];
var currentBoundary = 0;
for (var i = 0; i < numCols; i++)
{
currentBoundary += colWidthTwips;
cellBoundaries.push(currentBoundary);
}
var tableRTF = "";
var writeRow = function(rowData, isHeaderRow) {
var rowRTF = "\\trowd\\trgaph115\\trleft0";
for (var c = 0; c < numCols; c++) {
rowRTF += "\\clbrdrt\\brdrs\\brdrw10\\clbrdrb\\brdrs\\brdrw10\\clbrdrl\\brdrs\\brdrw10\\clbrdrr\\brdrs\\brdrw10";
rowRTF += "\\cellx" + cellBoundaries[c];
}
for (var c = 0; c < numCols; c++) {
var cellText = "";
if (c < [rowData count]) {
cellText = [rowData objectAtIndex:c];
}
cellText = cellText.replace(/\\/g, '\\\\');
cellText = cellText.replace(/{/g, '\\{');
cellText = cellText.replace(/}/g, '\\}');
cellText = cellText.replace(/\n/g, '\\line ');
if (isHeaderRow) {
rowRTF += "{\\intbl\\b " + cellText + "\\b0\\cell}";
} else {
rowRTF += "{\\intbl " + cellText + "\\cell}";
}
}
rowRTF += "\\row\n";
return rowRTF;
};
if ([headers count] > 0) {
tableRTF += writeRow(headers, YES);
}
for (var r = 0; r < [rows count]; r++) {
tableRTF += writeRow([rows objectAtIndex:r], NO);
}
return tableRTF;
}
}
var result = "",
headerString = "",
trailerString = "",
attribEnum,
currAttrib;
// --- DUCK-TYPING PROTOCOL DETECTION ---
// Safely scan all incoming attributes for an object supporting headers & rows.
// If found, completely divert processing to native RTF table construction.
var keys = [attributes allKeys],
count = [keys count],
tableObject = nil;
for (var i = 0; i < count; i++)
{
var key = [keys objectAtIndex:i],
val = [attributes objectForKey:key];
if (val && typeof val.respondsToSelector === "function" &&
[val respondsToSelector:@selector(headers)] &&
[val respondsToSelector:@selector(rows)])
{
tableObject = val;
break;
}
}
if (tableObject)
{
return [self rtfStringForTable:tableObject];
}
// --------------------------------------
if (first)
{
var paraStyle = [attributes objectForKey:CPParagraphStyleAttributeName];
@@ -520,10 +458,10 @@ function _points2twips(a) { return (a) * 20.0; }
}
/*
* Analyze attributes of current run
* analyze attributes of current run
*
* FIXME: All the character attributes should be output relative to the font
* attributes of the paragraph. So if the paragraph has underline on, it should
* attributes of the paragraph. So if the paragraph has underline on it should
* still be possible to switch it off for some characters, which currently is
* not possible.
*/
@@ -534,7 +472,7 @@ function _points2twips(a) { return (a) * 20.0; }
if ([currAttrib isEqualToString:CPFontAttributeName])
{
/*
* Handle fonts
* handle fonts
*/
var font,
fontName,
@@ -545,13 +483,13 @@ function _points2twips(a) { return (a) * 20.0; }
traits = [[CPFontManager sharedFontManager] traitsOfFont:font];
/*
* Font name
* font name
*/
if (currentFont == nil || ![fontName isEqualToString:[currentFont familyName]])
headerString += [self fontToken:fontName];
/*
* Font size
* font size
*/
if (currentFont == nil || [font size] != [currentFont size])
{
@@ -562,7 +500,7 @@ function _points2twips(a) { return (a) * 20.0; }
headerString += pString;
}
/*
* Font attributes
* font attributes
*/
if (traits & CPItalicFontMask)
{
@@ -652,8 +590,6 @@ function _points2twips(a) { return (a) * 20.0; }
substring = substring.replace(/\t/g, '\\tab');
substring = substring.replace(/{/g, '\\{');
substring = substring.replace(/}/g, '\\}');
// FIXME: All characters not in the standard encoding must be
// replaced by \'xx
if (!first)
{
@@ -691,8 +627,7 @@ function _points2twips(a) { return (a) * 20.0; }
completeRange = CPMakeRange(0, length),
first = YES;
// FIXME <!> split along newline characters and run as outer loop
while (CPMaxRange(currRange) < CPMaxRange(completeRange)) // Save all "runs"
while (CPMaxRange(currRange) < CPMaxRange(completeRange)) // save all "runs"
{
var attributes,
substring,
@@ -725,9 +660,6 @@ function _points2twips(a) { return (a) * 20.0; }
text = aText;
docDict = dict;
/*
* Do not change order! (esp. body has to be generated first; builds context)
*/
bodyString = [self bodyString];
trailerString = [self trailerString];
headerString = [self headerString];
@@ -737,5 +669,4 @@ function _points2twips(a) { return (a) * 20.0; }
output += trailerString;
return output;
}
@end
+332
View File
@@ -0,0 +1,332 @@
/* _CPTableTextAttachment.j
* A self-contained, renderable text attachment representation of a table.
*
* Copyright (C) 2026 Daniel Boehringer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
@import <AppKit/CPView.j>
@import <AppKit/CPTextView.j>
@import <AppKit/CPTextField.j>
@import <Foundation/CPAttributedString.j>
@implementation _CPTableTextAttachment : CPView
{
CPArray _headers;
CPArray _rows;
}
- (id)initWithHeaders:(CPArray)headers rows:(CPArray)rows
{
return [self initWithHeaders:headers rows:rows width:500.0];
}
- (id)initWithHeaders:(CPArray)headers rows:(CPArray)rows width:(float)totalWidth
{
self = [super initWithFrame:CGRectMake(0, 0, totalWidth, 20)];
if (self)
{
_headers = headers;
_rows = rows;
var numCols = [headers count];
if (numCols == 0 && [rows count] > 0)
numCols = [[rows objectAtIndex:0] count];
// Apply borders on the outer left and top container edges
if (self._DOMElement) {
self._DOMElement.style.borderTop = "1px solid #e0e0e0";
self._DOMElement.style.borderLeft = "1px solid #e0e0e0";
}
// Initialize header cells
if ([headers count] > 0) {
for (var c = 0; c < numCols; c++) {
var headerText = [headers objectAtIndex:c];
var cellView = [self createCellWithText:headerText frame:CGRectMakeZero() isHeader:YES];
[self addSubview:cellView];
}
}
// Initialize body rows
for (var r = 0; r < [rows count]; r++) {
var rowData = [rows objectAtIndex:r];
for (var c = 0; c < numCols; c++) {
var cellText = @"";
if (c < [rowData count])
cellText = [rowData objectAtIndex:c];
var cellView = [self createCellWithText:cellText frame:CGRectMakeZero() isHeader:NO];
[self addSubview:cellView];
}
}
[self resizeToWidth:totalWidth];
}
return self;
}
- (CPArray)headers
{
return _headers;
}
- (CPArray)rows
{
return _rows;
}
- (CPView)viewForWidth:(float)width
{
[self resizeToWidth:width];
return self;
}
- (CPView)createCellWithText:(CPString)text frame:(CGRect)frame isHeader:(BOOL)isHeader
{
var initialWidth = (frame.size.width > 0) ? frame.size.width : 120.0;
var initialHeight = (frame.size.height > 0) ? frame.size.height : 28.0;
var cellContainer = [[CPView alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, initialWidth, initialHeight)];
[cellContainer setBackgroundColor:isHeader ? [CPColor colorWithWhite:0.92 alpha:1.0] : [CPColor whiteColor]];
// Bottom and right edge borders to construct the grid
var borderView = [[CPView alloc] initWithFrame:CGRectMake(0, 0, initialWidth, initialHeight)];
[borderView setBackgroundColor:[CPColor clearColor]];
[borderView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
if (borderView._DOMElement) {
borderView._DOMElement.style.borderBottom = "1px solid #e0e0e0";
borderView._DOMElement.style.borderRight = "1px solid #e0e0e0";
borderView._DOMElement.style.boxSizing = "border-box";
}
[cellContainer addSubview:borderView];
var textContainer = [[CPTextContainer alloc] initWithContainerSize:CGSizeMake(initialWidth - 8, 1e7)];
var textView = [[CPTextView alloc] initWithFrame:CGRectMake(4, 2, initialWidth - 8, initialHeight - 4) textContainer:textContainer];
[textView setEditable:NO];
[textView setSelectable:YES];
[textView setBackgroundColor:[CPColor clearColor]];
[textView setVerticallyResizable:YES];
[textView setHorizontallyResizable:NO];
[[textView textContainer] setWidthTracksTextView:YES];
// Construct cell text using standard fonts
var cellFont = isHeader ? [CPFont boldSystemFontOfSize:11.0] : [CPFont systemFontOfSize:11.0];
var parsedText = [[CPAttributedString alloc] initWithString:text attributes:@{
CPFontAttributeName: cellFont,
CPForegroundColorAttributeName: [CPColor blackColor]
}];
var storage = [textView textStorage];
if (storage && [storage respondsToSelector:@selector(setAttributedString:)]) {
[storage setAttributedString:parsedText];
} else {
[textView setEditable:YES];
[textView setString:@""];
[textView insertText:parsedText];
[textView setEditable:NO];
}
[cellContainer addSubview:textView];
return cellContainer;
}
- (CPTextView)getTextViewFromCell:(CPView)cellView
{
var subviews = [cellView subviews];
for (var i = 0; i < [subviews count]; i++) {
var sub = [subviews objectAtIndex:i];
if ([sub isKindOfClass:[CPTextView class]]) {
return sub;
}
}
return nil;
}
- (void)resizeToWidth:(float)newWidth
{
var numCols = [_headers count];
if (numCols == 0 && [_rows count] > 0) {
numCols = [[_rows objectAtIndex:0] count];
}
if (numCols == 0) return;
var subviews = [self subviews];
var colNaturalWidths = [];
var colMinWidths = [];
for (var c = 0; c < numCols; c++) {
colNaturalWidths[c] = 80.0;
colMinWidths[c] = 60.0;
}
var measureTextField = [[CPTextField alloc] initWithFrame:CGRectMake(0, 0, 10000.0, 24.0)];
[measureTextField setFont:[CPFont systemFontOfSize:13.0]];
var measureCell = function(cellText, isHeader, colIndex) {
var cellFont = isHeader ? [CPFont boldSystemFontOfSize:11.0] : [CPFont systemFontOfSize:11.0];
[measureTextField setFont:cellFont];
[measureTextField setStringValue:cellText];
[measureTextField sizeToFit];
var naturalW = CGRectGetWidth([measureTextField frame]) + 24.0;
if (naturalW > colNaturalWidths[colIndex]) {
colNaturalWidths[colIndex] = naturalW;
}
var words = cellText.split(/[\s\-]/);
var maxWordW = 50.0;
for (var w = 0; w < words.length; w++) {
var word = words[w].trim();
if (word.length === 0) continue;
[measureTextField setStringValue:word];
[measureTextField sizeToFit];
var wordW = CGRectGetWidth([measureTextField frame]) + 30.0;
if (wordW > maxWordW) {
maxWordW = wordW;
}
}
if (maxWordW > colMinWidths[colIndex]) {
colMinWidths[colIndex] = maxWordW;
}
};
for (var c = 0; c < [_headers count]; c++) {
measureCell([_headers objectAtIndex:c], YES, c);
}
for (var r = 0; r < [_rows count]; r++) {
var rowData = [_rows objectAtIndex:r];
for (var c = 0; c < numCols; c++) {
var cellText = @"";
if (c < [rowData count]) {
cellText = [rowData objectAtIndex:c];
}
measureCell(cellText, NO, c);
}
}
var totalMinWidth = 0.0;
for (var c = 0; c < numCols; c++) {
totalMinWidth += colMinWidths[c];
}
var colWidths = [];
if (newWidth <= totalMinWidth) {
var remainingWidth = newWidth;
for (var c = 0; c < numCols; c++) {
var w = Math.floor((colMinWidths[c] / totalMinWidth) * newWidth);
colWidths[c] = w;
remainingWidth -= w;
}
if (numCols > 0) colWidths[numCols - 1] += remainingWidth;
} else {
for (var c = 0; c < numCols; c++) {
colWidths[c] = colMinWidths[c];
}
var totalGrowthCapacity = 0.0;
var growthCapacities = [];
for (var c = 0; c < numCols; c++) {
var capacity = Math.max(0.0, colNaturalWidths[c] - colMinWidths[c]);
growthCapacities[c] = capacity;
totalGrowthCapacity += capacity;
}
var extraWidth = newWidth - totalMinWidth;
var remainingExtra = extraWidth;
for (var c = 0; c < numCols; c++) {
if (totalGrowthCapacity > 0) {
var w = Math.floor((growthCapacities[c] / totalGrowthCapacity) * extraWidth);
colWidths[c] += w;
remainingExtra -= w;
}
}
if (numCols > 0) {
colWidths[numCols - 1] += remainingExtra;
}
}
var cellIndex = 0;
var currentY = 0;
var layoutRow = function(startIndex) {
var maxCellHeight = 28.0;
for (var c = 0; c < numCols; c++) {
var idx = startIndex + c;
if (idx < [subviews count]) {
var cellView = [subviews objectAtIndex:idx];
var textView = [self getTextViewFromCell:cellView];
if (textView) {
var targetWidth = Math.max(10.0, colWidths[c] - 8);
[[textView textContainer] setContainerSize:CGSizeMake(targetWidth, 1e7)];
var usedRect = [[textView layoutManager] usedRectForTextContainer:[textView textContainer]];
var wrappedHeight = CGRectGetHeight(usedRect) + 12.0;
if (wrappedHeight > maxCellHeight) {
maxCellHeight = wrappedHeight;
}
}
}
}
var currentX = 0;
for (var c = 0; c < numCols; c++) {
var idx = startIndex + c;
if (idx < [subviews count]) {
var cellView = [subviews objectAtIndex:idx];
[cellView setFrame:CGRectMake(currentX, currentY, colWidths[c], maxCellHeight)];
var textView = [self getTextViewFromCell:cellView];
if (textView) {
var targetWidth = Math.max(10.0, colWidths[c] - 8);
var textY = 4.0;
var finalTextViewHeight = maxCellHeight - 8.0;
[textView setFrame:CGRectMake(4, textY, targetWidth, finalTextViewHeight)];
}
var cellSubviews = [cellView subviews];
if ([cellSubviews count] > 0) {
[[cellSubviews objectAtIndex:0] setFrame:CGRectMake(0, 0, colWidths[c], maxCellHeight)];
}
}
currentX += colWidths[c];
}
return maxCellHeight;
};
if ([_headers count] > 0) {
var headerHeight = layoutRow(cellIndex);
cellIndex += numCols;
currentY += headerHeight;
}
for (var r = 0; r < [_rows count]; r++) {
var rowHeight = layoutRow(cellIndex);
cellIndex += numCols;
currentY += rowHeight;
}
[self setFrameSize:CGSizeMake(newWidth, currentY)];
}
@end