ezdwg-core 0.22.0

Pure Rust DWG reader and native AC1015 writer
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
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
use crate::bit::{BitReader, Endian};
use crate::core::error::{DwgError, ErrorKind};
use crate::core::result::Result;
use crate::entities::common::parse_common_entity_header_r14_with_handle;
use crate::entities::common::{
    parse_common_entity_handles, parse_common_entity_header, parse_common_entity_header_r2007,
    parse_common_entity_header_r2010, parse_common_entity_header_r2013,
    parse_common_entity_layer_handle, read_handle_reference, string_stream_reader,
    CommonEntityHeader,
};
use crate::entities::common::{parse_common_entity_header_for_format, StringStreamFormat};
use crate::entities::mtext::{decode_embedded_mtext_r2010, EmbeddedMTextData};
use crate::entities::text::decode_r21_text_tail;

#[derive(Debug, Clone)]
pub struct AttribEntity {
    pub handle: u64,
    pub owner_handle: Option<u64>,
    pub color_index: Option<u16>,
    pub true_color: Option<u32>,
    pub layer_handle: u64,
    pub text: String,
    pub insertion: (f64, f64, f64),
    pub alignment: Option<(f64, f64, f64)>,
    pub extrusion: (f64, f64, f64),
    pub thickness: f64,
    pub oblique_angle: f64,
    pub height: f64,
    pub rotation: f64,
    pub width_factor: f64,
    pub generation: u16,
    pub horizontal_alignment: u16,
    pub vertical_alignment: u16,
    pub style_handle: Option<u64>,
    pub tag: Option<String>,
    pub flags: u8,
    pub lock_position: bool,
    pub prompt: Option<String>,
}

#[derive(Debug, Clone, Default)]
struct AttribTailData {
    tag: Option<String>,
    flags: u8,
    lock_position: bool,
    prompt: Option<String>,
    embedded_mtext: Option<EmbeddedMTextData>,
}

/// The most strings an attribute keeps in its string stream: TEXT value,
/// embedded MTEXT text, tag and prompt, with room for writers that add more.
const MAX_ATTRIB_STRINGS: usize = 8;

/// ATTRIB or ATTDEF of R2007 and later, read as the specification lays it out
/// (ODA specification 20.4.4 and 20.4.5).
///
/// These versions keep every string of an object in its string stream: the
/// data stream holds the TEXT fields without the text value and then the
/// attribute fields, and the string stream holds the text value, the tag and,
/// for ATTDEF, the prompt. The data stream ends exactly where the strings
/// begin, which is what this function checks before it accepts a record; the
/// callers keep the older heuristics as a fallback for records that do not
/// pass.
///
/// A multi-line attribute (R2018, attribute type 2 or 4) embeds a whole MTEXT
/// between the type and the attribute fields. Its text is the string in front
/// of the tag; the flags and the lock bit are the last fields of the data
/// stream and are read from its end. The position and size are the ones of the
/// TEXT fields.
///
/// `object_data_end_bit` is where the handle stream begins; R2007 stores it in
/// the record, so the argument is not used there.
pub fn decode_attrib_exact(
    reader: &mut BitReader<'_>,
    format: StringStreamFormat,
    object_data_end_bit: u32,
    object_handle: u64,
    is_attdef: bool,
) -> Result<AttribEntity> {
    let header =
        parse_common_entity_header_for_format(reader, format, object_data_end_bit, object_handle)?;

    let data_flags = reader.read_rc()?;
    let elevation = if (data_flags & 0x01) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        0.0
    };
    let insertion_x = reader.read_rd(Endian::Little)?;
    let insertion_y = reader.read_rd(Endian::Little)?;
    let alignment = if (data_flags & 0x02) == 0 {
        let align_x = reader.read_dd(insertion_x)?;
        let align_y = reader.read_dd(insertion_y)?;
        Some((align_x, align_y, elevation))
    } else {
        None
    };
    let extrusion = reader.read_be()?;
    let thickness = reader.read_bt()?;
    let oblique_angle = if (data_flags & 0x04) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        0.0
    };
    let rotation = if (data_flags & 0x08) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        0.0
    };
    let height = reader.read_rd(Endian::Little)?;
    let width_factor = if (data_flags & 0x10) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        1.0
    };
    let generation = if (data_flags & 0x20) == 0 {
        reader.read_bs()?
    } else {
        0
    };
    let horizontal_alignment = if (data_flags & 0x40) == 0 {
        reader.read_bs()?
    } else {
        0
    };
    let vertical_alignment = if (data_flags & 0x80) == 0 {
        reader.read_bs()?
    } else {
        0
    };

    let has_version = format != StringStreamFormat::R2007;
    if has_version {
        let _version = reader.read_rc()?;
    }
    let attribute_type = if format == StringStreamFormat::R2018 {
        reader.read_rc()?
    } else {
        1
    };
    let multi_line = match attribute_type {
        1 => false,
        2 | 4 => true,
        _ => {
            return Err(DwgError::new(
                ErrorKind::Format,
                format!("unknown attribute type: {attribute_type}"),
            ))
        }
    };

    let not_exact = |what: &str| DwgError::new(ErrorKind::Format, format!("attribute {what}"));
    let (mut string_reader, strings_end) = string_stream_reader(reader, header.obj_size)
        .ok_or_else(|| not_exact("has no string stream"))?;
    let strings_start = string_reader.tell_bits();

    // The attribute fields end the data stream: [ATTDEF version RC], lock
    // position B and, in front of it, flags RC.
    let attdef_version_bits = if is_attdef && has_version { 8 } else { 0 };
    let flags_bit = strings_start
        .checked_sub(attdef_version_bits + 9)
        .filter(|bit| *bit >= reader.tell_bits())
        .ok_or_else(|| not_exact("data is shorter than its fields"))?;
    let mut tail_reader = reader.clone();
    tail_reader.set_bit_pos(flags_bit as u32);
    let flags = tail_reader.read_rc()?;
    let lock_position = tail_reader.read_b()? != 0;

    if !multi_line {
        let _field_length = reader.read_bs()?;
        let _flags = reader.read_rc()?;
        let _lock_position = reader.read_b()?;
        if attdef_version_bits != 0 {
            let _attdef_version = reader.read_rc()?;
        }
        if reader.tell_bits() != strings_start {
            return Err(not_exact("data does not end at its string stream"));
        }
    }

    let mut strings: Vec<String> = Vec::new();
    while strings.len() < MAX_ATTRIB_STRINGS && string_reader.tell_bits() < u64::from(strings_end) {
        match string_reader.read_tu() {
            Ok(value) if string_reader.tell_bits() <= u64::from(strings_end) => strings.push(value),
            _ => break,
        }
    }
    // Single line: text value, tag, [prompt]. Multi line: the text of the
    // embedded MTEXT sits between the (usually empty) text value and the tag.
    let trailing = if is_attdef { 2 } else { 1 };
    let (text, tag, prompt) = if multi_line {
        if strings.len() < trailing + 2 {
            return Err(not_exact("has too few strings"));
        }
        let prompt = is_attdef.then(|| strings[strings.len() - 1].clone());
        let tag = strings[strings.len() - trailing].clone();
        let mut text = mtext_plain_text(&strings[strings.len() - trailing - 1]);
        if text.is_empty() {
            text = strings[0].clone();
        }
        (text, tag, prompt)
    } else {
        if strings.len() != trailing + 1 {
            return Err(not_exact("has an unexpected number of strings"));
        }
        let prompt = is_attdef.then(|| strings[2].clone());
        (strings[0].clone(), strings[1].clone(), prompt)
    };
    if tag.is_empty() || tag.chars().any(char::is_control) {
        return Err(not_exact("has no usable tag"));
    }
    if ![insertion_x, insertion_y, elevation, height, rotation]
        .iter()
        .all(|value| value.is_finite())
        || height <= 0.0
    {
        return Err(not_exact("has an unusable position or height"));
    }

    reader.set_bit_pos(header.obj_size);
    let (owner_handle, layer_handle, style_handle) =
        match parse_common_entity_handles(reader, &header) {
            Ok(common_handles) => (
                common_handles.owner_ref,
                common_handles.layer,
                // The handles of an embedded MTEXT come first in a multi-line attribute.
                if multi_line {
                    None
                } else {
                    read_handle_reference(reader, header.handle).ok()
                },
            ),
            Err(_) => (None, 0, None),
        };

    Ok(AttribEntity {
        handle: header.handle,
        owner_handle,
        color_index: header.color.index,
        true_color: header.color.true_color,
        layer_handle,
        text,
        insertion: (insertion_x, insertion_y, elevation),
        alignment,
        extrusion,
        thickness,
        oblique_angle,
        height,
        rotation,
        width_factor,
        generation,
        horizontal_alignment,
        vertical_alignment,
        style_handle,
        tag: Some(tag),
        flags,
        lock_position,
        prompt,
    })
}

