Skip to content

fix(entities): MTEXT and friends read their TV fields from the R2007+ string stream - #28

Merged
DrunkOnJava merged 3 commits into
mainfrom
fix/mtext-string-stream
Aug 30, 2026
Merged

DrunkOnJava merged 3 commits into
mainfrom
fix/mtext-string-stream

Conversation

@DrunkOnJava

@DrunkOnJava DrunkOnJava commented Aug 30, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #27 (fix/r2004-header-and-mtext). Review that one first; this branch's base will become main once it merges. The diff below is this branch's own commit only.

Summary

MTEXT (0x2C) read its TV from the data cursor. On R2007+ that position holds the next data field, so MTEXT never errored — it returned "ѕ", a single UTF-16 code unit built from whatever two bytes followed extents_width, for every record in the file. Silent wrong is worse than an error: the coverage report counted all 33 records as decoded.

This ports MTEXT to the split-stream layout, audits every other TV-bearing decoder for the same failure mode, fixes the cheap ones (TOLERANCE, HATCH, the DIMENSION family), and fixes #26 in the same area.

Spec reference

§19.1 split streams / §19.4.44 MTEXT. src/entities/mtext.rs gains decode_modern_split_stream, wired into dispatch_split_stream_entity alongside the #23 ports.

Self-validating: MTEXT's string stream holds exactly one TV

text is MTEXT's only variable-text field, so its string stream must contain one string and nothing else. Measured across all 22 MTEXT records in sample_AC1032.dwg's main object stream, the stream length equals that string's encoded length to the bit, with no padding:

Text Encoded Stream length
"Text" 74 bits 74
"Table sample" 202 202
"Sample annotation" 282 282
"this is a Mtext\nwith multiple lines in it" 666 666
the 3,436-character MTEXT 54,978 54,978

So the decoder requires (a) the data fields not to run past the string-stream start bit and (b) the reader to be exhausted after one read_tv. Either failing is an error, not a plausible-looking string.

Measured: background_scale_factor is a BD, not a BL

Handle 0x6D8 (text "\A1;7.0711") is the one record in the corpus with the background bit set. Reading the field as a BL leaves the following CMC on a 16-bit code yielding colour index 768 and then a reserved 11 pattern; reading a BD recovers 1.25 (bytes 00 00 00 00 00 00 F4 3F at bit 559) and the record decodes.

Not decoded: the R2018 MTEXT tail (documented, not guessed)

The fields this decoder understands end 567 bits short of the string stream on the first MTEXT of sample_AC1032.dwg (data fields end at bit 480, string stream starts at 1047). Scanning that gap for the doubles already read shows the record repeats them, each as a BD with the two-bit 00 full-double prefix:

Value Bit
insertion.x 493
insertion.y 559
rect_width 627
extents_width 695
extents_height 761
rect_width again 847

That is consistent with the R2018 annotative / column block restating the geometry, but the field boundaries between the repeats are not established from bytes, so per CONTRIBUTING.md the offsets are documented and the decoder asserts the weaker <= string_start bound instead of guessing. examples/probe_mtext_fields.rs reproduces it.

Verification on sample_AC1032.dwg — a sample of what MTEXT now returns (was "ѕ" for all of them):

[247] MTEXT insertion=(183.589,5.226,0.000) rect_width=15.741 text="this is a Mtext\nwith multiple lines in it"
[281] MTEXT insertion=(741.024,14.697,0.000) rect_width=0.000  text="Sample annotation"
[327] MTEXT insertion=(51.297,-32.956,0.000) rect_width=102.526 text="This table will be imported as an           Insert entity"
[389] MTEXT insertion=(626.674,27.908,0.000) rect_width=0.000  text="∅45,6"
[412] MTEXT insertion=(390.757,33.668,0.000) rect_width=0.000  text="4'-0{\H1x;\S1#4;}\""
[470] MTEXT insertion=(183.589,-1.386,0.000) rect_width=15.741 text="this is a really long Mtext\nbla bla bla …"  (3,436 chars)

The TV-field audit

examples/audit_string_streams.rs (new) walks every object in a file, locates its string stream and prints the strings it holds. A type whose records carry strings there but whose decoder reads TV from the data cursor is silently wrong on that file, and the printed strings are what it should have returned. Census on sample_AC1032.dwg:

