acadrust 0.3.2

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
//! Table entity implementation.
//!
//! The Table entity represents a grid of cells that can contain text,
//! blocks, or formulas, with extensive styling and formatting options.

use crate::entities::{Entity, EntityCommon};
use crate::types::{BoundingBox3D, Color, Handle, LineWeight, Transparency, Vector3};

use bitflags::bitflags;

// ============================================================================
// Enums
// ============================================================================

/// Cell content type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum CellType {
    /// Text content.
    #[default]
    Text = 1,
    /// Block reference content.
    Block = 2,
}

impl From<u8> for CellType {
    fn from(value: u8) -> Self {
        match value {
            1 => Self::Text,
            2 => Self::Block,
            _ => Self::Text,
        }
    }
}

/// Cell value data type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u32)]
pub enum CellValueType {
    /// Unknown type.
    #[default]
    Unknown = 0,
    /// Long integer.
    Long = 1,
    /// Double precision float.
    Double = 2,
    /// Text string.
    String = 4,
    /// Date value.
    Date = 8,
    /// 2D point.
    Point2D = 0x10,
    /// 3D point.
    Point3D = 0x20,
    /// Object handle reference.
    Handle = 0x40,
    /// Binary buffer.
    Buffer = 0x80,
    /// Result buffer.
    ResultBuffer = 0x100,
    /// General value.
    General = 0x200,
}

impl From<u32> for CellValueType {
    fn from(value: u32) -> Self {
        match value {
            1 => Self::Long,
            2 => Self::Double,
            4 => Self::String,
            8 => Self::Date,
            0x10 => Self::Point2D,
            0x20 => Self::Point3D,
            0x40 => Self::Handle,
            0x80 => Self::Buffer,
            0x100 => Self::ResultBuffer,
            0x200 => Self::General,
            _ => Self::Unknown,
        }
    }
}

/// Value unit type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u32)]
pub enum ValueUnitType {
    /// No units.
    #[default]
    NoUnits = 0,
    /// Distance units.
    Distance = 1,
    /// Angle units.
    Angle = 2,
    /// Area units.
    Area = 4,
    /// Volume units.
    Volume = 8,
    /// Currency units.
    Currency = 0x10,
    /// Percentage.
    Percentage = 0x20,
}

impl From<u32> for ValueUnitType {
    fn from(value: u32) -> Self {
        match value {
            1 => Self::Distance,
            2 => Self::Angle,
            4 => Self::Area,
            8 => Self::Volume,
            0x10 => Self::Currency,
            0x20 => Self::Percentage,
            _ => Self::NoUnits,
        }
    }
}

/// Border type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(i16)]
pub enum BorderType {
    /// Single line border.
    #[default]
    Single = 1,
    /// Double line border.
    Double = 2,
}

impl From<i16> for BorderType {
    fn from(value: i16) -> Self {
        match value {
            1 => Self::Single,
            2 => Self::Double,
            _ => Self::Single,
        }
    }
}

/// Cell content type for table content.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum TableCellContentType {
    /// Unknown content.
    #[default]
    Unknown = 0,
    /// Value content.
    Value = 1,
    /// Field content.
    Field = 2,
    /// Block content.
    Block = 4,
}

impl From<u8> for TableCellContentType {
    fn from(value: u8) -> Self {
        match value {
            1 => Self::Value,
            2 => Self::Field,
            4 => Self::Block,
            _ => Self::Unknown,
        }
    }
}

/// Cell style type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum CellStyleType {
    /// Cell style.
    #[default]
    Cell = 1,
    /// Row style.
    Row = 2,
    /// Column style.
    Column = 3,
    /// Formatted table data style.
    FormattedTableData = 4,
    /// Table style.
    Table = 5,
}

impl From<u8> for CellStyleType {
    fn from(value: u8) -> Self {
        match value {
            1 => Self::Cell,
            2 => Self::Row,
            3 => Self::Column,
            4 => Self::FormattedTableData,
            5 => Self::Table,
            _ => Self::Cell,
        }
    }
}

/// Break flow direction for table breaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum BreakFlowDirection {
    /// Break to the right.
    #[default]
    Right = 1,
    /// Break vertically.
    Vertical = 2,
    /// Break to the left.
    Left = 4,
}

impl From<u8> for BreakFlowDirection {
    fn from(value: u8) -> Self {
        match value {
            1 => Self::Right,
            2 => Self::Vertical,
            4 => Self::Left,
            _ => Self::Right,
        }
    }
}

// ============================================================================
// Bitflags
// ============================================================================

bitflags! {
    /// Cell edge flags indicating which borders to affect.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct CellEdgeFlags: u32 {
        /// No edges.
        const NONE = 0;
        /// Top edge.
        const TOP = 1;
        /// Right edge.
        const RIGHT = 2;
        /// Bottom edge.
        const BOTTOM = 4;
        /// Left edge.
        const LEFT = 8;
        /// Inside vertical edges.
        const INSIDE_VERTICAL = 16;
        /// Inside horizontal edges.
        const INSIDE_HORIZONTAL = 32;
        /// All edges.
        const ALL = 63;
    }
}