/// Plain text of MTEXT content: paragraph breaks become line feeds and the
/// formatting codes are dropped.
fn mtext_plain_text(value: &str) -> String {
    let chars: Vec<char> = value.chars().collect();
    let mut out = String::with_capacity(value.len());
    let mut index = 0;
    // Skips the argument of a formatting code, up to and including its ';'.
    let skip_argument = |index: &mut usize| {
        while *index < chars.len() && chars[*index] != ';' {
            *index += 1;
        }
        if *index < chars.len() {
            *index += 1;
        }
    };
    while index < chars.len() {
        let ch = chars[index];
        if ch == '{' || ch == '}' {
            index += 1;
            continue;
        }
        if ch != '\\' {
            out.push(ch);
            index += 1;
            continue;
        }
        let Some(&code) = chars.get(index + 1) else {
            out.push('\\');
            break;
        };
        index += 2;
        match code {
            '\\' | '{' | '}' => out.push(code),
            'P' | 'X' => out.push('\n'),
            '~' => out.push(' '),
            'L' | 'l' | 'O' | 'o' | 'K' | 'k' => {}
            'U' | 'u'
                if chars.get(index) == Some(&'+')
                    && chars.len() >= index + 5
                    && chars[index + 1..index + 5]
                        .iter()
                        .all(char::is_ascii_hexdigit) =>
            {
                let digits: String = chars[index + 1..index + 5].iter().collect();
                match u32::from_str_radix(&digits, 16)
                    .ok()
                    .and_then(char::from_u32)
                {
                    Some(decoded) => out.push(decoded),
                    None => out.push(code),
                }
                index += 5;
            }
            'S' => {
                // Stacked text: keep both parts, separated by a slash.
                while index < chars.len() && chars[index] != ';' {
                    out.push(match chars[index] {
                        '#' | '^' => '/',
                        other => other,
                    });
                    index += 1;
                }
                if index < chars.len() {
                    index += 1;
                }
            }
            'A' | 'C' | 'c' | 'F' | 'f' | 'H' | 'h' | 'Q' | 'q' | 'T' | 't' | 'W' | 'w' | 'p' => {
                skip_argument(&mut index);
            }
            other => out.push(other),
        }
    }
    out
}

pub fn decode_attrib_r14(reader: &mut BitReader<'_>, object_handle: u64) -> Result<AttribEntity> {
    decode_attrib_like_r14(reader, object_handle, false)
}

pub fn decode_attdef_r14(reader: &mut BitReader<'_>, object_handle: u64) -> Result<AttribEntity> {
    decode_attrib_like_r14(reader, object_handle, true)
}

/// R13/R14 (ODA specification 20.4.4 and 20.4.5): the TEXT fields are stored in
/// full, without the data flags of R2000, followed by the tag, the field
/// length and the flags; an ATTDEF ends with its prompt.
fn decode_attrib_like_r14(
    reader: &mut BitReader<'_>,
    object_handle: u64,
    is_attdef: bool,
) -> Result<AttribEntity> {
    let header = parse_common_entity_header_r14_with_handle(reader, object_handle)?;
    let elevation = reader.read_bd()?;
    let insertion_x = reader.read_rd(Endian::Little)?;
    let insertion_y = reader.read_rd(Endian::Little)?;
    let align_x = reader.read_rd(Endian::Little)?;
    let align_y = reader.read_rd(Endian::Little)?;
    let extrusion = reader.read_3bd()?;
    let thickness = reader.read_bd()?;
    let oblique_angle = reader.read_bd()?;
    let rotation = reader.read_bd()?;
    let height = reader.read_bd()?;
    let width_factor = reader.read_bd()?;
    let text = reader.read_tv()?;
    let generation = reader.read_bs()?;
    let horizontal_alignment = reader.read_bs()?;
    let vertical_alignment = reader.read_bs()?;
    let tag = reader.read_tv()?;
    let _field_length = reader.read_bs()?;
    let flags = reader.read_rc()?;
    let prompt = if is_attdef {
        Some(reader.read_tv()?)
    } else {
        None
    };

    reader.set_bit_pos(header.obj_size);
    let common_handles = parse_common_entity_handles(reader, &header)?;
    let style_handle = read_handle_reference(reader, header.handle).ok();

    Ok(AttribEntity {
        handle: header.handle,
        owner_handle: common_handles.owner_ref,
        color_index: header.color.index,
        true_color: header.color.true_color,
        layer_handle: common_handles.layer,
        text,
        insertion: (insertion_x, insertion_y, elevation),
        alignment: Some((align_x, align_y, elevation)),
        extrusion,
        thickness,
        oblique_angle,
        height,
        rotation,
        width_factor,
        generation,
        horizontal_alignment,
        vertical_alignment,
        style_handle,
        tag: Some(tag),
        flags,
        lock_position: false,
        prompt,
    })
}

