diagram_view#
draws diagram pages (the display list of diagram_core) on render2d and gfx -- crate root lib/diagram_view/src/lib.rs
diagram_view -- draws diagram pages (the display list of diagram_core) on render2d and gfx
FontSet / Class / FontSource the fonts texts are drawn with (the app hands them over:
its style's fonts, installed ones); missing families are
substituted by class with a width factor (TX-09)
PageView::new(&doc, page, &mut fonts, &opts) a page as a render2d scene (made without a
device) plus gradients and pictures
view.update(&doc, &mut fonts, &shapes) -> Option<[f64; 4]> (JD7) edited shapes made anew
in the list and the scene, the box of what changed
view.draw(dc, sf, r, &cam) on the CPU: render2d's CPU path, gfx in between
view.render(w, h) -> Surface the whole page as an XRGB image (tests, exports, thumbnails)
view.fit(size, margin) -> Camera
image::{bytes, decode, base64} Foreign shapes' pictures: PNG and JPEG decoded, EMF / WMF
and the rest as placeholders
export::{pdf, svg, raster} (JD12) pages as PDF (lib/pdf), SVG, PNG and JPEG
Metrics::new(&fonts) (JD7) the formula engine's TextMetrics (TEXTWIDTH,
TEXTHEIGHT) measured as the page views draw
Why a crate of its own (JD4): diagram_core holds the model and the display list without any
dependency, so that diagram_io's exports (SVG, PDF, JD12) and JD7's hit tests use the same
list; drawing it needs render2d (and through it the GPU layer), gfx and the image codecs,
which neither the model nor the file formats should pull in. ui knows nothing of diagrams:
the app connects a PageView to its canvas (ui.diagram's DgPaint, or a ui.gpu_view later).
What render2d's scene cannot hold -- gradient fills and pictures -- is drawn by gfx between
two of the scene's layers on the CPU path; a scene attached to a GPU (Scene::attach) shows
everything else. Coordinates: paper inches, y up, the origin at the page's bottom left
corner (render2d's camera has y up too).
diagram_view/src/export/mod.rs#
Source: lib/diagram_view/src/export/mod.rs
export -- the pages of a diagram as files (JD12: EX-01 PDF, EX-03 SVG, EX-04 PNG, EX-05 JPEG)
pages(doc, &Pages) -> Vec<PageRef> which pages: the one shown, every foreground page, a
range of them (from 1), a list
page_name(doc, page) -> String Name, else NameU, else its number among the pages
links(doc, drawing) -> Vec<Link> the shapes' hyperlinks with their boxes on the page
pdf::write(doc, fonts, &PdfOptions) a vector PDF: a PDF page per page in its size, text
as text in embedded subsets, links, a bookmark per page
pdf::Sheets drawings placed on sheets of paper (printing: tiles,
margins, scaling) through the same drawing code
svg::write(doc, drawing, &SvgOptions) one page as SVG: paths, text, pictures, gradients,
hatches, links
raster::render(view, &RasterOptions) a page (or a part of it) at a resolution, on a colour
or transparent; raster::png / raster::jpeg encode it
Why here and not in diagram_io: a page is exported as the screen shows it, so the texts must
be measured with the fonts they are drawn with (PageView builds the display list with this
crate's FontSet and render2d's text layout), the PDF must embed the very faces the screen
uses (FontSet's substitution, TX-09), and PNG / JPEG are this crate's renderer. diagram_io
stays the file format crate without render2d; lib/pdf adds no crate this one did not pull in
already (gfx, img_core, text_shape).
Every export reads the display list (diagram_core::render::Drawing: paper inches, y up, the
origin at the page's bottom left corner). PDF and SVG write it in points (1/72 inch); SVG
with y down (its own convention), PDF with y up. Text runs keep the width the layout
measured: the PDF scales each run horizontally to it, the SVG gives textLength.
enum Pageswhich pages an export takesCurrent(PageRef)-- one page (the one shown; may be a background page)All-- every foreground page in the document's orderRange { from: u32, to: u32 }-- foreground pages from..=to, counted from 1 (clamped to the pages there are)List(Vec<PageRef>)-- these pages in this order
fn foreground_pages(doc: &Document) -> Vec<PageRef>the foreground pages in the document's orderfn pages(doc: &Document, sel: &Pages) -> Vec<PageRef>the pages a selection namesfn page_name(doc: &Document, page: PageRef) -> Stringa page's name: Name, else NameU, else its number among all pages (from 1)fn page_by_name(doc: &Document, sub_address: &str) -> Option<PageRef>the page a hyperlink's sub-address names ("Seite-2", "Seite-2/Sheet.5", "Page-2,200"), by Name or NameU, case-insensitiveenum LinkTargetwhere a hyperlink goesUri(String)-- an address (URL, mail, file) as the file has itPage(PageRef)-- a page of the same document
struct Linka shape's hyperlink on the pageshape: ShapeRefbbox: [f64; 4]-- the box of what the shape draws (paper inches, y up)target: LinkTargetdescription: String-- Description (may be empty)
fn links(doc: &Document, drawing: &Drawing) -> Vec<Link>the hyperlinks of the shapes a drawing shows: per shape its first Hyperlink row with an address (else a sub-address naming a page), on the box of the items of the shape and its subshapes; shapes without anything drawn have no link
diagram_view/src/export/pdf.rs#
Source: lib/diagram_view/src/export/pdf.rs
pdf -- pages as a vector PDF through lib/pdf (EX-01), and drawings placed on sheets of paper
write(doc, fonts, &PdfOptions) -> Result<bytes, pdf::Error> the export: a PDF page per
page in the page's size (points), text as text in embedded
subsets, the shapes' hyperlinks (addresses and pages of the
export), a bookmark per page, the document information
Sheets::new(fonts) drawings on sheets of any size (printing: paper, margins,
scale, tiles)
sheets.add(doc, drawing, (w, h), place, clip, links) -> pdf::PageId
sheets.pdf() -> &mut pdf::Document outlines, information, language
sheets.finish() -> Result<bytes, pdf::Error>
The display list (paper inches, y up) is drawn in the sheet's space through `place` (paper
inches -> points, y up from the sheet's bottom left corner). Fills: solid with their alpha,
gradients as PDF shadings (axial, radial; varying alpha as a soft mask, lib/pdf), hatches as
lines through the page's origin (a pixel at 96 DPI wide) stroked inside the clipped area
(lib/pdf's fill_hatch: tiling patterns showed seams in pdfium); lines with
width (0: the thinnest line the device draws), dashes, caps, joins, miter limit 4; pictures
clipped to the shape's box (JPEG passed through, PNG as pixels with alpha, metafiles as the
screen's placeholder); texts per run in the face the screen uses (diagram_view's FontSet with
its substitution), scaled horizontally so that the run is as wide as the layout measured it,
Letterspace as added advance, a synthetic italic slanted like the screen's. A font whose
licence forbids embedding (or that lib/pdf refuses) is replaced by the set's face of its class.
Pages larger than PDF allows (200 inches a side) are scaled down to fit.
struct PdfOptionswhat write puts into the PDFpages: Vec<PageRef>-- the pages in order (export::pages)render: render::Options-- background pages under the pages, hidden layerslinks: bool-- the shapes' hyperlinks as PDF linksbookmarks: bool-- a bookmark per page (its name)info: pdf::Info-- the document information (title, author ...)language: String-- the document's language ("de-DE"; empty: none)
fn write(doc: &Document, fonts: &mut FontSet, opts: &PdfOptions) -> Result<Vec<u8>, pdf::Error>the export: the pages ofoptsas a PDF documentstruct Sheets<'f>drawings on sheets of paper
impl<'f> Sheets<'f>
fn new(fonts: &'f mut FontSet) -> Sheets<'f>an empty document whose texts take their faces fromfontsfn pdf(&mut self) -> &mut pdf::Documentthe document being written (outlines, information, language, compression)fn skipped_runs(&self) -> u32text runs left out so far because no font could be embeddedfn add(&mut self, doc: &Document, d: &Drawing, size: (f64, f64), place: Xform, clip: Option<[f64; 4]>, targets: &[(PageRef, PageId)], with_links: bool) -> PageIda sheet ofsizepoints with the drawing on it:placemaps paper inches (y up) to sheet points (y up from the bottom left corner),clip(x0, y0, x1, y1 in sheet points) cuts it (None: the sheet);targetsnames the PDF pages of the pages links may go to;with_linkswrites the shapes' hyperlinksfn finish(self) -> Result<Vec<u8>, pdf::Error>the PDF's bytes
diagram_view/src/export/raster.rs#
Source: lib/diagram_view/src/export/raster.rs
raster -- a page as pixels (EX-04 PNG, EX-05 JPEG) through the CPU path
render(view, &RasterOptions) -> Option<Surface> the page (or a part of it) at a resolution:
XRGB on a colour, straight ARGB when transparent
size(view, &RasterOptions) -> (w, h) the pixels render would make
png(sf, dpi) -> Option<Vec<u8>> PNG (lossless, palette when it fits, pHYs = dpi)
jpeg(sf, quality, dpi, under) JPEG (transparency over the colour `under`, JFIF density)
flatten(sf, color) -> Surface straight ARGB over a colour -> XRGB
The picture's top left pixel is the region's top left corner; one pixel is 1/dpi inch. A
transparent picture is drawn twice, on black and on white: where they differ the page let
the background through, and colour and alpha follow from the two (exact for anything that
blends linearly, which the CPU path does), so render2d needs no premultiplied target.
/// the largest side render makes (larger requests give None)
MAX_SIDE: u32 = 30_000
/// the most pixels render makes (larger requests give None)
MAX_PIXELS: u64 = 200_000_000
enum Backgroundwhat lies under the page's shapesPage-- the page's own colour (white unless the page says otherwise)Color(u32)-- a colour 0xRRGGBBTransparent-- nothing: alpha 0 where no shape is
struct RasterOptionswhat render drawsdpi: f64-- pixels per paper inch (Visio: screen 96, printer 300, own)region: Option<[f64; 4]>-- the part of the page (paper inches, y up: x0, y0, x1, y1); None: the whole pagebackground: Background
fn size(view: &PageView, opts: &RasterOptions) -> (u32, u32)the size in pixels render makes for these options (0 when the resolution is not usable)fn render(view: &mut PageView, opts: &RasterOptions) -> Option<Surface>the page drawn at the options' resolution: FMT_XRGB on a colour, FMT_ARGB (straight) when transparent; None when it would be larger than MAX_SIDE / MAX_PIXELS or memory is shortfn flatten(sf: &Surface, color: u32) -> Surfacea surface over a colour (0xRRGGBB) as XRGB: straight ARGB and premultiplied PARGB blend, anything else counts as opaquefn png(sf: &Surface, dpi: f64) -> Option<Vec<u8>>PNG of a surface (render's): RGB or RGBA, a palette when there are few colours, the resolution as pHYsfn jpeg(sf: &Surface, quality: i32, dpi: f64, under: u32) -> Option<Vec<u8>>JPEG of a surface at quality 1..100; a transparent one overunder(0xRRGGBB); the resolution as JFIF density
diagram_view/src/export/svg.rs#
Source: lib/diagram_view/src/export/svg.rs
svg -- a page as an SVG document (EX-03)
write(doc, drawing, &SvgOptions) -> String the display list of one page (PageView::
drawing: measured with the fonts drawn), or
of a region of it (a selection's box)
The document: width and height in inches, the viewBox in points (1/72 inch) with y down;
the page's colour as a rectangle (unless transparent); per top-level shape a group
(id "shape<ID>", data-name, optionally its shape data as data-prop-* attributes), the
shape's hyperlinks as <a> around what the linked shape draws. Items: fills as paths with
fill-rule evenodd (solid, a linear or radial gradient in user space, a hatch as one pattern
per line family: lines through the page's origin, a pixel at 96 DPI wide), lines as paths
with width, dashes, caps and joins (a hairline stays one pixel: non-scaling-stroke), texts
as <text> per run with its font family (and a generic family after it), size, weight, style,
colour and the measured width as textLength (lengthAdjust spacingAndGlyphs, so a reader with
another font keeps the layout), pictures as <image> with the file's own PNG / JPEG / GIF /
BMP bytes (data: URI) cut at the shape's box, metafiles as the screen's placeholder.
struct SvgOptionswhat write puts into the SVGbackground: bool-- the page's colour under the shapes (false: transparent)links: bool-- the shapes' hyperlinks as <a> elements (links to other pages as "#page-<n>")shape_data: bool-- the shapes' shape data as data-prop-<name> attributes of their groupstitle: String-- the document's <title> (empty: none)region: Option<[f64; 4]>-- only this part of the page (paper inches, y up: x0, y0, x1, y1; None: the whole page), e.g. the box of a selection
fn write(doc: &Document, drawing: &Drawing, opts: &SvgOptions) -> Stringthe page ofdrawingas an SVG document
diagram_view/src/fonts.rs#
Source: lib/diagram_view/src/fonts.rs
fonts -- the fonts a diagram's texts are drawn with, and the substitution of missing ones
FontSet::new() empty: the app adds what it has
set.add(Class::Sans, bold, italic, bytes) a font of the substitution set (TrueType or
OpenType bytes); the app's own (its style's) fonts
set.add_family("Calibri", bold, italic, bytes, face) a font under its own name (an
installed font the app found)
set.set_source(Box<dyn FontSource>) asked once per family the set does not know (the
app looks at the installed fonts there)
set.clone() (JD7) another handle on the same set: what one adds
or finds, all see (Metrics keeps one)
class_of(family) -> Class serif, monospaced or sans by the family's name
SAMPLE_WIDTHS how wide common fonts set a sample line (em)
TX-09: a family the set does not have is drawn with the set's font of its class (sans when
the class is missing too), stretched by the width factor that makes the sample line as wide
as in the missing font (Calibri set in Inter: about 0.85), so lines wrap about where Visio
wraps them. An italic without its own face leans 0.2 radians (synthetic), a bold without its
own face stays regular. Only fonts the app hands over are used; the crate embeds none.
The set lives behind a shared handle (Rc<RefCell<..>>): the page views and the formula
engine's Metrics (which measures through `&self`) pick from the same faces and ask the
source once for all of them. One thread, as everything of a page view.
enum Classwhat kind of face a family is (the substitution goes by it)SansSerifMono
trait FontSourceinstalled fonts the app knows how to findfn find(&mut self, family: &str, bold: bool, italic: bool) -> Option<(Vec<u8>, u32)>the bytes and face index offamilyin this style, if installed
struct FontSetthe fonts a page view may use; a clone is another handle on the same set
impl FontSet
fn new() -> FontSetfn add(&mut self, class: Class, bold: bool, italic: bool, data: &[u8])a face of the substitution setfn add_family(&mut self, family: &str, bold: bool, italic: bool, data: &[u8], index: u32)a face under its family namefn set_source(&mut self, source: Box<dyn FontSource>)where faces of unknown families are looked forfn is_empty(&self) -> boolfn class_of(family: &str) -> Classserif, monospaced or sans by the family's name
/// the sample line the widths are measured on
SAMPLE: &str = "The quick brown fox jumps over the lazy dog 0123456789"
/// how wide common fonts set SAMPLE (em, regular and bold): advance widths from the fonts'
/// metrics, the numbers only
SAMPLE_WIDTHS: &[(&str, f64, f64)] = &[ ("Calibri", 23.4209, 23.8364), ("Calibri Light", 23.0, ...
fn sample_width(family: &str, bold: bool) -> Option<f64>the sample width of a family (regular or bold), if the table knows it
diagram_view/src/image.rs#
Source: lib/diagram_view/src/image.rs
image -- the pictures of Foreign shapes: bytes from the package or inline base64, decoded
bytes(doc, &ImageSource) -> Option<Vec<u8>> a part's bytes, or the inline data decoded
decode(bytes) -> Picture PNG, JPEG, (JD8 rest) GIF (its first frame)
and BMP as pixels (straight ARGB rows); EMF,
WMF and anything else: a placeholder
base64(text) RFC 4648 with padding and line breaks
The format is told by the bytes (the signatures), not by the file's attributes. A picture
larger than MAX_SIDE on a side is not decoded (a placeholder): a page shows it scaled down
anyway, and a hostile file must not make the view allocate gigabytes.
/// the largest side of a picture the view decodes
MAX_SIDE: u32 = 8192
struct Picturea decoded picture: w x h pixels, 0xAARRGGBB straight, rows top to bottomw: u32h: u32px: Vec<u32>
enum Decodedwhat a picture becamePicture(Picture)Placeholder(&'static str)-- not decodable here: the format's name ("EMF", "WMF", "?")
fn bytes(doc: &Document, src: &ImageSource) -> Option<Vec<u8>>the bytes of a picturefn decode(data: &[u8]) -> Decodeddecode a picture by its signaturefn base64(s: &[u8]) -> Option<Vec<u8>>base64 with padding; whitespace is skipped; None: a character outside the alphabet
diagram_view/src/measure.rs#
Source: lib/diagram_view/src/measure.rs
measure -- text measured with the fonts it is drawn with: the display list's Measure of a
page view, and Metrics, the formula engine's TextMetrics (TEXTWIDTH, TEXTHEIGHT; JD7)
Metrics::new(&fonts) measures with a handle on the app's FontSet (shared: faces
the set finds later count too); Engine::with_metrics(Rc::new(m))
metrics.measure(text, font, size, max_width) -> (w, h) inches, through
render::measure_text: lines wrapped as a shape's text wraps
Both measure alike: a family resolves through FontSet::pick (its own face, else the face of
its class), a substitute is stretched by the sample line's width factor (fonts.rs), the
advance comes from render2d's layout of the line (shaped: kerning, ligatures), in em. So
TEXTWIDTH(TheText) is the width the page view draws the same text with. A family named
nowhere ("" -- a Font cell the engine cannot name) is Calibri, the layout's default. The
faces resolved and the widths measured are kept (at most WIDTHS_MAX widths).
struct Metricsreal text sizes for the formula engine (TEXTWIDTH, TEXTHEIGHT), measured as a page view draws: Engine::with_metrics(Rc::new(Metrics::new(&fonts)))
impl Metrics
fn new(fonts: &FontSet) -> Metricsmeasuring with the fonts offonts(a handle on the same set)fn substitutions(&self) -> Vec<String>the families measured with a substitute so far
diagram_view/src/view.rs#
Source: lib/diagram_view/src/view.rs
view -- a page of a diagram as a render2d scene plus what the scene cannot hold
PageView::new(&doc, page, &mut fonts, &opts) the display list (diagram_core::render,
texts measured with the fonts drawn), the scene made of
it, pictures decoded
view.update(&doc, &mut fonts, &shapes) -> Option<[f64; 4]> (JD7) the named shapes (their
top-level shapes, render::affected) made anew in the list
and the scene; the box of what changed, old and new place
(paper inches; a zero box: nothing drawn either way); None:
shapes came, went or changed their order -- the page was
built anew
view.draw(dc, sf, r, &cam) the page on the CPU into the rectangle r of a surface
(render2d's CPU path; gradients and pictures in between)
view.render(w, h) -> Surface the page fitted into w x h pixels on its colour (XRGB)
view.fit(size, margin_px) -> Camera the camera showing the whole page
view.drawing() / substitutions() / refused() / scene()
The scene: render2d layers in painter's order. A run of items render2d can draw (solid and
hatched fills, lines with dashes, caps and joins, texts) lies on layers of at most
LAYER_ITEMS items each; a gradient fill or a picture ends the run and is drawn by gfx between
two layers (direct.rs). On the CPU the layers between two such items are drawn in one go
(render2d keeps the painter's order across layers) while the others are hidden, so the order
holds; without such items every layer stays shown. On a GPU (Scene::attach, the app's
choice) the same scene shows everything but those items.
An update (JD7): render::rebuild replaces the items of the named top-level shapes, then the
scene follows, the cheapest way that keeps the order: (1) each item keeps its kind and its
number of entities -> every entity updated in place (render2d keeps an entity's place);
(2) the shape's items lie on one layer and none is drawn by gfx -> its entities updated in
order, the surplus removed, more added at the layer's end when the shape is the layer's last;
(3) else the layers holding the shape's items are made anew from their items, with orders
between the neighbours' (Layer::order, GAP apart, renumbered when the room runs out). The
fonts, the measured widths, the styles and the scene's glyph outlines stay across updates and
across a page built anew. Measured (diagramiotest group editview): 1000 shapes, one moved:
update well under a millisecond, the drawing of the page dominates.
/// how far a synthetic italic leans (radians)
SYNTHETIC_ITALIC: f64 = 0.2
/// the pixels a view's pictures hold together (256 MB): past it a picture is a placeholder
PIC_BUDGET: u64 = 1 << 26
struct PageViewa page ready to draw
impl PageView
fn new(doc: &Document, page: PageRef, fonts: &mut FontSet, opts: &Options) -> PageViewthe page as a scene without a devicefn drawing(&self) -> &Drawingfn scene(&mut self) -> &mut Scenefn substitutions(&self) -> &[String]the font families drawn with a substitute (TX-09: shown to the user)fn refused(&self) -> u32items render2d did not take (geometry it calls invalid)fn picture_pixels(&self) -> u64the pixels the view's decoded pictures hold together (at most PIC_BUDGET; each source once, whatever number of items show it)fn update(&mut self, doc: &Document, fonts: &mut FontSet, shapes: &[ShapeRef]) -> Option<[f64; 4]>the named shapes made anew (their top-level shapes; subshapes name their group, shapes of other pages are passed over): the box of what changed (old and new, paper inches, line widths and shadows included; a zero box: they draw nothing either way); None: shapes came, went or changed their order, or the page's size changed -- the page was built anew. Changes the shapes do not show (the page's layers, styles, masters, themes) need PageView::newfn fit(&self, size: (u32, u32), margin: f64) -> Camerathe camera that shows the whole page in a target ofsize,marginpixels around itfn draw(&mut self, dc: &mut Dc, sf: &mut Surface, r: [i32; 4], cam: &Camera)the page on the CPU into the rectangle r (x, y, w, h relative to dc's origin) of sf, over what is there (the app paints the page's paper first). Only the part of r that dc's clip keeps is drawn, with a camera on that part alone (render2d culls by its view): a changed box drawn again (update's area) costs what lies therefn render(&mut self, w: u32, h: u32) -> Surfacethe page fitted into w x h pixels (a margin of 2 % around it) on the canvas grey, the page in its colour: an XRGB surface