bitflags! {
    /// Cell state flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct CellStateFlags: u32 {
        /// No state.
        const NONE = 0;
        /// Content is locked.
        const CONTENT_LOCKED = 1;
        /// Content is read-only.
        const CONTENT_READ_ONLY = 2;
        /// Cell is linked.
        const LINKED = 4;
        /// Content modified after update.
        const CONTENT_MODIFIED_AFTER_UPDATE = 8;
        /// Format is locked.
        const FORMAT_LOCKED = 16;
        /// Format is read-only.
        const FORMAT_READ_ONLY = 32;
        /// Format modified after update.
        const FORMAT_MODIFIED_AFTER_UPDATE = 64;
    }
}

bitflags! {
    /// Cell style property override flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct CellStylePropertyFlags: u32 {
        /// No properties.
        const NONE = 0;
        /// Data type.
        const DATA_TYPE = 1;
        /// Data format.
        const DATA_FORMAT = 2;
        /// Rotation.
        const ROTATION = 4;
        /// Block scale.
        const BLOCK_SCALE = 8;
        /// Alignment.
        const ALIGNMENT = 16;
        /// Content color.
        const CONTENT_COLOR = 32;
        /// Text style.
        const TEXT_STYLE = 64;
        /// Text height.
        const TEXT_HEIGHT = 128;
        /// Auto scale.
        const AUTO_SCALE = 256;
        /// Background color.
        const BACKGROUND_COLOR = 512;
        /// Left margin.
        const MARGIN_LEFT = 1024;
        /// Top margin.
        const MARGIN_TOP = 2048;
        /// Right margin.
        const MARGIN_RIGHT = 4096;
        /// Bottom margin.
        const MARGIN_BOTTOM = 8192;
        /// Content layout.
        const CONTENT_LAYOUT = 16384;
        /// Merge all.
        const MERGE_ALL = 32768;
        /// Flow direction bottom to top.
        const FLOW_DIRECTION_BOTTOM_TO_TOP = 65536;
        /// Horizontal spacing.
        const MARGIN_HORIZONTAL_SPACING = 131072;
        /// Vertical spacing.
        const MARGIN_VERTICAL_SPACING = 262144;
    }
}

bitflags! {
    /// Border property override flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct BorderPropertyFlags: u32 {
        /// No properties.
        const NONE = 0;
        /// Border type.
        const BORDER_TYPE = 1;
        /// Line weight.
        const LINE_WEIGHT = 2;
        /// Line type.
        const LINE_TYPE = 4;
        /// Color.
        const COLOR = 8;
        /// Invisibility.
        const INVISIBILITY = 16;
        /// Double line spacing.
        const DOUBLE_LINE_SPACING = 32;
        /// All properties.
        const ALL = 63;
    }
}

bitflags! {
    /// Content layout flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct ContentLayoutFlags: u32 {
        /// No layout.
        const NONE = 0;
        /// Flow layout.
        const FLOW = 1;
        /// Stacked horizontal.
        const STACKED_HORIZONTAL = 2;
        /// Stacked vertical.
        const STACKED_VERTICAL = 4;
    }
}

bitflags! {
    /// Break option flags.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub struct BreakOptionFlags: u32 {
        /// No options.
        const NONE = 0;
        /// Enable breaks.
        const ENABLE_BREAKS = 1;
        /// Repeat top labels.
        const REPEAT_TOP_LABELS = 2;
        /// Repeat bottom labels.
        const REPEAT_BOTTOM_LABELS = 4;
        /// Allow manual positions.
        const ALLOW_MANUAL_POSITIONS = 8;
        /// Allow manual heights.
        const ALLOW_MANUAL_HEIGHTS = 16;
    }
}

// ============================================================================
// Cell Border
// ============================================================================

/// Border definition for a cell edge.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CellBorder {
    /// Border type.
    pub border_type: BorderType,
    /// Border color.
    pub color: Color,
    /// Border line weight.
    pub line_weight: LineWeight,
    /// Whether the border is invisible.
    pub invisible: bool,
    /// Double line spacing.
    pub double_spacing: f64,
    /// Override flags.
    pub override_flags: BorderPropertyFlags,
}

impl CellBorder {
    /// Creates a default cell border.
    pub fn new() -> Self {
        Self {
            border_type: BorderType::Single,
            color: Color::ByBlock,
            line_weight: LineWeight::ByLayer,
            invisible: false,
            double_spacing: 0.0,
            override_flags: BorderPropertyFlags::NONE,
        }
    }

    /// Creates a visible border with the given color.
    pub fn with_color(color: Color) -> Self {
        let mut border = Self::new();
        border.color = color;
        border.override_flags |= BorderPropertyFlags::COLOR;
        border
    }

    /// Creates an invisible border.
    pub fn invisible() -> Self {
        let mut border = Self::new();
        border.invisible = true;
        border
    }
}

impl Default for CellBorder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Cell Value
// ============================================================================

/// Value stored in a table cell.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CellValue {
    /// Value type.
    pub value_type: CellValueType,
    /// Unit type.
    pub unit_type: ValueUnitType,
    /// Value flags.
    pub flags: i32,
    /// Text string value.
    pub text: String,
    /// Format string.
    pub format: String,
    /// Formatted display value.
    pub formatted_value: String,
    /// Numeric value (for Long/Double types).
    pub numeric_value: f64,
    /// Handle value (for Handle type).
    pub handle_value: Option<Handle>,
}

impl CellValue {
    /// Creates an empty cell value.
    pub fn new() -> Self {
        Self {
            value_type: CellValueType::Unknown,
            unit_type: ValueUnitType::NoUnits,
            flags: 0,
            text: String::new(),
            format: String::new(),
            formatted_value: String::new(),
            numeric_value: 0.0,
            handle_value: None,
        }
    }

    /// Creates a text value.
    pub fn text(s: &str) -> Self {
        Self {
            value_type: CellValueType::String,
            unit_type: ValueUnitType::NoUnits,
            flags: 0,
            text: s.to_string(),
            format: String::new(),
            formatted_value: s.to_string(),
            numeric_value: 0.0,
            handle_value: None,
        }
    }

    /// Creates a numeric value.
    pub fn number(n: f64) -> Self {
        Self {
            value_type: CellValueType::Double,
            unit_type: ValueUnitType::NoUnits,
            flags: 0,
            text: String::new(),
            format: String::new(),
            formatted_value: n.to_string(),
            numeric_value: n,
            handle_value: None,
        }
    }

    /// Creates an integer value.
    pub fn integer(n: i64) -> Self {
        Self {
            value_type: CellValueType::Long,
            unit_type: ValueUnitType::NoUnits,
            flags: 0,
            text: String::new(),
            format: String::new(),
            formatted_value: n.to_string(),
            numeric_value: n as f64,
            handle_value: None,
        }
    }

    /// Returns true if the value is empty.
    pub fn is_empty(&self) -> bool {
        self.value_type == CellValueType::Unknown && self.text.is_empty()
    }

    /// Returns the display string.
    pub fn display(&self) -> &str {
        if !self.formatted_value.is_empty() {
            &self.formatted_value
        } else if !self.text.is_empty() {
            &self.text
        } else {
            ""
        }
    }
}

impl Default for CellValue {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Cell Content
// ============================================================================

/// Content within a table cell.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CellContent {
    /// Content type.
    pub content_type: TableCellContentType,
    /// Cell value.
    pub value: CellValue,
    /// Block content handle (for block type).
    pub block_handle: Option<Handle>,
    /// Text style handle.
    pub text_style_handle: Option<Handle>,
    /// Content color.
    pub color: Color,
    /// Rotation angle in radians.
    pub rotation: f64,
    /// Scale factor (for blocks).
    pub scale: f64,
    /// Text height.
    pub text_height: f64,
}

impl CellContent {
    /// Creates empty cell content.
    pub fn new() -> Self {
        Self {
            content_type: TableCellContentType::Unknown,
            value: CellValue::new(),
            block_handle: None,
            text_style_handle: None,
            color: Color::ByBlock,
            rotation: 0.0,
            scale: 1.0,
            text_height: 0.18,
        }
    }

    /// Creates text content.
    pub fn text(s: &str) -> Self {
        Self {
            content_type: TableCellContentType::Value,
            value: CellValue::text(s),
            block_handle: None,
            text_style_handle: None,
            color: Color::ByBlock,
            rotation: 0.0,
            scale: 1.0,
            text_height: 0.18,
        }
    }

    /// Creates block content.
    pub fn block(block_handle: Handle) -> Self {
        Self {
            content_type: TableCellContentType::Block,
            value: CellValue::new(),
            block_handle: Some(block_handle),
            text_style_handle: None,
            color: Color::ByBlock,
            rotation: 0.0,
            scale: 1.0,
            text_height: 0.18,
        }
    }
}

impl Default for CellContent {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Cell Style
// ============================================================================

/// Style applied to a table cell.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CellStyle {
    /// Style type.
    pub style_type: CellStyleType,
    /// Property override flags.
    pub property_flags: CellStylePropertyFlags,
    /// Background fill color.
    pub background_color: Color,
    /// Content color.
    pub content_color: Color,
    /// Text style handle.
    pub text_style_handle: Option<Handle>,
    /// Text height.
    pub text_height: f64,
    /// Rotation angle.
    pub rotation: f64,
    /// Scale factor.
    pub scale: f64,
    /// Alignment value.
    pub alignment: i32,
    /// Background fill enabled.
    pub fill_enabled: bool,
    /// Content layout flags.
    pub layout_flags: ContentLayoutFlags,
    /// Margins.
    pub margin_left: f64,
    pub margin_top: f64,
    pub margin_right: f64,
    pub margin_bottom: f64,
    /// Spacing.
    pub horizontal_spacing: f64,
    pub vertical_spacing: f64,
    /// Borders.
    pub top_border: CellBorder,
    pub right_border: CellBorder,
    pub bottom_border: CellBorder,
    pub left_border: CellBorder,
}

impl CellStyle {
    /// Creates a default cell style.
    pub fn new() -> Self {
        Self {
            style_type: CellStyleType::Cell,
            property_flags: CellStylePropertyFlags::NONE,
            background_color: Color::ByBlock,
            content_color: Color::ByBlock,
            text_style_handle: None,
            text_height: 0.18,
            rotation: 0.0,
            scale: 1.0,
            alignment: 0,
            fill_enabled: false,
            layout_flags: ContentLayoutFlags::FLOW,
            margin_left: 0.06,
            margin_top: 0.06,
            margin_right: 0.06,
            margin_bottom: 0.06,
            horizontal_spacing: 0.0,
            vertical_spacing: 0.0,
            top_border: CellBorder::new(),
            right_border: CellBorder::new(),
            bottom_border: CellBorder::new(),
            left_border: CellBorder::new(),
        }
    }

    /// Sets uniform margins.
    pub fn set_margins(&mut self, margin: f64) {
        self.margin_left = margin;
        self.margin_top = margin;
        self.margin_right = margin;
        self.margin_bottom = margin;
    }

    /// Sets all borders to the same style.
    pub fn set_border_color(&mut self, color: Color) {
        self.top_border.color = color;
        self.right_border.color = color;
        self.bottom_border.color = color;
        self.left_border.color = color;
    }
}

impl Default for CellStyle {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Table Cell
// ============================================================================

/// A cell in a table.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TableCell {
    /// Cell type (text or block).
    pub cell_type: CellType,
    /// Cell state flags.
    pub state: CellStateFlags,
    /// Cell contents (can have multiple).
    pub contents: Vec<CellContent>,
    /// Cell style override.
    pub style: Option<CellStyle>,
    /// Cell tooltip.
    pub tooltip: String,
    /// Rotation angle.
    pub rotation: f64,
    /// Auto-fit content.
    pub auto_fit: bool,
    /// Merged cell width (number of columns).
    pub merge_width: i32,
    /// Merged cell height (number of rows).
    pub merge_height: i32,
    /// Flag value.
    pub flag: i32,
    /// Merged value (encoding of merge info).
    pub merged: i32,
    /// Virtual edge flag.
    pub virtual_edge: i16,
    /// Has linked data.
    pub has_linked_data: bool,
    /// Custom data value.
    pub custom_data: i32,
}

impl TableCell {
    /// Creates an empty cell.
    pub fn new() -> Self {
        Self {
            cell_type: CellType::Text,
            state: CellStateFlags::NONE,
            contents: Vec::new(),
            style: None,
            tooltip: String::new(),
            rotation: 0.0,
            auto_fit: false,
            merge_width: 1,
            merge_height: 1,
            flag: 0,
            merged: 0,
            virtual_edge: 0,
            has_linked_data: false,
            custom_data: 0,
        }
    }

    /// Creates a cell with text content.
    pub fn text(s: &str) -> Self {
        let mut cell = Self::new();
        cell.contents.push(CellContent::text(s));
        cell
    }

    /// Creates a cell with block content.
    pub fn block(block_handle: Handle) -> Self {
        let mut cell = Self::new();
        cell.cell_type = CellType::Block;
        cell.contents.push(CellContent::block(block_handle));
        cell
    }

    /// Gets the first content (convenience method).
    pub fn content(&self) -> Option<&CellContent> {
        self.contents.first()
    }

    /// Gets the text value of the first content.
    pub fn text_value(&self) -> &str {
        self.contents.first()
            .map(|c| c.value.display())
            .unwrap_or("")
    }

    /// Sets the text value.
    pub fn set_text(&mut self, s: &str) {
        self.contents.clear();
        self.contents.push(CellContent::text(s));
        self.cell_type = CellType::Text;
    }

    /// Returns true if this cell spans multiple cells.
    pub fn is_merged(&self) -> bool {
        self.merge_width > 1 || self.merge_height > 1
    }

    /// Returns true if the cell has content.
    pub fn has_content(&self) -> bool {
        !self.contents.is_empty()
    }

    /// Returns true if this cell has multiple contents.
    pub fn has_multiple_contents(&self) -> bool {
        self.contents.len() > 1
    }
}

impl Default for TableCell {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Table Row
// ============================================================================

/// A row in a table.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TableRow {
    /// Row height.
    pub height: f64,
    /// Cells in this row.
    pub cells: Vec<TableCell>,
    /// Row style override.
    pub style: Option<CellStyle>,
    /// Custom data value.
    pub custom_data: i32,
}

impl TableRow {
    /// Creates a new row with the given number of cells.
    pub fn new(num_cells: usize) -> Self {
        let cells = (0..num_cells).map(|_| TableCell::new()).collect();
        Self {
            height: 0.25,
            cells,
            style: None,
            custom_data: 0,
        }
    }

    /// Creates a row from cell values.
    pub fn from_texts(texts: &[&str]) -> Self {
        let cells = texts.iter().map(|t| TableCell::text(t)).collect();
        Self {
            height: 0.25,
            cells,
            style: None,
            custom_data: 0,
        }
    }

    /// Returns the number of cells.
    pub fn cell_count(&self) -> usize {
        self.cells.len()
    }

    /// Gets a cell by index.
    pub fn cell(&self, index: usize) -> Option<&TableCell> {
        self.cells.get(index)
    }

    /// Gets a mutable cell by index.
    pub fn cell_mut(&mut self, index: usize) -> Option<&mut TableCell> {
        self.cells.get_mut(index)
    }
}

impl Default for TableRow {
    fn default() -> Self {
        Self::new(0)
    }
}

// ============================================================================
// Table Column
// ============================================================================

/// A column definition in a table.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TableColumn {
    /// Column name.
    pub name: String,
    /// Column width.
    pub width: f64,
    /// Column style override.
    pub style: Option<CellStyle>,
    /// Custom data value.
    pub custom_data: i32,
}

impl TableColumn {
    /// Creates a new column with default width.
    pub fn new() -> Self {
        Self {
            name: String::new(),
            width: 2.5,
            style: None,
            custom_data: 0,
        }
    }

    /// Creates a column with the given width.
    pub fn with_width(width: f64) -> Self {
        Self {
            name: String::new(),
            width,
            style: None,
            custom_data: 0,
        }
    }

    /// Creates a named column.
    pub fn named(name: &str, width: f64) -> Self {
        Self {
            name: name.to_string(),
            width,
            style: None,
            custom_data: 0,
        }
    }
}

impl Default for TableColumn {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Cell Range
// ============================================================================

/// A range of cells in a table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CellRange {
    /// Top row index.
    pub top_row: usize,
    /// Left column index.
    pub left_col: usize,
    /// Bottom row index (inclusive).
    pub bottom_row: usize,
    /// Right column index (inclusive).
    pub right_col: usize,
}

impl CellRange {
    /// Creates a range for a single cell.
    pub fn cell(row: usize, col: usize) -> Self {
        Self {
            top_row: row,
            left_col: col,
            bottom_row: row,
            right_col: col,
        }
    }

    /// Creates a range of cells.
    pub fn new(top_row: usize, left_col: usize, bottom_row: usize, right_col: usize) -> Self {
        Self {
            top_row,
            left_col,
            bottom_row,
            right_col,
        }
    }

    /// Returns the number of rows in the range.
    pub fn row_count(&self) -> usize {
        self.bottom_row - self.top_row + 1
    }

    /// Returns the number of columns in the range.
    pub fn col_count(&self) -> usize {
        self.right_col - self.left_col + 1
    }

    /// Returns the total number of cells in the range.
    pub fn cell_count(&self) -> usize {
        self.row_count() * self.col_count()
    }

    /// Returns true if this range contains the given cell.
    pub fn contains(&self, row: usize, col: usize) -> bool {
        row >= self.top_row && row <= self.bottom_row &&
        col >= self.left_col && col <= self.right_col
    }
}

impl Default for CellRange {
    fn default() -> Self {
        Self::cell(0, 0)
    }
}

// ============================================================================
// Table Entity
// ============================================================================

/// Table entity.
///
/// A table is a grid of cells containing text, blocks, or formulas,
/// with extensive styling and formatting options.
///
/// # Example
///
/// ```ignore
/// use acadrust::entities::{Table, TableRow};
/// use acadrust::types::Vector3;
///
/// // Create a 3x4 table
/// let mut table = Table::new(Vector3::new(0.0, 0.0, 0.0), 3, 4);
///
/// // Set header row
/// table.set_cell_text(0, 0, "Name");
/// table.set_cell_text(0, 1, "Value");
/// table.set_cell_text(0, 2, "Unit");
/// table.set_cell_text(0, 3, "Notes");
///
/// // Add data rows
/// table.set_cell_text(1, 0, "Length");
/// table.set_cell_text(1, 1, "100.0");
/// table.set_cell_text(1, 2, "mm");
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Table {
    /// Common entity data.
    pub common: EntityCommon,
    /// Insertion point.
    pub insertion_point: Vector3,
    /// Horizontal direction vector.
    pub horizontal_direction: Vector3,
    /// Normal vector.
    pub normal: Vector3,
    /// Table style handle.
    pub table_style_handle: Option<Handle>,
    /// Block record handle (table is based on block).
    pub block_record_handle: Option<Handle>,
    /// Table data version.
    pub data_version: i16,
    /// Table value flags.
    pub value_flags: i32,
    /// Flag overrides.
    pub override_flag: bool,
    pub override_border_color: bool,
    pub override_border_line_weight: bool,
    pub override_border_visibility: bool,
    /// Rows.
    pub rows: Vec<TableRow>,
    /// Columns.
    pub columns: Vec<TableColumn>,
    /// Break options.
    pub break_options: BreakOptionFlags,
    /// Break flow direction.
    pub break_flow_direction: BreakFlowDirection,
    /// Break spacing.
    pub break_spacing: f64,
}