Type Records / with stream / strings Decoder status Evidence
TEXT 0x01 25 / 25 / 25 already correct (#23) returns "Hello this is a single line text"
ATTRIB 0x02 4 / 4 / 9 already correct (#23) tag="ATTINFO" value="17"
ATTDEF 0x03 5 / 5 / 16 already correct (#23) — prompt included tag="ATTINFO" prompt="Enter number:"
BLOCK 0x04 22 / 22 / 22 already correct — by accident The name is BLOCK's only field, so the data cursor after the common entity preamble already sits on the string-stream start bit and the inline TV read lands on the string stream. Names decode as *Model_Space, _ArchTick, *D3. Not a counter-example to the split layout; noted in ARCHITECTURE.md §7c.
MTEXT 0x2C 34 / 33 / 33 FIXED here see above
TOLERANCE 0x2E 3 / 3 / 3 FIXED here, fully self-validating 3 errors → 0; recovers {\Fgdt;j}%%v{\Fgdt;n}%%v…, 99\na, {\Fgdt;p}
DIMENSION 0x14–0x1A 11 / 10 / 11 FIXED here (partial) user_text from the stream keeps every later field aligned; 10 errors → 2
HATCH 0x4E 5 / 4 / 8 FIXED here (partial) — pattern + gradient names still 5 errors: the boundary-path tree reads handles from the data stream, a separate bug
INSERT 0x07 9 / 0 / 0 N/A — no TV at all; the block name comes through a handle still 3 errors, unrelated to text
LEADER 0x2D 1 / 0 / 0 N/A — no TV
ENDBLK 0x05, SEQEND 0x06, LINE, CIRCLE, ARC, POINT, LWPOLYLINE, SPLINE, SOLID, ELLIPSE, RAY, XLINE, MLINE, 3DFACE 0 streams N/A — no TV fields
XRECORD 0x4F 27 / 0 / 0 N/A — XRECORD stores its data as raw typed bytes, not TV; also never dispatched
UNDERLAY / IMAGE 0 streams N/A — the path lives in the definition object, not the entity
MLEADER (class 526) 10 / 10 / 10 still wrong — mtext_default_text read inline strings are MLeader text, hello!, MULTILEADER TEST, MULTILEADER\PTEST\P123. Not cheap: MLEADER also reads three H handles from the data stream, which on R2007+ live in the handle stream, so the record is misaligned before the TV.
IMAGEDEF (class 528) 1 / 1 / 1 still wrong — file_path read inline string is .\image.JPG. Not reachable from decode_from_raw (custom classes dispatch IMAGE, not IMAGEDEF), so it is only wrong through the direct public API.
DICTIONARY 0x2A 65 / 52 / 174 still wrong — keys read inline ACAD_COLOR, ACAD_CIP_PREVIOUS_PRODUCT_INFO, … Not reachable from decode_from_raw (non-entity, non-table → Unhandled); wrong only through crate::objects::dictionary::decode.
LAYOUT 0x52 4 / 4 / 20 still wrong — same, direct-API only ANSI_A_(8.50_x_11.00_Inches), none_device
GROUP 0x48, MLINESTYLE 0x49, MATERIAL / VISUALSTYLE / SCALE / PLOTSETTINGS / PROPERTYSET (custom classes) streams present still wrong — same, direct-API only e.g. STANDARD, 1:1, Flat, strokes_ogs.tif
LIGHT not in this corpus still wrong, and worse: its private read_tv ignores the version entirely and always reads 8-bit bytes, so it is wrong on R2007+ even before the split-stream question code inspection, src/entities/light.rs:139
GEODATA not in this corpus still wrong — five inline TV reads code inspection
Symbol tables (LAYER, LTYPE, STYLE, VIEW, UCS, VPORT, APPID, DIMSTYLE, BLOCK_HEADER) streams present already correct (#23) names decode; each asserts exact string-stream alignment

Fixed in this PR: MTEXT, TOLERANCE, DIMENSION, HATCH. Left for follow-ups, listed with evidence above: MLEADER, IMAGEDEF, LIGHT, GEODATA, and the non-entity object decoders (DICTIONARY, LAYOUT, GROUP, MLINESTYLE, MATERIAL, VISUALSTYLE, SCALE, PLOTSETTINGS, PROPERTYSET).

Structural finding: a record with no string stream still has its TV slots

Some R2007+ records have the strings present trailer bit clear. Their TV slots still exist in the field table and still consume no data-stream bits, so falling back to an inline read there shifts every following field. StringReader::empty gives those records a reader that yields "", and modern::open_entity returns it with the handle-stream start as the bound. That alone removed two errors (one HATCH, one DIMENSION).

#26 — Layer::is_locked tested the wrong bit

The DWG values word (§20.4.53) is not the DXF group-70 flag word. DXF puts locked at 0x04; DWG puts frozen in new viewports there and locked at 0x08. So is_locked reported every layer frozen-in-new-viewports as locked, and every genuinely locked layer as unlocked.

  • is_locked now tests 0x08 (LAYER_VALUE_LOCKED).
  • New is_frozen_in_new_viewports tests 0x04 (LAYER_VALUE_FROZEN_IN_NEW) so the bit is not lost.
  • is_frozen and is_locked now use the named constants rather than repeating literals.
  • The decode_modern_split_stream doc comment that recorded the bug is updated.
  • The existing layer_with_flags test now writes 0x0D (frozen + frozen-in-new-viewports + locked) and asserts all three; a new frozen_in_new_viewports_is_not_locked test pins that 0x04 alone is not locked.

Measured coverage — before / after

cargo run --release --example coverage_report -- <samples> over the 19-file corpus. "Before" is the state after #27 (this branch's base).

Version Files Before (dec / err / rate) After (dec / err / rate)
R14 / R2000 / R2007 9 n/a (no handle map) n/a (no handle map)
R2004 (AC1018) 3 75 / 0 / 12.6 % 75 / 0 / 12.6 %
R2010 (AC1024) 3 69 / 0 / 12.7 % 69 / 0 / 12.7 %
R2013 (AC1027) 3 69 / 0 / 17.4 % 69 / 0 / 17.4 %
R2018 (AC1032) 1 374 / 34 / 50.2 % 384 / 24 / 51.5 %
Aggregate 19 587 / 34 / 25.7 % 597 / 24 / 26.2 %

Error histogram on sample_AC1032.dwg, before → after:

Type Before After
DIMENSION family (0x14–0x1A) 10 2
TOLERANCE 0x2E 3 0
HATCH 0x4E 5 5
MTEXT 0x2C 1 1 (a 25 KB record whose graphics block consumes the payload — pre-existing, unchanged)
LTYPE 0x39 3 3
INSERT 0x07 3 3
others 9 10

Note the MTEXT count is unchanged at 1 because the previously "decoded" records were silently wrong, not erroring — the win is 33 records of real text, not a count change.

Test plan

  • cargo fmt --all -- --check
  • cargo clippy --all-targets --all-features -- -D warnings
  • cargo test --release — 669 lib tests (was 666; +3) + all integration suites
  • cargo deny check all
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features
  • cargo +1.85.0 test --no-run (MSRV, no let-chains)
  • Coverage-report numbers attached above

New tests:

  • entities::mtext::tests::r2018_split_stream_mtext_reads_text_from_string_stream — a BitWriter-built R2018 payload (common entity preamble + §19.4.44 field body + string stream + trailer) read back through decode_modern_split_stream, asserting the text and every geometry field.
  • entities::mtext::tests::r2018_split_stream_mtext_rejects_a_short_body — a truncated field list must error rather than return a plausible string.
  • tables::layer::tests::frozen_in_new_viewports_is_not_locked — Layer::is_locked tests bit 0x04, but the LAYER values word puts locked at 0x08 (0x04 is frozen-in-new-viewports) #26's regression pin.

tests/canonical_corpus.rs value pins and the synthetic fixtures are untouched by this branch.

Source-provenance declaration

By submitting this PR I certify that my contribution does not incorporate executable code from any source whose license is incompatible with Apache-2.0. Specifically:

  • No Autodesk DWG SDK source (RealDWG, ObjectARX, ObjectDBX) or NDA-protected Autodesk documentation was consulted or imported.
  • No Open Design Alliance Teigha / Drawings SDK source was consulted or imported.
  • No GPL-licensed DWG implementation source (LibreDWG, etc.) was consulted or imported.

This contribution is based on the ODA's freely-redistributable Open Design Specification for .dwg files (v5.4.1) and on first-party byte inspection of publicly-available sample DWG files, reproduced by the two probes under examples/. No permissively-licensed third-party comments were consulted, so no CLEANROOM.md disclosure entry is needed.

Closes #25
Closes #26


Note

Medium Risk
Changes bit-level entity decoding and public Layer flag semantics on real R2007+ files; misalignment checks reduce silent garbage but wrong field layouts could still surface as new errors rather than wrong values.

Overview
Fixes silent wrong text on R2007+ where decoders still read TV from the data stream instead of the per-object string stream (ODA §19.1). MTEXT previously returned a one-character garbage string for every record without erroring; it now uses decode_modern_split_stream, validates a single exhausted TV in the string stream, and treats background_scale_factor as BD (not BL).

TOLERANCE, HATCH (pattern + gradient names), and the DIMENSION family (user_text) follow the same split-stream path via modern::read_tv_field and new decode_modern_split_stream entry points, wired from dispatch_split_stream_entity. Shared plumbing adds StringReader::empty and open_entity handling when the strings-present bit is clear (TV slots exist but consume no data bits).

Also fixes #26: Layer::is_locked now tests DWG bit 0x08 (not DXF-aligned 0x04); adds is_frozen_in_new_viewports for 0x04.

Adds examples/audit_string_streams.rs and probe_mtext_fields.rs; docs and coverage stats move to 597/24/26.2% aggregate (384/24/51.5% on R2018).

Reviewed by Cursor Bugbot for commit eac228d. Configure here.

…y common object data

ODA v5.4.1 §19.1 puts an `RL` "object data size in bits" between the
object type and the object handle for the whole R2000..R2007 band;
R2010+ replaces it with the leading `MC` handle-stream size. The reader
consumed it for R2000 alone, leaving every AC1018 record 32 bits out of
phase from the handle onwards — ~20 `Bit cursor exhausted` errors per
R2004 sample.

Also read the §19.4.2 common object data (EED chain, `BL` reactor count,
xdictionary flag) before the pre-R2007 symbol-table decoders, which
started at the entry name with the cursor still on the EED chain; fix
the legacy STYLE decoder's `RC`-for-two-`B`-bits overread; and give the
legacy VPORT decoder the same field table as the already-verified
R2007+ split-stream decoder.

samples/ corpus: R2004 15 decoded / 60 errored / 2.5% -> 75 / 0 / 12.6%;
aggregate 527 / 94 / 23.1% -> 587 / 34 / 25.7%. All remaining errors are
in the single R2018 sample.

Closes #24
…he R2007+ string stream

MTEXT decoded silently wrong on R2007+ — it read its TV from the data
cursor, which at that position holds the next data field, so it returned
a one-character garbage string for every record and never errored. It
now reads through the object's string stream. Its only TV is the text,
so the stream must hold exactly one string and nothing else; that makes
"the reader is exhausted after one read_tv" a self-validating check,
measured exact across all 22 MTEXT records of sample_AC1032.dwg.

TOLERANCE gets the same port and is fully self-validating (its text is
the last data field, so the fields must end exactly on the string-stream
start bit); the measurement also shows its BS unknown_short / BD height /
BD dimgap fields are absent on R2018. DIMENSION and HATCH take their TV
fields from the string stream so every field after them keeps alignment.
StringReader::empty covers records whose "strings present" bit is clear.

Layer::is_locked tested 0x04, which is frozen-in-new-viewports in the DWG
values word; locked is 0x08. Adds is_frozen_in_new_viewports.

samples/ corpus: R2018 374 decoded / 34 errored / 50.2% -> 384 / 24 /
51.5%; aggregate 587 / 34 / 25.7% -> 597 / 24 / 26.2%.

Closes #25
Closes #26
@cursor

cursor Bot commented Aug 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_ff900666-66c5-4924-a6f3-736b6d0ca46f)

# Conflicts:
#	ARCHITECTURE.md
#	CHANGELOG.md
#	README.md
#	STATUS.md
@cursor

cursor Bot commented Aug 30, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_92cd039e-51e8-49f2-9aa6-61073a250558)

@DrunkOnJava
DrunkOnJava merged commit 52ed80f into main Aug 30, 2026
20 checks passed
@DrunkOnJava
DrunkOnJava deleted the fix/mtext-string-stream branch August 30, 2026 15:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant