diagram_io/src/textdraw.rs#
Source: lib/diagram_io/src/textdraw.rs
textdraw -- (JD18, IM-08) a connected drawing from a text file: records of the types "Shape"
and "Link" (Visio's text import filter; Visio 5.0 user guide, chapter 21, on connected
drawings from text files) read into a plan, which then becomes shapes and dynamic connectors
on a page
parse(text, &Options, &Limits) -> Plan the records: shapes (ID, master, text, position,
size, shape data), links (ID, master, text, from, to), the master names
they use, the problems with their line numbers; it never fails (a
record it cannot use is a problem and left out)
detect_sep(text, fallback) the field separator the records use
layout(&sizes, &edges, gap) -> centres the automatic arrangement of the shapes without a
position (top to bottom in layers, see below)
apply(tx, eng, page, &plan, &masters, &Build) -> Built the plan on a page inside the
caller's transaction: instances of the chosen masters (else plain
rectangles), text, size, shape data, laid out; the links as dynamic
connectors (or instances of a chosen 1-D master) glued to the whole
shapes and routed. The caller takes stencil masters into the document
first (instance::import_master) and passes one master (or None) per
Plan::masters entry.
The format as the guide describes it, and what is decided here where it says nothing:
* One record per line (CR, LF or CR LF ends it); the first field names the record type,
"Shape" or "Link" (any case). Another type is a warning and the line is left out.
* Fields are separated by a comma (the guide: the default of .csv files), a tab (.txt files)
or -- decided here, the CSV of a German Excel -- a semicolon. The separator is the one an
Excel first line "sep=X" names (the line is no record), else the character right after the
type word of the first record or field heading (";Shape,ID,..."), else the caller's fallback
(the file's extension).
* A field in double quotes is text as it stands: separators, line breaks (kept as paragraph
breaks, '\n') and doubled quotes ("" for ") inside; an unquoted field is trimmed of spaces.
A quote left open at the end of the file is an error and its record is left out.
* A line that starts with a semicolon (spaces before it allowed) is a comment. Decided here:
a comment that lists the field headings of Shape records (";Shape,ID,Master,Text,X,Y,Width,
Height,Cost,Owner") names the shape data fields of the records after it by the headings
past Height (a heading "Property" names nothing).
* Shape: ID, Master, Text, X, Y, Width, Height, then shape data fields. Link: ID, Master,
Text, From, To (the IDs of two shapes; further fields are ignored). Empty fields are
allowed (the guide's example leaves Master and the link IDs empty).
* IDs are compared trimmed and without regard to ASCII case. A shape without an ID is drawn
but cannot be linked (a warning); a second shape with the same ID is an error and left out;
a link whose end is missing or names no shape is an error, a link from a shape to itself as
well (both left out); two links with the same ID only a warning.
* Masters are named by the master's name (NameU or the name in any language; the caller maps
each name to a master of its stencils or of the document). An empty master is the default:
a plain rectangle for a shape, the dynamic connector for a link. A chosen master that does
not fit (a 1-D master for shapes, a 2-D one for links) is replaced by the default
(Built::unfit names it).
* Numbers (X, Y, Width, Height) are in the unit the caller gives (Options::per_number, drawing
inches per number: the guide says nothing about units; the wizard asks), or carry their own
unit: "25 mm", "2.5cm", "1 m", "1.5 in", "1.5\"", "2 ft", "36 pt". A decimal comma is
taken when there is no point ("2,5"). X and Y are the middle of the shape (its pin for
nearly every master) in page coordinates as Visio has them: from the page's bottom left
corner, y up. A number that does not read, X without Y and the like are warnings: the
record is drawn without that value. Lengths beyond 100 000 inches and sizes <= 0 are
refused. Width and Height replace the master's size (around the same middle).
* A shape data field "Name=Value" sets field Name (Name: letters, digits, spaces, '_', '-',
'.' only, at most 64 characters, else the whole field is the value); otherwise the field's
heading names it, else "Property1", "Property2" ... by its place. An empty field sets
nothing. A value of the form -12 / 12.5 / 12,5 (no leading zeros) becomes a number (Type 2),
everything else text. A field the shape has already (by name or by label, any case) gets
the value; otherwise a new Property row (its name made of letters, digits and '_').
The automatic layout (layout()), for the shapes without X and Y: each connected group of shapes
(the links between them) is laid out in layers from top to bottom -- the guide's example, an
organisation chart, comes out as its picture shows. Cycles are broken where a depth-first walk
meets a shape on its own path; a shape's layer is one below the lowest layer of the shapes
linking to it (longest path), a shape that no link reaches sits right above its highest
successor; the order within a layer starts as the file's order, then follows the mean place of
the neighbours (barycentre sweeps down and up); the x places are where the neighbours want
them, the overlaps taken out with the least movement (isotonic regression: order kept, the gap
between neighbours), in alternating passes up and down, so children centre under their parents
and parents over their children. The groups (and single shapes) are then packed left to right
in rows no wider than about 1.5 times the square root of their total area (a grid for shapes
without links). The whole block starts at the page's top left corner (Build::margin inside
it); when it would cover the page's earlier shapes or the shapes placed by X and Y there, it
starts right of all of them.
Every text is untrusted input: its size, the number of records, of fields per record, of shape
data fields per shape, the length of each field and of an ID and the number of problems are
bounded (Limits); the walks of the layout use explicit stacks (no recursion over the file).
struct Optionshow to read the numbers and the fieldssep: Option<char>-- the field separator; None: detected (detect_sep), elsefallback_sepfallback_sep: char-- the separator when none is detected (',' for .csv, '\t' for .txt)per_number: f64-- drawing inches per number without a unit (1/25.4: the numbers are millimetres)
struct Limitsthe bounds of a text (untrusted input)max_bytes: usize-- the text's size in bytesmax_records: usize-- Shape and Link records togethermax_fields: usize-- fields of one record (more are left out)max_field_chars: usize-- characters of one field (more are cut)max_id_chars: usize-- characters of an ID (a longer one is an error)max_props: usize-- shape data fields of one shapemax_problems: usize-- problems kept (then one TooManyProblems)
impl Limits
const DEFAULT: Limits = Limits { max_bytes: 16 << 20, max_records: 10_000, max_fi ...what the app reads: 16 MiB, 10 000 records, 1 000 fields of up to 32 768 charactersstruct Propa shape data field of a shape recordname: String-- the row's name (Prop.<name>): letters, digits, '_'label: String-- the label as the file names itvalue: String-- the value as written
struct ShapeReca Shape recordline: u32-- the line it starts on (from 1)id: String-- its ID (empty: none, it cannot be linked)master: usize-- index into Plan::masterstext: String-- the text ('\n' between paragraphs)pos: Option<[f64; 2]>-- X and Y: the middle (drawing inches, y up; None: laid out)size: [Option<f64>; 2]-- Width and Height (drawing inches; None: the master's or the default)props: Vec<Prop>-- shape data
struct LinkReca Link recordline: u32-- the line it starts on (from 1)id: String-- its ID (may be empty)master: usize-- index into Plan::masterstext: String-- the connector's textfrom: usize-- the shapes it connects (indices into Plan::shapes)to: usize
struct MasterUsea master name as the records use it: one entry per name and kind of recordname: String-- the name as first written ("" for the default)link: bool-- used by Link records (a 1-D master is wanted), else by Shape recordscount: usize-- how many records use it
enum NumFielda number field of a Shape recordXYWidthHeight
enum Issuewhat is wrong with a record or the textTooBig-- the text is larger than Limits::max_bytes: nothing readTooManyRecords-- more records than Limits::max_records: the rest is left outTooManyProblems-- more problems than Limits::max_problems: the rest is not listedUnknownRecord(String)-- a record type other than Shape and Link (the type as written, cut to 40 characters)UnclosedQuote-- a quote left open at the end of the textTooManyFields-- more fields than Limits::max_fields (the rest left out)FieldTooLong-- a field longer than Limits::max_field_chars (cut)IdTooLong-- an ID longer than Limits::max_id_charsNoId-- a shape without an ID (drawn, but no link can reach it)DuplicateId(String)-- a second shape with this IDDuplicateLinkId(String)-- a second link with this ID (kept)NoEnd-- a link without From or ToUnknownEnd(String)-- a link to an ID no shape hasSelfLink(String)-- a link from a shape to itselfBadNumber(NumField, String)-- a number field that does not read (the field, the text)OutOfRange(NumField, String)-- a number out of range (beyond 100 000 inches, a size <= 0)HalfPosition-- X without Y or Y without X: laid out insteadTooManyProps-- more shape data fields than Limits::max_props (the rest left out)
struct Problema problem of the text, at its lineline: u32-- the line (from 1; 0: the whole text)issue: Issueskipped: bool-- the record was left out (an error), else only a warning
struct Planwhat a text sayssep: char-- the separator usedsep_detected: bool-- it was detected from the records (not the fallback, not given)shapes: Vec<ShapeRec>links: Vec<LinkRec>masters: Vec<MasterUse>-- the master names the records use, shapes' first, each in the order it first appearsproblems: Vec<Problem>comments: usize-- comment lines
impl Plan
fn errors(&self) -> usizethe problems that left a record outfn warnings(&self) -> usizethe problems that did notfn detect_sep(text: &str, fallback: char) -> (char, bool)the separator of the records: Excel's first line "sep=X", else the character right after "Shape" or "Link" in the first record or comment heading that has ',', a tab or ';' there -> (it, detected); else (fallback, false)fn length(s: &str, per_number: f64) -> Option<f64>a length "number [unit]" -> drawing inches (per_numberinches per number without a unit; None: no number, an unknown unit)fn plain_number(s: &str) -> Option<f64>a shape data value that is a number: -12, 12.5, 12,5 (no leading zeros, no exponent, no plus sign: "0049", "+49" and "1e3" stay text)fn row_name(s: &str) -> Stringa name as a shape data row name: letters, digits and '_', not starting with a digitfn parse(text: &str, opts: &Options, lim: &Limits) -> Planread a text (see the file header) -> the plan; never failsfn layout(sizes: &[[f64; 2]], edges: &[(usize, usize)], gap: [f64; 2]) -> Vec<[f64; 2]>the arrangement of shapes ofsizes(width, height) linked byedges(from, to; indices into sizes): their middles, x to the right and y down from the block's top left corner (see the file header);gap: the space across and down between shapesstruct Buildhow apply builds (lengths in drawing inches)lang: usize-- the language of new instances' names (instance::LANGS)default_size: [f64; 2]-- a plain rectangle's size when the record gives nonegap: [f64; 2]-- the space between laid-out shapes: across, downmargin: f64-- the laid-out block's distance from the page's top left corner
struct Builtwhat apply builtshapes: Vec<ShapeRef>-- the shape of each Plan::shapes entryconnectors: Vec<ShapeRef>-- the connector of each Plan::links entryunfit: Vec<usize>-- the Plan::masters entries whose master did not fit (a 1-D master for shapes, a 2-D one for links): drawn as the default insteadbounds: Option<[f64; 4]>-- the box of all of it on the page (x0, y0, x1, y1; None: nothing built)
fn apply(tx: &mut Transaction, eng: &mut Engine, page: PageRef, plan: &Plan, masters: &[Option<MasterRef>], opts: &Build) -> Result<Built, EditError>build the plan on pagepageinside the caller's transaction (see the file header):masters[k]is the master (of tx's document) for Plan::masters[k], None or missing: the default (a plain rectangle, the dynamic connector) -> what was built