impl Table {
    /// Creates a new table with the given dimensions.
    pub fn new(insertion_point: Vector3, num_rows: usize, num_cols: usize) -> Self {
        let rows = (0..num_rows).map(|_| TableRow::new(num_cols)).collect();
        let columns = (0..num_cols).map(|_| TableColumn::new()).collect();

        Self {
            common: EntityCommon::default(),
            insertion_point,
            horizontal_direction: Vector3::new(1.0, 0.0, 0.0),
            normal: Vector3::new(0.0, 0.0, 1.0),
            table_style_handle: None,
            block_record_handle: None,
            data_version: 0,
            value_flags: 0,
            override_flag: false,
            override_border_color: false,
            override_border_line_weight: false,
            override_border_visibility: false,
            rows,
            columns,
            break_options: BreakOptionFlags::NONE,
            break_flow_direction: BreakFlowDirection::Right,
            break_spacing: 0.0,
        }
    }

    /// Returns the number of rows.
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Returns the number of columns.
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// Gets a cell at the given position.
    pub fn cell(&self, row: usize, col: usize) -> Option<&TableCell> {
        self.rows.get(row).and_then(|r| r.cells.get(col))
    }

    /// Gets a mutable cell at the given position.
    pub fn cell_mut(&mut self, row: usize, col: usize) -> Option<&mut TableCell> {
        self.rows.get_mut(row).and_then(|r| r.cells.get_mut(col))
    }

    /// Sets the text content of a cell.
    pub fn set_cell_text(&mut self, row: usize, col: usize, text: &str) -> bool {
        if let Some(cell) = self.cell_mut(row, col) {
            cell.set_text(text);
            true
        } else {
            false
        }
    }

    /// Gets the text content of a cell.
    pub fn cell_text(&self, row: usize, col: usize) -> Option<&str> {
        self.cell(row, col).map(|c| c.text_value())
    }

    /// Sets the height of a row.
    pub fn set_row_height(&mut self, row: usize, height: f64) {
        if let Some(r) = self.rows.get_mut(row) {
            r.height = height;
        }
    }

    /// Sets the width of a column.
    pub fn set_column_width(&mut self, col: usize, width: f64) {
        if let Some(c) = self.columns.get_mut(col) {
            c.width = width;
        }
    }

    /// Gets the total table width.
    pub fn total_width(&self) -> f64 {
        self.columns.iter().map(|c| c.width).sum()
    }

    /// Gets the total table height.
    pub fn total_height(&self) -> f64 {
        self.rows.iter().map(|r| r.height).sum()
    }

    /// Adds a new row at the end.
    pub fn add_row(&mut self) -> &mut TableRow {
        let num_cols = self.columns.len();
        self.rows.push(TableRow::new(num_cols));
        self.rows.last_mut().unwrap()
    }

    /// Adds a new column at the end.
    pub fn add_column(&mut self, width: f64) {
        self.columns.push(TableColumn::with_width(width));
        // Add a cell to each row
        for row in &mut self.rows {
            row.cells.push(TableCell::new());
        }
    }

    /// Inserts a row at the given index.
    pub fn insert_row(&mut self, index: usize) {
        let num_cols = self.columns.len();
        if index <= self.rows.len() {
            self.rows.insert(index, TableRow::new(num_cols));
        }
    }

    /// Inserts a column at the given index.
    pub fn insert_column(&mut self, index: usize, width: f64) {
        if index <= self.columns.len() {
            self.columns.insert(index, TableColumn::with_width(width));
            for row in &mut self.rows {
                row.cells.insert(index, TableCell::new());
            }
        }
    }

    /// Removes a row.
    pub fn remove_row(&mut self, index: usize) -> Option<TableRow> {
        if index < self.rows.len() {
            Some(self.rows.remove(index))
        } else {
            None
        }
    }

    /// Removes a column.
    pub fn remove_column(&mut self, index: usize) -> Option<TableColumn> {
        if index < self.columns.len() {
            let col = self.columns.remove(index);
            for row in &mut self.rows {
                if index < row.cells.len() {
                    row.cells.remove(index);
                }
            }
            Some(col)
        } else {
            None
        }
    }

    /// Merges cells in the given range.
    pub fn merge_cells(&mut self, range: CellRange) {
        if let Some(cell) = self.cell_mut(range.top_row, range.left_col) {
            cell.merge_width = range.col_count() as i32;
            cell.merge_height = range.row_count() as i32;
        }
    }

    /// Unmerges a cell.
    pub fn unmerge_cell(&mut self, row: usize, col: usize) {
        if let Some(cell) = self.cell_mut(row, col) {
            cell.merge_width = 1;
            cell.merge_height = 1;
        }
    }

    /// Sets uniform row height for all rows.
    pub fn set_uniform_row_height(&mut self, height: f64) {
        for row in &mut self.rows {
            row.height = height;
        }
    }