pub fn decode_attrib(reader: &mut BitReader<'_>) -> Result<AttribEntity> {
    let header = parse_common_entity_header(reader)?;
    decode_attrib_like_with_header(reader, header, false, false, false, false, false)
}

pub fn decode_attrib_r2007(reader: &mut BitReader<'_>) -> Result<AttribEntity> {
    let header = parse_common_entity_header_r2007(reader)?;
    decode_attrib_like_with_header(reader, header, true, false, true, false, false)
}

pub fn decode_attrib_r2010(
    reader: &mut BitReader<'_>,
    object_data_end_bit: u32,
    object_handle: u64,
) -> Result<AttribEntity> {
    let mut header = parse_common_entity_header_r2010(reader, object_data_end_bit)?;
    header.handle = object_handle;
    decode_attrib_like_with_header(reader, header, true, false, true, true, false)
}

pub fn decode_attrib_r2013(
    reader: &mut BitReader<'_>,
    object_data_end_bit: u32,
    object_handle: u64,
) -> Result<AttribEntity> {
    let mut header = parse_common_entity_header_r2013(reader, object_data_end_bit)?;
    header.handle = object_handle;
    decode_attrib_like_with_header(reader, header, true, false, true, true, true)
}

pub fn decode_attdef(reader: &mut BitReader<'_>) -> Result<AttribEntity> {
    let header = parse_common_entity_header(reader)?;
    decode_attrib_like_with_header(reader, header, false, true, false, false, false)
}

pub fn decode_attdef_r2007(reader: &mut BitReader<'_>) -> Result<AttribEntity> {
    let header = parse_common_entity_header_r2007(reader)?;
    decode_attrib_like_with_header(reader, header, true, true, true, false, false)
}

pub fn decode_attdef_r2010(
    reader: &mut BitReader<'_>,
    object_data_end_bit: u32,
    object_handle: u64,
) -> Result<AttribEntity> {
    let mut header = parse_common_entity_header_r2010(reader, object_data_end_bit)?;
    header.handle = object_handle;
    decode_attrib_like_with_header(reader, header, true, true, true, true, false)
}

pub fn decode_attdef_r2013(
    reader: &mut BitReader<'_>,
    object_data_end_bit: u32,
    object_handle: u64,
) -> Result<AttribEntity> {
    let mut header = parse_common_entity_header_r2013(reader, object_data_end_bit)?;
    header.handle = object_handle;
    decode_attrib_like_with_header(reader, header, true, true, true, true, true)
}

fn decode_attrib_like_with_header(
    reader: &mut BitReader<'_>,
    header: CommonEntityHeader,
    allow_handle_decode_failure: bool,
    is_attdef: bool,
    use_unicode_text: bool,
    use_r2010_plus_tail: bool,
    r2013_plus_tail: bool,
) -> Result<AttribEntity> {
    decode_attrib_like_body(
        reader,
        header,
        allow_handle_decode_failure,
        is_attdef,
        use_unicode_text,
        use_r2010_plus_tail,
        r2013_plus_tail,
        true,
    )
}

fn decode_attrib_like_body(
    reader: &mut BitReader<'_>,
    header: CommonEntityHeader,
    allow_handle_decode_failure: bool,
    is_attdef: bool,
    use_unicode_text: bool,
    use_r2010_plus_tail: bool,
    r2013_plus_tail: bool,
    log_prefix_debug: bool,
) -> Result<AttribEntity> {
    let data_flags = reader.read_rc()?;

    let elevation = if (data_flags & 0x01) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        0.0
    };

    let insertion_x = reader.read_rd(Endian::Little)?;
    let insertion_y = reader.read_rd(Endian::Little)?;

    let alignment = if (data_flags & 0x02) == 0 {
        let align_x = reader.read_dd(insertion_x)?;
        let align_y = reader.read_dd(insertion_y)?;
        Some((align_x, align_y, elevation))
    } else {
        None
    };

    let extrusion = reader.read_be()?;
    let thickness = reader.read_bt()?;

    let oblique_angle = if (data_flags & 0x04) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        0.0
    };

    let rotation = if (data_flags & 0x08) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        0.0
    };

    let height = reader.read_rd(Endian::Little)?;

    let width_factor = if (data_flags & 0x10) == 0 {
        reader.read_rd(Endian::Little)?
    } else {
        1.0
    };

    let (text, generation, horizontal_alignment, vertical_alignment) = if use_unicode_text {
        decode_r21_text_tail(reader, data_flags)?
    } else {
        let text = reader.read_tv()?;
        let generation = if (data_flags & 0x20) == 0 {
            reader.read_bs()?
        } else {
            0
        };
        let horizontal_alignment = if (data_flags & 0x40) == 0 {
            reader.read_bs()?
        } else {
            0
        };
        let vertical_alignment = if (data_flags & 0x80) == 0 {
            reader.read_bs()?
        } else {
            0
        };
        (text, generation, horizontal_alignment, vertical_alignment)
    };

    let tail_start = reader.get_pos();
    let mut tail = AttribTailData::default();
    if use_r2010_plus_tail {
        reader.set_pos(tail_start.0, tail_start.1);
        tail = match parse_attrib_tail_data_r2010_plus_with_candidates(
            reader,
            tail_start,
            is_attdef,
            header.handle,
            r2013_plus_tail,
        ) {
            Ok(tail) => tail,
            Err(err) => {
                if log_prefix_debug && attrib_prefix_debug_enabled() {
                    eprintln!(
                        "[attrib-prefix] handle={} type={} tail_err={:?} text={:?} ins=({:.6e},{:.6e},{:.6e}) align={:?} ext=({:.6e},{:.6e},{:.6e}) h={:.6e} rot={:.6e} width={:.6e} gen={} halign={} valign={}",
                        header.handle,
                        if is_attdef { "ATTDEF" } else { "ATTRIB" },
                        err,
                        text,
                        insertion_x,
                        insertion_y,
                        elevation,
                        alignment,
                        extrusion.0,
                        extrusion.1,
                        extrusion.2,
                        height,
                        rotation,
                        width_factor,
                        generation,
                        horizontal_alignment,
                        vertical_alignment,
                    );
                }
                return Err(err);
            }
        };
    } else {
        for with_version_prefix in [false, true] {
            reader.set_pos(tail_start.0, tail_start.1);
            // The lock position flag exists from R2007 on, the versions that
            // store their text as Unicode.
            match parse_attrib_tail_data(reader, is_attdef, with_version_prefix, use_unicode_text) {
                Ok(parsed) => {
                    tail = parsed;
                    break;
                }
                Err(err)
                    if matches!(
                        err.kind,
                        ErrorKind::Format | ErrorKind::Decode | ErrorKind::Io
                    ) => {}
                Err(err) => return Err(err),
            }
        }
    }

    // Handles are stored in the handle stream at obj_size bit offset.
    reader.set_bit_pos(header.obj_size);
    let handles_pos = reader.get_pos();
    let (owner_handle, layer_handle, style_handle) =
        match parse_common_entity_handles(reader, &header) {
            Ok(common_handles) => (
                common_handles.owner_ref,
                common_handles.layer,
                read_handle_reference(reader, header.handle).ok(),
            ),
            Err(err)
                if allow_handle_decode_failure
                    && matches!(
                        err.kind,
                        ErrorKind::Format | ErrorKind::Decode | ErrorKind::Io
                    ) =>
            {
                reader.set_pos(handles_pos.0, handles_pos.1);
                let layer = parse_common_entity_layer_handle(reader, &header).unwrap_or(0);
                (None, layer, None)
            }
            Err(err) => return Err(err),
        };

    let mut final_text = text;
    let mut final_insertion = (insertion_x, insertion_y, elevation);
    let mut final_alignment = alignment;
    let mut final_extrusion = extrusion;
    let mut final_height = height;
    let mut final_rotation = rotation;
    let mut final_style_handle = style_handle;
    let mut final_owner_handle = owner_handle;
    let mut final_layer_handle = layer_handle;
    if let Some(embedded) = tail.embedded_mtext.as_ref() {
        if !embedded.text.is_empty() {
            final_text = embedded.text.clone();
        }
        final_insertion = embedded.insertion;
        final_alignment = None;
        final_extrusion = embedded.extrusion;
        if embedded.text_height.is_finite() && embedded.text_height > 0.0 {
            final_height = embedded.text_height;
        }
        if let Some(embedded_rotation) = rotation_from_x_axis_dir(embedded.x_axis_dir) {
            final_rotation = embedded_rotation;
        }
        final_style_handle = final_style_handle.or(embedded.style_handle);
        if final_owner_handle.is_none() {
            final_owner_handle = embedded.owner_handle;
        }
        if final_layer_handle == 0 && embedded.layer_handle != 0 {
            final_layer_handle = embedded.layer_handle;
        }
    }

    Ok(AttribEntity {
        handle: header.handle,
        owner_handle: final_owner_handle,
        color_index: header.color.index,
        true_color: header.color.true_color,
        layer_handle: final_layer_handle,
        text: final_text,
        insertion: final_insertion,
        alignment: final_alignment,
        extrusion: final_extrusion,
        thickness,
        oblique_angle,
        height: final_height,
        rotation: final_rotation,
        width_factor,
        generation,
        horizontal_alignment,
        vertical_alignment,
        style_handle: final_style_handle,
        tag: tail.tag,
        flags: tail.flags,
        lock_position: tail.lock_position,
        prompt: tail.prompt,
    })
}

fn attrib_prefix_debug_enabled() -> bool {
    std::env::var("EZDWG_DEBUG_ATTRIB_PREFIX")
        .ok()
        .is_some_and(|value| value != "0")
}

fn parse_attrib_tail_data_r2010_plus_with_candidates(
    reader: &mut BitReader<'_>,
    tail_start: (usize, u8),
    is_attdef: bool,
    object_handle: u64,
    r2013_plus: bool,
) -> Result<AttribTailData> {
    let start_bits = (tail_start.0 as u64)
        .saturating_mul(8)
        .saturating_add(tail_start.1 as u64);
    let deltas = r2010_plus_attrib_tail_candidate_deltas();
    let mut best: Option<(i32, BitReader<'_>, AttribTailData)> = None;
    let mut first_err: Option<DwgError> = None;

    for delta in deltas {
        let candidate_bits_i64 = i64::try_from(start_bits).unwrap_or(i64::MAX) + i64::from(delta);
        if candidate_bits_i64 < 0 {
            continue;
        }
        let Ok(candidate_bits) = u32::try_from(candidate_bits_i64) else {
            continue;
        };
        match try_parse_r2010_plus_attrib_tail_candidate(
            reader,
            candidate_bits,
            start_bits,
            is_attdef,
            object_handle,
            r2013_plus,
        ) {
            Ok(Some((score, candidate_reader, tail))) => match &best {
                Some((best_score, ..)) if score <= *best_score => {}
                _ => best = Some((score, candidate_reader, tail)),
            },
            Ok(None) => {}
            Err(err) => {
                if first_err.is_none() {
                    first_err = Some(err);
                }
            }
        }
    }

    if let Some((_score, chosen_reader, tail)) = best {
        *reader = chosen_reader;
        return Ok(tail);
    }

    Err(first_err.unwrap_or_else(|| {
        DwgError::not_implemented("R2010+ multiline ATTRIB/ATTDEF is not yet supported")
    }))
}

fn r2010_plus_attrib_tail_candidate_deltas() -> Vec<i32> {
    let mut deltas = vec![0];
    for magnitude in (4..=128).step_by(4) {
        deltas.push(magnitude);
        deltas.push(-magnitude);
    }
    for magnitude in (160..=512).step_by(16) {
        deltas.push(magnitude);
        deltas.push(-magnitude);
    }
    for magnitude in (640..=4096).step_by(64) {
        deltas.push(magnitude);
        deltas.push(-magnitude);
    }
    deltas
}

fn parse_attrib_tail_data_r2010_plus(
    reader: &mut BitReader<'_>,
    is_attdef: bool,
    object_handle: u64,
    r2013_plus: bool,
) -> Result<AttribTailData> {
    let _version = reader.read_rc()?;
    let attribute_type = reader.read_rc()?;

    if attribute_type == 1 {
        return parse_single_line_attrib_tail_data_r2010_plus(reader, is_attdef);
    }

    if !matches!(attribute_type, 2 | 4) {
        return Err(DwgError::new(
            ErrorKind::Format,
            format!("unsupported R2010+ attribute type: {attribute_type}"),
        ));
    }

    parse_multiline_attrib_tail_data_r2010_plus(reader, is_attdef, object_handle, r2013_plus)
}

fn try_parse_r2010_plus_attrib_tail_candidate<'a>(
    reader: &BitReader<'a>,
    candidate_bits: u32,
    tail_start_bits: u64,
    is_attdef: bool,
    object_handle: u64,
    r2013_plus: bool,
) -> Result<Option<(i32, BitReader<'a>, AttribTailData)>> {
    if !prefilter_r2010_plus_attrib_tail_start(reader, candidate_bits)? {
        return Ok(None);
    }

    let mut candidate_reader = reader.clone();
    candidate_reader.set_bit_pos(candidate_bits);
    let tail = parse_attrib_tail_data_r2010_plus(
        &mut candidate_reader,
        is_attdef,
        object_handle,
        r2013_plus,
    )?;

    let mut score = score_r2010_plus_attrib_tail_candidate(&tail);
    let distance = u64::from(candidate_bits).abs_diff(tail_start_bits);
    score = score.saturating_sub(i32::try_from(distance / 32).unwrap_or(i32::MAX));
    Ok(Some((score, candidate_reader, tail)))
}