    /// Sets uniform column width for all columns.
    pub fn set_uniform_column_width(&mut self, width: f64) {
        for col in &mut self.columns {
            col.width = width;
        }
    }

    /// Clears all cell content but keeps structure.
    pub fn clear_content(&mut self) {
        for row in &mut self.rows {
            for cell in &mut row.cells {
                cell.contents.clear();
            }
        }
    }
}

impl Default for Table {
    fn default() -> Self {
        Self::new(Vector3::ZERO, 3, 3)
    }
}

impl Entity for Table {
    fn handle(&self) -> Handle {
        self.common.handle
    }

    fn set_handle(&mut self, handle: Handle) {
        self.common.handle = handle;
    }

    fn layer(&self) -> &str {
        &self.common.layer
    }

    fn set_layer(&mut self, layer: String) {
        self.common.layer = layer;
    }

    fn color(&self) -> Color {
        self.common.color
    }

    fn set_color(&mut self, color: Color) {
        self.common.color = color;
    }

    fn line_weight(&self) -> LineWeight {
        self.common.line_weight
    }

    fn set_line_weight(&mut self, line_weight: LineWeight) {
        self.common.line_weight = line_weight;
    }

    fn transparency(&self) -> Transparency {
        self.common.transparency
    }

    fn set_transparency(&mut self, transparency: Transparency) {
        self.common.transparency = transparency;
    }

    fn is_invisible(&self) -> bool {
        self.common.invisible
    }

    fn set_invisible(&mut self, invisible: bool) {
        self.common.invisible = invisible;
    }

    fn bounding_box(&self) -> BoundingBox3D {
        let min = self.insertion_point;
        let max = Vector3::new(
            min.x + self.total_width(),
            min.y + self.total_height(),
            min.z,
        );
        BoundingBox3D::new(min, max)
    }

    fn translate(&mut self, offset: Vector3) {
        super::translate::translate_table(self, offset);
    }

    fn entity_type(&self) -> &'static str {
        "ACAD_TABLE"
    }
    
    fn apply_transform(&mut self, transform: &crate::types::Transform) {
        super::transform::transform_table(self, transform);
    }
}

// ============================================================================
// Builder
// ============================================================================

/// Builder for Table entities.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TableBuilder {
    table: Table,
}

impl TableBuilder {
    /// Creates a new builder.
    pub fn new(rows: usize, cols: usize) -> Self {
        Self {
            table: Table::new(Vector3::ZERO, rows, cols),
        }
    }

    /// Sets the insertion point.
    pub fn at(mut self, point: Vector3) -> Self {
        self.table.insertion_point = point;
        self
    }

    /// Sets uniform row height.
    pub fn row_height(mut self, height: f64) -> Self {
        self.table.set_uniform_row_height(height);
        self
    }

    /// Sets uniform column width.
    pub fn column_width(mut self, width: f64) -> Self {
        self.table.set_uniform_column_width(width);
        self
    }

    /// Sets the layer.
    pub fn layer(mut self, layer: &str) -> Self {
        self.table.common.layer = layer.to_string();
        self
    }

    /// Sets text in a cell.
    pub fn cell_text(mut self, row: usize, col: usize, text: &str) -> Self {
        self.table.set_cell_text(row, col, text);
        self
    }

    /// Sets a header row (first row) with texts.
    pub fn header(mut self, headers: &[&str]) -> Self {
        for (col, text) in headers.iter().enumerate() {
            self.table.set_cell_text(0, col, text);
        }
        self
    }

    /// Builds the table.
    pub fn build(self) -> Table {
        self.table
    }
}