fn prefilter_r2010_plus_attrib_tail_start(
    reader: &BitReader<'_>,
    candidate_bits: u32,
) -> Result<bool> {
    let mut probe = reader.clone();
    probe.set_bit_pos(candidate_bits);
    let version = probe.read_rc()?;
    if version > 32 {
        return Ok(false);
    }
    let attribute_type = probe.read_rc()?;
    Ok(matches!(attribute_type, 1 | 2 | 4))
}

fn parse_single_line_attrib_tail_data_r2010_plus(
    reader: &mut BitReader<'_>,
    is_attdef: bool,
) -> Result<AttribTailData> {
    let tag = read_r2010_plus_attrib_text(reader)?;
    let _field_length = reader.read_bs()?;
    let flags = reader.read_rc()?;
    let lock_position = reader.read_b()? != 0;
    let prompt = if is_attdef {
        Some(read_r2010_plus_attdef_prompt(reader)?)
    } else {
        None
    };

    Ok(AttribTailData {
        tag: Some(tag),
        flags,
        lock_position,
        prompt,
        embedded_mtext: None,
    })
}

fn parse_multiline_attrib_tail_data_r2010_plus(
    reader: &mut BitReader<'_>,
    is_attdef: bool,
    object_handle: u64,
    r2013_plus: bool,
) -> Result<AttribTailData> {
    let original_reader = reader.clone();
    let original_abs_bits = u64::try_from(original_reader.get_pos().0)
        .unwrap_or(u64::MAX)
        .saturating_mul(8)
        .saturating_add(u64::from(original_reader.get_pos().1));
    let mut best: Option<(i32, BitReader<'_>, AttribTailData)> = None;
    let mut first_err: Option<crate::core::error::DwgError> = None;

    for delta in [
        -64i32, -48, -32, -24, -16, -12, -8, -4, 0, 4, 8, 12, 16, 24, 32, 48, 64,
    ] {
        let candidate_bits_i64 =
            i64::try_from(original_abs_bits).unwrap_or(i64::MAX) + i64::from(delta);
        if candidate_bits_i64 < 0 {
            continue;
        }
        let Ok(candidate_bits) = u32::try_from(candidate_bits_i64) else {
            continue;
        };

        for parse_handles_inline in [true, false] {
            let mut candidate_reader = original_reader.clone();
            candidate_reader.set_bit_pos(candidate_bits);
            let embedded = match decode_embedded_mtext_r2010(
                &mut candidate_reader,
                object_handle,
                r2013_plus,
                parse_handles_inline,
            ) {
                Ok(embedded) => embedded,
                Err(err) => {
                    if first_err.is_none() {
                        first_err = Some(err);
                    }
                    continue;
                }
            };

            if !is_plausible_embedded_mtext(&embedded) {
                continue;
            }

            let mut score = score_attrib_text_candidate(&embedded.text);
            if parse_handles_inline {
                score += 6;
            }
            score = score.saturating_sub(delta.abs() / 4);
            if embedded.rect_width >= 0.0 {
                score += 1;
            }
            if (1..=9).contains(&embedded.attachment) {
                score += 2;
            }
            if embedded.drawing_dir <= 5 {
                score += 1;
            }

            let fallback_tail = AttribTailData {
                tag: None,
                flags: 0,
                lock_position: false,
                prompt: None,
                embedded_mtext: Some(embedded.clone()),
            };
            match &best {
                Some((best_score, ..)) if score - 12 <= *best_score => {}
                _ => best = Some((score - 12, candidate_reader.clone(), fallback_tail)),
            }

            let annotative_size = match candidate_reader.read_bs() {
                Ok(value) => usize::from(value),
                Err(_) => continue,
            };
            if annotative_size > 4096 {
                continue;
            }
            let mut parse_failed = false;
            for _ in 0..annotative_size {
                if candidate_reader.read_rc().is_err() {
                    parse_failed = true;
                    break;
                }
            }
            if parse_failed {
                continue;
            }

            if candidate_reader.read_h().is_err() {
                continue;
            }
            let tag_unknown = match candidate_reader.read_bs() {
                Ok(value) => value,
                Err(_) => continue,
            };
            let tag = match read_r2010_plus_attrib_text(&mut candidate_reader) {
                Ok(text) => text,
                Err(_) => continue,
            };
            let flag_unknown = match candidate_reader.read_bs() {
                Ok(value) => value,
                Err(_) => continue,
            };
            let flags = match candidate_reader.read_rc() {
                Ok(value) => value,
                Err(_) => continue,
            };
            if flags > 15 {
                continue;
            }
            let lock_position = match candidate_reader.read_b() {
                Ok(value) => value != 0,
                Err(_) => continue,
            };
            let prompt = if is_attdef {
                match read_r2010_plus_attdef_prompt(&mut candidate_reader) {
                    Ok(text) => Some(text),
                    Err(_) => continue,
                }
            } else {
                None
            };

            score += score_attrib_text_candidate(&tag);
            if let Some(prompt_text) = prompt.as_deref() {
                score += score_attrib_text_candidate(prompt_text);
            }
            if tag_unknown == 0 {
                score += 4;
            } else {
                score -= 2;
            }
            if flag_unknown == 0 {
                score += 4;
            } else {
                score -= 2;
            }
            if annotative_size == 0 {
                score += 2;
            }

            let tail = AttribTailData {
                tag: Some(tag),
                flags,
                lock_position,
                prompt,
                embedded_mtext: Some(embedded),
            };
            match &best {
                Some((best_score, ..)) if score <= *best_score => {}
                _ => best = Some((score, candidate_reader, tail)),
            }
        }
    }

    if let Some((_score, chosen_reader, tail)) = best {
        *reader = chosen_reader;
        return Ok(tail);
    }

    Err(first_err.unwrap_or_else(|| {
        DwgError::not_implemented("R2010+ multiline ATTRIB/ATTDEF is not yet supported")
    }))
}

fn is_plausible_embedded_mtext(embedded: &EmbeddedMTextData) -> bool {
    if score_attrib_text_candidate(&embedded.text) < 0 {
        return false;
    }
    if !embedded.insertion.0.is_finite()
        || !embedded.insertion.1.is_finite()
        || !embedded.insertion.2.is_finite()
    {
        return false;
    }
    if embedded.insertion.0.abs() > 1.0e6
        || embedded.insertion.1.abs() > 1.0e6
        || embedded.insertion.2.abs() > 1.0e6
    {
        return false;
    }
    embedded.text_height.is_finite()
        && embedded.text_height > 0.0
        && embedded.text_height <= 10_000.0
}

fn parse_attrib_tail_data(
    reader: &mut BitReader<'_>,
    is_attdef: bool,
    with_version_prefix: bool,
    has_lock_position: bool,
) -> Result<AttribTailData> {
    if with_version_prefix {
        let _version = reader.read_rc()?;
    }

    let tag = reader.read_tv()?;
    let _field_length = reader.read_bs()?;
    let flags = reader.read_rc()?;
    let lock_position = has_lock_position && reader.read_b()? != 0;
    let prompt = if is_attdef {
        Some(reader.read_tv()?)
    } else {
        None
    };
    Ok(AttribTailData {
        tag: Some(tag),
        flags,
        lock_position,
        prompt,
        embedded_mtext: None,
    })
}

fn read_r2010_plus_attrib_text(reader: &mut BitReader<'_>) -> Result<String> {
    let mut tv_candidate: Option<(i32, BitReader<'_>, String)> = None;
    let mut tu_candidate: Option<(i32, BitReader<'_>, String)> = None;

    {
        let mut candidate_reader = reader.clone();
        if let Ok(text) = candidate_reader.read_tv() {
            let score = score_attrib_text_candidate(&text);
            tv_candidate = Some((score, candidate_reader, text));
        }
    }

    {
        let mut candidate_reader = reader.clone();
        if let Ok(text) = candidate_reader.read_tu() {
            let score = score_attrib_text_candidate(&text).saturating_add(1);
            tu_candidate = Some((score, candidate_reader, text));
        }
    }

    if let Some((tv_score, chosen_reader, text)) = tv_candidate.as_ref() {
        let tu_better = tu_candidate
            .as_ref()
            .is_some_and(|(tu_score, ..)| *tu_score > *tv_score && *tv_score < 0);
        if !tu_better {
            *reader = chosen_reader.clone();
            return Ok(text.clone());
        }
    }

    if let Some((_score, chosen_reader, text)) = tu_candidate {
        *reader = chosen_reader;
        return Ok(text);
    }

    reader.read_tv()
}

fn read_r2010_plus_attdef_prompt(reader: &mut BitReader<'_>) -> Result<String> {
    let mut best: Option<(i32, BitReader<'_>, String)> = None;

    for with_version_prefix in [false, true] {
        let mut candidate_reader = reader.clone();
        if with_version_prefix && candidate_reader.read_rc().is_err() {
            continue;
        }
        let text = match read_r2010_plus_attrib_text(&mut candidate_reader) {
            Ok(text) => text,
            Err(_) => continue,
        };
        let mut score = score_attrib_text_candidate(&text);
        if with_version_prefix {
            score += 1;
        }
        match &best {
            Some((best_score, ..)) if score <= *best_score => {}
            _ => best = Some((score, candidate_reader, text)),
        }
    }

    if let Some((_score, chosen_reader, text)) = best {
        *reader = chosen_reader;
        return Ok(text);
    }

    read_r2010_plus_attrib_text(reader)
}

fn score_attrib_text_candidate(text: &str) -> i32 {
    if text.is_empty() {
        return -4;
    }
    let mut score = 0i32;
    for ch in text.chars() {
        score += score_attrib_text_char(ch);
    }
    score
}

/// Per-code-point score table for the BMP, built once. Candidate strings are
/// scored for every offset/layout guess, and for garbage-length TU strings
/// that means millions of characters; `char::is_alphabetic()` on non-ASCII
/// characters is a Unicode table search that dominated the profile.
static BMP_TEXT_CHAR_SCORES: std::sync::OnceLock<Vec<i8>> = std::sync::OnceLock::new();

fn score_attrib_text_char(ch: char) -> i32 {
    let code = ch as u32;
    if code < 0x1_0000 {
        let table = BMP_TEXT_CHAR_SCORES.get_or_init(|| {
            (0..0x1_0000u32)
                .map(|value| match char::from_u32(value) {
                    // Surrogate code points cannot occur in a `char`; any value works.
                    None => 0,
                    Some(ch) => score_attrib_text_char_uncached(ch) as i8,
                })
                .collect()
        });
        return table[code as usize] as i32;
    }
    score_attrib_text_char_uncached(ch)
}

fn score_attrib_text_char_uncached(ch: char) -> i32 {
    if ch == '\u{FFFD}' || ('\u{E000}'..='\u{F8FF}').contains(&ch) {
        return -8;
    }
    if ch.is_control() && !matches!(ch, '\n' | '\r' | '\t') {
        return -6;
    }
    if ch.is_ascii_alphanumeric() {
        return 3;
    }
    if ch.is_ascii_punctuation() || ch.is_ascii_whitespace() {
        return 1;
    }
    if matches!(
        ch,
        '\u{3000}'..='\u{303F}'
            | '\u{3040}'..='\u{309F}'
            | '\u{30A0}'..='\u{30FF}'
            | '\u{3400}'..='\u{4DBF}'
            | '\u{4E00}'..='\u{9FFF}'
            | '\u{FF01}'..='\u{FF60}'
            | '\u{FFE0}'..='\u{FFE6}'
    ) {
        return 3;
    }
    if ch.is_alphabetic() || ch.is_numeric() || ch.is_whitespace() {
        return 1;
    }
    -2
}

pub fn is_plausible_attrib_entity(entity: &AttribEntity) -> bool {
    score_attrib_entity_candidate(entity).is_some()
}

fn score_attrib_entity_candidate(entity: &AttribEntity) -> Option<i32> {
    let scalar_values = [
        entity.insertion.0,
        entity.insertion.1,
        entity.insertion.2,
        entity.extrusion.0,
        entity.extrusion.1,
        entity.extrusion.2,
        entity.thickness,
        entity.oblique_angle,
        entity.height,
        entity.rotation,
        entity.width_factor,
    ];
    if scalar_values
        .iter()
        .any(|value| !value.is_finite() || value.abs() > 1.0e12)
    {
        return None;
    }
    if let Some(alignment) = entity.alignment {
        let values = [alignment.0, alignment.1, alignment.2];
        if values
            .iter()
            .any(|value| !value.is_finite() || value.abs() > 1.0e12)
        {
            return None;
        }
    }
    if entity.height < 1.0e-8 || entity.height > 1.0e6 {
        return None;
    }
    if entity.width_factor <= 1.0e-8 || entity.width_factor > 1.0e4 {
        return None;
    }
    if entity.generation > 6 || entity.generation % 2 != 0 {
        return None;
    }
    if entity.horizontal_alignment > 6 || entity.vertical_alignment > 6 {
        return None;
    }
    if entity.flags > 15 {
        return None;
    }
    if !is_plausible_attrib_text(&entity.text) {
        return None;
    }
    if entity
        .tag
        .as_deref()
        .is_some_and(|tag| !is_plausible_attrib_text(tag))
    {
        return None;
    }
    if entity
        .prompt
        .as_deref()
        .is_some_and(|prompt| !is_plausible_attrib_text(prompt))
    {
        return None;
    }

    let mut score = 0i32;
    if !entity.text.is_empty() {
        score += score_attrib_text_candidate(&entity.text);
    }
    if let Some(tag) = entity.tag.as_deref() {
        score += score_attrib_text_candidate(tag);
    }
    if let Some(prompt) = entity.prompt.as_deref() {
        score += score_attrib_text_candidate(prompt);
    }
    if entity.layer_handle != 0 {
        score += 2;
    }
    if entity.style_handle.is_some() {
        score += 1;
    }
    if entity.owner_handle.is_some() {
        score += 1;
    }
    if entity.alignment.is_some() {
        score += 1;
    }
    Some(score)
}

fn is_plausible_attrib_text(text: &str) -> bool {
    if text.is_empty() {
        return true;
    }
    if text.chars().count() > 512 {
        return false;
    }
    let mut score = 0i32;
    let mut count = 0i32;
    for ch in text.chars() {
        count += 1;
        score += score_attrib_text_char(ch);
    }
    score >= -(count / 2)
}

fn score_r2010_plus_attrib_tail_candidate(tail: &AttribTailData) -> i32 {
    let mut score = 0i32;
    if let Some(embedded) = tail.embedded_mtext.as_ref() {
        score += score_attrib_text_candidate(&embedded.text);
        if embedded.text_height.is_finite() && embedded.text_height > 1.0e-6 {
            score += 4;
        }
        if embedded.layer_handle != 0 {
            score += 2;
        }
    }
    if let Some(tag) = tail.tag.as_deref() {
        score += score_attrib_text_candidate(tag);
    }
    if let Some(prompt) = tail.prompt.as_deref() {
        score += score_attrib_text_candidate(prompt);
    }
    if tail.flags <= 15 {
        score += 2;
    }
    score
}

fn rotation_from_x_axis_dir(x_axis_dir: (f64, f64, f64)) -> Option<f64> {
    if !x_axis_dir.0.is_finite() || !x_axis_dir.1.is_finite() {
        return None;
    }
    if x_axis_dir.0.abs() < 1.0e-12 && x_axis_dir.1.abs() < 1.0e-12 {
        return None;
    }
    Some(x_axis_dir.1.atan2(x_axis_dir.0))
}

#[cfg(test)]
mod tests {
    use super::{
        parse_attrib_tail_data_r2010_plus, parse_attrib_tail_data_r2010_plus_with_candidates,
    };
    use crate::bit::{BitReader, BitWriter, Endian};

    fn write_tu(writer: &mut BitWriter, text: &str) {
        writer
            .write_bs(text.encode_utf16().count() as u16)
            .expect("write tu length");
        for unit in text.encode_utf16() {
            writer
                .write_rs(Endian::Little, unit)
                .expect("write tu unit");
        }
    }

    fn write_minimal_embedded_mtext(writer: &mut BitWriter, text: &str, with_handles_inline: bool) {
        writer.write_bb(0).expect("write entity mode");
        writer.write_bl(0).expect("write reactor count");
        writer.write_b(1).expect("write xdic missing");
        writer.write_b(1).expect("write no links");
        writer.write_b(0).expect("write color unknown");
        writer.write_bd(1.0).expect("write ltype scale");
        writer.write_bb(0).expect("write ltype flags");
        writer.write_bb(0).expect("write plotstyle flags");
        writer.write_bb(0).expect("write material flags");
        writer.write_rc(0).expect("write shadow flags");
        writer.write_b(0).expect("write full visual style");
        writer.write_b(0).expect("write face visual style");
        writer.write_b(0).expect("write edge visual style");
        writer.write_bs(0).expect("write invisibility");
        writer.write_rc(0).expect("write line weight");
        writer.write_3bd(10.0, 20.0, 0.0).expect("write insertion");
        writer.write_3bd(0.0, 0.0, 1.0).expect("write extrusion");
        writer.write_3bd(1.0, 0.0, 0.0).expect("write x axis");
        writer.write_bd(0.0).expect("write rect width");
        writer.write_bd(0.0).expect("write rect height");
        writer.write_bd(2.5).expect("write text height");
        writer.write_bs(1).expect("write attachment");
        writer.write_bs(1).expect("write drawing dir");
        writer.write_bd(0.0).expect("write extents height");
        writer.write_bd(0.0).expect("write extents width");
        write_tu(writer, text);
        writer.write_bs(1).expect("write linespacing style");
        writer.write_bd(1.0).expect("write linespacing factor");
        writer.write_b(0).expect("write unknown bit");
        writer.write_bl(0).expect("write background flags");
        if with_handles_inline {
            writer.write_h(0x02, 0).expect("write owner");
            writer.write_h(0x02, 0x10).expect("write layer");
            writer.write_h(0x02, 0x20).expect("write style");
        }
    }

    #[test]
    fn parse_r2010_plus_single_line_attrib_tail() {
        let mut writer = BitWriter::new();
        writer.write_rc(0).expect("write version");
        writer.write_rc(1).expect("write attribute type");
        writer.write_tv("TAG1").expect("write tag");
        writer.write_bs(12).expect("write field length");
        writer.write_rc(8).expect("write flags");
        writer.write_b(1).expect("write lock position");
        let bytes = writer.into_bytes();

        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data_r2010_plus(&mut reader, false, 0x100, false)
            .expect("parse tail");

        assert_eq!(tail.tag.as_deref(), Some("TAG1"));
        assert_eq!(tail.flags, 8);
        assert!(tail.lock_position);
        assert_eq!(tail.prompt, None);
        assert!(tail.embedded_mtext.is_none());
    }

    #[test]
    fn parse_r2010_plus_single_line_attdef_tail() {
        let mut writer = BitWriter::new();
        writer.write_rc(0).expect("write version");
        writer.write_rc(1).expect("write attribute type");
        writer.write_tv("TAG2").expect("write tag");
        writer.write_bs(0).expect("write field length");
        writer.write_rc(2).expect("write flags");
        writer.write_b(0).expect("write lock position");
        writer.write_tv("PROMPT").expect("write prompt");
        let bytes = writer.into_bytes();

        let mut reader = BitReader::new(&bytes);
        let tail =
            parse_attrib_tail_data_r2010_plus(&mut reader, true, 0x100, false).expect("parse tail");

        assert_eq!(tail.tag.as_deref(), Some("TAG2"));
        assert_eq!(tail.flags, 2);
        assert!(!tail.lock_position);
        assert_eq!(tail.prompt.as_deref(), Some("PROMPT"));
        assert!(tail.embedded_mtext.is_none());
    }

    #[test]
    fn parse_r2010_plus_multiline_attrib_tail_reads_embedded_mtext() {
        let mut writer = BitWriter::new();
        writer.write_rc(0).expect("write version");
        writer.write_rc(2).expect("write attribute type");
        write_minimal_embedded_mtext(&mut writer, "VALUE", true);
        writer.write_bs(0).expect("write annotative size");
        writer.write_h(0x02, 0x30).expect("write regapp");
        writer.write_bs(0).expect("write tag unknown");
        writer.write_tv("TAG").expect("write tag");
        writer.write_bs(0).expect("write flag unknown");
        writer.write_rc(4).expect("write flags");
        writer.write_b(1).expect("write lock position");
        let bytes = writer.into_bytes();

        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data_r2010_plus(&mut reader, false, 0x100, false)
            .expect("multiline tail");

        assert_eq!(tail.tag.as_deref(), Some("TAG"));
        assert_eq!(tail.flags, 4);
        assert!(tail.lock_position);
        let embedded = tail.embedded_mtext.expect("embedded mtext");
        assert_eq!(embedded.text, "VALUE");
        assert_eq!(embedded.insertion, (10.0, 20.0, 0.0));
        assert_eq!(embedded.layer_handle, 0x10);
        assert_eq!(embedded.style_handle, Some(0x20));
    }

    #[test]
    fn parse_r2010_plus_multiline_attdef_tail_reads_prompt() {
        let mut writer = BitWriter::new();
        writer.write_rc(0).expect("write version");
        writer.write_rc(4).expect("write attribute type");
        write_minimal_embedded_mtext(&mut writer, "DEFAULT", true);
        writer.write_bs(0).expect("write annotative size");
        writer.write_h(0x02, 0x30).expect("write regapp");
        writer.write_bs(0).expect("write tag unknown");
        writer.write_tv("NAME").expect("write tag");
        writer.write_bs(0).expect("write flag unknown");
        writer.write_rc(2).expect("write flags");
        writer.write_b(0).expect("write lock position");
        writer.write_tv("PROMPT").expect("write prompt");
        let bytes = writer.into_bytes();

        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data_r2010_plus(&mut reader, true, 0x100, false)
            .expect("multiline attdef tail");

        assert_eq!(tail.tag.as_deref(), Some("NAME"));
        assert_eq!(tail.prompt.as_deref(), Some("PROMPT"));
        assert_eq!(tail.flags, 2);
        assert!(!tail.lock_position);
    }

    #[test]
    fn parse_r2010_plus_multiline_attrib_tail_recovers_shifted_embedded_mtext() {
        let mut writer = BitWriter::new();
        writer.write_rc(0).expect("write version");
        writer.write_rc(2).expect("write attribute type");
        writer.write_bits_msb(0b1010, 4).expect("write pad bits");
        write_minimal_embedded_mtext(&mut writer, "VALUE", true);
        let bytes = writer.into_bytes();

        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data_r2010_plus(&mut reader, false, 0x100, false)
            .expect("shifted multiline tail");

        let embedded = tail.embedded_mtext.expect("embedded mtext");
        assert_eq!(embedded.text, "VALUE");
        assert_eq!(embedded.insertion, (10.0, 20.0, 0.0));
    }

    #[test]
    fn parse_r2010_plus_tail_candidates_recover_far_shifted_multiline_attrib_tail() {
        let mut writer = BitWriter::new();
        writer.write_bits_msb(0, 64).expect("write far pad bits");
        writer.write_bits_msb(0, 32).expect("write far pad bits");
        writer.write_rc(0).expect("write version");
        writer.write_rc(2).expect("write attribute type");
        write_minimal_embedded_mtext(&mut writer, "VALUE", true);
        let bytes = writer.into_bytes();

        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data_r2010_plus_with_candidates(
            &mut reader,
            (0, 0),
            false,
            0x100,
            false,
        )
        .expect("recover far shifted multiline tail");

        let embedded = tail.embedded_mtext.expect("embedded mtext");
        assert_eq!(embedded.text, "VALUE");
        assert_eq!(embedded.insertion, (10.0, 20.0, 0.0));
    }
}

#[cfg(test)]
mod layout_tests {
    use super::{mtext_plain_text, parse_attrib_tail_data};
    use crate::bit::{BitReader, BitWriter};

    #[test]
    fn mtext_plain_text_drops_formatting_and_keeps_paragraphs() {
        assert_eq!(mtext_plain_text("first\\Psecond"), "first\nsecond");
        assert_eq!(
            mtext_plain_text("{\\fArial|b0|i0;\\H2.5;bold} \\C1;red\\~x"),
            "bold red x"
        );
        assert_eq!(
            mtext_plain_text("\\S1#2; \\U+00B0 \\\\ \\{a\\}"),
            "1/2 \u{b0} \\ {a}"
        );
        assert_eq!(mtext_plain_text("C:\\Users"), "C:Users");
        assert_eq!(mtext_plain_text("plain"), "plain");
    }

    fn attdef_tail(with_lock_position: bool) -> Vec<u8> {
        let mut writer = BitWriter::new();
        writer.write_tv("PART_NO").expect("write tag");
        writer.write_bs(0).expect("write field length");
        writer.write_rc(2).expect("write flags");
        if with_lock_position {
            writer.write_b(1).expect("write lock position");
        }
        writer.write_tv("Part number?").expect("write prompt");
        writer.into_bytes()
    }

    #[test]
    fn attdef_tail_before_r2007_has_no_lock_position_bit() {
        // R2000/R2004: tag, field length, flags, prompt. Reading a lock bit that
        // is not there shifts the prompt by one bit.
        let bytes = attdef_tail(false);
        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data(&mut reader, true, false, false).expect("parse tail");
        assert_eq!(tail.tag.as_deref(), Some("PART_NO"));
        assert_eq!(tail.flags, 2);
        assert!(!tail.lock_position);
        assert_eq!(tail.prompt.as_deref(), Some("Part number?"));

        let bytes = attdef_tail(true);
        let mut reader = BitReader::new(&bytes);
        let tail = parse_attrib_tail_data(&mut reader, true, false, true).expect("parse tail");
        assert!(tail.lock_position);
        assert_eq!(tail.prompt.as_deref(), Some("Part number?"));
    }
}

#[cfg(test)]
mod score_table_tests {
    use super::{score_attrib_text_char, score_attrib_text_char_uncached};

    #[test]
    fn cached_scores_match_uncached_for_every_bmp_char() {
        for value in 0..0x1_0000u32 {
            let Some(ch) = char::from_u32(value) else {
                continue;
            };
            assert_eq!(
                score_attrib_text_char(ch),
                score_attrib_text_char_uncached(ch),
                "U+{value:04X}"
            );
        }
        assert_eq!(
            score_attrib_text_char('\u{1F600}'),
            score_attrib_text_char_uncached('\u{1F600}')
        );
    }
}