impl Default for TableBuilder {
    fn default() -> Self {
        Self::new(3, 3)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_table_creation() {
        let table = Table::new(Vector3::ZERO, 3, 4);
        assert_eq!(table.row_count(), 3);
        assert_eq!(table.column_count(), 4);
    }

    #[test]
    fn test_table_cell_access() {
        let mut table = Table::new(Vector3::ZERO, 2, 2);
        table.set_cell_text(0, 0, "A1");
        table.set_cell_text(1, 1, "B2");

        assert_eq!(table.cell_text(0, 0), Some("A1"));
        assert_eq!(table.cell_text(1, 1), Some("B2"));
        assert_eq!(table.cell_text(0, 1), Some(""));
    }

    #[test]
    fn test_table_dimensions() {
        let mut table = Table::new(Vector3::ZERO, 2, 3);
        table.set_uniform_row_height(1.0);
        table.set_uniform_column_width(2.0);

        assert_eq!(table.total_height(), 2.0);
        assert_eq!(table.total_width(), 6.0);
    }

    #[test]
    fn test_table_add_row() {
        let mut table = Table::new(Vector3::ZERO, 2, 2);
        table.add_row();
        assert_eq!(table.row_count(), 3);
        assert_eq!(table.rows[2].cell_count(), 2);
    }

    #[test]
    fn test_table_add_column() {
        let mut table = Table::new(Vector3::ZERO, 2, 2);
        table.add_column(3.0);
        assert_eq!(table.column_count(), 3);
        assert_eq!(table.columns[2].width, 3.0);
        assert_eq!(table.rows[0].cell_count(), 3);
    }

    #[test]
    fn test_table_remove_row() {
        let mut table = Table::new(Vector3::ZERO, 3, 2);
        table.remove_row(1);
        assert_eq!(table.row_count(), 2);
    }

    #[test]
    fn test_table_remove_column() {
        let mut table = Table::new(Vector3::ZERO, 2, 3);
        table.remove_column(1);
        assert_eq!(table.column_count(), 2);
        assert_eq!(table.rows[0].cell_count(), 2);
    }

    #[test]
    fn test_cell_merge() {
        let mut table = Table::new(Vector3::ZERO, 3, 3);
        table.merge_cells(CellRange::new(0, 0, 1, 2));

        let cell = table.cell(0, 0).unwrap();
        assert!(cell.is_merged());
        assert_eq!(cell.merge_width, 3);
        assert_eq!(cell.merge_height, 2);
    }

    #[test]
    fn test_cell_value() {
        let text = CellValue::text("Hello");
        assert_eq!(text.display(), "Hello");
        assert!(!text.is_empty());

        let number = CellValue::number(42.5);
        assert_eq!(number.numeric_value, 42.5);
    }

    #[test]
    fn test_cell_range() {
        let range = CellRange::new(1, 2, 3, 4);
        assert_eq!(range.row_count(), 3);
        assert_eq!(range.col_count(), 3);
        assert_eq!(range.cell_count(), 9);
        assert!(range.contains(2, 3));
        assert!(!range.contains(0, 0));
    }

    #[test]
    fn test_table_builder() {
        let table = TableBuilder::new(2, 3)
            .at(Vector3::new(10.0, 20.0, 0.0))
            .row_height(0.5)
            .column_width(2.0)
            .header(&["A", "B", "C"])
            .cell_text(1, 0, "Data")
            .build();

        assert_eq!(table.insertion_point.x, 10.0);
        assert_eq!(table.cell_text(0, 0), Some("A"));
        assert_eq!(table.cell_text(1, 0), Some("Data"));
    }

    #[test]
    fn test_table_bounding_box() {
        let mut table = Table::new(Vector3::new(5.0, 10.0, 0.0), 2, 3);
        table.set_uniform_row_height(1.0);
        table.set_uniform_column_width(2.0);

        let bbox = table.bounding_box();
        assert_eq!(bbox.min.x, 5.0);
        assert_eq!(bbox.min.y, 10.0);
        assert_eq!(bbox.max.x, 11.0); // 5 + 3*2
        assert_eq!(bbox.max.y, 12.0); // 10 + 2*1
    }

    #[test]
    fn test_table_translate() {
        let mut table = Table::new(Vector3::new(0.0, 0.0, 0.0), 2, 2);
        table.translate(Vector3::new(10.0, 20.0, 5.0));
        assert_eq!(table.insertion_point, Vector3::new(10.0, 20.0, 5.0));
    }

    #[test]
    fn test_cell_content() {
        let text = CellContent::text("Hello");
        assert_eq!(text.content_type, TableCellContentType::Value);

        let block = CellContent::block(Handle::new(0x100));
        assert_eq!(block.content_type, TableCellContentType::Block);
        assert!(block.block_handle.is_some());
    }

    #[test]
    fn test_cell_border() {
        let border = CellBorder::with_color(Color::from_index(1));
        assert!(!border.invisible);
        assert!(border.override_flags.contains(BorderPropertyFlags::COLOR));
    }

    #[test]
    fn test_cell_style() {
        let mut style = CellStyle::new();
        style.set_margins(0.1);
        style.set_border_color(Color::from_index(2));

        assert_eq!(style.margin_left, 0.1);
        assert_eq!(style.top_border.color, Color::from_index(2));
    }

    #[test]
    fn test_table_row() {
        let row = TableRow::from_texts(&["A", "B", "C"]);
        assert_eq!(row.cell_count(), 3);
        assert_eq!(row.cell(0).unwrap().text_value(), "A");
    }

    #[test]
    fn test_table_column() {
        let col = TableColumn::named("Width", 5.0);
        assert_eq!(col.name, "Width");
        assert_eq!(col.width, 5.0);
    }

    #[test]
    fn test_insert_operations() {
        let mut table = Table::new(Vector3::ZERO, 2, 2);
        table.insert_row(1);
        assert_eq!(table.row_count(), 3);

        table.insert_column(1, 3.0);
        assert_eq!(table.column_count(), 3);
        assert_eq!(table.rows[0].cell_count(), 3);
    }

    #[test]
    fn test_cell_state_flags() {
        let flags = CellStateFlags::CONTENT_LOCKED | CellStateFlags::FORMAT_LOCKED;
        assert!(flags.contains(CellStateFlags::CONTENT_LOCKED));
        assert!(!flags.contains(CellStateFlags::LINKED));
    }
}