Compare commits

...
Author SHA1 Message Date
james.maes 188c8b1ef7 Merge pull request 'feat(renderer): scene 2 barcodes: whole-dot module fit, alignment in the box, decode tests (P3a)' (#18) from feat/scene2-barcode-fit into develop
maven / build (push) Successful in 15m45s
build / maven (push) Successful in 15m50s
2026-11-13 14:00:10 +00:00
james.maesandClaude Fable 5.2 05518acd02 fix(renderer): scene 2 barcodes after independent review: no symbol reads as another value, rules by symbology, nothing painted over a symbol
maven / build (push) Successful in 6m59s
build / maven (push) Successful in 6m59s
A label is scanned, so a symbol must never read as something other than
the value it was given. Record values are untrusted and stay out of every
diagnostic and exception.

- No value, literal or bound, may hold the two characters an escape of the
  encoder begins with. \<FNC1> in a plain Code 128 value drew a GS1-128 of
  the record's choosing, \<FNC3> set the reader-programming flag, and QR
  dropped the escape. Refused in every symbology, with a count only.
- Interleaved 2 of 5 of an odd number of digits is refused, not padded.
- EAN and UPC values are the whole number with its check digit, which is
  verified; a shorter number is refused, never completed or padded.
- The check digit of every GS1 key in a gs1-128 element string is
  verified: the identifiers the GS1 Syntax Dictionary marks, as the
  bundled Zint carries it.
- VALUE_NOT_ENCODABLE joins the errors for these and for a value a
  symbology cannot hold; SCENE_INVALID is no longer used for a value. A
  symbol of more modules than the encoder draws is BARCODE_DOES_NOT_FIT.
- Quiet zones and the smallest module are a table by symbology
  (scene2/barcode/Symbology), each number with its source. barcodeProfile
  names the rule: none, gs1-general or gs1-logistics; not stated, the
  strictest written for the symbology. A GS1-128 is so held to 0.495 mm
  unless its scene says otherwise, at which a GTIN with a date and a
  serial number fits no label 4 in wide.
- The bars of a linear symbol must be as tall as its symbology asks, and
  the height is part of the fit. minHeight overrides, with the standing
  warning BARCODE_HEIGHT_BELOW_RECOMMENDED.
- QUIET_ZONE_INTRUDED is an error: an element later in the list whose ink
  would enter a symbol or its quiet zones is refused, when a scene is
  validated as when it is rendered.
- A barcode sits in the middle of its box unless the scene says otherwise.
- A bound barcode takes maxLength and is proven at validation in a linear
  symbology. FIT_NOT_PROVEN stays for no length and for two-dimensional
  symbols, whose encoders have no largest symbol of a length.

Codes and property names are added in one change: foundation's
FailureCode and warning set, the preview's sentences, the bridge's
accepted refusals and schema vocabulary, the renderer's vocabulary and
the schema. The three barcode goldens are unchanged byte for byte;
barcode-retail is new.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 18:19:02 -06:00
james.maesandClaude Fable 5.2 f9a5def4f6 feat(renderer): scene 2 barcodes: whole-dot module fit, alignment in the box, decode tests (P3a)
A `barcode` element of a version 2 scene is now drawn into the picture of
the label instead of being refused as RENDERER_TOO_OLD.

- ModuleFit: the module is the largest whole number of dots at which the
  symbol, quiet zones included, fits its box; never under `minModule`
  (default 0.25 mm linear, 0.375 mm two-dimensional, taken up to whole dots)
  and never over `maxModule`. Integer arithmetic only.
- A linear symbol is fitted along its width and its bars take the whole
  height of the box; qr, datamatrix, pdf417 and aztec are fitted on both
  axes. The fitted symbol is placed by `align` and `valign`, turned by
  `rotation`, and paints its own white ground, quiet zones included.
- A value that does not fit at the minimum module is BARCODE_DOES_NOT_FIT,
  validated or rendered, with the modules and dots it needs and the dots
  the box has. A smaller module is drawn only when the scene states one,
  and then with the warning BARCODE_MODULE_BELOW_RECOMMENDED every time.
- The thirteen fit-qualified symbologies, `value` and `valuePath`, the
  dynamic symbology allowlist and the scanner profile are carried over from
  version 1, whose own barcode path is not changed. Every refusal is a
  diagnostic of numbers; what an encoder says about a value is dropped.
- `gs1` and `hri` stay declared; an element that states either is refused
  as RENDERER_TOO_OLD until the package that draws them.

Tests: every symbology at 203, 300 and 600 dpi for a short, a typical and
the longest value, rebuilt from the emitted ZPL and decoded by ZXing
(GS1-128 with FNC1 as `]C1`); seeded properties of the fit and of the
picture; goldens for a GS1-128 on 4 x 1 in, linear and two-dimensional
symbols; the version 2 mutation campaign extended to barcode elements.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 17:25:40 -06:00
james.maes a147efee88 Merge pull request 'feat(renderer): scene 2 text: bundled fonts, measurement before drawing, stated fit rules (P2)' (#16) from feat/scene2-text into develop
maven / build (push) Successful in 7m40s
build / maven (push) Successful in 7m40s
2026-11-12 23:11:02 +00:00
james.maesandClaude Fable 5.2 589b6d41ee fix(renderer): scene 2 text after independent review: a proof that never cuts, a bounded shrink search, named refusals
maven / build (push) Successful in 10m28s
build / maven (push) Successful in 10m28s
The proof of `maxLength`
- The proof never cuts. With `overflow: truncate` the proof was given a cut
  block, which counts as fitting, so a bound element whose box held ten
  characters validated clean with `maxLength: 40` and every long value was cut
  at print. The proof now runs with cutting off. When it fails, an element
  that did not ask for cutting is refused as before; one that did still
  validates, since cutting is what its author chose, with the warning
  FIT_NOT_PROVEN at every validation carrying `measured.provenCharacters`,
  the longest length proven to fit whole (found by halving: fewer characters
  never fit worse), against `limit.characters`. No new code: FIT_NOT_PROVEN
  already means that the fit of a bound value is not proven.
- A bound element with `maxLength` is judged for legibility, when validated,
  at the size the proof shrank to (the floor when it fails and the element
  cuts), not at its stated size.

The shrink search
- The size chosen is still exactly the one a search of every quarter-point
  step gives, but that search is no longer made. A count that errs only
  toward yes says whether a size could hold the text: lines filled at any
  character, each held to a width no real line can be under, and a block to
  its lines' ascent, pitches and descent. It never refuses a size that fits
  and, once it allows a size, allows every smaller one, so the largest size it
  allows is found by halving and only the steps from there are laid out. When
  one line at the floor is higher than the box nothing is searched, and a cut
  tries no line count the box is too low for.
- 1024 characters at 600 dpi from 1000 pt to 1 pt took 180 to 250 ms a fit and
  now takes under 1 ms: at most 21 555 characters visited where the search of
  every size visits 15.6 million.
- A text is fitted once: what `check` composed is what `paint` draws.
- The text of one scene may take 64 million steps (a character visited while
  fitting is one, a character to be drawn 16, a glyph the scene draws for the
  first time at a size 4096, since the runtime rasterises it once). The
  element that passes it, and every text after it, is SCENE_INVALID at the
  element with `textWorkSteps`, as the painted-area limit is. The count is
  integer arithmetic: the same on every machine, and the same validated or
  rendered. A thousand of the worst elements validate in well under a second.

Ink outside the measure
- TEXT_INK_OUTSIDE_MEASURE was an IllegalStateException thrown while
  painting, which failed the whole render after part of the text was on the
  label. The dots of a text are now gathered first and reach the label only
  when none strayed; otherwise the one element is refused as
  TEXT_DOES_NOT_FIT with `glyphsOutsideMeasure` and `dotsOutsideMeasure`. A
  literal is held to the glyph bounds when the scene is validated.
- The bound is tested at 1, 2, 300 and 1000 pt as well as from 5 to 72 pt, for
  every character of every face at the three resolutions; nothing strays.

Schema and vocabulary
- `fit` declares `maxLines`, `shrinkTo` and `overflow` under `properties` with
  `additionalProperties: false`. The three names are in the renderer's and the
  host bridge's pointer vocabularies, and a wrong member is reported at the
  member (`/elements/3/fit/maxLines`, or in the override that states `fit`).
- A bound number is printed as the schema says: plain decimal digits, no
  exponent, no fraction that is only zeros (`1.0E10` prints `10000000000`,
  `2.50` prints `2.5`). A number that is not finite is VALUE_MISSING.

Tests
- The widest-advance check covers every character a face draws, inked or not
  (a no-break space advances the pen), so a font update cannot break the proof
  unseen.
- Property: `fit` equals the search of every size, block for block, over 3600
  generated texts, boxes, sizes, floors and line counts.
- The goldens are unchanged. A README beside them records the JDK builds and the
  FreeType each ships.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 14:58:53 -06:00
james.maes 6fc086bb4e Merge pull request 'feat(preview): layout preview inside the QBit: service, action and record widget (P6b); bound preview painting and pin the version 1 job frame' (#17) from feat/preview-ui into develop
maven / build (push) Successful in 13m59s
build / maven (push) Successful in 13m59s
2026-11-12 20:50:53 +00:00
james.maesandClaude Fable 5.2 363e96f641 fix(preview): only a publication is previewed by revision; the action's widget request carries no record
maven / build (push) Successful in 12m0s
build / maven (push) Successful in 12m0s
Changes after the independent review of the layout preview.

A person who may not author a template cannot obtain the picture of an
unpublished draft by naming a revision. The revision table also holds the
frozen drafts that the retained preview writes; a named revision is now
resolved only when it is a publication, and any other row is answered
"Document definition not found.", with the type and the words of an identity
that does not exist, from the service, from the action before and after its
form, and from the widget. A draft is previewed through its template alone.

The widget of the "Preview layout" action is requested by the identifier of
the run and reads the person's choices from the state of that run. A client
sends every plain process value as a parameter of the widget request, and
the framework's widget route logs the parameters of a request that fails or
takes over a second, so the chosen record's identity and the sample's name
were logged for a slow preview. The check step now holds the accepted
choices as one structured process value, which is not sent, and the widget
no longer reads a revision, record, sample, stock or resolution from any
request parameter.

A source record is read within the channel and credential ceilings the print
path applies to the source table, asked before the record is read.

A label whose picture alone is refused (PREVIEW_TOO_LARGE and no other
refusal) is no longer said to be unprintable: "This label is too dense to
preview; printing is not affected."

The help of the form says that the longest values picture is drawn with
capital W, is indicative, and that the renderer's proof at publication
decides. The README records what a host must configure for label previews:
no-store for widget responses, which neither a widget renderer nor the
widget route sets, and what the request log holds.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 14:38:15 -06:00
james.maesandClaude Fable 5.2 1db82957c9 fix(bridge): a placeholder of no area draws nothing; name the answer table for what it is
ZplRaster.hatch returns at once for an area of no width or no height. Its
outline and diagonals would otherwise be placed one dot outside the area:
with no width the diagonal's column divides down to -1 and a stray line is
drawn. The guard that the refused page had around its call is now in the
painter itself, so every caller has it. An empty printer font text field did
not reach the painter before this change either: such a field is refused as
no field (RASTER_FIELD), and by the output policy before that; the existing
test for it is unchanged. ZplRaster stays at 100% lines.

ReleasedRendererAnswerTest is renamed VersionOneAnswerTableTest and its
header says what it is: 71 synthetic answers in the shape the released
renderer answers with, and the outcomes of today's bridge for them. They were
not captured at the released tag, unlike the job frame golden, so the table
holds today's behaviour still and does not show equality with the release.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 14:38:14 -06:00
james.maesandClaude Fable 5.2 6aba6ce8d4 docs(preview): the placeholder is outlined and crossed; record the bridge review findings
maven / build (push) Successful in 12m0s
build / maven (push) Successful in 12m0s
The widget's sentences, the authoring guide, the bridge README and the
design follow the bounded painting of the preview: a placeholder is an
outline with its two diagonals, and a page painted more than sixteen
times over is PREVIEW_TOO_LARGE. The design also records that the
version question is asked again after any RENDERER_TOO_OLD and that the
released version 1 job frame is pinned.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:49:54 -06:00
james.maesandClaude Fable 5.2 1828ae9c48 fix(bridge): ask the renderer's version again after any RENDERER_TOO_OLD
The comments said that nothing of a version 2 scene reaches a renderer
that cannot draw it. That is not so: the answer to the version question is
remembered, so after a renderer image is rolled back ONE job reaches the
old (0.1.0) renderer, scene and record values included, and is then
refused as RENDERER_TOO_OLD. The class, field, invoke and probe comments
now say exactly that.

The window stays one job in every case: a job that ends in
RENDERER_TOO_OLD, from render, validate or preview, forgets what was
remembered, so the next job that needs renderer 0.2.0 asks the version
first. An answer from 0.1.0 already did this; a refusal that renderer
0.2.0 names itself, as an error answer or among collected diagnostics, did
not.

FakeWorker can stand for an image that is replaced while a bridge uses it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:49:06 -06:00
james.maesandClaude Fable 5.2 bbb4b60a1b test(bridge): golden of the released version 1 job frame and a table of released answers
Nothing held the version 1 print request to the released bytes, and the
0.1.0 answers were tested at the units and not through render().

- compat-v1/job-frame-render.json is the frame the bridge of tag
  v1.1.0-RC.2 (e9ffba484e) wrote to its
  exchange for one render() with fixed inputs. VersionOneJobFrameTest
  compiles unchanged at that tag and is its own capture tool; the .md
  beside the frame gives the inputs and the commands.
- The frame is compared byte for byte except for the order of the seven
  members of "stock": the released bridge writes them in the iteration
  order of an immutable Map.of, which the JVM changes from run to run (four
  captures at the tag gave four orders and were otherwise identical).
- ReleasedRendererAnswerTest is one row for each answer of
  qqq-renderer-0.1.0 to a version 1 job, accepted, refused by code or
  rejected, every row through render(), with the name the version rule
  gives the same frame.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:49:06 -06:00
james.maesandClaude Fable 5.2 9e5b16d686 fix(bridge): bound preview painting to sixteen times the page
ZplRaster painted a box and a placeholder by testing every dot of the
field's area. The output policy allows 6000 fields, so a label of
page-sized boxes was tens of thousands of millions of dots of work on the
host while an admission slot was held, and the page of a refused scene had
the same cost for each of up to 2048 diagnostic boxes.

- Every painter counts the dots it is about to paint, an overlap each
  time, and the field that would take the page past sixteen times its dots
  is refused as PREVIEW_TOO_LARGE. This is the renderer's own limit for a
  scene. A graphic counts eight dots for each byte.
- A box is the whole area when its border meets itself, else four bars
  that do not overlap, filled whole bytes at a time. The dots are the same
  as before.
- A placeholder (printer font text, a refused element's box) is an outline
  and its two diagonals, so it costs its perimeter and not its area. This
  changes its look: the diagonal hatch every six dots is gone.
- preview() returns the refusal as a result, like the page limit: not
  printable, no page, PREVIEW_TOO_LARGE with limit.paintedPercent 1600. For
  a refused scene it joins the diagnostics the worker sent.

Printing is not changed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:49:05 -06:00
james.maesandClaude Fable 5.2 ed11495120 feat(preview): layout preview inside the QBit: service, action and record widget (P6b)
A person editing a label template sees the picture that would print, with
its refusals and warnings, before anything is printed, from the module's
own screens and with no host code.

- DocumentPreviewService: authorises by the existing permissions (a draft
  needs configure, a published revision needs view, a record needs
  generate and is read as the person, with their permissions and record
  locks, before any context is built), loads the draft or the published
  snapshot without writing, builds the context as generation does and
  calls IsolatedRenderer.preview. Data is a sample from the scene, the
  longest declared values, or one record. One log line, no content.
- "Preview layout" action on templates and published revisions: data,
  sample, record, stock and resolution; the result is the preview widget.
- "Label preview" section on the template record screen: the draft with
  sample data (the published revision for a person who may only view).
- The widget is fetched, never seeded from a process value: QQQ keeps the
  state of a finished process for hours (in a table with the shared
  provider), so the picture, the context and the diagnostics exist only
  in the answer to the widget request. The process state holds the
  person's choices only.
- Bounded answer: one page, a picture of at most 2 MiB, fifty diagnostics.
- The existing action is relabelled "Generate retained preview file"; its
  process name and behaviour are unchanged.
- The record selector asks for generate alone, so a person who may
  preview a published revision with a record can choose one.
- Help on every new process, step, field, section, widget and choice list.

Tests: DocumentPreviewTest (data sources, permission matrix, unreadable
record, nothing written, process state, PDF refusal, refused scene,
version 1 label, bounds, log line, help coverage, instance validation)
and LayoutPreviewServiceTest in bridges/renderer (through the service and
the bridge, the preview has the hash of the bytes the print path returns
at 203, 300 and 600 dpi). The registration and process tests are updated
for the new wiring and the relabel. bridges/renderer gains the RDBMS
module at test scope for that test.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:37:56 -06:00
james.maesandClaude Fable 5.2 f5acf93e3d feat(renderer): scene 2 text: bundled faces, measurement before drawing, stated fit rules (P2)
maven / build (push) Successful in 10m16s
build / maven (push) Successful in 10m16s
A version 2 `text` element is now drawn. It replaces the placeholder that
parsed and placed a text and refused it as RENDERER_TOO_OLD.

What a scene can say
- `font` names one of the five bundled faces (or comes from `defaults`); any
  other name is FONT_UNKNOWN. There is no printer font and no installed font.
- `size` is the em as a physical length (1 pt to 1000 pt), not rounded to dots.
- `value` or `valuePath`; `align`/`valign` place the block in the box and each
  line in the block; `lineHeight`, `rotation`, `reverse`, `threshold`.
- `fit`: one line by default, shrunk in quarter-point steps to 70% of the size
  (not below 5 pt), then refused. Opt in to more lines (`maxLines`) and to
  cutting with an ellipsis (`overflow: truncate`).
- `maxLength`: validation proves the longest value fits, so a length refusal
  happens when a scene is published; printing refuses a longer value first.

How it is measured and drawn
- Measurement is integer arithmetic on the face's own numbers (thousandths of
  the em, read once at a reference size), so it is the same on every machine.
  Every character sits at a whole-dot pen position and is drawn there by the
  Java rasteriser that version 1 raster text uses, then reduced to ink at the
  threshold. A line's box is its advance widened to its ink plus two dots a
  side; a render whose ink would leave it fails instead of clipping.
- At each size a line is broken between words while that fits and at any
  character when it does not, which is also what makes a length provable.
- One glyph for each character, left to right: no kerning, ligatures, mark
  placement or bidirectional text. A character that cannot be drawn that way
  is FONT_MISSING_GLYPH with a count.

Diagnostics (ids and numbers only; no value ever enters one)
TEXT_DOES_NOT_FIT, VALUE_MISSING, VALUE_TOO_LONG, FONT_UNKNOWN,
FONT_MISSING_GLYPH, RESERVED_FONT_NAME; TEXT_TRUNCATED, TEXT_SMALL_FOR_DPI,
TEXT_LIGHT_FACE, FIT_NOT_PROVEN; TEXT_SHRUNK, TEXT_WRAPPED.

Core seams added: `ElementSource.inherit` gives an element the scene's
`defaults` for the properties its type reads, and `ElementSource.refuse`
raises a coded refusal at a property (FONT_UNKNOWN at the place that names
the face, in the element, the defaults or an override).

Tests: goldens for the five faces and for fit, rotation and reverse at 203,
300 and 600 dpi, generated in the CI image (Linux, Temurin 21.0.9) and the
same bytes on Windows (21.0.12) and on Linux Temurin 21.0.13; every character
of every face drawn inside its measured line; seeded property tests of fit
(never shrunk when it fits, the largest size that fits, never below the floor,
never more lines than allowed, cut only when asked and always with the mark,
a proven length never refused); licence, provenance and hash of every face;
the version 2 mutation campaign extended to text. The version 1 corpus is
untouched. 100% line coverage of the scene 2 packages.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:37:13 -06:00
james.maesandClaude Fable 5.2 d3378825d7 feat(renderer): bundle five OFL fonts for version 2 label text
Version 2 label scenes draw text in faces shipped inside the renderer, so a
label needs no printer font, no installed font and no object storage:

  qqq-sans, qqq-sans-bold   IBM Plex Sans Regular and Bold (@ibm/plex-sans@1.1.0)
  qqq-condensed-bold        IBM Plex Sans Condensed Bold (@ibm/plex-sans-condensed@2.0.0)
  qqq-mono, qqq-mono-bold   JetBrains Mono Regular and Bold (v2.304)

The files are unmodified, taken from each project's official release archive.
Each licence was confirmed as the SIL Open Font License 1.1 from the archive's
own licence file, which is shipped byte for byte beside the fonts with a
provenance note (release, archive URL and hash, path in the archive, font
version). /fonts/SHA256SUMS lists the hashes. git is told never to rewrite
anything under /fonts.

THIRD-PARTY.md and NOTICE record the fonts. The OFL is not on the K22-DEP-02
allowlist; the maintainer approved one recorded exception for unmodified OFL
fonts shipped as data, and the register entry is proposed with the pull request.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:26:38 -06:00
james.maes bb25d6c46a Merge pull request 'feat(bridge): accept renderer 0.2.0, structured diagnostics, ZplRaster and preview; render target dpi end to end (P5, P7)' (#15) from feat/bridge-preview into develop
maven / build (push) Successful in 10m58s
build / maven (push) Successful in 10m58s
2026-11-12 18:28:12 +00:00
135 changed files with 14548 additions and 215 deletions

No files matched your search

+3
View File
@@ -16,3 +16,6 @@
# Stored renderer outputs are compared byte for byte: git must never rewrite them. # Stored renderer outputs are compared byte for byte: git must never rewrite them.
renderer/src/test/resources/compat-v1/** -text renderer/src/test/resources/compat-v1/** -text
renderer/src/test/resources/scene2/golden/** -text renderer/src/test/resources/scene2/golden/** -text
# Bundled fonts and their licence texts are shipped exactly as released and are hashed: git must never rewrite them.
renderer/src/main/resources/fonts/** -text
+7
View File
@@ -45,6 +45,13 @@ Every default provider fails closed. No adapter calls the trusted in-process ren
Context contains bounded immutable JSON-like data, including the authorized selected `record`. A script may add context objects but cannot replace that reserved original record. Credentials, QQQ sessions, raw host objects and lazy entities are rejected. Source-record permissions are checked before context preparation, before rendering, before intake and before printing. Asset access is rechecked by the isolated renderer adapter, and retained-version access by retained/printing adapters. Context contains bounded immutable JSON-like data, including the authorized selected `record`. A script may add context objects but cannot replace that reserved original record. Credentials, QQQ sessions, raw host objects and lazy entities are rejected. Source-record permissions are checked before context preparation, before rendering, before intake and before printing. Asset access is rechecked by the isolated renderer adapter, and retained-version access by retained/printing adapters.
### What a host must configure for label previews
The "Label preview" widget and the "Preview layout" action arrive with the QBit's registration and need no host code. Two things are the host's:
- **Send `Cache-Control: no-store` for widget responses.** The widget's answer holds the picture of a label, which in the action can show the values of a record. QQQ's widget route sets no `Cache-Control` header and a widget renderer cannot set response headers, so the host, or the proxy in front of it, must send `no-store` for widget responses. Nothing in this QBit can.
- **Know what your request log holds.** QQQ's widget route writes the parameters of a widget request that fails or takes longer than one second to the application log. For this widget those parameters hold no record identity and no sample name: from a template's record screen they are the table name and the template's identity, and from the action they are the identifier of the run (`processUUID`) with the plain process values a client adds to it (`previewTemplateId` or `previewRevisionId`, `sourceTable`, and whatever the client itself sent to start the run, which for the standard clients is its selection of the template or revision row). The chosen record, sample, stock and resolution stay in the state of the run and are not sent; this holds for a client that sends plain process values only, as the standard clients do. `DocumentPreviewService` itself logs one line per preview: the actor, the template or revision identity, the kind of data, the resolution, the outcome and the diagnostic codes.
## Known boundaries before release ## Known boundaries before release
Native table/record processes and source-editor forms are implemented through standard QQQ metadata. Results include record navigation and download/preview metadata consumed by generic frontend components. Authenticated delivery requires verified bytes and a completed owner receipt before preview. There is no visual designer. Final integrated browser workflow acceptance, a qualified worker deployment, production storage/restore and printing integration remain release work. Service-only fields cannot be edited through unrestricted generic CRUD. Domain actions use validated services. Native table/record processes and source-editor forms are implemented through standard QQQ metadata. Results include record navigation and download/preview metadata consumed by generic frontend components. Authenticated delivery requires verified bytes and a completed owner receipt before preview. There is no visual designer. Final integrated browser workflow acceptance, a qualified worker deployment, production storage/restore and printing integration remain release work. Service-only fields cannot be edited through unrestricted generic CRUD. Domain actions use validated services.
+4 -2
View File
@@ -36,8 +36,10 @@ nothing of the scene or the record.
- **Preview.** `preview(PreviewRequest)` is the print path stopped before retention: the same job with collected - **Preview.** `preview(PreviewRequest)` is the print path stopped before retention: the same job with collected
diagnostics, the same integrity checks and output policy, and a page decoded by `ZplRaster` from the accepted diagnostics, the same integrity checks and output policy, and a page decoded by `ZplRaster` from the accepted
label bytes (`PreviewPage` is a one-bit PNG, one pixel for each dot). Refusals come back as diagnostics with label bytes (`PreviewPage` is a one-bit PNG, one pixel for each dot). Refusals come back as diagnostics with
`printable: false`, never as a label: a refused scene has no output, and its page shows only the hatched `printable: false`, never as a label: a refused scene has no output, and its page shows only the outlined,
boxes of the refused elements. A page of more than sixteen million dots is `PREVIEW_TOO_LARGE`. PDF previews crossed boxes of the refused elements. A page of more than sixteen million dots is `PREVIEW_TOO_LARGE`, and so
is a label (or the boxes of a refused scene) that would paint more than sixteen times its page's dots; such a
label still prints, and the foundation's widget says so. PDF previews
are not provided. The bridge writes and logs nothing for a preview. are not provided. The bridge writes and logs nothing for a preview.
Three transports share the same bridge, asset, wire and output policy: Three transports share the same bridge, asset, wire and output policy:
+2
View File
@@ -14,6 +14,8 @@
</exclusions></dependency> </exclusions></dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.22.4</version></dependency> <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.22.4</version></dependency>
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>6.0.1</version><scope>test</scope></dependency> <dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>6.0.1</version><scope>test</scope></dependency>
<!-- Test only: the foundation's store names the RDBMS module (optional there), and LayoutPreviewServiceTest drives the foundation's preview service over this bridge. -->
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-rdbms</artifactId><version>${qqq.version}</version><scope>test</scope></dependency>
</dependencies> </dependencies>
<build> <build>
<resources> <resources>
@@ -47,6 +47,13 @@ import com.kingsrook.qqq.backend.core.exceptions.QException;
** refused as `RENDERER_TOO_OLD` when the worker is older: the host asks the ** refused as `RENDERER_TOO_OLD` when the worker is older: the host asks the
** worker its version with a fixed, empty job before it sends such a scene, and ** worker its version with a fixed, empty job before it sends such a scene, and
** an answer from an older worker to such a job is refused whatever it says. ** an answer from an older worker to such a job is refused whatever it says.
**
** The worker's answer to that question is remembered, so asking first is not
** a promise about every job. After a renderer image is rolled back, ONE such
** job can reach the old (0.1.0) renderer, its scene and its record's values
** with it, before the bridge knows. That job is refused as
** `RENDERER_TOO_OLD`, and a job that ends in `RENDERER_TOO_OLD`, however it
** came to, ends what was remembered: the next such job asks the version first.
*******************************************************************************/ *******************************************************************************/
public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRenderer public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRenderer
{ {
@@ -68,7 +75,11 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
// whether the last verified answer came from a renderer that draws version 2 scenes. It only // // whether the last verified answer came from a renderer that draws version 2 scenes. It only //
// saves the version question; every answer is still held to the version rule // // saves the version question; every answer is still held to the version rule. It is what //
// the bridge last saw, not what the renderer is now: after a renderer image is rolled back, //
// ONE job that only 0.2.0 can do is sent to the old (0.1.0) renderer on the strength of it. //
// That job is refused as RENDERER_TOO_OLD, and every job that ends in RENDERER_TOO_OLD //
// clears this, so the window is that one job and the next asks the version again //
//////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////
private volatile boolean structured; private volatile boolean structured;
@@ -231,8 +242,12 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
** **
** A scene with a refused element has no label at all (the worker sends ** A scene with a refused element has no label at all (the worker sends
** none), so there is nothing a host could print by mistake. Its page shows ** none), so there is nothing a host could print by mistake. Its page shows
** only where the refused elements are, hatched, from the boxes in their ** only where the refused elements are, outlined and crossed, from the boxes
** diagnostics; when no diagnostic has a box there is no page. ** in their diagnostics; when no diagnostic has a box there is no page.
**
** Drawing is bounded like the page: a label, or the boxes of a refused
** scene, that would paint more than sixteen times the page's dots is
** `PREVIEW_TOO_LARGE`, a result like any other named refusal.
***************************************************************************/ ***************************************************************************/
@Override @Override
@SuppressWarnings("try") // The admission slot is held for its scope only; its value is never read. @SuppressWarnings("try") // The admission slot is held for its scope only; its value is never read.
@@ -271,7 +286,15 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
return (refused(printed, answer.diagnostics())); return (refused(printed, answer.diagnostics()));
} }
byte[] bytes = output(answer, request.format(), maximum, printed); byte[] bytes = output(answer, request.format(), maximum, printed);
ZplRaster page = ZplRaster.page(bytes, printed); ZplRaster page;
try
{
page = ZplRaster.page(bytes, printed);
}
catch(IllegalArgumentException undrawn)
{
throw (painted(undrawn));
}
List<Diagnostic> diagnostics = new ArrayList<>(answer.diagnostics()); List<Diagnostic> diagnostics = new ArrayList<>(answer.diagnostics());
if(!page.exact()) if(!page.exact())
{ {
@@ -297,12 +320,15 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
** host from the diagnostics' boxes, which are in dots from the top left of ** host from the diagnostics' boxes, which are in dots from the top left of
** the printable area: the stock less its margins, placed as the renderer ** the printable area: the stock less its margins, placed as the renderer
** places it (the left and top margins rounded up to whole dots and moved ** places it (the left and top margins rounded up to whole dots and moved
** back only as far as keeps the area on the page). ** back only as far as keeps the area on the page). Boxes that would paint
** more than a page may be painted with are not drawn at all: there is no
** page, and `PREVIEW_TOO_LARGE` joins the diagnostics.
***************************************************************************/ ***************************************************************************/
private static GenerationPorts.Preview refused(GenerationPorts.Stock printed, List<Diagnostic> diagnostics) throws Exception private static GenerationPorts.Preview refused(GenerationPorts.Stock printed, List<Diagnostic> diagnostics) throws Exception
{ {
List<List<Integer>> boxes = diagnostics.stream().filter(diagnostic -> diagnostic.severity() == Diagnostic.Severity.ERROR && diagnostic.box() != null).map(Diagnostic::box).toList(); List<List<Integer>> boxes = diagnostics.stream().filter(diagnostic -> diagnostic.severity() == Diagnostic.Severity.ERROR && diagnostic.box() != null).map(Diagnostic::box).toList();
List<GenerationPorts.PreviewPage> pages = List.of(); List<GenerationPorts.PreviewPage> pages = List.of();
List<Diagnostic> findings = diagnostics;
if(!boxes.isEmpty()) if(!boxes.isEmpty())
{ {
int dpi = printed.dpi(); int dpi = printed.dpi();
@@ -310,10 +336,38 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
int height = dots(printed.heightMicrons(), dpi, 12700); int height = dots(printed.heightMicrons(), dpi, 12700);
int left = Math.min(dots(printed.leftMicrons(), dpi, 25399), width - dots(printed.widthMicrons() - printed.leftMicrons() - printed.rightMicrons(), dpi, 0)); int left = Math.min(dots(printed.leftMicrons(), dpi, 25399), width - dots(printed.widthMicrons() - printed.leftMicrons() - printed.rightMicrons(), dpi, 0));
int top = Math.min(dots(printed.topMicrons(), dpi, 25399), height - dots(printed.heightMicrons() - printed.topMicrons() - printed.bottomMicrons(), dpi, 0)); int top = Math.min(dots(printed.topMicrons(), dpi, 25399), height - dots(printed.heightMicrons() - printed.topMicrons() - printed.bottomMicrons(), dpi, 0));
ZplRaster page = ZplRaster.refused(width, height, left, top, boxes); try
pages = List.of(new GenerationPorts.PreviewPage(page.png(), page.width(), page.height())); {
ZplRaster page = ZplRaster.refused(width, height, left, top, boxes);
pages = List.of(new GenerationPorts.PreviewPage(page.png(), page.width(), page.height()));
}
catch(IllegalArgumentException undrawn)
{
if(!(painted(undrawn) instanceof GenerationPorts.RenderException large))
{
throw (undrawn);
}
findings = new ArrayList<>(diagnostics);
findings.add(large.diagnostic());
}
} }
return (new GenerationPorts.Preview(pages, false, false, diagnostics, 0L, RendererJson.hash(new byte[0]))); return (new GenerationPorts.Preview(pages, false, false, findings, 0L, RendererJson.hash(new byte[0])));
}
/***************************************************************************
** What `ZplRaster` would not draw. A page that would be painted with more
** than `ZplRaster.MAXIMUM_COATS` times its dots becomes the named refusal,
** with the limit as a percentage of the page as the renderer states its
** own; anything else it refuses stays what it was, an opaque failure.
***************************************************************************/
private static Exception painted(IllegalArgumentException undrawn)
{
if(!GenerationPorts.FailureCode.PREVIEW_TOO_LARGE.name().equals(undrawn.getMessage()))
{
return (undrawn);
}
return (new GenerationPorts.RenderException(GenerationPorts.FailureCode.PREVIEW_TOO_LARGE, new Diagnostic("PREVIEW_TOO_LARGE", Diagnostic.Severity.ERROR, null, null, null,
Map.of("paintedPercent", 100 * ZplRaster.MAXIMUM_COATS))));
} }
/*************************************************************************** /***************************************************************************
@@ -377,6 +431,14 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
** target is sent only for a version 2 scene, and collected diagnostics only ** target is sent only for a version 2 scene, and collected diagnostics only
** for a preview. A version 1 scene or a PDF asked for another resolution than ** for a preview. A version 1 scene or a PDF asked for another resolution than
** its stock's is refused here, because a renderer would ignore the target. ** its stock's is refused here, because a renderer would ignore the target.
**
** A job only renderer 0.2.0 can do is sent without the version question when
** the last verified answer came from 0.2.0. If the renderer was replaced by
** an older one since, this one job reaches it and is refused as
** `RENDERER_TOO_OLD` whatever it answers. Any job that ends in
** `RENDERER_TOO_OLD` (the worker is older, or a worker names the refusal
** itself, alone or among collected diagnostics) forgets what was remembered,
** so the next such job asks the version before it sends anything.
*******************************************************************************/ *******************************************************************************/
private WorkerAnswer invoke(String id, String operation, GenerationPorts.Format format, GenerationPorts.Revision revision, private WorkerAnswer invoke(String id, String operation, GenerationPorts.Format format, GenerationPorts.Revision revision,
Map<String, Object> context, List<Map<String, Object>> resolved, int maximum, Integer targetDpi, boolean collect) throws Exception Map<String, Object> context, List<Map<String, Object>> resolved, int maximum, Integer targetDpi, boolean collect) throws Exception
@@ -424,13 +486,32 @@ public final class IsolatedRendererBridge implements GenerationPorts.IsolatedRen
int maximumFrame = (int) Math.min(room, 4L * ((config.maximumBytes() + 2) / 3) + ENVELOPE_BYTES); int maximumFrame = (int) Math.min(room, 4L * ((config.maximumBytes() + 2) / 3) + ENVELOPE_BYTES);
WorkerAnswer answer = WorkerAnswer.read(exchange.invoke(id, input, maximumFrame), maximumFrame, id, facts); WorkerAnswer answer = WorkerAnswer.read(exchange.invoke(id, input, maximumFrame), maximumFrame, id, facts);
structured = answer.version().structured(); structured = answer.version().structured();
return (answer.settle(operation, collect, current)); try
{
answer.settle(operation, collect, current);
}
catch(GenerationPorts.RenderException refusal)
{
if(refusal.code() == GenerationPorts.FailureCode.RENDERER_TOO_OLD)
{
structured = false;
}
throw (refusal);
}
if(answer.diagnostics().stream().anyMatch(diagnostic -> GenerationPorts.FailureCode.RENDERER_TOO_OLD.name().equals(diagnostic.code())))
{
structured = false;
}
return (answer);
} }
/*************************************************************************** /***************************************************************************
** Ask the worker its version before a job only renderer 0.2.0 can do, so ** Ask the worker its version before a job only renderer 0.2.0 can do, so
** that nothing of a version 2 scene or its record reaches a renderer that ** that a renderer the bridge does not know to be 0.2.0 is sent nothing of a
** cannot draw it. The question is a constant. ** version 2 scene or its record. The question is a constant. It is asked
** when nothing is remembered, not before every job: after a renderer image
** is rolled back, ONE job can reach an old (0.1.0) renderer unasked and is
** then refused as `RENDERER_TOO_OLD`; the job after it asks here first.
***************************************************************************/ ***************************************************************************/
private void probe() throws Exception private void probe() throws Exception
{ {
@@ -33,7 +33,7 @@ import com.kingsrook.qbits.documentgeneration.GenerationPorts.FailureCode;
** | Renderer | Answers | Refusals it may name | Version 2 scene, render target, preview | ** | Renderer | Answers | Refusals it may name | Version 2 scene, render target, preview |
** |----------|--------------------------------------------|-------------------------------|-----------------------------------------| ** |----------|--------------------------------------------|-------------------------------|-----------------------------------------|
** | 0.1.0 | the released fields only | the 13 released codes | refused: `RENDERER_TOO_OLD` | ** | 0.1.0 | the released fields only | the 13 released codes | refused: `RENDERER_TOO_OLD` |
** | 0.2.0 | the same, with `diagnostics` (and `detail`) | those and the 15 scene codes | rendered | ** | 0.2.0 | the same, with `diagnostics` (and `detail`) | those and the 17 scene codes | rendered |
** **
** Each set is written out. A range of the enum would take in whatever is added ** Each set is written out. A range of the enum would take in whatever is added
** between its ends, and a worker would gain a refusal nobody decided it has. ** between its ends, and a worker would gain a refusal nobody decided it has.
@@ -53,7 +53,8 @@ enum RendererVersion
FailureCode.SCANNER_BARCODE_CHECKSUM_MISMATCH, FailureCode.UNSUPPORTED_BARCODE_OPTION, FailureCode.SCANNER_BARCODE_CHECKSUM_MISMATCH, FailureCode.UNSUPPORTED_BARCODE_OPTION,
FailureCode.SCENE_INVALID, FailureCode.STOCK_MISMATCH, FailureCode.TARGET_REQUIRES_SCENE_2, FailureCode.ELEMENT_OUTSIDE_PRINTABLE_AREA, FailureCode.TEXT_DOES_NOT_FIT, FailureCode.SCENE_INVALID, FailureCode.STOCK_MISMATCH, FailureCode.TARGET_REQUIRES_SCENE_2, FailureCode.ELEMENT_OUTSIDE_PRINTABLE_AREA, FailureCode.TEXT_DOES_NOT_FIT,
FailureCode.VALUE_MISSING, FailureCode.VALUE_TOO_LONG, FailureCode.FONT_UNKNOWN, FailureCode.FONT_MISSING_GLYPH, FailureCode.RESERVED_FONT_NAME, FailureCode.VALUE_MISSING, FailureCode.VALUE_TOO_LONG, FailureCode.FONT_UNKNOWN, FailureCode.FONT_MISSING_GLYPH, FailureCode.RESERVED_FONT_NAME,
FailureCode.BARCODE_DOES_NOT_FIT, FailureCode.GS1_INVALID, FailureCode.ASSET_UNKNOWN, FailureCode.PREVIEW_TOO_LARGE, FailureCode.RENDERER_TOO_OLD)); FailureCode.BARCODE_DOES_NOT_FIT, FailureCode.GS1_INVALID, FailureCode.ASSET_UNKNOWN, FailureCode.PREVIEW_TOO_LARGE, FailureCode.RENDERER_TOO_OLD,
FailureCode.VALUE_NOT_ENCODABLE, FailureCode.QUIET_ZONE_INTRUDED));
private final String wire; private final String wire;
private final boolean structured; private final boolean structured;
@@ -58,8 +58,9 @@ final class SceneFacts
static final Set<String> VOCABULARY = Set.of("schema", "design", "defaults", "samples", "elements", "overrides", "when", "dpi", "set", "children", static final Set<String> VOCABULARY = Set.of("schema", "design", "defaults", "samples", "elements", "overrides", "when", "dpi", "set", "children",
"id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "id", "type", "anchor", "x", "y", "width", "height", "align", "valign",
"thickness", "fill", "thickness", "fill",
"value", "valuePath", "font", "size", "lineHeight", "fit", "maxLength", "threshold", "reverse", "rotation", "value", "valuePath", "font", "size", "lineHeight", "fit", "maxLines", "shrinkTo", "overflow", "maxLength", "threshold", "reverse", "rotation",
"symbology", "symbologyPath", "allowedSymbologies", "minModule", "maxModule", "quiet", "gs1", "hri", "scannerSymbologyPath", "aimIdentifierPath", "symbology", "symbologyPath", "allowedSymbologies", "minModule", "maxModule", "quiet", "gs1", "hri", "scannerSymbologyPath", "aimIdentifierPath",
"barcodeProfile", "minHeight",
"asset", "mode"); "asset", "mode");
private static final SceneFacts NONE = new SceneFacts(false, Set.of()); private static final SceneFacts NONE = new SceneFacts(false, Set.of());
@@ -41,7 +41,14 @@ import com.kingsrook.qbits.documentgeneration.GenerationPorts;
** large to draw is refused by name. Graphic fields (`^GFA`) and boxes (`^GB`) ** large to draw is refused by name. Graphic fields (`^GFA`) and boxes (`^GB`)
** are painted exactly. Printer font text (`^A0N`), which only a version 1 ** are painted exactly. Printer font text (`^A0N`), which only a version 1
** scene emits, cannot be drawn without the printer's font: its estimated area ** scene emits, cannot be drawn without the printer's font: its estimated area
** is hatched and the page says it is not exact. ** is outlined and crossed and the page says it is not exact.
**
** The work is bounded as well as the page. Every field is counted before it
** is painted, an overlap each time, and the field that would take the page
** past sixteen times its dots is refused as `PREVIEW_TOO_LARGE`. Nothing is
** painted by testing every dot of an area: a box is at most four solid bars
** and a placeholder is an outline and two diagonals, so a label of thousands
** of fields costs what it inks, never fields times the page.
** **
** No image or font is decoded here. The only image work is writing this ** No image or font is decoded here. The only image work is writing this
** class's own one-bit bitmap as a PNG. ** class's own one-bit bitmap as a PNG.
@@ -53,7 +60,16 @@ final class ZplRaster
/////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////
static final long MAXIMUM_DOTS = 16_000_000L; static final long MAXIMUM_DOTS = 16_000_000L;
private static final int HATCH = 6; ////////////////////////////////////////////////////////////////////////////////////////////////
// what one page may be painted with, in pages: the dots its fields paint, an overlap counted //
// each time, may total sixteen times the page. Sixteen is the renderer's own limit for what //
// a version 2 scene may paint, and the label of such a scene is its one composed canvas, so //
// none comes near it. A version 1 label that painted its page more than sixteen times over //
// would print and not be previewed. The limit holds the 6000 fields the output policy //
// allows to sixteen fills of the page where 6000 were possible //
////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXIMUM_COATS = 16;
private static final byte[] SIGNATURE = {(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10}; private static final byte[] SIGNATURE = {(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10};
private final int width; private final int width;
@@ -61,6 +77,7 @@ final class ZplRaster
private final int stride; private final int stride;
private final byte[] ink; private final byte[] ink;
private boolean exact = true; private boolean exact = true;
private long painted;
@@ -138,9 +155,11 @@ final class ZplRaster
/*************************************************************************** /***************************************************************************
** A page that shows only where elements were refused: each box, given in ** A page that shows only where elements were refused: each box, given in
** dots from the printable area's top left as a diagnostic gives it, hatched ** dots from the printable area's top left as a diagnostic gives it, outlined
** at its place on the page and cut to the page. It is drawn from numbers ** and crossed at its place on the page and cut to the page. It is drawn from
** alone. No label exists for it, so nothing of it can be printed. ** numbers alone. No label exists for it, so nothing of it can be printed.
** The boxes are counted like the fields of a label: more of them than the
** page may be painted with is `PREVIEW_TOO_LARGE`.
***************************************************************************/ ***************************************************************************/
static ZplRaster refused(int width, int height, int originX, int originY, List<List<Integer>> boxes) static ZplRaster refused(int width, int height, int originX, int originY, List<List<Integer>> boxes)
{ {
@@ -152,10 +171,7 @@ final class ZplRaster
long top = Math.max(0L, (long) originY + box.get(1)); long top = Math.max(0L, (long) originY + box.get(1));
long right = Math.min(width, (long) originX + box.get(0) + box.get(2)); long right = Math.min(width, (long) originX + box.get(0) + box.get(2));
long bottom = Math.min(height, (long) originY + box.get(1) + box.get(3)); long bottom = Math.min(height, (long) originY + box.get(1) + box.get(3));
if(left < right && top < bottom) page.hatch((int) left, (int) top, (int) Math.max(0L, right - left), (int) Math.max(0L, bottom - top));
{
page.hatch((int) left, (int) top, (int) (right - left), (int) (bottom - top));
}
} }
return (page); return (page);
} }
@@ -281,7 +297,8 @@ final class ZplRaster
/*************************************************************************** /***************************************************************************
** Printer font text: the area the policy holds it to (one cell of the font ** Printer font text: the area the policy holds it to (one cell of the font
** width for each character, one line of the font height), hatched. ** width for each character, one line of the font height), outlined and
** crossed.
***************************************************************************/ ***************************************************************************/
private void text(Reader reader, int x, int y) private void text(Reader reader, int x, int y)
{ {
@@ -324,21 +341,70 @@ final class ZplRaster
{ {
throw new IllegalArgumentException("RASTER_FIELD"); throw new IllegalArgumentException("RASTER_FIELD");
} }
for(int row = 0; row < boxHeight; row++) border(x, y, boxWidth, boxHeight, thickness);
}
/***************************************************************************
** A border inside an area that is known to be on the page: the whole area
** when the border meets itself, else four bars that do not overlap (the top
** and bottom across the whole width, the sides between them).
***************************************************************************/
private void border(int x, int y, int areaWidth, int areaHeight, int thickness)
{
if(2L * thickness >= Math.min(areaWidth, areaHeight))
{ {
boolean border = row < thickness || row >= boxHeight - thickness; fill(x, y, areaWidth, areaHeight);
for(int column = 0; column < boxWidth; column++) return;
}
fill(x, y, areaWidth, thickness);
fill(x, y + areaHeight - thickness, areaWidth, thickness);
fill(x, y + thickness, thickness, areaHeight - 2 * thickness);
fill(x + areaWidth - thickness, y + thickness, thickness, areaHeight - 2 * thickness);
}
/***************************************************************************
** Ink a solid rectangle that is known to be on the page, whole bytes at a
** time: the first and last byte of each row are masked to the rectangle.
***************************************************************************/
private void fill(int x, int y, int areaWidth, int areaHeight)
{
admit((long) areaWidth * areaHeight);
int first = x / 8;
int last = (x + areaWidth - 1) / 8;
int head = 0xFF >> x % 8;
int tail = 0xFF << (7 - (x + areaWidth - 1) % 8);
for(int row = y; row < y + areaHeight; row++)
{
for(int index = first; index <= last; index++)
{ {
if(border || column < thickness || column >= boxWidth - thickness) ink[row * stride + index] |= (byte) ((index == first ? head : 0xFF) & (index == last ? tail : 0xFF));
{
set(x + column, y + row);
}
} }
} }
} }
/***************************************************************************
** Count the dots a field is about to paint, or refuse the field that would
** take the page past `MAXIMUM_COATS` times its dots. Every painter counts
** before it paints, so the work a label can cause is bounded by its page
** and not by the number of its fields.
***************************************************************************/
private void admit(long dots)
{
if(painted + dots > MAXIMUM_COATS * (long) width * height)
{
throw new IllegalArgumentException("PREVIEW_TOO_LARGE");
}
painted += dots;
}
/*************************************************************************** /***************************************************************************
** An uncompressed graphic field: rows of whole bytes, most significant bit ** An uncompressed graphic field: rows of whole bytes, most significant bit
** first. Bits that pad the last byte of a row past the page edge must be ** first. Bits that pad the last byte of a row past the page edge must be
@@ -358,6 +424,7 @@ final class ZplRaster
throw new IllegalArgumentException("RASTER_FIELD"); throw new IllegalArgumentException("RASTER_FIELD");
} }
inside(x, y, 1, total / rowBytes); inside(x, y, 1, total / rowBytes);
admit(8L * total);
for(int index = 0; index < total; index++) for(int index = 0; index < total; index++)
{ {
int value = reader.hex() * 16 + reader.hex(); int value = reader.hex() * 16 + reader.hex();
@@ -393,20 +460,28 @@ final class ZplRaster
/*************************************************************************** /***************************************************************************
** An outline with diagonal lines across it: plainly a placeholder, never ** An outline with its two diagonals across it: plainly a placeholder, never
** mistaken for ink the label holds. ** mistaken for ink the label holds. It costs its perimeter and the length
** of its diagonals, not its area: each diagonal has one dot for each step
** along the longer side. An area of no width or no height has no dots and
** nothing is drawn for it: its outline and diagonals would otherwise be
** placed one dot outside it.
***************************************************************************/ ***************************************************************************/
private void hatch(int x, int y, int areaWidth, int areaHeight) private void hatch(int x, int y, int areaWidth, int areaHeight)
{ {
for(int row = 0; row < areaHeight; row++) if(areaWidth < 1 || areaHeight < 1)
{ {
for(int column = 0; column < areaWidth; column++) return;
{ }
if(row == 0 || column == 0 || row == areaHeight - 1 || column == areaWidth - 1 || (row + column) % HATCH == 0) border(x, y, areaWidth, areaHeight, 1);
{ int steps = Math.max(areaWidth, areaHeight);
set(x + column, y + row); admit(2L * steps);
} for(int step = 0; step < steps; step++)
} {
int column = (int) ((long) step * (areaWidth - 1) / Math.max(1, steps - 1));
int row = (int) ((long) step * (areaHeight - 1) / Math.max(1, steps - 1));
set(x + column, y + row);
set(x + areaWidth - 1 - column, y + row);
} }
} }
@@ -185,7 +185,7 @@ class BridgeTest
{ {
var released = java.util.EnumSet.range(GenerationPorts.FailureCode.BARCODE_FIT_TOO_SMALL, GenerationPorts.FailureCode.UNSUPPORTED_BARCODE_OPTION); var released = java.util.EnumSet.range(GenerationPorts.FailureCode.BARCODE_FIT_TOO_SMALL, GenerationPorts.FailureCode.UNSUPPORTED_BARCODE_OPTION);
assertEquals(13, released.size()); assertEquals(13, released.size());
assertEquals(28, GenerationPorts.FailureCode.values().length); assertEquals(30, GenerationPorts.FailureCode.values().length);
for(var code : GenerationPorts.FailureCode.values()) for(var code : GenerationPorts.FailureCode.values())
{ {
var bridge = new IsolatedRendererBridge(config(directory), (actor, asset, maximum) -> new byte[0], (id, input, maximum) -> var bridge = new IsolatedRendererBridge(config(directory), (actor, asset, maximum) -> new byte[0], (id, input, maximum) ->
@@ -29,6 +29,7 @@ import java.util.Base64;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Supplier;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.kingsrook.qbits.documentgeneration.GenerationPorts; import com.kingsrook.qbits.documentgeneration.GenerationPorts;
@@ -49,7 +50,7 @@ final class FakeWorker implements IsolatedRendererBridge.Exchange
final List<JsonNode> jobs = new ArrayList<>(); final List<JsonNode> jobs = new ArrayList<>();
final List<JsonNode> questions = new ArrayList<>(); final List<JsonNode> questions = new ArrayList<>();
final List<Integer> frameLimits = new ArrayList<>(); final List<Integer> frameLimits = new ArrayList<>();
private final String version; private final Supplier<String> version;
private final Answer answer; private final Answer answer;
@@ -72,6 +73,17 @@ final class FakeWorker implements IsolatedRendererBridge.Exchange
** A worker of a version that answers every job the same way. ** A worker of a version that answers every job the same way.
***************************************************************************/ ***************************************************************************/
FakeWorker(String version, Answer answer) FakeWorker(String version, Answer answer)
{
this(() -> version, answer);
}
/***************************************************************************
** A worker whose image can be replaced while a bridge uses it: it answers
** the version question as the renderer that is running at that moment.
***************************************************************************/
FakeWorker(Supplier<String> version, Answer answer)
{ {
this.version = version; this.version = version;
this.answer = answer; this.answer = answer;
@@ -90,7 +102,7 @@ final class FakeWorker implements IsolatedRendererBridge.Exchange
if(IsolatedRendererBridge.PROBE_SCENE.equals(job.path("source").textValue())) if(IsolatedRendererBridge.PROBE_SCENE.equals(job.path("source").textValue()))
{ {
questions.add(job); questions.add(job);
return (frame(validated(requestId, version))); return (frame(validated(requestId, version.get())));
} }
jobs.add(job); jobs.add(job);
frameLimits.add(maximumOutput); frameLimits.add(maximumOutput);
@@ -0,0 +1,218 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.documentgeneration.renderer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kingsrook.qbits.documentgeneration.DocumentDefinitionService;
import com.kingsrook.qbits.documentgeneration.DocumentGenerationQBitConfig;
import com.kingsrook.qbits.documentgeneration.DocumentGenerationQBitProducer;
import com.kingsrook.qbits.documentgeneration.DocumentPreviewService;
import com.kingsrook.qbits.documentgeneration.GenerationPorts;
import com.kingsrook.qbits.documentgeneration.GenerationPorts.Diagnostic;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.session.QSession;
import com.kingsrook.qqq.backend.core.model.session.QUser;
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryRecordStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The layout preview from the module's own service down to this bridge: what a
** person sees is decoded from exactly the bytes the print path would validate
** for the same template, data and resolution.
*******************************************************************************/
class LayoutPreviewServiceTest
{
@TempDir
Path directory;
private final List<GenerationPorts.PreviewRequest> previewed = new ArrayList<>();
private DocumentGenerationQBitConfig config;
private IsolatedRendererBridge bridge;
private FakeWorker worker;
private Integer template;
/***************************************************************************
** The QBit on a memory backend with this bridge as its renderer, and one
** person who may author templates.
***************************************************************************/
@BeforeEach
void setup() throws Exception
{
MemoryRecordStore.getInstance().reset();
QInstance instance = new QInstance().withInstanceDefaultAuthentication(new QAuthenticationMetaData().withName("anonymous").withType(QAuthenticationType.FULLY_ANONYMOUS));
instance.addBackend(new QBackendMetaData().withName("memory").withBackendType(MemoryBackendModule.class));
instance.addTable(new QTableMetaData().withName("orders").withBackendName("memory").withPrimaryKeyField("id").withField(new QFieldMetaData("id", QFieldType.INTEGER)));
config = new DocumentGenerationQBitConfig().withBackendName("memory").withSourceTables(List.of("orders")).withMaximumOutputBytes(1024 * 1024)
.withRenderer(new GenerationPorts.IsolatedRenderer()
{
/***************************************************************************
** Publication is not part of this test.
***************************************************************************/
public void validate(String actor, GenerationPorts.Revision revision)
{
}
/***************************************************************************
** The print path of the bridge.
***************************************************************************/
public GenerationPorts.Content render(GenerationPorts.RenderRequest request) throws QException
{
return (bridge.render(request));
}
/***************************************************************************
** The preview of the bridge, remembering the job the service built.
***************************************************************************/
@Override
public GenerationPorts.Preview preview(GenerationPorts.PreviewRequest request) throws QException
{
previewed.add(request);
return (bridge.preview(request));
}
});
new DocumentGenerationQBitProducer().withQBitConfig(config).produce(instance);
QContext.init(instance, new QSession().withUser(new QUser().withIdReference("author-1")).withPermissions("document-generation.view", "document-generation.configure"));
}
/***************************************************************************
** Release the context and the in-memory records.
***************************************************************************/
@AfterEach
void clear()
{
QContext.clear();
MemoryRecordStore.getInstance().reset();
}
/***************************************************************************
** A draft with this scene on this stock.
***************************************************************************/
private void draft(String scene, GenerationPorts.Stock stock) throws Exception
{
DocumentDefinitionService definitions = new DocumentDefinitionService(config);
Integer type = definitions.createType("label");
Integer stockId = definitions.createStock("stock", stock);
definitions.bind(type, "orders", true, true);
template = definitions.createTemplate("label", type, stockId, "orders");
definitions.saveDraft(template, stockId, new DocumentDefinitionService.Draft(null, scene, null, List.of()));
}
/***************************************************************************
** At each resolution the preview the service returns for a version 2 scene
** with its sample data has the size and hash of exactly the bytes the print
** path returns for the same revision, context and render target, and the
** worker received the same job both times. Nothing is written to disk.
***************************************************************************/
@ParameterizedTest
@ValueSource(ints = {203, 300, 600})
void thePreviewOfAVersionTwoSceneHasTheHashOfTheBytesThePrintPathValidates(int dpi) throws Exception
{
ObjectNode scene = (ObjectNode) RendererJson.JSON.readTree(FakeWorker.scene("margins"));
scene.putObject("samples").putObject("typical").putObject("record").put("name", "A synthetic sample");
draft(RendererJson.JSON.writeValueAsString(scene), FakeWorker.stock("margins"));
worker = new FakeWorker(FakeWorker.CURRENT, job -> FakeWorker.rendered(job.path("requestId").textValue(), FakeWorker.CURRENT, FakeWorker.golden("margins", dpi), List.of()));
bridge = FakeWorker.bridge(directory, worker);
DocumentPreviewService.Result result = new DocumentPreviewService(config).preview(new DocumentPreviewService.Options(template, null, GenerationPorts.Format.ZPL,
DocumentPreviewService.Data.SAMPLE, null, null, null, dpi));
GenerationPorts.PreviewRequest request = previewed.get(0);
GenerationPorts.Content printed = bridge.render(new GenerationPorts.RenderRequest("request-1", request.actorId(), new GenerationPorts.Source("orders", "1"), request.format(),
request.revision(), request.context(), request.maximumBytes(), request.targetDpi()));
assertTrue(result.preview().printable());
assertTrue(result.preview().exact());
assertEquals(dpi, result.dpi());
assertArrayEquals(FakeWorker.golden("margins", dpi), printed.bytes());
assertEquals(RendererJson.hash(printed.bytes()), result.preview().outputSha256());
assertEquals((long) printed.bytes().length, result.preview().outputBytes());
assertEquals(1, result.preview().pages().size());
assertEquals(2, worker.jobs.size());
ObjectNode previewJob = (ObjectNode) worker.jobs.get(0);
ObjectNode printJob = (ObjectNode) worker.jobs.get(1);
assertEquals("COLLECT", previewJob.remove("diagnostics").textValue());
previewJob.remove("requestId");
printJob.remove("requestId");
assertEquals(printJob, previewJob);
assertEquals("A synthetic sample", previewJob.path("context").path("record").path("name").textValue());
assertEquals(dpi, previewJob.path("targetDpi").intValue());
try(Stream<Path> files = Files.walk(directory))
{
assertEquals(List.of(), files.filter(Files::isRegularFile).toList());
}
}
/***************************************************************************
** A version 1 label comes back through the service as a picture that is not
** exact, with the warning that printer font text is not shown.
***************************************************************************/
@Test
void aVersionOneLabelIsNotExactAndSaysWhy() throws Exception
{
byte[] label = BridgeTest.LABEL.getBytes(StandardCharsets.US_ASCII);
draft(FakeWorker.VERSION_ONE_SCENE, BridgeTest.STOCK);
worker = new FakeWorker(FakeWorker.CURRENT, job -> FakeWorker.rendered(job.path("requestId").textValue(), FakeWorker.CURRENT, label, List.of()));
bridge = FakeWorker.bridge(directory, worker);
DocumentPreviewService.Result result = new DocumentPreviewService(config).preview(new DocumentPreviewService.Options(template, null, GenerationPorts.Format.ZPL,
DocumentPreviewService.Data.SAMPLE, null, null, null, null));
assertTrue(result.preview().printable());
assertFalse(result.preview().exact());
assertEquals(List.of(new Diagnostic("PRINTER_FONT_NOT_SHOWN", Diagnostic.Severity.WARNING, null, null, null, null)), result.preview().diagnostics());
assertEquals(RendererJson.hash(label), result.preview().outputSha256());
assertEquals(Map.of(), previewed.get(0).context());
assertEquals(BridgeTest.STOCK.dpi(), result.dpi());
}
}
@@ -27,6 +27,9 @@ import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -44,6 +47,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -157,7 +161,7 @@ class PreviewTest
** the preview has no output. Its page is drawn on the host from the boxes of ** the preview has no output. Its page is drawn on the host from the boxes of
** the error diagnostics alone, placed from the printable area's corner as ** the error diagnostics alone, placed from the printable area's corner as
** the renderer places it (the corner of the golden label at each ** the renderer places it (the corner of the golden label at each
** resolution), cut to the page and hatched. ** resolution), cut to the page, outlined and crossed.
***************************************************************************/ ***************************************************************************/
@ParameterizedTest @ParameterizedTest
@ValueSource(ints = {203, 300, 600}) @ValueSource(ints = {203, 300, 600})
@@ -190,8 +194,8 @@ class PreviewTest
{ {
for(int x = 0; x < page.getWidth(); x++) for(int x = 0; x < page.getWidth(); x++)
{ {
boolean first = hatched(x - left, y - top, 16, 12); boolean first = ZplRasterTest.crossed(x - left, y - top, 16, 12);
boolean last = hatched(x, y - top - 30, left + 20, page.getHeight() - top - 30); boolean last = ZplRasterTest.crossed(x, y - top - 30, left + 20, page.getHeight() - top - 30);
assertEquals(first || last, (page.getRGB(x, y) & 0xFFFFFF) == 0, x + ", " + y); assertEquals(first || last, (page.getRGB(x, y) & 0xFFFFFF) == 0, x + ", " + y);
} }
} }
@@ -201,17 +205,6 @@ class PreviewTest
/***************************************************************************
** Whether a dot is ink in a hatched area of this size whose corner is the
** origin of `column` and `row`.
***************************************************************************/
private static boolean hatched(int column, int row, int width, int height)
{
return (column >= 0 && column < width && row >= 0 && row < height && (column == 0 || row == 0 || column == width - 1 || row == height - 1 || (column + row) % 6 == 0));
}
/*************************************************************************** /***************************************************************************
** A refusal is a result of a preview, not an exception: whatever the print ** A refusal is a result of a preview, not an exception: whatever the print
** path would refuse by name comes back as the diagnostic, not printable, ** path would refuse by name comes back as the diagnostic, not printable,
@@ -296,6 +289,69 @@ class PreviewTest
/***************************************************************************
** A label the output policy accepts can still hold thousands of boxes that
** each cover the page. It is not drawn dot by dot while an admission slot is
** held: a label that would paint more than sixteen times its page comes
** back at once as `PREVIEW_TOO_LARGE`, a result with the limit and no page.
** Printing the same label is not changed by it.
***************************************************************************/
@Test
void aLabelThatWouldPaintTooMuchIsRefusedAsAResult() throws Exception
{
GenerationPorts.Stock stock = new GenerationPorts.Stock(101600, 152400, 0, 0, 0, 0, 600);
byte[] label = ("^XA^PW2400^LL3600^LH0,0^CI28\n" + "^FO0,0^GB2400,3600,1200^FS\n".repeat(6000) + "^XZ\n").getBytes(StandardCharsets.US_ASCII);
FakeWorker worker = answering(job -> FakeWorker.rendered(job.path("requestId").textValue(), FakeWorker.CURRENT, label, List.of()));
IsolatedRendererBridge bridge = FakeWorker.bridge(directory, worker);
var request = new GenerationPorts.PreviewRequest("actor-1", GenerationPorts.Format.ZPL, FakeWorker.revision(FakeWorker.VERSION_ONE_SCENE, stock), Map.of(), null, MAXIMUM);
GenerationPorts.Preview preview = assertTimeoutPreemptively(Duration.ofSeconds(10), () -> bridge.preview(request));
assertFalse(preview.printable());
assertFalse(preview.exact());
assertEquals(List.of(new Diagnostic("PREVIEW_TOO_LARGE", Diagnostic.Severity.ERROR, null, null, null, Map.of("paintedPercent", 1600))), preview.diagnostics());
assertEquals(List.of(), preview.pages());
assertEquals(0L, preview.outputBytes());
assertEquals(NOTHING, preview.outputSha256());
assertEquals(1, worker.jobs.size());
assertArrayEquals(label, bridge.render(new GenerationPorts.RenderRequest("request-1", "actor-1", new GenerationPorts.Source("orders", "1"), GenerationPorts.Format.ZPL, request.revision(), Map.of(),
MAXIMUM)).bytes());
}
/***************************************************************************
** The page of a refused scene is bounded too. On a narrow stock of 8 x
** 15984 dots a box of the whole page costs 63948 dots of outline and
** diagonals, so 31 such boxes are within sixteen times the page and are
** drawn; with 32 there is no page, and `PREVIEW_TOO_LARGE` joins the
** diagnostics the worker sent.
***************************************************************************/
@Test
void aRefusedSceneWithTooManyLargeBoxesHasNoPage() throws Exception
{
GenerationPorts.Stock narrow = new GenerationPorts.Stock(1000, 2000000, 0, 0, 0, 0, 203);
var request = new GenerationPorts.PreviewRequest("actor-1", GenerationPorts.Format.ZPL, FakeWorker.revision(FakeWorker.scene("anchors"), narrow), Map.of(), null, MAXIMUM);
Map<String, Object> whole = FakeWorker.diagnostic("ELEMENT_OUTSIDE_PRINTABLE_AREA", "ERROR", "box", List.of(0, 0, 8, 15984));
Diagnostic read = new Diagnostic("ELEMENT_OUTSIDE_PRINTABLE_AREA", Diagnostic.Severity.ERROR, null, List.of(0, 0, 8, 15984), null, null);
GenerationPorts.Preview drawn = FakeWorker.bridge(directory, answering(job -> FakeWorker.refused(job.path("requestId").textValue(), Collections.nCopies(31, whole)))).preview(request);
assertEquals(1, drawn.pages().size());
assertEquals(8, drawn.pages().get(0).widthDots());
assertEquals(15984, drawn.pages().get(0).heightDots());
assertEquals(Collections.nCopies(31, read), drawn.diagnostics());
GenerationPorts.Preview undrawn = FakeWorker.bridge(directory, answering(job -> FakeWorker.refused(job.path("requestId").textValue(), Collections.nCopies(32, whole)))).preview(request);
List<Diagnostic> expected = new ArrayList<>(Collections.nCopies(32, read));
expected.add(new Diagnostic("PREVIEW_TOO_LARGE", Diagnostic.Severity.ERROR, null, null, null, Map.of("paintedPercent", 1600)));
assertEquals(expected, undrawn.diagnostics());
assertEquals(List.of(), undrawn.pages());
assertFalse(undrawn.printable());
assertFalse(undrawn.exact());
assertEquals(0L, undrawn.outputBytes());
assertEquals(NOTHING, undrawn.outputSha256());
}
/*************************************************************************** /***************************************************************************
** A version 1 label previews with its graphics and boxes exact and each ** A version 1 label previews with its graphics and boxes exact and each
** printer font field as a placeholder: the page is not exact and says why. ** printer font field as a placeholder: the page is not exact and says why.
@@ -60,7 +60,7 @@ class SceneFactsTest
Set<String> declared = new TreeSet<>(); Set<String> declared = new TreeSet<>();
names(RendererJson.JSON.readTree(Files.readAllBytes(Path.of("..", "..", "renderer", "schema", "zpl-scene-2.schema.json"))), declared); names(RendererJson.JSON.readTree(Files.readAllBytes(Path.of("..", "..", "renderer", "schema", "zpl-scene-2.schema.json"))), declared);
assertEquals(declared, new TreeSet<>(SceneFacts.VOCABULARY)); assertEquals(declared, new TreeSet<>(SceneFacts.VOCABULARY));
assertEquals(43, SceneFacts.VOCABULARY.size()); assertEquals(48, SceneFacts.VOCABULARY.size());
} }
@@ -0,0 +1,378 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.documentgeneration.renderer;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import com.kingsrook.qbits.documentgeneration.GenerationPorts;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*******************************************************************************
** What today's bridge does with an answer to a version 1 print job: one row
** for each answer, every row through `render`.
**
** What this is, and what it is not. The answers are synthetic: the fake worker
** of these tests builds each one in the shape the released renderer
** (`qqq-renderer-0.1.0`) answers with, or in that shape with one stated
** change. None was captured from the released renderer. The expected outcome
** of each row is what the bridge of this branch does with that answer, written
** down when the table was made. No row was run against the released bridge
** (tag `v1.1.0-RC.2`), so the table does not show that today's bridge treats
** an answer as the released one did. It holds today's behaviour still: a
** change to what the bridge accepts, refuses or rejects fails a row. The one
** artefact captured at the released tag is the job frame, which
** `VersionOneJobFrameTest` compares.
**
** `render` has three outcomes and no other: the label, a typed refusal with a
** code of the closed vocabulary, or the one generic rejection, which names
** nothing. Each row states which. Beside it the row states the name the
** version rule (`WorkerAnswer`) gives the same frame for the same job, or `-`
** when the rule passes it; a row that the rule passes and `render` rejects was
** rejected by the checks on the document that follow the rule (its size and
** hash, its metadata, the output policy), whose names never leave the bridge.
*******************************************************************************/
class VersionOneAnswerTableTest
{
private static final String ACCEPTED = "ACCEPTED";
private static final String REJECTED = "REJECTED";
private static final String PASSES = "-";
private static final String REQUEST_ID = "request-1";
private static final int MAXIMUM = 4096;
private static final byte[] LABEL = "^XA^PW812^LL1218^LH0,0^CI28\n^FO2,40^GB20,10,1^FS\n^XZ\n".getBytes(StandardCharsets.US_ASCII);
private static final byte[] ELSEWHERE = "^XA^PW406^LL203^LH0,0^CI28\n^FO2,40^GB20,10,1^FS\n^XZ\n".getBytes(StandardCharsets.US_ASCII);
private static final byte[] COMMAND = "^XA^PW812^LL1218^LH0,0^CI28\n^FO2,40^GB20,10,1^FS\n^XZ\n~JR".getBytes(StandardCharsets.US_ASCII);
@TempDir
Path directory;
/***************************************************************************
** The frame a worker answers a request with.
***************************************************************************/
@FunctionalInterface
interface Frame
{
/************************************************************************
** The bytes of the answer to the request of this id.
************************************************************************/
byte[] to(String requestId) throws Exception;
}
/***************************************************************************
** A row whose answer is the well-formed answer of the released renderer
** with one change to its fields.
***************************************************************************/
private static Arguments changed(String name, String outcome, String rule, Consumer<Map<String, Object>> change)
{
Frame frame = id ->
{
Map<String, Object> fields = FakeWorker.rendered(id, FakeWorker.RELEASED, LABEL, List.of());
change.accept(fields);
return (FakeWorker.frame(fields));
};
return (Arguments.of(name, frame, outcome, rule));
}
/***************************************************************************
** A row whose answer is the well-formed answer for another document.
***************************************************************************/
private static Arguments document(String name, String outcome, String rule, byte[] label)
{
return (Arguments.of(name, (Frame) id -> FakeWorker.frame(FakeWorker.rendered(id, FakeWorker.RELEASED, label, List.of())), outcome, rule));
}
/***************************************************************************
** A row whose answer is an error answer of the released renderer, with one
** change to its fields.
***************************************************************************/
private static Arguments error(String name, String outcome, String rule, String code, Consumer<Map<String, Object>> change)
{
Frame frame = id ->
{
Map<String, Object> fields = FakeWorker.error(id, FakeWorker.RELEASED, code, null);
change.accept(fields);
return (FakeWorker.frame(fields));
};
return (Arguments.of(name, frame, outcome, rule));
}
/***************************************************************************
** A row whose answer is the well-formed frame with its bytes changed.
***************************************************************************/
private static Arguments bytes(String name, String outcome, String rule, UnaryOperator<String> change)
{
Frame frame = id -> change.apply(new String(FakeWorker.frame(FakeWorker.rendered(id, FakeWorker.RELEASED, LABEL, List.of())), StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8);
return (Arguments.of(name, frame, outcome, rule));
}
/***************************************************************************
** No change: the row's answer is sent as its renderer writes it.
***************************************************************************/
private static void unchanged(Map<String, Object> fields)
{
////////////////////////////////////////////
// nothing is added, removed or reordered //
////////////////////////////////////////////
}
/***************************************************************************
** The fields of an answer in the opposite order.
***************************************************************************/
private static void reverse(Map<String, Object> fields)
{
List<Map.Entry<String, Object>> entries = new ArrayList<>(fields.entrySet().stream().map(entry -> Map.entry(entry.getKey(), entry.getValue())).toList());
fields.clear();
for(Map.Entry<String, Object> entry : entries.reversed())
{
fields.put(entry.getKey(), entry.getValue());
}
}
/***************************************************************************
** The table. Its rows follow the rule as it is written in `WorkerAnswer`,
** `RendererVersion` and the bridge's checks on the document.
***************************************************************************/
static Stream<Arguments> answers() throws Exception
{
Map<String, Object> warning = FakeWorker.diagnostic("DEVICE_UNIT_USED", "WARNING");
Map<String, Object> fit = FakeWorker.diagnostic("BARCODE_FIT_TOO_SMALL", "ERROR");
String other = RendererJson.hash(ELSEWHERE);
return (Stream.of(
///////////////////////////////////////////////////////////////////////////////
// accepted: the released answer, whatever the order and spacing of its JSON //
///////////////////////////////////////////////////////////////////////////////
changed("the released answer", ACCEPTED, PASSES, VersionOneAnswerTableTest::unchanged),
changed("its fields in another order", ACCEPTED, PASSES, VersionOneAnswerTableTest::reverse),
bytes("spaces between its tokens", ACCEPTED, PASSES, frame -> frame.replace("\":", "\" : ").replace(",\"", " , \"")),
bytes("spaces after its object", ACCEPTED, PASSES, frame -> frame.replace("}\n", "} \n")),
changed("base64 without its padding", ACCEPTED, PASSES, fields -> fields.put("base64", ((String) fields.get("base64")).replace("=", ""))),
/////////////////////////////////////////////////////////////////////////////
// typed refusals: an error answer that names one of the 13 released codes //
/////////////////////////////////////////////////////////////////////////////
error("an error with a released code", "BARCODE_FIT_TOO_SMALL", "BARCODE_FIT_TOO_SMALL", "BARCODE_FIT_TOO_SMALL", VersionOneAnswerTableTest::unchanged),
error("an error with the last released code", "UNSUPPORTED_BARCODE_OPTION", "UNSUPPORTED_BARCODE_OPTION", "UNSUPPORTED_BARCODE_OPTION", VersionOneAnswerTableTest::unchanged),
/////////////////////////////////////////////////
// rejected: what only renderer 0.2.0 may send //
/////////////////////////////////////////////////
changed("with empty diagnostics", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("diagnostics", List.of())),
changed("with a warning in diagnostics", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("diagnostics", List.of(warning))),
changed("with a detail", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("detail", fit)),
changed("with the outcome REFUSED", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("outcome", "REFUSED")),
error("a bare REFUSED answer", REJECTED, "WORKER_RESPONSE_REJECTED", "BARCODE_FIT_TOO_SMALL", fields ->
{
fields.put("outcome", "REFUSED");
fields.remove("code");
}),
error("a REFUSED answer with an error in diagnostics", REJECTED, "WORKER_RESPONSE_REJECTED", "BARCODE_FIT_TOO_SMALL", fields ->
{
fields.put("outcome", "REFUSED");
fields.remove("code");
fields.put("diagnostics", List.of(fit));
}),
error("an error with a detail", REJECTED, "WORKER_ERROR_REJECTED", "BARCODE_FIT_TOO_SMALL", fields -> fields.put("detail", fit)),
error("an error with diagnostics", REJECTED, "WORKER_ERROR_REJECTED", "BARCODE_FIT_TOO_SMALL", fields -> fields.put("diagnostics", List.of(fit))),
error("an error with a version 2 scene code", REJECTED, "WORKER_ERROR_REJECTED", "SCENE_INVALID", VersionOneAnswerTableTest::unchanged),
error("an error that says the renderer is too old", REJECTED, "WORKER_ERROR_REJECTED", "RENDERER_TOO_OLD", VersionOneAnswerTableTest::unchanged),
error("an error that says the preview is too large", REJECTED, "WORKER_ERROR_REJECTED", "PREVIEW_TOO_LARGE", VersionOneAnswerTableTest::unchanged),
changed("renderer 0.2.0 named on the released fields", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("rendererVersion", FakeWorker.CURRENT)),
///////////////////////////////////////////////////////
// rejected: an error answer that is not exactly one //
///////////////////////////////////////////////////////
error("an error with an unknown code", REJECTED, "WORKER_ERROR_REJECTED", "NOT_A_CODE", VersionOneAnswerTableTest::unchanged),
error("an error with a code in lower case", REJECTED, "WORKER_ERROR_REJECTED", "barcode_fit_too_small", VersionOneAnswerTableTest::unchanged),
error("an error with no code", REJECTED, "WORKER_ERROR_REJECTED", "BARCODE_FIT_TOO_SMALL", fields -> fields.remove("code")),
error("an error with a field too many", REJECTED, "WORKER_ERROR_REJECTED", "BARCODE_FIT_TOO_SMALL", fields -> fields.put("pageCount", 1)),
changed("the released answer with a code", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("code", "BARCODE_FIT_TOO_SMALL")),
///////////////////////////////////////////////////////////////////////////////////
// rejected: the envelope is not this protocol, this request, this catalog or an //
// accepted renderer //
///////////////////////////////////////////////////////////////////////////////////
changed("another protocol", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("protocol", "qbit-document-renderer/2")),
changed("no protocol", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.remove("protocol")),
changed("another request", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("requestId", "request-2")),
changed("another catalog", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("catalogVersion", "qqq-barcodes-8")),
changed("an outcome that is not one", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("outcome", "DONE")),
changed("no outcome", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.remove("outcome")),
changed("a later patch version", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("rendererVersion", "qqq-renderer-0.1.1")),
changed("a later renderer", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("rendererVersion", "qqq-renderer-0.3.0")),
changed("the version number alone", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("rendererVersion", "0.1.0")),
changed("the version in upper case", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("rendererVersion", "QQQ-RENDERER-0.1.0")),
changed("the version with a space after it", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.put("rendererVersion", "qqq-renderer-0.1.0 ")),
changed("no version", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.remove("rendererVersion")),
changed("a version longer than a version", REJECTED, "RESPONSE_TEXT_LIMIT", fields -> fields.put("rendererVersion", "qqq-renderer-0.1.0" + "0".repeat(111))),
//////////////////////////////////////////////////////////////////////
// rejected: the fields are not the released fields in their shapes //
//////////////////////////////////////////////////////////////////////
changed("a field missing", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.remove("pageCount")),
changed("the answer to a validation", REJECTED, "WORKER_RESPONSE_REJECTED", fields -> fields.keySet().retainAll(List.of("protocol", "requestId", "outcome", "rendererVersion", "catalogVersion"))),
changed("an unknown field", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("note", "x")),
changed("a render target", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("targetDpi", 203)),
changed("the length as text", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("length", String.valueOf(LABEL.length))),
changed("the length as a fraction", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("length", (double) LABEL.length)),
changed("the media type as a number", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("mediaType", 1)),
changed("a null field", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("sha256", null)),
changed("diagnostics that are not a list", REJECTED, "RESPONSE_FIELD_REJECTED", fields -> fields.put("diagnostics", "none")),
/////////////////////////////////////////////////////////////////////////////
// rejected: the frame is not one line of one JSON object within its bound //
/////////////////////////////////////////////////////////////////////////////
bytes("no line end", REJECTED, "FRAME_TRUNCATED", frame -> frame.substring(0, frame.length() - 1)),
bytes("nothing", REJECTED, "FRAME_TRUNCATED", frame -> ""),
bytes("two frames", REJECTED, "EXTRA_FRAME", frame -> frame + frame),
bytes("a carriage return", REJECTED, "EXTRA_FRAME", frame -> frame.replace("}\n", "}\r\n")),
bytes("a list", REJECTED, "RESPONSE_OBJECT_REQUIRED", frame -> "[" + frame.trim() + "]\n"),
bytes("a second value", REJECTED, "RESPONSE_TRAILING_VALUE", frame -> frame.trim() + "{}\n"),
bytes("a field twice", REJECTED, "JsonParseException", frame -> frame.replace("{\"protocol\"", "{\"pageCount\":1,\"protocol\"")),
bytes("cut short", REJECTED, "JsonEOFException", frame -> frame.substring(0, frame.length() - 2) + "\n"),
document("a document past the frame's bound", REJECTED, "RESPONSE_BYTE_LIMIT", new byte[8000]),
/////////////////////////////////////////////////////////////////////////////////////////
// rejected by the checks on the document, after the version rule has passed the frame //
/////////////////////////////////////////////////////////////////////////////////////////
changed("another hash", REJECTED, PASSES, fields -> fields.put("sha256", other)),
changed("the hash in upper case", REJECTED, PASSES, fields -> fields.put("sha256", ((String) fields.get("sha256")).toUpperCase(Locale.ROOT))),
changed("a hash longer than a hash", REJECTED, PASSES, fields -> fields.put("sha256", fields.get("sha256") + "0")),
changed("a length one more", REJECTED, PASSES, fields -> fields.put("length", LABEL.length + 1)),
changed("a length of nothing", REJECTED, PASSES, fields -> fields.put("length", 0)),
changed("a length past the limit", REJECTED, PASSES, fields -> fields.put("length", MAXIMUM + 1)),
changed("another document under the same hash", REJECTED, PASSES, fields -> fields.put("base64", Base64.getEncoder().encodeToString(ELSEWHERE))),
changed("base64 that is not base64", REJECTED, PASSES, fields -> fields.put("base64", "****")),
changed("no document", REJECTED, PASSES, fields -> fields.put("base64", "")),
changed("the media type of a page", REJECTED, PASSES, fields -> fields.put("mediaType", "application/pdf")),
changed("the media type in upper case", REJECTED, PASSES, fields -> fields.put("mediaType", "APPLICATION/VND.ZEBRA-ZPL")),
changed("two pages", REJECTED, PASSES, fields -> fields.put("pageCount", 2)),
changed("no pages", REJECTED, PASSES, fields -> fields.put("pageCount", 0)),
document("a label for another stock", REJECTED, PASSES, ELSEWHERE),
document("a label with a device command after it", REJECTED, PASSES, COMMAND),
document("a document past the job's limit", REJECTED, PASSES, new byte[MAXIMUM + 1])));
}
/***************************************************************************
** What the version rule says of a frame as the answer to the version 1
** print job of these tests: the name it rejects the frame by, the code of
** the refusal it reads from it, or `-` when it passes the frame on.
***************************************************************************/
private static String rule(byte[] frame, int maximumFrame) throws Exception
{
try
{
WorkerAnswer.read(frame, maximumFrame, REQUEST_ID, SceneFacts.of(GenerationPorts.Format.ZPL, FakeWorker.VERSION_ONE_SCENE)).settle("RENDER", false, false);
return (PASSES);
}
catch(GenerationPorts.RenderException refusal)
{
return (refusal.code().name());
}
catch(IllegalArgumentException rejected)
{
return (rejected.getMessage());
}
catch(IOException unreadable)
{
return (unreadable.getClass().getSimpleName());
}
}
/***************************************************************************
** One row: the job is sent once, as the released job, with no version
** question before it and no second attempt after it, and `render` ends as
** the row says.
***************************************************************************/
@ParameterizedTest(name = "{0}")
@MethodSource("answers")
void anAnswerInTheReleasedShapeIsHeldToTheRule(String name, Frame frame, String outcome, String rule) throws Exception
{
List<Integer> bounds = new ArrayList<>();
List<String> sent = new ArrayList<>();
IsolatedRendererBridge bridge = FakeWorker.bridge(directory, (id, input, maximum) ->
{
RendererJson.parse(input, 16 * 1024 * 1024).fieldNames().forEachRemaining(sent::add);
bounds.add(maximum);
return (frame.to(id));
});
var request = new GenerationPorts.RenderRequest(REQUEST_ID, "actor-1", new GenerationPorts.Source("orders", "1"), GenerationPorts.Format.ZPL,
FakeWorker.revision(FakeWorker.VERSION_ONE_SCENE, BridgeTest.STOCK), Map.of(), MAXIMUM);
if(outcome.equals(ACCEPTED))
{
assertArrayEquals(LABEL, bridge.render(request).bytes(), name);
}
else if(outcome.equals(REJECTED))
{
QException failure = assertThrows(QException.class, () -> bridge.render(request), name);
assertEquals(QException.class, failure.getClass(), name);
assertEquals("Isolated renderer rejected or could not complete the request.", failure.getMessage(), name);
assertNull(failure.getCause(), name);
}
else
{
GenerationPorts.RenderException refusal = assertThrows(GenerationPorts.RenderException.class, () -> bridge.render(request), name);
assertEquals(outcome, refusal.code().name(), name);
assertEquals(outcome, refusal.getMessage(), name);
assertNull(refusal.diagnostic(), name);
}
assertEquals(List.of(4 * ((MAXIMUM + 2) / 3) + 4096), bounds, name);
assertEquals(List.of("protocol", "requestId", "operation", "format", "source", "stock", "context", "assets", "maximumBytes"), sent, name);
assertEquals(rule, rule(frame.to(REQUEST_ID), bounds.get(0)), name);
}
}
@@ -0,0 +1,247 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.documentgeneration.renderer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.kingsrook.qbits.documentgeneration.GenerationPorts;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The job a version 1 scene is printed with is the released job, byte for
** byte: the frame `render` writes to the exchange for fixed inputs is compared
** with the frame the released bridge wrote for the same inputs, which is
** stored in this test's resources and was captured from the release tag by
** this same class (`compat-v1/job-frame-render.md` says how).
**
** One part of the frame has no fixed bytes to compare, in the release or
** since: the seven members of `stock` are written in the iteration order of an
** immutable map, which the JVM changes from one run to the next (four captures
** at the tag gave four orders and were otherwise identical). Those members are
** therefore compared as the same seven texts in any order; every other byte of
** the frame, before and after them, must be the stored byte.
**
** The class uses nothing a later bridge added, so that it compiles and runs
** unchanged in a checkout of that tag. With no stored frame, or a different
** one, it fails and leaves the frame it saw in `target/compat-v1-actual`.
*******************************************************************************/
class VersionOneJobFrameTest
{
private static final Path GOLDEN = Path.of("src", "test", "resources", "compat-v1", "job-frame-render.json");
private static final Path ACTUAL = Path.of("target", "compat-v1-actual", "job-frame-render.json");
///////////////////////////////////////////////////////////////////////////////////////////
// the SHA-256 of the stored frame, so it cannot be rewritten together with the code and //
// still pass //
///////////////////////////////////////////////////////////////////////////////////////////
private static final String GOLDEN_SHA256 = "f7fc3faa862dfd06875ad034174315012cd945580872b4d64df12fefc9b52e10";
private static final String REQUEST_ID = "compat-v1-job-0001";
private static final String ACTOR = "actor-1";
private static final int MAXIMUM = 4096;
private static final GenerationPorts.Stock STOCK = new GenerationPorts.Stock(101600, 152400, 1000, 2000, 3000, 4000, 203);
private static final byte[] LABEL = "^XA^PW812^LL1218^LH0,0^CI28\n^FO2,40^GB20,10,1^FS\n^XZ\n".getBytes(StandardCharsets.US_ASCII);
/////////////////////////////////////////////////////////////////////////////////////////////
// a version 1 scene of every element type, with line breaks, a tab and characters outside //
// ASCII in its text, because the source travels as one JSON string //
/////////////////////////////////////////////////////////////////////////////////////////////
private static final String SCENE = "{\"schema\":\"qqq-zpl-scene/1\",\"elements\":[\n"
+ "\t{\"type\":\"text\",\"x\":20,\"y\":20,\"width\":12,\"height\":24,\"valuePath\":\"/order/id\"},\n"
+ "\t{\"type\":\"box\",\"x\":20,\"y\":60,\"width\":500,\"height\":2,\"thickness\":2},\n"
+ "\t{\"type\":\"image\",\"x\":20,\"y\":90,\"asset\":\"mark\"},\n"
+ "\t{\"type\":\"rasterText\",\"x\":20,\"y\":150,\"fontAsset\":\"face\",\"fontSize\":24,\"width\":400,\"height\":40,\"value\":\"Café TEST-0001 €\"},\n"
+ "\t{\"type\":\"barcode\",\"x\":20,\"y\":220,\"symbology\":\"qr\",\"scale\":4,\"quiet\":4,\"value\":\"TEST-0001\"}]}\n";
@TempDir
Path directory;
/***************************************************************************
** The bytes of an asset: synthetic, every byte value in turn from a start.
** The bridge reads no image or font; it hashes and encodes what it is given.
***************************************************************************/
private static byte[] content(int length, int start)
{
byte[] bytes = new byte[length];
for(int index = 0; index < length; index++)
{
bytes[index] = (byte) (start + index);
}
return (bytes);
}
/***************************************************************************
** The context of the job, in a stated order: text that JSON must escape,
** every kind of number the bridge admits, both booleans, null, and nested
** and empty maps and lists. Every value is synthetic.
***************************************************************************/
private static Map<String, Object> context()
{
Map<String, Object> first = new LinkedHashMap<>();
first.put("sku", "TEST-0001");
first.put("quantity", 3);
first.put("weight", new BigDecimal("12.50"));
Map<String, Object> second = new LinkedHashMap<>();
second.put("sku", "TEST-0002");
second.put("quantity", 0);
second.put("weight", new BigDecimal("0.125"));
Map<String, Object> order = new LinkedHashMap<>();
order.put("id", "ORD-TEST-0001");
order.put("lines", List.of(first, second));
order.put("shipped", true);
order.put("cancelled", false);
order.put("note", null);
Map<String, Object> context = new LinkedHashMap<>();
context.put("order", order);
context.put("text", "quote \" backslash \\ slash / tab \t line \n return \r control \u0001 e-acute é euro € separator 
 pair 😀 markup <b>&</b>");
context.put("count", 2147483647);
context.put("total", -9007199254740993L);
context.put("big", new BigInteger("123456789012345678901234567890"));
context.put("ratio", 0.1);
context.put("small", -2.5E-7);
context.put("half", 1.5f);
context.put("byte", (byte) -8);
context.put("short", (short) 12345);
context.put("empty", new LinkedHashMap<>());
context.put("none", List.of());
return (context);
}
/***************************************************************************
** A well-formed answer of the released renderer, so the job completes.
***************************************************************************/
private static byte[] answer(String requestId) throws Exception
{
Map<String, Object> fields = new LinkedHashMap<>();
fields.put("protocol", RendererJson.PROTOCOL);
fields.put("requestId", requestId);
fields.put("outcome", "OK");
fields.put("rendererVersion", "qqq-renderer-0.1.0");
fields.put("catalogVersion", "qqq-barcodes-9");
fields.put("mediaType", "application/vnd.zebra-zpl");
fields.put("base64", Base64.getEncoder().encodeToString(LABEL));
fields.put("sha256", RendererJson.hash(LABEL));
fields.put("length", LABEL.length);
fields.put("pageCount", 1);
return ((RendererJson.JSON.writeValueAsString(fields) + "\n").getBytes(StandardCharsets.UTF_8));
}
/***************************************************************************
** One `render` of the fixed job, and what the exchange was handed for it.
***************************************************************************/
private byte[] sent() throws Exception
{
Map<String, byte[]> contents = Map.of("mark", content(256, 0), "face", content(5, 251));
List<GenerationPorts.Asset> assets = List.of(
new GenerationPorts.Asset("mark", "file-version-0001", RendererJson.hash(contents.get("mark")), "image/png"),
new GenerationPorts.Asset("face", "file-version-0002", RendererJson.hash(contents.get("face")), "font/ttf", "Test Face", 700, "italic"));
List<byte[]> frames = new ArrayList<>();
List<String> exchanged = new ArrayList<>();
IsolatedRendererBridge bridge = new IsolatedRendererBridge(BridgeTest.config(directory), (actor, asset, maximum) ->
{
assertEquals(ACTOR, actor);
return (contents.get(asset.name()).clone());
}, (id, input, maximum) ->
{
frames.add(input.clone());
exchanged.add(id + " " + maximum);
return (answer(id));
});
GenerationPorts.Revision revision = new GenerationPorts.Revision(7, 3, "orders", STOCK, null, SCENE, null, assets);
GenerationPorts.RenderRequest request = new GenerationPorts.RenderRequest(REQUEST_ID, ACTOR, new GenerationPorts.Source("orders", "1001"), GenerationPorts.Format.ZPL, revision, context(), MAXIMUM);
assertArrayEquals(LABEL, bridge.render(request).bytes());
///////////////////////////////////////////////////////////////////////////////////////////
// one exchange and no other: the job itself, under its own id, with the released bound //
// on its answer (the base64 of the largest label and 4096 bytes of envelope) //
///////////////////////////////////////////////////////////////////////////////////////////
assertEquals(List.of(REQUEST_ID + " " + (4 * ((MAXIMUM + 2) / 3) + 4096)), exchanged);
return (frames.get(0));
}
/***************************************************************************
** A frame with the members of its `stock` in sorted order and every other
** byte where it was. Each byte is one character here, so nothing is decoded
** or normalised; a frame with no `stock` object is left as it is.
***************************************************************************/
private static String ordered(byte[] frame)
{
String bytes = new String(frame, StandardCharsets.ISO_8859_1);
int start = bytes.indexOf("\"stock\":{") + 9;
int end = bytes.indexOf('}', start);
if(start < 9 || end < 0)
{
return (bytes);
}
String[] members = bytes.substring(start, end).split(",");
Arrays.sort(members);
return (bytes.substring(0, start) + String.join(",", members) + bytes.substring(end));
}
/***************************************************************************
** The frame is the stored one. On any difference the frame that was sent is
** left in `target/compat-v1-actual` and the first differing byte is named
** (counted with the members of `stock` in sorted order in both frames).
***************************************************************************/
@Test
void theVersionOneRenderJobIsTheReleasedFrame() throws Exception
{
byte[] sent = sent();
byte[] golden = Files.exists(GOLDEN) ? Files.readAllBytes(GOLDEN) : new byte[0];
String expected = ordered(golden);
String actual = ordered(sent);
if(!expected.equals(actual))
{
Files.createDirectories(ACTUAL.getParent());
Files.write(ACTUAL, sent);
}
assertEquals(GOLDEN_SHA256, RendererJson.hash(golden), "The stored frame was regenerated or edited");
int first = Arrays.mismatch(expected.toCharArray(), actual.toCharArray());
assertTrue(first < 0, "The version 1 job frame differs from the released frame at byte " + first + " (the frame that was sent is in " + ACTUAL + ")");
assertEquals(golden.length, sent.length);
}
}
@@ -28,6 +28,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicReference;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.kingsrook.qbits.documentgeneration.GenerationPorts; import com.kingsrook.qbits.documentgeneration.GenerationPorts;
import com.kingsrook.qbits.documentgeneration.GenerationPorts.Diagnostic; import com.kingsrook.qbits.documentgeneration.GenerationPorts.Diagnostic;
@@ -229,6 +230,142 @@ class VersionRuleTest
/***************************************************************************
** A renderer image that is rolled back while a bridge uses it. What the
** bridge remembered sends ONE version 2 job to the old renderer, scene and
** record value included, and that job is refused as `RENDERER_TOO_OLD`.
** Every job after it (a render, a validation, a preview) asks the version
** first and is refused with nothing of the scene or the record sent. When
** the image is rolled forward again the next job asks, is rendered, and the
** question is not asked again.
***************************************************************************/
@Test
void afterARollbackOneJobReachesTheOldRendererAndTheNextAsksFirst() throws Exception
{
AtomicReference<String> image = new AtomicReference<>(FakeWorker.CURRENT);
FakeWorker worker = new FakeWorker(image::get, job ->
{
String id = job.path("requestId").textValue();
return (job.path("operation").textValue().equals("VALIDATE") ? FakeWorker.validated(id, image.get()) : FakeWorker.rendered(id, image.get(), FakeWorker.golden("anchors", 203), List.of()));
});
IsolatedRendererBridge bridge = FakeWorker.bridge(directory, worker);
String scene = FakeWorker.scene("anchors");
var preview = new GenerationPorts.PreviewRequest("actor-1", GenerationPorts.Format.ZPL, job(scene, null).revision(), Map.of("name", SECRET), null, MAXIMUM);
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(List.of(1, 1), List.of(worker.questions.size(), worker.jobs.size()));
image.set(FakeWorker.RELEASED);
assertEquals(FailureCode.RENDERER_TOO_OLD, assertThrows(GenerationPorts.RenderException.class, () -> bridge.render(job(scene, null))).code());
///////////////////////////////////////////////////////////////////////////////////////////
// the window: this one job was sent unasked, with the scene and the record value //
///////////////////////////////////////////////////////////////////////////////////////////
assertEquals(List.of(1, 2), List.of(worker.questions.size(), worker.jobs.size()));
assertEquals(scene, worker.jobs.get(1).path("source").textValue());
assertEquals(SECRET, worker.jobs.get(1).path("context").path("name").textValue());
assertEquals(FailureCode.RENDERER_TOO_OLD, assertThrows(GenerationPorts.RenderException.class, () -> bridge.render(job(scene, null))).code());
assertEquals(List.of(2, 2), List.of(worker.questions.size(), worker.jobs.size()));
assertEquals(FailureCode.RENDERER_TOO_OLD, assertThrows(GenerationPorts.RenderException.class, () -> bridge.validate("actor-1", job(scene, null).revision())).code());
assertEquals(List.of(3, 2), List.of(worker.questions.size(), worker.jobs.size()));
assertEquals(List.of(new Diagnostic("RENDERER_TOO_OLD", Diagnostic.Severity.ERROR, null, null, null, null)), bridge.preview(preview).diagnostics());
assertEquals(List.of(4, 2), List.of(worker.questions.size(), worker.jobs.size()));
for(JsonNode question : worker.questions)
{
assertEquals(IsolatedRendererBridge.PROBE_SCENE, question.path("source").textValue());
assertFalse(question.toString().contains(SECRET) || question.toString().contains("qqq-zpl-scene/2"));
}
image.set(FakeWorker.CURRENT);
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(List.of(5, 3), List.of(worker.questions.size(), worker.jobs.size()));
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(List.of(5, 4), List.of(worker.questions.size(), worker.jobs.size()));
}
/***************************************************************************
** A job that ends in `RENDERER_TOO_OLD` ends what the bridge remembered,
** however the job came to it. Renderer 0.2.0 may name that refusal itself
** (an element it cannot draw yet), as an error answer or among collected
** diagnostics, and then its version alone says nothing new: the next job
** asks the version again, after a render, a validation and a preview
** alike. Any other refusal, and any job that is done, leaves the bridge
** remembering.
***************************************************************************/
@Test
void anyJobThatEndsAsTooOldMakesTheNextJobAskTheVersion() throws Exception
{
Map<String, Object> unavailable = FakeWorker.diagnostic("RENDERER_TOO_OLD", "ERROR", "element", "center", "box", List.of(0, 0, 10, 10));
FakeWorker.Answer done = job -> job.path("operation").textValue().equals("VALIDATE") ? FakeWorker.validated(job.path("requestId").textValue(), FakeWorker.CURRENT)
: FakeWorker.rendered(job.path("requestId").textValue(), FakeWorker.CURRENT, FakeWorker.golden("anchors", 203), List.of());
FakeWorker.Answer tooOld = job -> FakeWorker.error(job.path("requestId").textValue(), FakeWorker.CURRENT, "RENDERER_TOO_OLD", unavailable);
FakeWorker.Answer invalid = job -> FakeWorker.error(job.path("requestId").textValue(), FakeWorker.CURRENT, "SCENE_INVALID", null);
FakeWorker.Answer collected = job -> FakeWorker.refused(job.path("requestId").textValue(), List.of(unavailable));
AtomicReference<FakeWorker.Answer> next = new AtomicReference<>(done);
FakeWorker worker = new FakeWorker(FakeWorker.CURRENT, job -> next.get().to(job));
IsolatedRendererBridge bridge = FakeWorker.bridge(directory, worker);
String scene = FakeWorker.scene("anchors");
var preview = new GenerationPorts.PreviewRequest("actor-1", GenerationPorts.Format.ZPL, job(scene, null).revision(), Map.of(), null, MAXIMUM);
Diagnostic read = new Diagnostic("RENDERER_TOO_OLD", Diagnostic.Severity.ERROR, "center", List.of(0, 0, 10, 10), null, null);
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(1, worker.questions.size());
///////////////////////////////////////////////////////////////////////////////////////////
// another refusal, a validation and a preview that are done: nothing is asked again //
///////////////////////////////////////////////////////////////////////////////////////////
next.set(invalid);
assertEquals(FailureCode.SCENE_INVALID, assertThrows(GenerationPorts.RenderException.class, () -> bridge.render(job(scene, null))).code());
next.set(done);
bridge.validate("actor-1", job(scene, null).revision());
assertTrue(bridge.preview(preview).printable());
assertEquals(1, worker.questions.size());
///////////////////////////////////////////////////////////////////////////////////////////
// a render that the renderer refuses as too old: the job after it asks first //
///////////////////////////////////////////////////////////////////////////////////////////
next.set(tooOld);
var refusal = assertThrows(GenerationPorts.RenderException.class, () -> bridge.render(job(scene, null)));
assertEquals(FailureCode.RENDERER_TOO_OLD, refusal.code());
assertEquals(read, refusal.diagnostic());
assertEquals(1, worker.questions.size());
next.set(done);
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(2, worker.questions.size());
///////////////////////////////////////////////////////////////////////////////////////////
// a validation that ends the same way //
///////////////////////////////////////////////////////////////////////////////////////////
next.set(tooOld);
assertEquals(FailureCode.RENDERER_TOO_OLD, assertThrows(GenerationPorts.RenderException.class, () -> bridge.validate("actor-1", job(scene, null).revision())).code());
next.set(done);
bridge.validate("actor-1", job(scene, null).revision());
assertEquals(3, worker.questions.size());
///////////////////////////////////////////////////////////////////////////////////////////
// a preview whose answer is that error, and one whose collected diagnostics hold it //
///////////////////////////////////////////////////////////////////////////////////////////
next.set(tooOld);
assertEquals(List.of(read), bridge.preview(preview).diagnostics());
next.set(done);
assertTrue(bridge.preview(preview).printable());
assertEquals(4, worker.questions.size());
next.set(collected);
GenerationPorts.Preview refused = bridge.preview(preview);
assertFalse(refused.printable());
assertEquals(List.of(read), refused.diagnostics());
assertEquals(4, worker.questions.size());
next.set(done);
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(5, worker.questions.size());
assertArrayEquals(FakeWorker.golden("anchors", 203), bridge.render(job(scene, null)).bytes());
assertEquals(5, worker.questions.size());
}
/*************************************************************************** /***************************************************************************
** A renderer of a version this bridge was not built for is rejected, and so ** A renderer of a version this bridge was not built for is rejected, and so
** is a refusal a renderer may not name; a refusal renderer 0.2.0 may name ** is a refusal a renderer may not name; a refusal renderer 0.2.0 may name
@@ -27,6 +27,8 @@ import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Duration;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -38,6 +40,7 @@ import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -46,7 +49,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
** label of the renderer's version 2 cases decodes, dot for dot, to the golden ** label of the renderer's version 2 cases decodes, dot for dot, to the golden
** picture of the canvas it was emitted from, at 203, 300 and 600 dpi. Every ** picture of the canvas it was emitted from, at 203, 300 and 600 dpi. Every
** released version 1 label decodes too. A label that is not exactly the ** released version 1 label decodes too. A label that is not exactly the
** policy's grammar, or is too large to draw, is refused by name. ** policy's grammar, or is too large to draw, is refused by name, and so is
** one whose fields would paint more than sixteen times its page: the work of
** drawing is bounded by the page, never by the number of fields.
*******************************************************************************/ *******************************************************************************/
class ZplRasterTest class ZplRasterTest
{ {
@@ -54,6 +59,11 @@ class ZplRasterTest
private static final GenerationPorts.Stock STOCK = new GenerationPorts.Stock(25400, 12700, 0, 0, 0, 0, 203); private static final GenerationPorts.Stock STOCK = new GenerationPorts.Stock(25400, 12700, 0, 0, 0, 0, 203);
private static final String HEADER = "^XA^PW203^LL102^LH0,0^CI28\n"; private static final String HEADER = "^XA^PW203^LL102^LH0,0^CI28\n";
/////////////////////////////////////////////////////////////////////////////////////////////
// what the one-inch page of these tests may be painted with: sixteen times its 20706 dots //
/////////////////////////////////////////////////////////////////////////////////////////////
private static final long BUDGET = 16L * 203 * 102;
/*************************************************************************** /***************************************************************************
@@ -217,10 +227,10 @@ class ZplRasterTest
/*************************************************************************** /***************************************************************************
** Printer font text cannot be drawn on the host. Its area (one cell for each ** Printer font text cannot be drawn on the host. Its area (one cell for each
** character, counted as characters and not as bytes) is outlined and ** character, counted as characters and not as bytes) is outlined and
** hatched, and the page says it is not exact. ** crossed by its two diagonals, and the page says it is not exact.
***************************************************************************/ ***************************************************************************/
@Test @Test
void printerFontTextIsAHatchedPlaceholderAndThePageIsNotExact() void printerFontTextIsACrossedPlaceholderAndThePageIsNotExact()
{ {
ZplRaster page = ZplRaster.decode(label("^FO10,20^A0N,12,7^FH_^FD_41_C3_A9_E2_82_AC^FS\n")); ZplRaster page = ZplRaster.decode(label("^FO10,20^A0N,12,7^FH_^FD_41_C3_A9_E2_82_AC^FS\n"));
assertFalse(page.exact()); assertFalse(page.exact());
@@ -228,10 +238,7 @@ class ZplRasterTest
{ {
for(int x = 8; x < 34; x++) for(int x = 8; x < 34; x++)
{ {
int column = x - 10; assertEquals(crossed(x - 10, y - 20, 21, 12), page.ink(x, y), x + ", " + y);
int row = y - 20;
boolean inside = column >= 0 && column < 21 && row >= 0 && row < 12;
assertEquals(inside && (column == 0 || row == 0 || column == 20 || row == 11 || (column + row) % 6 == 0), page.ink(x, y), x + ", " + y);
} }
} }
} }
@@ -321,7 +328,8 @@ class ZplRasterTest
/*************************************************************************** /***************************************************************************
** The page of a refused scene shows only where its refused elements are: ** The page of a refused scene shows only where its refused elements are:
** each diagnostic box, moved from the printable area to the page, cut to the ** each diagnostic box, moved from the printable area to the page, cut to the
** page and hatched. It is never exact, and a box off the page draws nothing. ** page, outlined and crossed. It is never exact, and a box off the page
** draws nothing.
***************************************************************************/ ***************************************************************************/
@Test @Test
void theRefusedPageIsDrawnFromBoxesAlone() void theRefusedPageIsDrawnFromBoxesAlone()
@@ -333,9 +341,9 @@ class ZplRasterTest
{ {
for(int x = 0; x < 60; x++) for(int x = 0; x < 60; x++)
{ {
boolean first = hatched(x - 10, y - 5, 13, 7); boolean first = crossed(x - 10, y - 5, 13, 7);
boolean cut = hatched(x - 55, y - 35, 5, 5); boolean cut = crossed(x - 55, y - 35, 5, 5);
boolean corner = hatched(x, y, 12, 8); boolean corner = crossed(x, y, 12, 8);
assertEquals(first || cut || corner, page.ink(x, y), x + ", " + y); assertEquals(first || cut || corner, page.ink(x, y), x + ", " + y);
} }
} }
@@ -345,11 +353,193 @@ class ZplRasterTest
/*************************************************************************** /***************************************************************************
** Whether a dot is ink in a hatched area of this size whose corner is the ** A placeholder of no width or no height has no dots, so nothing is drawn
** origin of `column` and `row`. ** for it: no outline, and no diagonal one dot outside it. An empty printer
** font text field does not come this far: it is refused as no field.
***************************************************************************/ ***************************************************************************/
private static boolean hatched(int column, int row, int width, int height) @Test
void aPlaceholderOfNoWidthOrNoHeightDrawsNothing()
{ {
return (column >= 0 && column < width && row >= 0 && row < height && (column == 0 || row == 0 || column == width - 1 || row == height - 1 || (column + row) % 6 == 0)); ZplRaster page = ZplRaster.refused(60, 40, 0, 0, List.of(List.of(20, 10, 0, 12), List.of(20, 10, 12, 0), List.of(20, 10, 0, 0), List.of(70, 10, 5, 5), List.of(-9, 10, 5, 5),
List.of(20, 45, 5, 5), List.of(2147483647, 10, 5, 5)));
assertFalse(page.exact());
for(int y = 0; y < 40; y++)
{
for(int x = 0; x < 60; x++)
{
assertFalse(page.ink(x, y), x + ", " + y);
}
}
assertEquals("RASTER_FIELD", refusal(HEADER + "^FO10,20^A0N,12,7^FH_^FD^FS\n^XZ\n"));
}
/***************************************************************************
** Whether a dot is ink in a placeholder of this size whose corner is the
** origin of `column` and `row`: its outline, and its two diagonals, which
** have one dot in each row of a tall area and in each column of a wide one.
** Written from that definition, not from the way the page draws it.
***************************************************************************/
static boolean crossed(int column, int row, int width, int height)
{
if(column < 0 || column >= width || row < 0 || row >= height)
{
return (false);
}
if(column == 0 || row == 0 || column == width - 1 || row == height - 1)
{
return (true);
}
if(height >= width)
{
int across = row * (width - 1) / (height - 1);
return (column == across || column == width - 1 - across);
}
return (row == column * (height - 1) / (width - 1) || row == (width - 1 - column) * (height - 1) / (width - 1));
}
/***************************************************************************
** Filled boxes that paint exactly this many dots of the one-inch page: whole
** pages, then whole rows, then part of a row.
***************************************************************************/
private static String fills(long dots)
{
StringBuilder fields = new StringBuilder("^FO0,0^GB203,102,102^FS\n".repeat((int) (dots / (203 * 102))));
int rest = (int) (dots % (203 * 102));
if(rest >= 203)
{
fields.append("^FO0,0^GB203,").append(rest / 203).append(',').append(rest / 203).append("^FS\n");
}
if(rest % 203 > 0)
{
fields.append("^FO0,0^GB").append(rest % 203).append(",1,1^FS\n");
}
return (fields.toString());
}
/***************************************************************************
** A box is the same dots as painting it dot by dot, which is how it was
** painted before it was painted as bars: thin, thick, solid where the
** border meets itself, a single dot, a line, against the page's edges and
** across byte boundaries. The expected dots are computed here, one at a
** time, from the printer's rule.
***************************************************************************/
@Test
void aBoxIsTheSameDotsAsPaintingItDotByDot()
{
int boxes = 0;
for(int width = 1; width <= 40; width++)
{
for(int height = 1; height <= 12; height++)
{
for(int thickness = 1; thickness <= Math.min(width, height); thickness++)
{
for(int[] place : new int[][] {{0, 0}, {40 - width, 30 - height}, {Math.min(3, 40 - width), Math.min(2, 30 - height)}, {Math.min(8, 40 - width), Math.min(17, 30 - height)}})
{
int left = place[0];
int top = place[1];
String box = "^FO" + left + "," + top + "^GB" + width + "," + height + "," + thickness + "^FS\n";
ZplRaster page = ZplRaster.decode(("^XA^PW40^LL30^LH0,0^CI28\n" + box + "^XZ\n").getBytes(StandardCharsets.US_ASCII));
for(int y = 0; y < 30; y++)
{
for(int x = 0; x < 40; x++)
{
int column = x - left;
int row = y - top;
boolean inside = column >= 0 && column < width && row >= 0 && row < height;
boolean ink = inside && (row < thickness || row >= height - thickness || column < thickness || column >= width - thickness);
if(page.ink(x, y) != ink)
{
throw new AssertionError(box.trim() + " differs from the box painted dot by dot at " + x + ", " + y);
}
}
}
boxes++;
}
}
}
}
assertEquals(4 * 2834, boxes);
}
/***************************************************************************
** Thousands of boxes that each cover the page are valid output: the policy
** allows 6000 fields. Painted dot by dot, 6000 solid boxes of a 4 x 6 in
** label at 600 dpi were 52 thousand million dots of work while an admission
** slot was held. The page is painted at most sixteen times over, so the
** seventeenth is refused by name at once; and 6000 outlines, which ink only
** their bars, are drawn for what they ink.
***************************************************************************/
@Test
void thousandsOfPageSizedBoxesAreRefusedOrCostOnlyTheirInk() throws Exception
{
GenerationPorts.Stock stock = new GenerationPorts.Stock(101600, 152400, 0, 0, 0, 0, 600);
String header = "^XA^PW2400^LL3600^LH0,0^CI28\n";
byte[] solid = (header + "^FO0,0^GB2400,3600,1200^FS\n".repeat(6000) + "^XZ\n").getBytes(StandardCharsets.US_ASCII);
ZplOutputPolicy.validate(solid, stock);
assertEquals("PREVIEW_TOO_LARGE", assertTimeoutPreemptively(Duration.ofSeconds(10), () -> assertThrows(IllegalArgumentException.class, () -> ZplRaster.page(solid, stock)).getMessage()));
byte[] outlines = (header + "^FO0,0^GB2400,3600,1^FS\n".repeat(6000) + "^XZ\n").getBytes(StandardCharsets.US_ASCII);
ZplRaster page = assertTimeoutPreemptively(Duration.ofSeconds(10), () -> ZplRaster.page(outlines, stock));
assertTrue(page.ink(0, 0) && page.ink(2399, 3599) && page.ink(0, 1800) && page.ink(1200, 3599));
assertFalse(page.ink(1, 1) || page.ink(1200, 1800));
}
/***************************************************************************
** The limit is exact, and every painter counts against it what it paints: a
** solid box its area, an outline its four bars, a graphic eight dots for
** each byte, a placeholder its outline and its two diagonals. A field that
** takes the page to exactly sixteen times its dots is drawn; the same field
** after one more dot is refused.
***************************************************************************/
@Test
void thePaintedBudgetIsExactForEveryPainter()
{
assertTrue(ZplRaster.decode(label(fills(BUDGET))).ink(202, 101));
assertEquals("PREVIEW_TOO_LARGE", refusal(HEADER + fills(BUDGET + 1) + "^XZ\n"));
for(Map.Entry<String, Integer> field : Map.of(
"^FO0,0^GB1,1,1^FS\n", 1,
"^FO20,10^GB6,5,3^FS\n", 30,
"^FO20,10^GB6,5,1^FS\n", 6 + 6 + 3 + 3,
"^FO8,2^GFA,4,4,2,A0018001^FS\n", 32,
"^FO10,20^A0N,12,7^FH_^FD_41^FS\n", 7 + 7 + 10 + 10 + 12 + 12,
"^FO10,20^A0N,2,30^FH_^FD_41^FS\n", 60 + 30 + 30).entrySet())
{
assertTrue(ZplRaster.decode(label(fills(BUDGET - field.getValue()) + field.getKey())).ink(0, 0), field.getKey());
assertEquals("PREVIEW_TOO_LARGE", refusal(HEADER + fills(BUDGET - field.getValue() + 1) + field.getKey() + "^XZ\n"), field.getKey());
}
}
/***************************************************************************
** The page of a refused scene is bounded the same way. A worker may send
** 2048 diagnostics; hatched dot by dot, 2048 boxes of a sixteen million dot
** page were 32 thousand million dots of work. Each now costs its outline
** and its diagonals, and boxes that would paint more than sixteen times the
** page are refused by name.
***************************************************************************/
@Test
void theRefusedPageIsBoundedHoweverManyBoxesItHas()
{
ZplRaster page = assertTimeoutPreemptively(Duration.ofSeconds(10), () -> ZplRaster.refused(4000, 4000, 0, 0, Collections.nCopies(2048, List.of(0, 0, 4000, 4000))));
assertTrue(page.ink(0, 0) && page.ink(3999, 2000) && page.ink(2000, 2000) && page.ink(1000, 2999));
assertFalse(page.ink(2000, 1000) || page.ink(1, 2));
///////////////////////////////////////////////////////////////////////////////////////////
// on a page of 8 x 32000 dots a box of the whole page costs 64012 dots of outline and //
// 64000 of diagonals; 31 of them are within sixteen times the page and 32 are not //
///////////////////////////////////////////////////////////////////////////////////////////
assertTrue(ZplRaster.refused(8, 32000, 0, 0, Collections.nCopies(31, List.of(0, 0, 8, 32000))).ink(7, 31999));
assertEquals("PREVIEW_TOO_LARGE", assertThrows(IllegalArgumentException.class, () -> ZplRaster.refused(8, 32000, 0, 0, Collections.nCopies(32, List.of(0, 0, 8, 32000)))).getMessage());
} }
} }
@@ -0,0 +1 @@
{"protocol":"qbit-document-renderer/1","requestId":"compat-v1-job-0001","operation":"RENDER","format":"ZPL","source":"{\"schema\":\"qqq-zpl-scene/1\",\"elements\":[\n\t{\"type\":\"text\",\"x\":20,\"y\":20,\"width\":12,\"height\":24,\"valuePath\":\"/order/id\"},\n\t{\"type\":\"box\",\"x\":20,\"y\":60,\"width\":500,\"height\":2,\"thickness\":2},\n\t{\"type\":\"image\",\"x\":20,\"y\":90,\"asset\":\"mark\"},\n\t{\"type\":\"rasterText\",\"x\":20,\"y\":150,\"fontAsset\":\"face\",\"fontSize\":24,\"width\":400,\"height\":40,\"value\":\"Café TEST-0001 €\"},\n\t{\"type\":\"barcode\",\"x\":20,\"y\":220,\"symbology\":\"qr\",\"scale\":4,\"quiet\":4,\"value\":\"TEST-0001\"}]}\n","stock":{"rightMicrons":2000,"bottomMicrons":3000,"dpi":203,"heightMicrons":152400,"leftMicrons":4000,"topMicrons":1000,"widthMicrons":101600},"context":{"order":{"id":"ORD-TEST-0001","lines":[{"sku":"TEST-0001","quantity":3,"weight":12.50},{"sku":"TEST-0002","quantity":0,"weight":0.125}],"shipped":true,"cancelled":false,"note":null},"text":"quote \" backslash \\ slash / tab \t line \n return \r control \u0001 e-acute é euro € separator 
 pair 😀 markup <b>&</b>","count":2147483647,"total":-9007199254740993,"big":123456789012345678901234567890,"ratio":0.1,"small":-2.5E-7,"half":1.5,"byte":-8,"short":12345,"empty":{},"none":[]},"assets":[{"name":"mark","sha256":"40aff2e9d2d8922e47afd4648e6967497158785fbd1da870e7110266bf944880","mediaType":"image/png","base64":"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="},{"name":"face","sha256":"93a2541056fb33566545ab2dec2ef36467ff8ca7ffdc40efbd966b4bfd16128b","mediaType":"font/ttf","base64":"+/z9/v8=","fontFamily":"Test Face","fontWeight":700,"fontStyle":"italic"}],"maximumBytes":4096}
@@ -0,0 +1,74 @@
# Released version 1 job frame
`job-frame-render.json` is the request the released bridge wrote to its exchange for one `render` of a version 1
scene: 2021 bytes, one line of JSON ending in a line feed, exactly as the exchange received it.
SHA-256: `f7fc3faa862dfd06875ad034174315012cd945580872b4d64df12fefc9b52e10` (pinned in `VersionOneJobFrameTest`).
## Where the bytes came from
They were written by the source of tag `v1.1.0-RC.2` (commit `e9ffba484e8d97f9853cb071cdac14f3bfd7acda`), not by
the branch that added this file. `VersionOneJobFrameTest.java` is its own capture tool: it uses only what that tag
has (`BridgeTest.config`, `RendererJson` and the bridge constructor that takes an exchange), so it was copied
unchanged into a checkout of the tag, with no stored frame, and run there:
```
git worktree add --detach <directory> v1.1.0-RC.2
cp bridges/renderer/src/test/java/com/kingsrook/qbits/documentgeneration/renderer/VersionOneJobFrameTest.java \
<directory>/bridges/renderer/src/test/java/com/kingsrook/qbits/documentgeneration/renderer/
cd <directory>
./mvnw --batch-mode -pl bridges/renderer -am test -Dtest=VersionOneJobFrameTest -Dsurefire.failIfNoSpecifiedTests=false
```
The test fails in that state and leaves the frame that the released `IsolatedRendererBridge.render` handed to the
exchange in `bridges/renderer/target/compat-v1-actual/job-frame-render.json`. That file, from the first of four
such runs, is the stored frame. With the stored frame copied into the checkout as well, the test passed against
the tag three times in a row. The runs were on Temurin 21.0.12 on Windows with Maven 3.9.11. Nothing else was
added to the checkout and nothing of it was committed.
The four capture runs used the class as it first was: the same inputs and the same capturing exchange, a strict
comparison of every byte and no pinned hash. Those runs showed that the order of the members of `stock` is not
fixed (below); the comparison was then written as it is now and the hash pinned, and that is the class which
passed at the tag.
## The inputs
All of them are constants of the test; every value is synthetic.
| Input | Value |
|---|---|
| Request id | `compat-v1-job-0001` |
| Actor | `actor-1` |
| Source record | table `orders`, record `1001` (not part of a job) |
| Format | `ZPL` |
| Output limit | 4096 bytes, which is also the deployment's limit (`BridgeTest.config`) |
| Revision | id 7, template 3, source table `orders`, no page source, no script |
| Stock | 101600 x 152400 micrometres, margins top 1000, right 2000, bottom 3000, left 4000, 203 dpi |
| Scene | the constant `SCENE`: one `text`, `box`, `image`, `rasterText` and `barcode` element, with line feeds, tabs and two characters outside ASCII in its text |
| Asset `mark` | `image/png`, file version `file-version-0001`, the 256 bytes 0 to 255 |
| Asset `face` | `font/ttf`, file version `file-version-0002`, family `Test Face`, weight 700, style `italic`, the 5 bytes 251 to 255 |
| Context | the map `context()` builds, in its insertion order: a nested order with two lines, text that JSON must escape (quote, backslash, tab, line feed, carriage return, a control character, characters outside ASCII and outside the basic plane), an `Integer`, a `Long`, a `BigInteger`, a `BigDecimal` with a trailing zero, a `Double`, a `Float`, a `Byte`, a `Short`, both booleans, null, an empty map and an empty list |
| Answer | a well-formed answer of `qqq-renderer-0.1.0` with a one-box label for the stock, so that `render` completes |
The asset bytes are not an image or a font. The bridge reads neither: it hashes the bytes and encodes them.
## What is compared
Every byte of the frame, with one exception that the released bridge itself makes. It writes the seven members of
`stock` in the iteration order of an immutable `Map.of`, and the JVM changes that order from one run to the next:
the four captures at the tag were four different files that differed in the order of those members and in
nothing else. The stored file has the order of the first run. The test therefore compares the members of `stock`
as the same seven `"name":value` texts in any order, and everything before and after them byte for byte. No
stricter comparison is true of the release.
The test also holds the job to one exchange, under its own request id, with the released bound on the answer
(the base64 of 4096 bytes and 4096 bytes of envelope: 9560).
Not covered: `validate` (its request id is random), a page (PDF) job, and any job only renderer 0.2.0 can do.
## Rules
- Never regenerate or edit `job-frame-render.json`. If `VersionOneJobFrameTest` fails, the code changed what a
version 1 print job sends; fix the code. The failure names the first differing byte and the frame that was sent
is in `bridges/renderer/target/compat-v1-actual`.
- A new frame may be added only with bytes captured the same way, from a released tag.
+3 -1
View File
@@ -26,7 +26,9 @@ Source editing displays the included names and preserves their manifest; submitt
TrueType assets expose CSS family, integer weight100–900 and normal/italic style. Older four-field font references keep their name as family and400/normal defaults, including the canonical hash of already queued revisions. Explicit nondefault faces participate in that hash. Images cannot carry font attributes. Existing databases need the additive nullable font columns; `db/h2/002_asset_font_faces.sql` is an H2 upgrade, not a MySQL deployment migration. Published revisions pin asset identities, script identity, sources, stock and margins. TrueType assets expose CSS family, integer weight100–900 and normal/italic style. Older four-field font references keep their name as family and400/normal defaults, including the canonical hash of already queued revisions. Explicit nondefault faces participate in that hash. Images cannot carry font attributes. Existing databases need the additive nullable font columns; `db/h2/002_asset_font_faces.sql` is an H2 upgrade, not a MySQL deployment migration. Published revisions pin asset identities, script identity, sources, stock and margins.
**Generate retained draft preview** accepts one source record identity and PDF/ZPL selection. It creates an immutable PREVIEW revision, executes the ordinary source authorization, isolated rendering, strict audit and Record Files intake workflow, and leaves the active published revision unchanged. The preview has a normal generation request and retained attachment. Retrying its process request key returns the same request; it does not regenerate bytes. Quarantine rules still apply. Results expose native request/file links and, when an authorized download provider is installed and release completed, explicit preview/download actions. Authenticated delivery uses verified response bytes and a durable completion receipt; its URL is never rendered as an ordinary browser link or iframe. PDF display uses the shared canvas preview component. The resulting preview remains a retained, audited file. **Preview layout** shows a label as it would print, before anything is printed and without saving anything. It is an action on a template (its current draft, for a person with `document-generation.configure`) and on a published revision (for a person with `document-generation.view`), and the template record screen shows the same picture in its **Label preview** section. The person chooses the data (a sample written in the scene under `samples`, the same sample with every bound text filled with capital W to the `maxLength` it declares, or one source record), optionally another stock, and a resolution of 203, 300 or 600 dpi. A record preview also needs `document-generation.generate`; the record is read with the person's own permissions and record locks, and one they cannot read is refused as not found. The longest values picture is indicative: W is not the widest character of every font, and the renderer's own proof of the declared length at publication decides whether every value fits. A revision row that is not a publication (the frozen draft a retained preview writes) is not previewed: it is answered as not found, and a draft is previewed from its template. The picture is decoded from the bytes the print path validated, one pixel per printer dot, and is shown with whether it is exact, whether the label can print, its size in dots and millimetres, and each refusal, warning and note with the element it concerns. A version 1 scene is drawn with its printer font text as outlined, crossed areas and is marked as not exact; a label that would paint more than a preview draws is said to be too dense to preview and prints all the same; a page (PDF) document is not previewed this way. No revision, request, audit event or file is written, and the picture and the record's values are not kept in the process state: the client fetches the preview widget by the identifier of the run, the widget reads the person's choices from the state of that run (so the record is not a parameter of the request), and the picture exists only in that answer. Samples must be synthetic. See the [design](design/LABEL-LAYOUT-FONTS-PREVIEW.md), section 6.
**Generate retained preview file** (the action formerly labelled "Preview draft") accepts one source record identity and PDF/ZPL selection. It creates an immutable PREVIEW revision, executes the ordinary source authorization, isolated rendering, strict audit and Record Files intake workflow, and leaves the active published revision unchanged. The preview has a normal generation request and retained attachment. Retrying its process request key returns the same request; it does not regenerate bytes. Quarantine rules still apply. Results expose native request/file links and, when an authorized download provider is installed and release completed, explicit preview/download actions. Authenticated delivery uses verified response bytes and a durable completion receipt; its URL is never rendered as an ordinary browser link or iframe. PDF display uses the shared canvas preview component. The resulting preview remains a retained, audited file.
**Barcode catalog and template examples** displays the optional renderer's bounded packaged catalog plus editable FreeMarker HTML and restricted ZPL JSON examples. The renderer owns the catalog and its supported options; the foundation copies no encoder registry and does not evaluate source to display help. An unavailable catalog provider fails explicitly. Renderer version qualification and physical barcode acceptance remain separate. **Barcode catalog and template examples** displays the optional renderer's bounded packaged catalog plus editable FreeMarker HTML and restricted ZPL JSON examples. The renderer owns the catalog and its supported options; the foundation copies no encoder registry and does not evaluate source to display help. An unavailable catalog provider fails explicitly. Renderer version qualification and physical barcode acceptance remain separate.
+297 -13
View File
@@ -209,7 +209,9 @@ negative. An omitted `width` or `height` means the rest of the container on that
**Where the content sits in the box (`align`, `valign`).** `align` is `left`, `center` or `right`; `valign` is `top`, **Where the content sits in the box (`align`, `valign`).** `align` is `left`, `center` or `right`; `valign` is `top`,
`middle` or `bottom`. They apply to text lines, to a fitted barcode whose size depends on its data, and to a scaled `middle` or `bottom`. They apply to text lines, to a fitted barcode whose size depends on its data, and to a scaled
image. Slack is split with integer division, so a centred element is off by at most one dot. image. Slack is split with integer division, so a centred element is off by at most one dot. The defaults are `left`
and `top`, except for a barcode, which sits in the middle of its box (`center`, `middle`) unless the scene says
otherwise: what its box has to spare is then quiet zone, the same on both sides (decided 2026-11-12).
`rotation` is 0, 90, 180 or 270 degrees clockwise for text, barcodes and images. The box is given as it appears on `rotation` is 0, 90, 180 or 270 degrees clockwise for text, barcodes and images. The box is given as it appears on
the label, after rotation. the label, after rotation.
@@ -346,6 +348,89 @@ Legibility on thermal heads:
- Guidance for the authoring guide: at 203 dpi use a bold face below 10 pt, keep text at or above 6 pt, prefer the - Guidance for the authoring guide: at 203 dpi use a bold face below 10 pt, keep text at or above 6 pt, prefer the
condensed bold over shrinking. condensed bold over shrinking.
**Decided while building text (P2).** The code is `scene2/text`; the renderer README states the rules for authors.
- **The set as shipped.** `qqq-sans` and `qqq-sans-bold` are IBM Plex Sans Regular and Bold (release
`@ibm/plex-sans@1.1.0`), `qqq-condensed-bold` is IBM Plex Sans Condensed Bold (`@ibm/plex-sans-condensed@2.0.0`),
`qqq-mono` and `qqq-mono-bold` are JetBrains Mono Regular and Bold (`v2.304`). Every licence was confirmed as SIL
OFL 1.1 from the release archive's own licence file. A scene names a face with `font`; the name carries family
and weight, and there is no separate weight or style property (the set has no italic). Only bundled faces are
drawn: a supplied `font/ttf` asset named by a version 2 text is `FONT_UNKNOWN` until the asset package (P8).
- **One glyph for each character, left to right.** No kerning, ligatures, mark placement or bidirectional
reordering, which is what version 1 raster text does too and what an identifier wants (JetBrains Mono would
otherwise join `->` and `!=`). A character that cannot be drawn that way (a control or format character, a
combining mark, a script that needs shaping, anything outside the Basic Multilingual Plane, or a character the
face lacks) is `FONT_MISSING_GLYPH` with the count; the value prints whole or not at all.
- **Measurement is integer arithmetic.** The faces have 1000 units to the em. Advances and outline boxes are
read once at a reference size and scaled as `units x millipoints x dpi / 72 000 000`, so the same value is the
same width on every machine. Each character sits at a whole-dot pen position. A line's box is its advance,
widened to the ink of its characters plus two dots on each inked side: the rasteriser fits an outline to the
dot grid within 1.4 dots of its exact scale (measured over every character of the five faces, from 1 pt to
1000 pt at the three resolutions). A text whose ink would leave the measured box is neither clipped nor printed
outside it nor printed in part: its dots are gathered first and reach the label only when none strayed, and
otherwise the one element is refused as `TEXT_DOES_NOT_FIT` with `glyphsOutsideMeasure` and
`dotsOutsideMeasure`. A literal is held to the glyph bounds when the scene is validated.
- **The size is found without trying every size.** The answer is defined as the one a search of every
quarter-point step from the size down to the floor gives, and a property test holds the implementation to that
search exactly. The implementation first asks, by halving, for the largest step at which the text could fit at
all: a count that fills lines at any character with a width no real line can be under, so it never refuses a
size that fits and, once it allows a size, allows every smaller one. Only the few steps from there are laid
out. When one line at the floor is higher than the box nothing is searched. The case of 1024 characters from
1000 pt to 1 pt, which took about 200 ms a fit, takes under 1 ms.
- **The work of a scene's text is bounded.** Every character visited while fitting is one step, every character
to be drawn 16, and every glyph a scene draws for the first time at a size 4096 (the runtime rasterises it
once). One scene may take 64 million steps, about a second of a worker; the element that passes it, and every
text after it, is `SCENE_INVALID` at the element with `textWorkSteps`. The count is integer arithmetic, so the
refusal is the same on every machine and the same whether the scene is validated or rendered. A text is
fitted once: what the check composed is what is painted.
- **Wrapping.** At each size a line is broken between words while the text then fits, and at any character when
it does not. So a larger size is preferred to whole words, a value with no space wraps (the example's GS1 line
has none), and a length is provable: n characters need no more lines than n of the widest.
- **Truncation.** At the floor size, as many lines as the box holds; the last ends with the ellipsis after as
many of its characters as fit with it, down to the ellipsis alone. A cut text is also reported as shrunk.
- **The proof of `maxLength`** lays out that many copies of a worst character: the face's greatest advance,
reaching as far left, right, above and below as the furthest-reaching character of the face (in IBM Plex Sans
Bold the per mille sign is 1.382 em wide, the fraction slash reaches 0.245 em past its advance on each side, and
a capital A with ring and acute rises to 1.15 em against an ascent of 1.025). It is therefore sound for any
value, and stricter than a typical value needs. The example scene of section 2.1 does not pass it: two lines at
the 7 pt floor need 59 dots at 203 dpi (53 from rounding the ascent, the line pitch and the descent up to whole
dots, 6 for the accent and the descender) and the 6.5 mm caption box has 51. A box of exactly `lines x line
height` is not proven; 7.5 mm is. The proof is for the render target of the request, so a host that prints
one revision at several resolutions validates at each (P5 or P6b). The proof never cuts: a cut value is not a
value that fits. An element with `overflow: truncate` whose `maxLength` is not proven stays valid, because
cutting is what its author chose, and carries the warning `FIT_NOT_PROVEN` at every validation with
`provenCharacters`, the longest length proven to fit whole, against the `characters` stated.
- **Validation reads no record.** A bound value is laid out only when rendering; `FIT_NOT_PROVEN` is raised for
a bound element without `maxLength` in both operations. When a bound element is validated, legibility is
judged at the size its `maxLength` is proven at, which is the smallest any value is printed at (the floor when
the proof fails and the element cuts), and at the stated size when it has no `maxLength`; when it is rendered,
at the size chosen.
- **A bound number** is printed in plain decimal digits: no exponent and no fraction that is only zeros
(`1.0E10` prints `10000000000`, `2.50` prints `2.5`, `12.0` prints `12`). A number that is not finite is
`VALUE_MISSING`.
- **Bounds.** A size from 1 pt to 1000 pt, `shrinkTo` from 1 pt up to the size, `lineHeight` from 0.5 to 5 with
three decimals, 64 lines, 1024 characters.
- **The members of `fit` are schema properties.** The published schema declares `maxLines`, `shrinkTo` and
`overflow` under `fit` with `additionalProperties: false`, so a host can check them by machine, and a member
that is wrong is reported at the member (`/elements/1/fit/maxLines`, or in the override that states `fit`).
The three names are in the host's list (`SceneFacts.VOCABULARY`, held to the schema by a test in the bridge)
and in the renderer's (`ElementFactory.VOCABULARY`). A member `fit` does not have is reported at `fit`,
because its name is not one the schema declares.
- **Rotation and reverse.** A text turned a quarter is fitted along the box's height, and `align` and `valign`
follow the direction of reading. Reverse text fills its own box black and clears the letters; it counts twice
against the painted-area cap.
- **`RESERVED_FONT_NAME`** is raised by a text element (with the count of supplied assets under `qqq-`), not for
the scene as a whole: a scene with no text has no face to shadow.
- **Determinism (section 10.2).** No tolerance was needed. The goldens are generated in the CI image (Linux,
Temurin 21.0.9) and are the same bytes on Windows (Temurin 21.0.12), at 203, 300 and 600 dpi, for the glyph
bitmaps (up to 100 dots to the em) and for the outline path above that; they are compared exactly on both.
Glyph bitmaps come from the FreeType each JDK ships; the versions are recorded beside the goldens
(`renderer/src/test/resources/scene2/README.md`).
One case depends on more than the scene: a line whose strip is over 8 million dots (type of several hundred
points) is drawn in bands of rows, and the rasteriser may shade a few edge dots at a band's border differently
than in one piece (fewer than 1 in 10 000 ink dots). Where the bands fall is a function of the line's box, so
the result is still the same on every machine.
## 4. Barcodes ## 4. Barcodes
### 4.1 Symbologies ### 4.1 Symbologies
@@ -381,14 +466,19 @@ A plain `value` in bracket syntax keeps working, so the first release does not d
- Bars are whole dots. The renderer picks the largest module, in dots, that fits the box on both axes including - Bars are whole dots. The renderer picks the largest module, in dots, that fits the box on both axes including
quiet zones, never smaller than `minModule` and never larger than `maxModule` if given. quiet zones, never smaller than `minModule` and never larger than `maxModule` if given.
- `minModule` is physical. Defaults: 0.25 mm for linear symbologies and 0.375 mm for two-dimensional ones. That is - `minModule` is physical. Without it the smallest module is that of the element's `barcodeProfile`, by symbology
2 and 3 dots at 203 dpi, 3 and 5 at 300 dpi, 6 and 9 at 600 dpi. These defaults are proposals to confirm on a (the table below). The design's own 0.25 mm for linear symbologies and 0.375 mm for two-dimensional ones (2 and
printer (section 10.6). 3 dots at 203 dpi, 3 and 5 at 300 dpi, 6 and 9 at 600 dpi) are proposals to confirm on a printer (section 10.6).
- For linear symbologies the bar height fills the box height (less the human-readable line) and no longer scales - For linear symbologies the bar height fills the box height (less the human-readable line) and no longer scales
with the module. In version 1 the height scales with the module, so a short box caps the module. with the module. In version 1 the height scales with the module, so a short box caps the module. The box must
- The fitted symbol is placed in its box by `align` and `valign`. Left over dots are blank. be as tall as the symbology asks of bars that wide; the scene may state its own `minHeight`, with a standing
- `quiet` is modules on each side, with the existing minimums (10 linear, 4 matrix). Quiet zones are inside the warning.
box and are never cropped. The warning `QUIET_ZONE_INTRUDED` fires when another element's ink lands in one. - The fitted symbol is placed in its box by `align` and `valign`, which for a barcode default to the middle
(section 2.4). Left over dots are blank.
- `quiet` is modules on each side. Without it each symbology has its own quiet zones (10 and 10 for Code 128,
Code 39, Code 93 and Interleaved 2 of 5; 11 and 7 for EAN-13; 7 and 7 for EAN-8; 9 and 9 for UPC-A; 9 and 7 for
UPC-E; 4 on every side of a two-dimensional symbol). Quiet zones are inside the box and are never cropped. An
element painted later whose ink would enter the symbol or a quiet zone is refused as `QUIET_ZONE_INTRUDED`.
### 4.4 When the data does not fit ### 4.4 When the data does not fit
@@ -418,6 +508,113 @@ rebuilds the bitmap from its graphic fields, and decodes it with ZXing (already
payload, the symbology, the module size in dots and the blank margins. This runs at 203, 300 and 600 dpi for each payload, the symbology, the module size in dots and the blank margins. This runs at 203, 300 and 600 dpi for each
fit-qualified symbology, for short, typical and longest values. fit-qualified symbology, for short, typical and longest values.
**Decided while building the barcode fit (P3a).**
- **Where the modules come from.** The symbol is taken from the version 1 encoder path at one dot to the module
(`Barcodes.renderForFormat`, the call `BarcodeFit.fit` itself measures with), and `scene2/barcode/ModuleFit`
chooses the module. `BarcodeFit.fit` is not called: it scales the bar height with the module and stops at a
scale of 16, which is what 4.3 ends. `BarcodeFit.TYPES` remains the list of fit-qualified symbologies, and
version 1 is untouched.
- **The rule, in dots.** `module = min(maxModule, floor(box / modules))`, the modules counting both quiet zones;
a two-dimensional symbol takes the smaller of its two axes. The symbol does not fit when that is under
`minModule`. Both limits go up to a whole dot (`Length.module`), so a design that states the same length for
both gets one module at every resolution; a maximum under the minimum is `SCENE_INVALID` at `maxModule`.
Going up to a whole dot costs most for a two-dimensional symbol at 300 dpi, where 0.375 mm becomes 5 dots
(0.423 mm).
- **`pdf417` is fitted as a two-dimensional symbol** (both axes, 4 quiet modules, the 0.375 mm default), the
grouping version 1 already uses for quiet zones. The default Data Matrix encoder may choose a rectangular
symbol; it is fitted as it comes.
- **The symbol is its own ground.** The fitted symbol's area, quiet zones included, is painted white and then
the bars, so ink painted under it cannot close a space. The rest of the box is left as it was.
- **Refusals that depend on the record.** A bound value, symbology or scanner profile that is absent is
`VALUE_MISSING` with the pointer of the binding property. A symbology outside `allowedSymbologies`, and a
scanner profile that does not name the symbology drawn, are `SCENE_INVALID` at that property. What the encoder
says about a value is dropped. (The code of a value that cannot be encoded changed after the review, below.)
- **The numbers of a refusal.** `BARCODE_DOES_NOT_FIT` carries `measured.modules`, `quietLeftModules`,
`quietRightModules`, `widthDots` and `heightDots` (needed at the minimum) and `moduleDots` (the largest module
that would fit), against `limit.widthDots`, `heightDots` and `minModuleDots`. For a symbol turned a quarter
they are the symbol's own width and height.
- **Left to P3b.** `gs1` and `hri` stay declared, and an element that states either is refused as
`RENDERER_TOO_OLD`. A `gs1-128` `value` is in the square brackets the encoder reads; the bracketed form a
person reads, in parentheses, is the caption's.
**Decided after the independent review of P3a.** A label is scanned, so the failure that matters most is a symbol
that reads as something other than the value it was given. The review found four ways the encoder made one, and
that nothing kept ink off a symbol.
- **No value holds an escape of the encoder.** The encoder reads `\<FNC1>` to `\<FNC4>` in a value as function
characters. A record value could so make a GS1-128, with application identifiers of its own choosing, of a
plain Code 128; set the reader-programming flag; or change a character; and QR drops the escape, so the symbol
differs from the value. A value, literal or bound, that holds the two characters `\<` is refused in every
symbology. A function character enters a symbol only through its symbology: `gs1-128` adds its own FNC1.
- **Interleaved 2 of 5 of an odd number of digits is refused**, where the encoder put a zero in front.
- **EAN and UPC values are the whole number.** The encoder wants the number without its check digit, works the
digit out and pads a short number with zeros, so a mistyped number printed as a valid symbol for another
product. A value is now 13 digits for `ean13`, 8 for `ean8`, 12 for `upca` and 8 for `upce`, check digit
included; the check digit is verified and the encoder is given the digits before it. The short form the encoder
takes is not accepted: nothing in this design asks for it, and it is the form that cannot be checked.
- **The check digit of every GS1 key is verified** in a `gs1-128` element string. The encoder checks lengths and
not check digits. The application identifiers are those the GS1 Syntax Dictionary marks with a check digit, as
the bundled Zint 2.16.0 carries it (`gs1_lint.h`): 00, 01, 02, 03, 253, 255, 402, 410 to 417, 8003, 8006,
8017, 8018 and 8026. The pair of check characters of 8013 and 8014 is not verified. The builder of section 4.2
will meet the same rule here, not a second one.
- **A code for a value that cannot be drawn.** `VALUE_NOT_ENCODABLE` joins the errors, at `value` or `valuePath`:
for the four refusals above (`GS1_INVALID` for a `gs1-128`), for a value the symbology cannot hold, and for a
value a scanner profile cannot reproduce. It carries numbers only: `measured.characters`; `limit.characters` or
`limit.charactersMultipleOf`; `checkDigitMatches` 0 against 1; and for a GS1 key `measured.applicationIdentifier`,
one of the fixed list above. `SCENE_INVALID` is no longer used for a value. A symbol of more modules than the
encoder draws (4096) is `BARCODE_DOES_NOT_FIT`, with `measured.characters` against `limit.modules`.
- **Quiet zones and the smallest module are a table by symbology**, in one place (`scene2/barcode/Symbology`),
each number with its source. Quiet zones are the symbology's own (section 4.3). The smallest module is chosen
by a named profile, `barcodeProfile`:
| `barcodeProfile` | EAN-13, EAN-8, UPC-A, UPC-E | GS1-128, Interleaved 2 of 5 | Code 128, Code 39, Code 93 | two-dimensional |
|---|---|---|---|---|
| `none` (the design's own) | 0.25 mm | 0.25 mm | 0.25 mm | 0.375 mm |
| `gs1-general` (GS1, general retail point of sale) | 0.264 mm | 0.25 mm | 0.25 mm | 0.375 mm |
| `gs1-logistics` (GS1, general distribution and logistic units) | 0.495 mm | 0.495 mm | 0.25 mm | 0.375 mm |
| not stated | as `gs1-general` | as `gs1-logistics` | as `none` | as `none` |
With no profile stated a symbology takes the strictest GS1 rule written for its own use. 0.264 mm is 3, 4 and 7
dots at 203, 300 and 600 dpi, and 0.495 mm is 4, 6 and 12. A scene may still state a smaller `minModule`, with
the standing warning. **The consequence for a GS1-128 of a GTIN, a date and a serial number** (44 characters as
a person reads them, 299 modules of bars and 319 with quiet zones): at the 4 dots of a logistic unit at 203 dpi
it is 1276 dots, 160 mm, and fits no label 4 in wide (812 dots with no margins), nor the 6 in of 4 x 6 in stock
(1218 dots). With no profile stated such a label is refused. Named `gs1-general` or `none` it is drawn at 2
dots, 0.25 mm, 638 dots; 3 dots would need 957. Whether such a label is printed below the GS1 minimum for
logistic units, on wider stock or as a two-dimensional symbol is a decision for whoever owns the label. The
example of section 2.1 states `minModule: 0.25mm` and no profile: it is drawn as before and now carries
`BARCODE_MODULE_BELOW_RECOMMENDED`; naming `gs1-general` is how such a scene says what it means.
- **Bars have a least height.** A linear symbol filled whatever height its box had, down to one dot. Its bars
must now be as tall as its symbology asks of bars that wide: 15% of the width of the bars and never under 5 mm
for Code 128 and GS1-128 (ISO/IEC 15417, Annex G), and by the same rule for Code 39, Code 93 and Interleaved 2
of 5, whose own specifications were not read; 69.24 modules for EAN-13, UPC-A and UPC-E and 55.24 for EAN-8
(GS1 General Specifications, the nominal 22.85 mm and 18.23 mm at a 0.330 mm module). The height is part of the
fit: a module that would make the symbol too wide for the height of its box is not chosen, so a short value in
a wide box is not refused for being short, and a box too short at the smallest module is
`BARCODE_DOES_NOT_FIT` with the height needed. The author who accepts less states `minHeight`, and the label
then carries the warning `BARCODE_HEIGHT_BELOW_RECOMMENDED`. The 31.75 mm GS1 asks of a symbol on a logistic
unit is not enforced by any profile: no label 1 in high could have it. The 44-character GS1-128 at 2 dots needs
90 dots, 11.3 mm. An EAN-13 at 3 dots needs 208 dots, 26 mm, more than a label 1 in high has.
- **Nothing is painted over a symbol.** `QUIET_ZONE_INTRUDED` is an error, raised by geometry when the scene is
validated and when it is rendered: an element later in the list whose ink (its box; for an outline, its four
bars; for a group, nothing) would enter the symbol or its quiet zones is refused, with the barcode's pointer
and both sets of edges. A panel of reverse text can no longer turn a symbol white on black. An element painted
before the barcode is cleared by the symbol's own ground and stays allowed. While a scene is validated and the
record gives the value or the symbology, the symbol is not known and the barcode keeps its whole box.
- **A barcode sits in the middle of its box** by default (section 2.4), unlike other elements.
- **A declared length proves a bound barcode.** A barcode takes `maxLength`. For a linear symbology validation
fits the widest symbol a value of that length can need (Code 128: 11 modules for each character and 35, for
values of characters from space to tilde; the other widths are in the table) and refuses the scene when that
does not fit; a longer value is `VALUE_TOO_LONG` when printing. The EAN and UPC symbols are one width and need
no length. A literal value is fitted in every symbology the record may name. `FIT_NOT_PROVEN` is left for a
bound value with no length, and for a two-dimensional symbol: the encoders choose among shapes (Data Matrix,
PDF417) or change mode at a cost (QR, Aztec), so no value of a length is the largest symbol of that length,
which tests hold them to. A two-dimensional symbol with a length is fitted for that many bytes, which refuses a
box they cannot fit and proves no more. The widest GS1-128 of a length is one of letters, about 1.7 times the
width of a label of digits, so a declared length rarely proves a GS1-128 written as a `value`; the builder of
section 4.2, which knows each identifier, can.
## 5. Graphics ## 5. Graphics
- **Image**: an asset (PNG or JPEG, as today) in a physical box. `fit` is `contain` (scale to the box, keep the - **Image**: an asset (PNG or JPEG, as today) in a physical box. `fit` is `contain` (scale to the box, keep the
@@ -564,6 +761,92 @@ for it.
**A host application** gets all of the above by registering the QBit as it does now. Forge adds help entries for **A host application** gets all of the above by registering the QBit as it does now. Forge adds help entries for
the new process, fields and widget (its help coverage test requires them) and nothing else. the new process, fields and widget (its help coverage test requires them) and nothing else.
**Decided while building the preview (P6b).**
- **The spike.** A composite widget whose `IMAGE` block has a data URL as its `path` renders as an `<img>` in the
frontend a host serves, both in a process step (seeded from the process value of the widget's name, and
fetched when no such value exists) and in a record screen section that names the widget. This was run as
component tests against the frontend's released source in a simulated browser document, with the payload shape
the backend's block classes serialise to (asserted in this repository's tests); it was not run in a real
browser against a running host. The `FILE_PREVIEW` fallback was not needed.
- **The result step fetches the widget; it is not seeded.** QQQ stores the state of a process after every
backend step and when it stops at a screen, and never removes it when the process ends: the in-memory provider
drops an entry five hours after the process started (a sweep every thirty minutes), and the shared table
provider keeps a row (encrypted when a key is configured) for its configured lifetime, twelve hours by default. A seeded widget would therefore put the picture of a real
record in memory for hours, or in a database table, which section 9 forbids. So the process state holds the
person's choices only (which template or revision, the data source, the sample name, the source table, the
record's identity, the stock and the resolution). The result step names the widget, the client requests it,
the request is authorised and drawn like any other, and the picture, the values and the diagnostics exist
only in that answer. The record's identity stays in the process state for the lifetime above; no value of the
record does.
- **The widget is requested by the run, not by the choices (independent review).** A client sends every plain
process value (a text, a number, a boolean) as a parameter of the widget request, and QQQ's widget route
writes the parameters of a request that fails or takes over a second to the application log. A render in an
isolated worker often takes that long, so the record's identity would have been logged. Once the form is
accepted, its choices are therefore held as one structured process value, which is not a plain value and is
not sent; the widget is given the run's `processUUID` and reads the choices from the state of the person's own
run (QQQ answers only the session that started it). The widget no longer reads a revision, record, sample,
stock or resolution from any request parameter.
- **One widget, two places.** The record screen sends the table and the template's identity; the action sends
the identifier of its run. The widget never trusts either: every request goes through
`DocumentPreviewService`, which applies the table of section 6.3. On the record screen an author sees the
draft and a person who may only view sees the published revision, both with sample data.
- **A revision that is named must be a publication (independent review).** The revision table also holds the
frozen drafts that the retained preview writes (`purpose` is `PREVIEW`). On the revision path the service
resolves only a publication; any other row is "Document definition not found.", the answer for an identity
that does not exist, from the action and from the widget alike. A draft is previewed through its template
alone, which needs `configure`. An earlier publication that a later one replaced is still a publication.
- **A record is read within the ceiling printing applies (independent review).** Before a source record is read
the service asks what the print path asks of the source table: that the person's channel and credential may
read it. The enforced read that follows is unchanged.
- **Too dense to preview is not "cannot print" (independent review).** When the only thing refused is the
picture (`PREVIEW_TOO_LARGE` and no other refusal), the widget says "This label is too dense to preview;
printing is not affected." (or "too large", for a page of more than sixteen million dots) in place of the
verdict that the layout cannot print.
- **No `Cache-Control` from the widget route.** A widget renderer cannot set a response header and QQQ's widget
route sets none, so a host or its proxy must send `no-store` for widget responses (README, "What a host must
configure for label previews").
- **Published revision with a record needs `generate` and not `view`**, as the table says. The record selector
(`GenerationPreviewSources`) therefore asks for `generate` alone; it asked for `configure` as well, which
would have kept a person who may generate but not author from choosing a record. Every record it offers is
still read as that person.
- **No draft fingerprint.** The service signature of section 6.3 named one. Nothing is saved against a preview,
so there is nothing a stale draft could overwrite; the preview is always of the draft as it stands.
- **Samples.** The schema allows sixteen samples where section 6.2 says eight; the schema is followed. The form
offers the first sixteen whose names are plain words. A version 1 scene has no `samples`, so its sample
preview has an empty context; a label bound to record values then cannot be drawn without a record, and the
widget says so.
- **Longest values on the host.** The host has no fonts and cannot know a face's widest glyph. It fills each
bound element that declares `maxLength` (1 to 4096) with that many capital W, starting from the first sample
so that barcodes and unbounded values keep their data. A capital W is not the widest glyph of every face, so
the picture is indicative, and the help of the form says so. A preview is a render of the values it is given;
it proves nothing about other values. The renderer's own worst-case layout at publication stays the proof of
fit.
- **What reaches the browser is bounded:** the first page only, a picture of at most two mebibytes (larger, the
facts and diagnostics are shown without it), and fifty diagnostics with a count of the rest.
- **Painting is bounded as well as the page (review of P5).** `ZplRaster` counts the dots every field paints, an
overlap each time, and refuses the field that would take the page past sixteen times its dots as
`PREVIEW_TOO_LARGE`, the renderer's own limit for a scene; a refused scene whose boxes would pass it has no
page and gains that diagnostic. A box is at most four solid bars and a placeholder is a one-dot outline with
its two diagonals, so the work a label can cause is what it inks and not its fields times its page. Where
this document says "hatched", read "outlined and crossed". A version 1 label that painted its page more than
sixteen times over would print and not be previewed.
- **The version question is asked again after any `RENDERER_TOO_OLD` (review of P5).** What the bridge remembers
about the renderer is what it last saw: after an image rollback one job that only 0.2.0 can do reaches the old
renderer and is refused. Any job that ends in that refusal clears what was remembered, so the window is one
job.
- **The released version 1 job frame is pinned (review of P5).** A golden captured at `v1.1.0-RC.2` is compared
with what `render()` sends today, byte for byte except the order of the seven members of `stock`, which the
released bridge already wrote in an order that varies from run to run.
- **A failure's own words are never shown.** The widget shows the fixed sentences of this module and the closed
code of a named render refusal. A message from the host's renderer adapter or context script, which could
quote record data, reaches a caller of the service but not the screen.
- **The existing action stays** beside the new one, relabelled "Generate retained preview file"; its behaviour
and its process name are unchanged.
- **Help** is carried by the metadata itself (process, steps, fields, section, widget and the two choice
lists), as this repository does for its other screens; it has no help bundle file. A host's coverage check
that counts metadata help needs no entries of its own for these.
### 6.5 Page (PDF) templates ### 6.5 Page (PDF) templates
- Today's retained preview keeps working for PDF and stays the way to obtain the exact file. - Today's retained preview keeps working for PDF and stays the way to obtain the exact file.
@@ -615,8 +898,8 @@ diagnostic is closed vocabulary and numbers only:
| Severity | Codes (first release) | | Severity | Codes (first release) |
|---|---| |---|---|
| ERROR | `SCENE_INVALID` (with the JSON pointer of the offending property), `STOCK_MISMATCH`, `TARGET_REQUIRES_SCENE_2`, `ELEMENT_OUTSIDE_PRINTABLE_AREA`, `TEXT_DOES_NOT_FIT`, `VALUE_MISSING`, `VALUE_TOO_LONG`, `FONT_UNKNOWN`, `FONT_MISSING_GLYPH`, `RESERVED_FONT_NAME`, `BARCODE_DOES_NOT_FIT`, `GS1_INVALID`, `ASSET_UNKNOWN`, `PREVIEW_TOO_LARGE`, `RENDERER_TOO_OLD` | | ERROR | `SCENE_INVALID` (with the JSON pointer of the offending property), `STOCK_MISMATCH`, `TARGET_REQUIRES_SCENE_2`, `ELEMENT_OUTSIDE_PRINTABLE_AREA`, `TEXT_DOES_NOT_FIT`, `VALUE_MISSING`, `VALUE_TOO_LONG`, `FONT_UNKNOWN`, `FONT_MISSING_GLYPH`, `RESERVED_FONT_NAME`, `BARCODE_DOES_NOT_FIT`, `GS1_INVALID`, `ASSET_UNKNOWN`, `PREVIEW_TOO_LARGE`, `RENDERER_TOO_OLD`, `VALUE_NOT_ENCODABLE`, `QUIET_ZONE_INTRUDED` |
| WARNING | `TEXT_TRUNCATED`, `TEXT_SMALL_FOR_DPI`, `TEXT_LIGHT_FACE`, `FIT_NOT_PROVEN`, `BARCODE_MODULE_BELOW_RECOMMENDED`, `QUIET_ZONE_INTRUDED`, `ELEMENTS_OVERLAP`, `IMAGE_UPSCALED`, `DEVICE_UNIT_USED`, `PRINTER_FONT_NOT_SHOWN` | | WARNING | `TEXT_TRUNCATED`, `TEXT_SMALL_FOR_DPI`, `TEXT_LIGHT_FACE`, `FIT_NOT_PROVEN`, `BARCODE_MODULE_BELOW_RECOMMENDED`, `BARCODE_HEIGHT_BELOW_RECOMMENDED`, `ELEMENTS_OVERLAP`, `IMAGE_UPSCALED`, `DEVICE_UNIT_USED`, `PRINTER_FONT_NOT_SHOWN` |
| INFO | `TEXT_SHRUNK` (from and to size), `TEXT_WRAPPED` (lines), `BARCODE_MODULE` (dots and micrometres), `IMAGE_SCALED` | | INFO | `TEXT_SHRUNK` (from and to size), `TEXT_WRAPPED` (lines), `BARCODE_MODULE` (dots and micrometres), `IMAGE_SCALED` |
Version 1 scenes keep their existing codes and the opaque `RENDER_FAILED`. Version 1 scenes keep their existing codes and the opaque `RENDER_FAILED`.
@@ -714,9 +997,10 @@ the server sends, so this needs no scanner or app release. The client's own word
pixel limits, SVG still refused. Assets are addressed by hash; identical bytes are stored once. pixel limits, SVG still refused. Assets are addressed by hash; identical bytes are stored once.
- **Bundled fonts.** Unmodified, each with licence, provenance and hash, listed in `THIRD-PARTY.md` and `NOTICE`. - **Bundled fonts.** Unmodified, each with licence, provenance and hash, listed in `THIRD-PARTY.md` and `NOTICE`.
- **No preview is stored.** No revision, request, event, retained file or log content. The PNG of a real-record - **No preview is stored.** No revision, request, event, retained file or log content. The PNG of a real-record
preview exists in the response and, when shown through a process step, in that process's server-side state until preview exists in the answer to the widget request and nowhere else: it is never a process value. (Decided in
it expires, as any process screen showing record data does. (That store's retention was not verified.) The record P6b, section 6.4, once the retention of process state had been read: hours in memory, or a table row with the
screen widget uses sample data only, so opening a template never renders customer data. shared provider.) The record screen widget uses sample data only, so opening a template never renders customer
data.
- **Samples** are synthetic by rule, stated in the field help and the authoring guide. - **Samples** are synthetic by rule, stated in the field help and the authoring guide.
- **Diagnostics and logs** carry element ids and numbers only. - **Diagnostics and logs** carry element ids and numbers only.
- **Permissions** are the existing five; section 6.3 gives the mapping. Uploading and converting need `configure`. - **Permissions** are the existing five; section 6.3 gives the mapping. Uploading and converting need `configure`.
+25 -5
View File
@@ -28,16 +28,36 @@ crashes:
- **Version 2 scene parser.** The target is the worker's own routing, so a mutated source may also become a - **Version 2 scene parser.** The target is the worker's own routing, so a mutated source may also become a
version 1 scene, which is then held to the version 1 property. An accepted version 2 scene, read by the version 1 scene, which is then held to the version 1 property. An accepted version 2 scene, read by the
second parser, has only the declared top-level properties, a physical design size, at most 1000 elements second parser, has only the declared top-level properties, a physical design size, at most 1000 elements
with unique ids of the fixed pattern, only `box` and `group` elements with only their declared properties with unique ids of the fixed pattern, only `box`, `group`, `text` and `barcode` elements with only their
(the other types are refused until their packages exist), groups at most four deep, every length a number declared properties (images are refused until their package exists), groups at most four deep, every
and a unit, and overrides only for the three resolutions and for declared ids. About one version 2 input in length a number and a unit, and overrides only for the three resolutions and for declared ids. A `text`
element is read as it stands at each resolution (the defaults, then the element, then the overrides for that
resolution): it names a bundled face, has a physical size from 1 to 1000 pt, exactly one of a literal value
and a pointer into the record, and only fit, length, threshold, rotation, reverse and line height settings of
the documented kinds and ranges. A `barcode` element is read the same way (the element, then the overrides):
it states one fit-qualified symbology or a pointer with a list of distinct ones, exactly one of a literal
value of 1 to 4000 characters that holds no encoder escape and a pointer into the record, a scanner profile
whole or not at all, module sizes and a minimum height that are more than nothing, a quiet zone from the
widest minimum of its symbologies to 64, a `maxLength` from 1 to 4000, one of the three named profiles, a
quarter-turn rotation, and neither `gs1` nor `hri`. The corpus holds the three text cases (`text-faces`,
`text-fit`, `text-turned`) and the three barcode cases (`barcode-linear`, `barcode-matrix`, `barcode-gs1`)
beside the layout cases. The spliced tokens include the text properties, a combining mark, a tab, half of a
surrogate pair, a size of `1000pt` and the number `1e400`; and the barcode properties, symbology names in and
out of the fit-qualified set, the profile names, an element string, a GTIN, the encoder's escape for a
function character and characters outside Latin-1. A barcode encoder's own exception is not a refusal: a
mutated value must end as a `Refusal` or as a label. The campaign asserts that it rendered labels holding a
barcode. About one version 2 input in
four, chosen by its bytes so that a replay does the same, is rendered instead of validated: the label is read four, chosen by its bytes so that a replay does the same, is rendered instead of validated: the label is read
back into a page, must be only the header, uncompressed graphic fields and the end of a label, must put no ink back into a page, must be only the header, uncompressed graphic fields and the end of a label, must put no ink
outside the printable area, and validation of the same input must give the same answer (accepted with the same outside the printable area, and validation of the same input must give the same answer (accepted with the same
findings, or refused with the same diagnostic). A refusal is the scene's own `Refusal`, the exception that findings, or refused with the same diagnostic). The one difference allowed is `VALUE_MISSING`: a text or a
barcode bound to the record has no value in the campaign's empty record, and validation reads no record. A
refusal is the scene's own `Refusal`, the exception that
carries a diagnostic, and nothing else: the routing turns unreadable JSON and an unknown schema into one. A carries a diagnostic, and nothing else: the routing turns unreadable JSON and an unknown schema into one. A
plain `IllegalArgumentException` is a finding, because the package raises those for its own broken invariants plain `IllegalArgumentException` is a finding, because the package raises those for its own broken invariants
(`CANVAS_BOUNDS`, `CANVAS_LIMIT`, `LENGTH_NOT_ABSOLUTE`, `LENGTH_NOT_PHYSICAL`), which no scene may reach. The (`CANVAS_BOUNDS`, `CANVAS_LIMIT`, `LENGTH_NOT_ABSOLUTE`, `LENGTH_NOT_PHYSICAL`), which no scene may reach; so is
the text package's `IllegalStateException` for ink outside a measured line (`TEXT_INK_OUTSIDE_MEASURE`), and
any arithmetic or number-format failure. The
one exception is a source the routing sends to the frozen version 1 parser, whose own refusal is a plain one exception is a source the routing sends to the frozen version 1 parser, whose own refusal is a plain
`IllegalArgumentException`; such sources are validated only. The campaign also asserts that it rendered labels. `IllegalArgumentException`; such sources are validated only. The campaign also asserts that it rendered labels.
- **Printer gate.** An accepted input contains only the commands the renderer may emit and no tilde command. - **Printer gate.** An accepted input contains only the commands the renderer may emit and no tilde command.
@@ -33,6 +33,7 @@ import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
import com.kingsrook.qqq.backend.core.context.QContext; import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException; import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException; import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QNotFoundException;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator; import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter; import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput; import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
@@ -599,6 +600,44 @@ public class DocumentDefinitionService
return (snapshot(id, row.getValueInteger("templateId"), row, row)); return (snapshot(id, row.getValueInteger("templateId"), row, row));
} }
/*******************************************************************************
** A published snapshot named by a person, for a layout preview. A revision
** holds either a publication or the frozen draft of a retained preview, and
** only a publication may be shown to a person who may not author: any other
** row is answered exactly as an identity that does not exist. A row written
** before revisions recorded their purpose is a publication, as everywhere
** else a revision is resolved.
*******************************************************************************/
GenerationPorts.Revision publishedSnapshot(Integer id) throws QException
{
QRecord row = GenerationStore.get(GenerationTables.REVISION, id);
if(row.getValueString("purpose") != null && !"PUBLISHED".equals(row.getValueString("purpose")))
{
throw (new QNotFoundException("Document definition not found."));
}
return (snapshot(id, row.getValueInteger("templateId"), row, row));
}
/*******************************************************************************
** The current draft as the renderer would receive it, for a layout preview.
** Nothing is frozen or written; the caller has already checked authority.
*******************************************************************************/
GenerationPorts.Revision draft(Integer templateId) throws QException
{
QRecord row = GenerationStore.get(GenerationTables.TEMPLATE, templateId);
return (snapshot(null, templateId, row, GenerationStore.get(GenerationTables.STOCK, row.getValueInteger("stockId"))));
}
/*******************************************************************************
** A stored stock by identity, held to the same physical limits as publication.
*******************************************************************************/
GenerationPorts.Stock stock(Integer stockId) throws QException
{
GenerationPorts.Stock stock = readStock(GenerationStore.get(GenerationTables.STOCK, stockId));
validateStock(stock);
return (stock);
}
/******************************************************************************* /*******************************************************************************
** Current binding policy is checked independently from revision pinning. ** Current binding policy is checked independently from revision pinning.
*******************************************************************************/ *******************************************************************************/
@@ -0,0 +1,414 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.documentgeneration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.logging.QLogger;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
import static com.kingsrook.qqq.backend.core.logging.LogUtils.logPair;
/*******************************************************************************
** A layout preview: the print path stopped before retention. The configured
** isolated renderer draws a template's draft or a published revision with
** sample data, its longest declared values or one record the person may read,
** and the answer is a picture with its diagnostics.
**
** Nothing is written: no revision, request, event or file. This service logs
** one line that names the actor, the template, the target and the outcome,
** and never any content or record identity.
**
** What a host's own request log holds is outside this service. The "Preview
** layout" action therefore keeps the person's choices in the state of their
** run, and the picture is requested by the run's identifier alone, so a record
** identity is not a parameter of that request (`GenerationPreviewProcesses`).
*******************************************************************************/
public final class DocumentPreviewService
{
static final int MAXIMUM_SAMPLES = 16;
static final int MAXIMUM_LENGTH = 4096;
private static final QLogger LOG = QLogger.getLogger(DocumentPreviewService.class);
private static final ObjectMapper JSON = new ObjectMapper();
private final DocumentGenerationQBitConfig config;
private final DocumentDefinitionService definitions;
/***************************************************************************
** Where the values of a preview come from.
***************************************************************************/
public enum Data
{
/////////////////////////////////////////////////////////////////////////////////////
// a named synthetic context the author wrote in the scene; the first when unnamed //
/////////////////////////////////////////////////////////////////////////////////////
SAMPLE,
/////////////////////////////////////////////////////////////////////////////////////
// the first sample, with every bound text that declares a maximum length filled //
// to that length, so overflow shows //
/////////////////////////////////////////////////////////////////////////////////////
LONGEST,
/////////////////////////////////////////////////////////////////////////////////////
// one source record, read as the person asking //
/////////////////////////////////////////////////////////////////////////////////////
RECORD
}
/***************************************************************************
** What to preview. Exactly one of the template (its current draft) and the
** revision (a published snapshot) is given. The stock and the render target
** are optional: absent, the template's or revision's own stock and that
** stock's resolution are used.
***************************************************************************/
public record Options(Integer templateId, Integer revisionId, GenerationPorts.Format format, Data data, String sampleName, String sourceRecordId, Integer stockId,
Integer targetDpi)
{
}
/***************************************************************************
** A preview and the resolution its pages were drawn at.
***************************************************************************/
public record Result(GenerationPorts.Preview preview, Integer dpi)
{
}
/***************************************************************************
** What a form needs before the person chooses: the source table of the
** template and the names of the samples its scene declares.
***************************************************************************/
public record Choices(String sourceTable, List<String> sampleNames)
{
}
/*******************************************************************************
** Use the host's configured renderer and context script execution.
*******************************************************************************/
public DocumentPreviewService(DocumentGenerationQBitConfig config)
{
this.config = config;
this.definitions = new DocumentDefinitionService(config);
}
/*******************************************************************************
** Draw the preview. A layout that cannot print is a result, not an exception:
** the preview says so and carries the diagnostics.
*******************************************************************************/
public Result preview(Options options) throws QException
{
String actor = authorize(options);
GenerationPorts.Revision revision = revision(options);
Map<String, Object> context = context(actor, revision, options);
Integer dpi = options.targetDpi() == null ? revision.stock().dpi() : options.targetDpi();
try
{
GenerationPorts.Preview preview = config.getRenderer().preview(new GenerationPorts.PreviewRequest(actor, options.format(), revision, context, options.targetDpi(),
config.getMaximumOutputBytes()));
log(actor, options, dpi, preview.printable() ? "PRINTABLE" : "REFUSED", preview.diagnostics().stream().map(GenerationPorts.Diagnostic::code).distinct().sorted().toList());
return (new Result(preview, dpi));
}
catch(QException failure)
{
log(actor, options, dpi, "FAILED", List.of());
throw (foreign(failure));
}
}
/*******************************************************************************
** Everything a preview checks before it renders: the permissions, the
** template or revision, the stock, and that the chosen record can be read
** or the chosen sample exists. A form calls this to refuse at once.
*******************************************************************************/
public void check(Options options) throws QException
{
authorize(options);
GenerationPorts.Revision revision = revision(options);
if(options.data() == Data.RECORD)
{
GenerationSecurity.requireRead(revision.sourceTable());
GenerationSecurity.source(new GenerationPorts.Source(revision.sourceTable(), options.sourceRecordId()));
}
else
{
sample(scene(revision.zplSource()), options.sampleName());
}
}
/*******************************************************************************
** The source table and sample names of a draft or a published revision, under
** the permission a sample preview of it needs.
*******************************************************************************/
public Choices choices(Integer templateId, Integer revisionId) throws QException
{
Options sample = new Options(templateId, revisionId, GenerationPorts.Format.ZPL, Data.SAMPLE, null, null, null, null);
authorize(sample);
GenerationPorts.Revision revision = revision(sample);
JsonNode samples = scene(revision.zplSource()).path("samples");
List<String> names = new ArrayList<>();
for(Iterator<String> name = samples.fieldNames(); name.hasNext() && names.size() < MAXIMUM_SAMPLES; )
{
String candidate = name.next();
if(samples.get(candidate).isObject() && candidate.matches("[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}"))
{
names.add(candidate);
}
}
return (new Choices(revision.sourceTable(), List.copyOf(names)));
}
/*******************************************************************************
** The published revision of a template, for a person who may view it but not
** author it; absent when the template has never been published.
*******************************************************************************/
public Integer publishedRevision(Integer templateId) throws QException
{
GenerationSecurity.require("view");
return (GenerationStore.get(GenerationTables.TEMPLATE, templateId).getValueInteger("publishedRevisionId"));
}
/*******************************************************************************
** Who may preview what. A draft needs `configure`; a published revision needs
** `view`; a real record needs `generate` (beside `configure` for a draft, and
** in place of `view` for a published revision) and is then read as the
** person. No permission is new. A draft is reached through its template
** alone: a revision named here is a publication or it is not found
** (`revision`), so neither `view` nor `generate` shows a draft.
*******************************************************************************/
private String authorize(Options options) throws QException
{
if(options == null || options.data() == null || options.format() == null || (options.templateId() == null) == (options.revisionId() == null)
|| (options.targetDpi() != null && !List.of(203, 300, 600).contains(options.targetDpi())))
{
throw new QBadRequestException("A preview needs a template draft or a published revision, a data source and a resolution of 203, 300 or 600 dpi.");
}
boolean record = options.data() == Data.RECORD;
String actor = GenerationSecurity.require(options.revisionId() == null ? "configure" : record ? "generate" : "view");
if(record)
{
GenerationSecurity.require("generate");
if(options.sourceRecordId() == null || options.sourceRecordId().isBlank())
{
throw new QBadRequestException("Choose the record to preview.");
}
}
if(options.format() != GenerationPorts.Format.ZPL)
{
throw new QBadRequestException("Preview is available for labels only.");
}
return (actor);
}
/*******************************************************************************
** The draft as it stands or the published snapshot, on the chosen stock.
** Neither is written anywhere. A revision that is not a publication (the
** frozen draft of a retained preview) is not found, in the words and with
** the type of an identity that does not exist.
*******************************************************************************/
private GenerationPorts.Revision revision(Options options) throws QException
{
GenerationPorts.Revision revision = options.revisionId() == null ? definitions.draft(options.templateId()) : definitions.publishedSnapshot(options.revisionId());
if(revision.zplSource() == null || revision.zplSource().isBlank())
{
throw new QBadRequestException("This template has no label (ZPL) source to preview.");
}
if(options.stockId() == null)
{
return (revision);
}
return (new GenerationPorts.Revision(revision.id(), revision.templateId(), revision.sourceTable(), definitions.stock(options.stockId()), revision.pdfSource(),
revision.zplSource(), revision.scriptArtifact(), revision.assets(), revision.outputBaseName(), revision.outputNameContextKey()));
}
/*******************************************************************************
** The values the renderer receives. A record is read as the person, with
** their permissions and record locks and within what their channel and
** credential may read (the ceiling printing applies to the source table),
** before any context is built, and the context is then built exactly as
** generation builds it, including the pinned context script. The record is
** read again after the script, as generation does, so access lost meanwhile
** still refuses.
*******************************************************************************/
private Map<String, Object> context(String actor, GenerationPorts.Revision revision, Options options) throws QException
{
if(options.data() != Data.RECORD)
{
JsonNode scene = scene(revision.zplSource());
Map<String, Object> sample = sample(scene, options.sampleName());
if(options.data() == Data.LONGEST)
{
longest(scene.path("elements"), sample, 0);
}
return (SafeContext.copy(sample));
}
GenerationSecurity.requireRead(revision.sourceTable());
QRecord selected = GenerationSecurity.source(new GenerationPorts.Source(revision.sourceTable(), options.sourceRecordId()));
GenerationPorts.Source source = new GenerationPorts.Source(revision.sourceTable(),
selected.getValueString(QContext.getQInstance().getTable(revision.sourceTable()).getPrimaryKeyField()));
Map<String, Object> record = SafeContext.copy(selected.getValues());
Map<String, Object> context = new LinkedHashMap<>();
if(revision.scriptArtifact() != null)
{
try
{
context.putAll(SafeContext.copy(config.getContextExecution().prepare(new GenerationPorts.ContextRequest(actor, revision.scriptArtifact(), source, record))));
}
catch(QException failure)
{
throw (foreign(failure));
}
GenerationSecurity.require("generate");
GenerationSecurity.requireRead(source.tableName());
GenerationSecurity.source(source);
}
context.put("record", record);
return (SafeContext.copy(context));
}
/*******************************************************************************
** A failure of the host's renderer or context script keeps its message for
** the caller of this service, but loses any type that a screen would show to
** a person as an explanation: such a message could quote record data, and
** only this service's own fixed sentences are shown. A named render refusal
** is closed vocabulary and stays as it is.
*******************************************************************************/
private static QException foreign(QException failure)
{
return (failure instanceof GenerationPorts.RenderException || failure.getClass() == QException.class ? failure : new QException(failure.getMessage()));
}
/*******************************************************************************
** The scene as JSON, read only for its samples and declared lengths. A source
** this host cannot read declares none; the renderer reports what is wrong.
*******************************************************************************/
private static JsonNode scene(String source)
{
try
{
return (JSON.readTree(source));
}
catch(JsonProcessingException unreadable)
{
return (JSON.missingNode());
}
}
/*******************************************************************************
** The named sample, or the first when no name is given. A scene without
** samples gives an empty context; a name it does not declare is refused.
*******************************************************************************/
@SuppressWarnings("unchecked")
private static Map<String, Object> sample(JsonNode scene, String name) throws QBadRequestException
{
JsonNode samples = scene.path("samples");
boolean named = name != null && !name.isBlank();
int seen = 0;
for(Iterator<String> candidate = samples.fieldNames(); candidate.hasNext() && seen < MAXIMUM_SAMPLES; seen++)
{
String key = candidate.next();
if(samples.get(key).isObject() && (!named || name.equals(key)))
{
return (JSON.convertValue(samples.get(key), LinkedHashMap.class));
}
}
if(named)
{
throw new QBadRequestException("The scene declares no sample of that name.");
}
return (new LinkedHashMap<>());
}
/*******************************************************************************
** Fill every bound element that declares a maximum length with a value of
** that length. The host has no fonts, so it cannot know a face's widest
** glyph: a capital W is wide but is not the widest glyph of every face, so
** the picture is indicative. A preview is a render of these values and
** proves nothing about other values; whether every value of the declared
** length fits is decided by the renderer when it validates the template for
** publication.
*******************************************************************************/
private static void longest(JsonNode elements, Map<String, Object> context, int depth)
{
for(JsonNode element : elements)
{
JsonNode path = element.path("valuePath");
JsonNode length = element.path("maxLength");
if(path.isTextual() && length.isInt() && length.intValue() >= 1 && length.intValue() <= MAXIMUM_LENGTH)
{
put(context, path.textValue().split("/", -1), "W".repeat(length.intValue()));
}
if(depth < 16)
{
longest(element.path("children"), context, depth + 1);
}
}
}
/*******************************************************************************
** Set one value by its JSON pointer, creating the objects on the way. A path
** that is not a pointer into objects is left alone.
*******************************************************************************/
@SuppressWarnings("unchecked")
private static void put(Map<String, Object> context, String[] segments, String value)
{
if(segments.length < 2 || segments.length > 17 || !segments[0].isEmpty())
{
return;
}
Map<String, Object> at = context;
for(int index = 1; index < segments.length - 1; index++)
{
Object next = at.get(key(segments[index]));
if(!(next instanceof Map<?, ?>))
{
next = new LinkedHashMap<String, Object>();
at.put(key(segments[index]), next);
}
at = (Map<String, Object>) next;
}
at.put(key(segments[segments.length - 1]), value);
}
/*******************************************************************************
** One pointer segment as the property name it stands for.
*******************************************************************************/
private static String key(String segment)
{
return (segment.replace("~1", "/").replace("~0", "~"));
}
/*******************************************************************************
** The one line this service logs for a preview: identities, the target and
** the outcome. No source, sample, record identity or record value is in it.
*******************************************************************************/
private static void log(String actor, Options options, Integer dpi, String outcome, List<String> codes)
{
LOG.info("Document layout preview", logPair("actor", actor), logPair("templateId", options.templateId()), logPair("revisionId", options.revisionId()),
logPair("data", options.data()), logPair("dpi", dpi), logPair("outcome", outcome), logPair("diagnostics", String.join(",", codes)));
}
}
@@ -133,7 +133,7 @@ public final class GenerationAuthoringProcesses
} }
register(instance, GenerationTables.TEMPLATE, "naming", "Edit output filename"); register(instance, GenerationTables.TEMPLATE, "naming", "Edit output filename");
register(instance, GenerationTables.TEMPLATE, "publish", "Validate and publish draft"); register(instance, GenerationTables.TEMPLATE, "publish", "Validate and publish draft");
register(instance, GenerationTables.TEMPLATE, "preview", "Preview draft"); register(instance, GenerationTables.TEMPLATE, "preview", "Generate retained preview file");
register(instance, GenerationTables.TEMPLATE, "asset", "Select retained asset for draft"); register(instance, GenerationTables.TEMPLATE, "asset", "Select retained asset for draft");
register(instance, GenerationTables.TEMPLATE, "removeAsset", "Remove included draft asset"); register(instance, GenerationTables.TEMPLATE, "removeAsset", "Remove included draft asset");
register(instance, GenerationTables.TEMPLATE, "replaceAsset", "Replace included draft asset"); register(instance, GenerationTables.TEMPLATE, "replaceAsset", "Replace included draft asset");
@@ -122,7 +122,9 @@ public final class GenerationPorts
GS1_INVALID, GS1_INVALID,
ASSET_UNKNOWN, ASSET_UNKNOWN,
PREVIEW_TOO_LARGE, PREVIEW_TOO_LARGE,
RENDERER_TOO_OLD RENDERER_TOO_OLD,
VALUE_NOT_ENCODABLE,
QUIET_ZONE_INTRUDED
} }
/*************************************************************************** /***************************************************************************
@@ -148,7 +150,7 @@ public final class GenerationPorts
{ {
private static final java.util.regex.Pattern POINTER = java.util.regex.Pattern.compile("(/(0|[1-9][0-9]{0,3}|[A-Za-z][A-Za-z0-9_-]{0,31})){0,16}"); private static final java.util.regex.Pattern POINTER = java.util.regex.Pattern.compile("(/(0|[1-9][0-9]{0,3}|[A-Za-z][A-Za-z0-9_-]{0,31})){0,16}");
private static final java.util.Set<String> WARNINGS = java.util.Set.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", private static final java.util.Set<String> WARNINGS = java.util.Set.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN",
"BARCODE_MODULE_BELOW_RECOMMENDED", "QUIET_ZONE_INTRUDED", "ELEMENTS_OVERLAP", "IMAGE_UPSCALED", "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN"); "BARCODE_MODULE_BELOW_RECOMMENDED", "BARCODE_HEIGHT_BELOW_RECOMMENDED", "ELEMENTS_OVERLAP", "IMAGE_UPSCALED", "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN");
private static final java.util.Set<String> INFORMATION = java.util.Set.of("TEXT_SHRUNK", "TEXT_WRAPPED", "BARCODE_MODULE", "IMAGE_SCALED"); private static final java.util.Set<String> INFORMATION = java.util.Set.of("TEXT_SHRUNK", "TEXT_WRAPPED", "BARCODE_MODULE", "IMAGE_SCALED");
/************************************************************************ /************************************************************************
@@ -21,15 +21,76 @@
package com.kingsrook.qbits.documentgeneration; package com.kingsrook.qbits.documentgeneration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import com.kingsrook.qqq.backend.core.actions.permissions.CustomPermissionChecker;
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException; import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessMetaDataAdjustment;
import com.kingsrook.qqq.backend.core.model.actions.processes.ProcessState;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
import com.kingsrook.qqq.backend.core.model.metadata.QInstance; import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
import com.kingsrook.qqq.backend.core.model.metadata.help.QHelpContent;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValue;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSourceType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QComponentType;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendComponentMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFrontendStepMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFunctionInputMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.processes.QRecordListMetaData;
/******************************************************************************* /*******************************************************************************
** Layout preview processes for a template: sample, stress and record data. ** The "Preview layout" action on a template (its current draft) and on a
** The producer already calls this registration point; it registers nothing yet. ** published revision: a form for the data, the stock and the resolution, and
** a result that is the preview widget.
**
** The process keeps the person's choices and nothing else. The picture, the
** values it was drawn from and its diagnostics are never process values: the
** result step names the widget, the client fetches it, and the picture exists
** only in that answer. QQQ keeps the state of a finished process for hours
** (and, with a shared state provider, in a table), so a picture of record
** data must not be put there.
**
** The widget is fetched by the identifier of the run, not by the choices. A
** client sends every plain process value (a text, a number, a boolean) as a
** parameter of the widget request, and QQQ's widget route writes the
** parameters of a request that fails or takes over a second to the
** application log. So once the form is accepted its choices, the record among
** them, are held as one structured process value (`CHOICES`), which is not a
** plain value and so not a request parameter, and the widget reads them from
** the state of the person's own run.
*******************************************************************************/ *******************************************************************************/
final class GenerationPreviewProcesses final class GenerationPreviewProcesses
{ {
static final String DATA = "document_generation_preview_data";
static final String RESOLUTION = "document_generation_preview_resolution";
static final String CHOICES = "document_generation_preview_choices";
private static final List<String> FORM = List.of("dataSource", "sampleName", "sourceRecordId", "stockId", "targetDpi");
private static final String RUN = "[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}";
/******************************************************************************* /*******************************************************************************
** Metadata namespace. ** Metadata namespace.
*******************************************************************************/ *******************************************************************************/
@@ -42,5 +103,229 @@ final class GenerationPreviewProcesses
*******************************************************************************/ *******************************************************************************/
static void register(QInstance instance, DocumentGenerationQBitConfig config) throws QException static void register(QInstance instance, DocumentGenerationQBitConfig config) throws QException
{ {
instance.addPossibleValueSource(new QPossibleValueSource().withName(DATA).withLabel("Preview data").withType(QPossibleValueSourceType.ENUM).withIdType(QFieldType.STRING)
.withEnumValues(List.of(new QPossibleValue<>("SAMPLE", "Sample data written in the scene"), new QPossibleValue<>("LONGEST", "Longest values"),
new QPossibleValue<>("RECORD", "A record I choose")))
.withHelpContent(QHelpContent.SLOT_HELP, GenerationTables.help("Where the values of a layout preview come from: a sample the author wrote in the scene, the same sample "
+ "with every bound text filled with capital W to the maximum length it declares, or one source record the person may read. The longest values picture is indicative: "
+ "W is not the widest character of every font, and the renderer's own proof of the declared length, made when the template is published, decides whether every value fits.")));
instance.addPossibleValueSource(new QPossibleValueSource().withName(RESOLUTION).withLabel("Preview resolution").withType(QPossibleValueSourceType.ENUM).withIdType(QFieldType.INTEGER)
.withEnumValues(List.of(new QPossibleValue<>(203, "203 dpi"), new QPossibleValue<>(300, "300 dpi"), new QPossibleValue<>(600, "600 dpi")))
.withHelpContent(QHelpContent.SLOT_HELP, GenerationTables.help("The printer resolutions a label can be drawn for. A version 1 scene is drawn only at the resolution of its stock.")));
instance.addWidget(GenerationPreviewWidget.metaData());
boolean selector = instance.getPossibleValueSource(GenerationAuthoringProcesses.PREVIEW_SOURCE) != null;
for(String table : List.of(GenerationTables.TEMPLATE, GenerationTables.REVISION))
{
boolean draft = GenerationTables.TEMPLATE.equals(table);
QFrontendStepMetaData options = new QFrontendStepMetaData().withName("options").withLabel("Preview layout")
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.EDIT_FORM))
.withHelpContent(GenerationTables.help("Choose what the label is drawn with. Sample data and longest values come from the scene and involve no record. "
+ "A record is read with your own permissions. Nothing is saved, and no file is created."))
.withFormField(new QFieldMetaData("dataSource", QFieldType.STRING).withLabel("Data to draw with").withIsRequired(true).withPossibleValueSourceName(DATA)
.withHelpContent(GenerationTables.help("Sample data uses a sample written in the scene. Longest values fills every bound text with capital W to the maximum length "
+ "it declares, so overflow shows. That picture is indicative: W is not the widest character of every font, and the renderer's own proof of the declared length, "
+ "made when the template is published, decides whether every value fits. A record uses one source record you can read.")))
.withFormField(new QFieldMetaData("sampleName", QFieldType.STRING).withLabel("Sample (blank = the first in the scene)").withMaxLength(64)
.withHelpContent(GenerationTables.help("The name of a sample the scene declares under samples. Samples are written by the template's author and must be synthetic: "
+ "never copy real record data into a scene.")));
if(selector)
{
options.withFormField(new QFieldMetaData("sourceTable", QFieldType.STRING).withLabel("Records this template belongs to").withIsEditable(false)
.withPossibleValueSourceName(GenerationAuthoringProcesses.SOURCES)
.withHelpContent(GenerationTables.help("The table whose records this template is generated for. It is set on the template and cannot be changed here.")));
}
QFieldMetaData record = new QFieldMetaData("sourceRecordId", QFieldType.STRING).withLabel("Record (only for a record preview)").withMaxLength(255)
.withHelpContent(GenerationTables.help("The record to draw the label with. Only records you can read are offered, and one you cannot read is refused as not found. "
+ "Its values are used for this one picture and are not stored or logged."));
if(selector)
{
record.setPossibleValueSourceName(GenerationAuthoringProcesses.PREVIEW_SOURCE);
}
options.withFormField(record)
.withFormField(new QFieldMetaData("stockId", QFieldType.INTEGER).withLabel("Stock (blank = " + (draft ? "the template's own)" : "the revision's own)"))
.withPossibleValueSourceName(GenerationTables.STOCK)
.withHelpContent(GenerationTables.help("Draw the label on another stock to see how the layout behaves there. The template is not changed.")))
.withFormField(new QFieldMetaData("targetDpi", QFieldType.INTEGER).withLabel("Resolution (blank = the stock's own)").withPossibleValueSourceName(RESOLUTION)
.withHelpContent(GenerationTables.help("The printer resolution to draw for. A version 2 scene can be drawn at 203, 300 or 600 dpi; "
+ "a version 1 scene only at the resolution of its stock.")));
instance.addProcess(new QProcessMetaData().withName(name(table)).withTableName(table).withLabel("Preview layout").withIcon(new QIcon("image"))
.withMinInputRecords(1).withMaxInputRecords(1)
.withHelpContent(QHelpContent.SLOT_HELP, GenerationTables.help((draft ? "Draw the current draft of this template" : "Draw this published revision")
+ " as the label that would print, with its warnings and refusals, before anything is printed. Nothing is saved and no file is created."))
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED).withCustomPermissionChecker(new QCodeReference(Permission.class)))
.withStep(new QBackendStepMetaData().withName("prepare").withCode(new QCodeReference(Prepare.class))
.withInputData(new QFunctionInputMetaData().withRecordListMetaData(new QRecordListMetaData().withTableName(table))))
.withStep(options)
.withStep(new QBackendStepMetaData().withName("check").withCode(new QCodeReference(Check.class)))
.withStep(new QFrontendStepMetaData().withName("result").withLabel("Layout preview")
.withComponent(new QFrontendComponentMetaData().withType(QComponentType.WIDGET).withValue("widgetName", GenerationPreviewWidget.NAME))
.withHelpContent(GenerationTables.help("The picture is decoded from the exact bytes that would be sent to the printer. The first line says whether it is exact "
+ "and whether the label can print; the lines below the picture give its size and each refusal, warning and note with the element it concerns."))));
}
}
/*******************************************************************************
** One stable name per table: the draft on a template, the snapshot on a revision.
*******************************************************************************/
static String name(String table)
{
return (table + "_preview_layout");
}
/*******************************************************************************
** The choices an accepted form left in the state of the person's own run,
** for the widget of the result step. QQQ answers only the person who started
** the run, in the session that started it, and only while they may still run
** the action; a run that is unknown, has expired or holds no choices is one
** refusal. The choices are authorised again by the preview service.
*******************************************************************************/
static DocumentPreviewService.Options choices(String processUUID) throws QException
{
Optional<ProcessState> state = processUUID != null && processUUID.matches(RUN) ? RunProcessAction.getStateForUser(processUUID, null) : Optional.empty();
if(state.isEmpty() || !(state.get().getValues().get(CHOICES) instanceof Map<?, ?> chosen))
{
throw new QBadRequestException("This preview is no longer available. Run Preview layout again.");
}
return (options(name -> chosen.get(name) == null ? null : String.valueOf(chosen.get(name))));
}
/*******************************************************************************
** The choices of the form, as the form submits them or as the state of the
** run holds them. Anything that is not a choice the form offers is refused.
*******************************************************************************/
static DocumentPreviewService.Options options(UnaryOperator<String> value) throws QBadRequestException
{
try
{
return (new DocumentPreviewService.Options(integer(value.apply("previewTemplateId")), integer(value.apply("previewRevisionId")), GenerationPorts.Format.ZPL,
DocumentPreviewService.Data.valueOf(value.apply("dataSource")), text(value.apply("sampleName")), text(value.apply("sourceRecordId")),
integer(value.apply("stockId")), integer(value.apply("targetDpi"))));
}
catch(RuntimeException invalid)
{
throw new QBadRequestException("Choose the data, the stock and the resolution of the preview from the form.");
}
}
/*******************************************************************************
** An absent or blank value is no choice.
*******************************************************************************/
private static String text(String value)
{
return (value == null || value.isBlank() ? null : value);
}
/*******************************************************************************
** A whole number, or no choice.
*******************************************************************************/
private static Integer integer(String value)
{
return (text(value) == null ? null : Integer.valueOf(value.trim()));
}
/*******************************************************************************
** Who may open the action: an author on a template, a viewer on a revision.
** A record preview also needs `generate`, which the service checks when a
** record is chosen.
*******************************************************************************/
public static class Permission implements CustomPermissionChecker
{
/*******************************************************************************
** Discovery and direct execution both apply the rule.
*******************************************************************************/
@Override
public void checkPermissionsThrowing(AbstractActionInput input, MetaDataWithPermissionRules metadata) throws QPermissionDeniedException
{
GenerationSecurity.require(name(GenerationTables.TEMPLATE).equals(metadata.getName()) ? "configure" : "view");
}
}
/*******************************************************************************
** Before the form: which template or revision, its source table, and the
** samples its scene declares.
*******************************************************************************/
public static class Prepare implements BackendStep
{
/*******************************************************************************
** Only the selected record's identity is used; everything else is read
** again under the person's authority.
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new Permission().checkPermissionsThrowing(input, input.getProcess());
if(input.getRecords() == null || input.getRecords().size() != 1)
{
throw new QBadRequestException("Select one template or one published revision.");
}
Integer id = input.getRecords().getFirst().getValueInteger("id");
boolean draft = name(GenerationTables.TEMPLATE).equals(input.getProcess().getName());
QInstance instance = QContext.getQInstance();
DocumentPreviewService.Choices choices = new DocumentPreviewService(GenerationProcesses.config(instance)).choices(draft ? id : null, draft ? null : id);
output.addValue(draft ? "previewTemplateId" : "previewRevisionId", id);
output.addValue("sourceTable", choices.sourceTable());
output.addValue("dataSource", DocumentPreviewService.Data.SAMPLE.name());
ProcessMetaDataAdjustment adjustment = new ProcessMetaDataAdjustment();
if(!choices.sampleNames().isEmpty())
{
List<QPossibleValue<?>> names = new ArrayList<>();
choices.sampleNames().forEach(name -> names.add(new QPossibleValue<>(name, name)));
QFieldMetaData sample = field(input, "sampleName");
sample.setInlinePossibleValueSource(new QPossibleValueSource().withName("document_generation_preview_samples").withType(QPossibleValueSourceType.ENUM)
.withIdType(QFieldType.STRING).withEnumValues(names));
adjustment.withUpdatedField(sample);
}
var source = instance.getTable(choices.sourceTable());
var selector = instance.getPossibleValueSource(GenerationAuthoringProcesses.sourceRecordChoices(choices.sourceTable()));
if(source != null && selector != null)
{
QFieldMetaData record = field(input, "sourceRecordId");
record.setType(source.getField(source.getPrimaryKeyField()).getType());
record.setLabel("Record (only for a record preview): " + Objects.requireNonNullElse(source.getLabel(), source.getName()));
record.setPossibleValueSourceName(selector.getName());
adjustment.withUpdatedField(record);
}
output.setProcessMetaDataAdjustment(adjustment);
}
/*******************************************************************************
** A copy of one form field, to adjust for this run only.
*******************************************************************************/
private static QFieldMetaData field(RunBackendStepInput input, String name)
{
return (input.getProcess().getFrontendStep("options").getFormFields().stream().filter(candidate -> name.equals(candidate.getName())).findFirst().orElseThrow().clone());
}
}
/*******************************************************************************
** After the form: refuse at once what the preview would refuse, so the
** person sees the reason on the form. Nothing is drawn, and nothing is kept
** but the choices.
*******************************************************************************/
public static class Check implements BackendStep
{
/*******************************************************************************
** The same checks the widget's request makes again when it draws. The
** accepted choices then leave the plain process values, which a client
** sends with the widget request, for the one structured value the widget
** reads from the state of the run.
*******************************************************************************/
@Override
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
{
new Permission().checkPermissionsThrowing(input, input.getProcess());
new DocumentPreviewService(GenerationProcesses.config(QContext.getQInstance())).check(options(input::getValueString));
LinkedHashMap<String, String> chosen = new LinkedHashMap<>();
for(String name : Stream.concat(Stream.of("previewTemplateId", "previewRevisionId"), FORM.stream()).toList())
{
String value = input.getValueString(name);
if(value != null)
{
chosen.put(name, value);
}
}
FORM.forEach(output.getValues()::remove);
output.addValue(CHOICES, chosen);
}
} }
} }
@@ -63,7 +63,11 @@ public class GenerationPreviewSources implements QCustomPossibleValueProvider<Se
@Override @Override
public List<QPossibleValue<Serializable>> search(SearchPossibleValueSourceInput input) throws QException public List<QPossibleValue<Serializable>> search(SearchPossibleValueSourceInput input) throws QException
{ {
GenerationSecurity.require("configure"); /////////////////////////////////////////////////////////////////////////////////////////////
// a record is chosen to generate from or to preview with, which both need `generate`; an //
// author previews a draft and a viewer previews a published revision, so `configure` is //
// not required of someone who may only generate. Every record is still read as the caller //
/////////////////////////////////////////////////////////////////////////////////////////////
GenerationSecurity.require("generate"); GenerationSecurity.require("generate");
var instance = QContext.getQInstance(); var instance = QContext.getQInstance();
var source = instance.getPossibleValueSource(input.getPossibleValueSourceName()); var source = instance.getPossibleValueSource(input.getPossibleValueSourceName());
@@ -21,14 +21,124 @@
package com.kingsrook.qbits.documentgeneration; package com.kingsrook.qbits.documentgeneration;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;
import com.kingsrook.qqq.backend.core.actions.dashboard.widgets.AbstractWidgetRenderer;
import com.kingsrook.qqq.backend.core.actions.permissions.CustomPermissionChecker;
import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.exceptions.QBadRequestException;
import com.kingsrook.qqq.backend.core.exceptions.QException;
import com.kingsrook.qqq.backend.core.exceptions.QNotFoundException;
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetInput;
import com.kingsrook.qqq.backend.core.model.actions.widgets.RenderWidgetOutput;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.CompositeWidgetData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.WidgetType;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.blocks.image.ImageBlockData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.blocks.image.ImageStyles;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.blocks.image.ImageValues;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.blocks.text.TextBlockData;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.blocks.text.TextStyles;
import com.kingsrook.qqq.backend.core.model.dashboard.widgets.blocks.text.TextValues;
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
import com.kingsrook.qqq.backend.core.model.metadata.dashboard.QWidgetMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.layout.QIcon;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.MetaDataWithPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QFieldSection;
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData; import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
import com.kingsrook.qqq.backend.core.model.metadata.tables.Tier;
/******************************************************************************* /*******************************************************************************
** The "Label preview" section of the template record screen. The template ** The label preview as a standard composite widget: a line that says whether
** table already offers itself here after its own sections; nothing is added yet. ** the picture is what prints, the picture itself (the page's PNG as a data
** URL, at the label's physical size), the facts, and one line per diagnostic.
**
** It appears in two places with no host code. On the template record screen
** it is the "Label preview" section, drawn with sample data only, so opening
** a template never renders record data. In the "Preview layout" action it is
** the result step, drawn from the choices the person made. Either way the
** client fetches the widget, the picture is drawn for that request and
** returned in its answer, and nothing of it is kept on the server: not in a
** table, not in a file and not in the process's state.
**
** The request names a template record (the record screen) or a run of the
** action (the result step) and nothing else is read from it: no revision,
** record, sample, stock or resolution is taken from a request parameter. QQQ's
** widget route logs the parameters of a request that fails or takes over a
** second, so what a request carries is what that log can hold: the widget's
** name with a table name and a template identity, or with the identifier of a
** run and the plain process values a client adds to it. After the form those
** are the template or revision identity, the source table's name and whatever
** the client itself sent to start the run (its selection of the template or
** revision row); no choice of the form is among them.
**
** A widget renderer cannot set response headers and the widget route sets no
** `Cache-Control`, so the host or its proxy must send `no-store` for widget
** responses (see the README).
*******************************************************************************/ *******************************************************************************/
final class GenerationPreviewWidget final class GenerationPreviewWidget
{ {
static final String NAME = "document_generation_preview";
static final String SECTION = "labelPreview";
static final int MAXIMUM_IMAGE_BYTES = 2 * 1024 * 1024;
static final int MAXIMUM_LINES = 50;
////////////////////////////////////////////////////////////////////////////////////////////////
// the closed set of verdicts for a label whose picture is not drawn although nothing says it //
// cannot print: a preview paints at most sixteen times the page and draws at most sixteen //
// million dots, and neither limit is a limit of printing //
////////////////////////////////////////////////////////////////////////////////////////////////
static final String TOO_DENSE = "This label is too dense to preview; printing is not affected.";
static final String TOO_LARGE = "This label is too large to preview; printing is not affected.";
////////////////////////////////////////////////////////////////////////////////////////////////
// one plain sentence for each code of the closed vocabulary that a preview can report; a //
// code without one is shown by its name, element and numbers alone //
////////////////////////////////////////////////////////////////////////////////////////////////
private static final Map<String, String> MEANINGS = Map.ofEntries(
Map.entry("SCENE_INVALID", "The scene is not valid at the place named."),
Map.entry("STOCK_MISMATCH", "The scene was drawn for another stock size."),
Map.entry("TARGET_REQUIRES_SCENE_2", "Only a version 2 scene can be drawn at a resolution other than its stock's."),
Map.entry("ELEMENT_OUTSIDE_PRINTABLE_AREA", "The element reaches outside the printable area."),
Map.entry("TEXT_DOES_NOT_FIT", "The text does not fit its box."),
Map.entry("VALUE_MISSING", "The data has no value for this element."),
Map.entry("VALUE_TOO_LONG", "The value is longer than the maximum length the element declares."),
Map.entry("FONT_UNKNOWN", "The font is not available."),
Map.entry("FONT_MISSING_GLYPH", "The font has no shape for a character of the value."),
Map.entry("RESERVED_FONT_NAME", "An included font uses a name reserved for the bundled fonts."),
Map.entry("BARCODE_DOES_NOT_FIT", "The barcode does not fit its box at the smallest module allowed."),
Map.entry("GS1_INVALID", "The GS1 data is not valid."),
Map.entry("ASSET_UNKNOWN", "The scene names an asset the template does not include."),
Map.entry("PREVIEW_TOO_LARGE", "The picture would be too large to draw."),
Map.entry("RENDERER_TOO_OLD", "The renderer in use cannot draw this yet."),
Map.entry("VALUE_NOT_ENCODABLE", "The value cannot be drawn as this barcode."),
Map.entry("QUIET_ZONE_INTRUDED", "A later element is drawn over the barcode or its quiet zone."),
Map.entry("TEXT_TRUNCATED", "The text was cut short."),
Map.entry("TEXT_SMALL_FOR_DPI", "The text is small for this resolution."),
Map.entry("TEXT_LIGHT_FACE", "A light face may print faintly at this size."),
Map.entry("FIT_NOT_PROVEN", "No maximum length is declared, so the fit is not proven for every value."),
Map.entry("BARCODE_MODULE_BELOW_RECOMMENDED", "The barcode's narrow bar is below the recommended width."),
Map.entry("BARCODE_HEIGHT_BELOW_RECOMMENDED", "The barcode's bars are shorter than recommended."),
Map.entry("ELEMENTS_OVERLAP", "Elements overlap."),
Map.entry("IMAGE_UPSCALED", "The image was enlarged and may look coarse."),
Map.entry("DEVICE_UNIT_USED", "A device unit (dots) is used, so the layout depends on the resolution."),
Map.entry("PRINTER_FONT_NOT_SHOWN", "Printer font text cannot be drawn; its estimated area is outlined and crossed."),
Map.entry("TEXT_SHRUNK", "The text was reduced to fit."),
Map.entry("TEXT_WRAPPED", "The text was wrapped."),
Map.entry("BARCODE_MODULE", "The width of the barcode's narrow bar."),
Map.entry("IMAGE_SCALED", "The image was scaled."));
/******************************************************************************* /*******************************************************************************
** Metadata namespace. ** Metadata namespace.
*******************************************************************************/ *******************************************************************************/
@@ -37,9 +147,300 @@ final class GenerationPreviewWidget
} }
/******************************************************************************* /*******************************************************************************
** Called once for the template table, after its standard sections. ** Called once for the template table, after its standard sections: the
** preview goes directly below the overview.
*******************************************************************************/ *******************************************************************************/
static void section(QTableMetaData table) static void section(QTableMetaData table)
{ {
List<QFieldSection> sections = new ArrayList<>(table.getSections() == null ? List.of() : table.getSections());
sections.add(Math.min(1, sections.size()), new QFieldSection(SECTION, new QIcon("image"), Tier.T2).withLabel("Label preview").withWidgetName(NAME)
.withHelpContent(GenerationTables.help("The label as it would print, drawn from the current draft with the first sample the scene declares, at the stock's own resolution. "
+ "It is drawn each time the record opens and nothing is saved. Use Preview layout to choose other data, another stock or another resolution.")));
table.setSections(sections);
}
/*******************************************************************************
** The widget a host gets by registering the QBit. Its renderer decides what
** each person may see, so the rule here is only that the person holds one of
** the existing permissions a preview can be drawn under.
*******************************************************************************/
static QWidgetMetaData metaData()
{
return (new QWidgetMetaData().withName(NAME).withType(WidgetType.COMPOSITE.getType()).withLabel("Label preview").withIsCard(true).withGridColumns(12)
.withShowReloadButton(true).withCodeReference(new QCodeReference(Renderer.class))
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.NOT_PROTECTED).withCustomPermissionChecker(new QCodeReference(Permission.class)))
.withHelpContent("label", GenerationTables.help("The picture is decoded from the exact bytes that would be sent to the printer, one pixel per printer dot. "
+ "Refusals mean the label cannot print as it stands; warnings do not stop printing. Reload after editing the layout.")));
}
/*******************************************************************************
** A person with none of the document permissions never reaches the renderer.
*******************************************************************************/
public static class Permission implements CustomPermissionChecker
{
/*******************************************************************************
** Discovery and direct execution both apply the rule.
*******************************************************************************/
@Override
public void checkPermissionsThrowing(AbstractActionInput input, MetaDataWithPermissionRules metadata) throws QPermissionDeniedException
{
var session = QContext.getQSession();
if(session == null || Stream.of("view", "configure", "generate").noneMatch(suffix -> session.hasPermission("document-generation." + suffix)))
{
throw new QPermissionDeniedException("Document Generation permission denied.");
}
}
}
/*******************************************************************************
** The standard widget route: the request names a template record or a run of
** the action, and what it leads to is authorised again by the preview service.
*******************************************************************************/
public static class Renderer extends AbstractWidgetRenderer
{
/*******************************************************************************
** Draw for this request only; the answer is not stored.
*******************************************************************************/
@Override
public RenderWidgetOutput render(RenderWidgetInput input) throws QException
{
return (new RenderWidgetOutput(widget(GenerationProcesses.config(QContext.getQInstance()), input.getQueryParams() == null ? Map.of() : input.getQueryParams())));
}
}
/*******************************************************************************
** The whole widget for one request. A refusal this module states in its own
** words (no source to draw, an unreadable record, an unknown sample) is one
** line; a failure of the renderer is a fixed sentence, never its message; a
** label too dense to draw is said to be so, and to print all the same; a
** missing permission stays a denial.
*******************************************************************************/
static CompositeWidgetData widget(DocumentGenerationQBitConfig config, Map<String, String> parameters) throws QException
{
CompositeWidgetData data = new CompositeWidgetData().withLayout(CompositeWidgetData.Layout.FLEX_COLUMN);
try
{
DocumentPreviewService service = new DocumentPreviewService(config);
DocumentPreviewService.Options options = options(service, parameters);
blocks(data, options, service.preview(options));
}
catch(QPermissionDeniedException denied)
{
throw (denied);
}
catch(QBadRequestException | QNotFoundException refused)
{
data.addBlock(line(refused.getMessage(), TextStyles.StandardColor.WARNING, true));
}
catch(GenerationPorts.RenderException named)
{
boolean dense = named.code() == GenerationPorts.FailureCode.PREVIEW_TOO_LARGE;
data.addBlock(line(dense ? TOO_DENSE : "The preview could not be drawn (" + named.code() + ").", dense ? TextStyles.StandardColor.WARNING : TextStyles.StandardColor.ERROR, true));
}
catch(QException failure)
{
data.addBlock(line("The preview could not be drawn. A label that takes its values from a record needs sample data in its scene, or use Preview layout with a record.",
TextStyles.StandardColor.ERROR, true));
}
return (data);
}
/*******************************************************************************
** On a record screen the client sends the table and the record: the draft
** for a person who may author it, the published revision for a person who
** may only view it, always with sample data. In the action the client sends
** the identifier of the run, and the choices of the form are read from the
** state of that run; whatever else the request carries is not read.
*******************************************************************************/
private static DocumentPreviewService.Options options(DocumentPreviewService service, Map<String, String> parameters) throws QException
{
if(parameters.containsKey("processUUID"))
{
return (GenerationPreviewProcesses.choices(parameters.get("processUUID")));
}
if(!GenerationTables.TEMPLATE.equals(parameters.get("tableName")))
{
throw new QBadRequestException("The label preview belongs to a document template.");
}
DocumentPreviewService.Options screen = GenerationPreviewProcesses.options(name -> switch(name)
{
case "previewTemplateId" -> parameters.get("id");
case "dataSource" -> "SAMPLE";
default -> null;
});
if(QContext.getQSession().hasPermission("document-generation.configure"))
{
return (screen);
}
Integer published = service.publishedRevision(screen.templateId());
if(published == null)
{
throw new QBadRequestException("This template has no published revision to preview.");
}
return (new DocumentPreviewService.Options(null, published, screen.format(), screen.data(), null, null, null, null));
}
/*******************************************************************************
** The verdict, what was drawn, the picture, the facts and the diagnostics.
*******************************************************************************/
private static void blocks(CompositeWidgetData data, DocumentPreviewService.Options options, DocumentPreviewService.Result result)
{
GenerationPorts.Preview preview = result.preview();
boolean page = !preview.pages().isEmpty();
List<GenerationPorts.Diagnostic> refusals = preview.diagnostics().stream().filter(diagnostic -> diagnostic.severity() == GenerationPorts.Diagnostic.Severity.ERROR).toList();
if(!page && !refusals.isEmpty() && refusals.stream().allMatch(refusal -> GenerationPorts.FailureCode.PREVIEW_TOO_LARGE.name().equals(refusal.code())))
{
/////////////////////////////////////////////////////////////////////////////////////
// the only thing refused is the picture: the label was not found unprintable, it //
// would paint or measure more than a preview draws //
/////////////////////////////////////////////////////////////////////////////////////
data.addBlock(line(refusals.getFirst().limit().containsKey("paintedPercent") ? TOO_DENSE : TOO_LARGE, TextStyles.StandardColor.WARNING, true));
}
else if(!preview.printable())
{
data.addBlock(line("This layout cannot print. " + (page ? "The picture shows only where the refused elements are." : "There is nothing to draw."),
TextStyles.StandardColor.ERROR, true));
}
else if(preview.exact())
{
data.addBlock(line("This is the picture that would print.", TextStyles.StandardColor.SUCCESS, true));
}
else
{
data.addBlock(line("This picture is not exact: what the printer draws itself is shown as an outlined, crossed area.", TextStyles.StandardColor.WARNING, true));
}
String values = options.data() == DocumentPreviewService.Data.SAMPLE ? "sample data" : options.data() == DocumentPreviewService.Data.LONGEST ? "longest values" : "one record";
data.addBlock(line((options.revisionId() == null ? "Current draft" : "Published revision " + options.revisionId()) + ", " + values + ", " + result.dpi() + " dpi.", null, false));
if(page)
{
GenerationPorts.PreviewPage first = preview.pages().getFirst();
byte[] png = first.png();
if(png.length <= MAXIMUM_IMAGE_BYTES)
{
data.addBlock(new ImageBlockData().withValues(new ImageValues().withPath("data:image/png;base64," + Base64.getEncoder().encodeToString(png))
.withAlt("Label preview, " + first.widthDots() + " by " + first.heightDots() + " dots"))
.withStyles(new ImageStyles().withWidth("min(100%, " + millimetres(first.widthDots(), result.dpi()) + "mm)")));
}
else
{
data.addBlock(line("The picture is " + png.length + " bytes, which is too large to show here.", TextStyles.StandardColor.WARNING, false));
}
data.addBlock(line("Size: " + first.widthDots() + " x " + first.heightDots() + " dots at " + result.dpi() + " dpi (" + millimetres(first.widthDots(), result.dpi()) + " x "
+ millimetres(first.heightDots(), result.dpi()) + " mm). Output: " + preview.outputBytes() + " bytes, SHA-256 " + preview.outputSha256() + ".", null, false));
}
List<GenerationPorts.Diagnostic> ordered = preview.diagnostics().stream().sorted(Comparator.comparing(GenerationPorts.Diagnostic::severity)).toList();
ordered.stream().limit(MAXIMUM_LINES).forEach(diagnostic -> data.addBlock(line(sentence(diagnostic, result.dpi()),
TextStyles.StandardColor.valueOf(diagnostic.severity().name()), false)));
if(ordered.size() > MAXIMUM_LINES)
{
data.addBlock(line("And " + (ordered.size() - MAXIMUM_LINES) + " more.", null, false));
}
if(ordered.isEmpty())
{
data.addBlock(line("No refusals and no warnings.", null, false));
}
}
/*******************************************************************************
** One diagnostic as a sentence: a refusal, a warning or a note, its code, the
** element the author named, what it means, and the measured values against
** the limits in dots and in physical units. A diagnostic holds identifiers
** and integers only, so no record value can appear here.
*******************************************************************************/
static String sentence(GenerationPorts.Diagnostic diagnostic, int dpi)
{
GenerationPorts.Diagnostic.Severity severity = diagnostic.severity();
StringBuilder text = new StringBuilder(severity == GenerationPorts.Diagnostic.Severity.ERROR ? "Refusal" : severity == GenerationPorts.Diagnostic.Severity.WARNING ? "Warning" : "Note")
.append(": ").append(diagnostic.code());
if(diagnostic.element() != null)
{
text.append(", element '").append(diagnostic.element()).append('\'');
}
if(diagnostic.pointer() != null)
{
text.append(", at ").append(diagnostic.pointer().isEmpty() ? "the scene" : diagnostic.pointer());
}
text.append('.');
if(MEANINGS.containsKey(diagnostic.code()))
{
text.append(' ').append(MEANINGS.get(diagnostic.code()));
}
if(!diagnostic.measured().isEmpty())
{
text.append(" Measured ").append(numbers(diagnostic.measured(), dpi)).append(diagnostic.limit().isEmpty() ? "." : " against a limit of " + numbers(diagnostic.limit(), dpi) + ".");
}
else if(!diagnostic.limit().isEmpty())
{
text.append(" Limit ").append(numbers(diagnostic.limit(), dpi)).append('.');
}
return (text.toString());
}
/*******************************************************************************
** Named integers in a fixed order, each with its unit.
*******************************************************************************/
private static String numbers(Map<String, Integer> values, int dpi)
{
return (String.join(", ", new TreeMap<>(values).entrySet().stream().map(entry -> number(entry.getKey(), entry.getValue(), dpi)).toList()));
}
/*******************************************************************************
** A value by the unit its name ends with: dots also in millimetres at the
** resolution drawn, hundredths of a point as points, micrometres as
** millimetres, a percentage as such, and anything else as the bare number.
*******************************************************************************/
private static String number(String name, int value, int dpi)
{
if(name.endsWith("Dots"))
{
return (words(name, 4) + " " + value + " dots (" + millimetres(value, dpi) + " mm)");
}
if(name.endsWith("Centipoints"))
{
return (words(name, 11) + " " + BigDecimal.valueOf(value, 2).stripTrailingZeros().toPlainString() + " pt");
}
if(name.endsWith("Micrometres"))
{
return (words(name, 11) + " " + BigDecimal.valueOf(value, 3).stripTrailingZeros().toPlainString() + " mm");
}
if(name.endsWith("Percent"))
{
return (words(name, 7) + " " + value + "%");
}
return (words(name, 0) + " " + value);
}
/*******************************************************************************
** A value's name without its unit, as lower-case words.
*******************************************************************************/
private static String words(String name, int unit)
{
return (name.substring(0, name.length() - unit).replaceAll("([a-z0-9])([A-Z])", "$1 $2").toLowerCase(Locale.ROOT));
}
/*******************************************************************************
** Dots as millimetres at a resolution, to a tenth.
*******************************************************************************/
private static String millimetres(int dots, int dpi)
{
return (BigDecimal.valueOf(dots * 254L).divide(BigDecimal.valueOf(dpi * 10L), 1, RoundingMode.HALF_UP).toPlainString());
}
/*******************************************************************************
** One line of text, coloured by what it reports and boxed when it is the
** verdict.
*******************************************************************************/
private static TextBlockData line(String text, TextStyles.StandardColor color, boolean verdict)
{
TextStyles styles = new TextStyles();
if(color != null)
{
styles.withColor(color);
}
if(verdict)
{
styles.withFormat(TextStyles.StandardFormat.ALERT).withWeight(TextStyles.StandardWeight.BOLD);
}
return (new TextBlockData().withValues(new TextValues(text)).withStyles(styles));
} }
} }
@@ -173,10 +173,12 @@ public final class GenerationTables
table.getField("id").setLabel("Template ID"); table.getField("id").setLabel("Template ID");
table.withSection(new QFieldSection("overview", new QIcon("description"), Tier.T1, table.withSection(new QFieldSection("overview", new QIcon("description"), Tier.T1,
List.of("name", "typeId", "stockId", "tableName", "publishedRevisionId")).withLabel("Overview") List.of("name", "typeId", "stockId", "tableName", "publishedRevisionId")).withLabel("Overview")
.withHelpContent(help("Choose Preview draft from this record's actions, select a source record and PDF or ZPL, then open Preview or Download on the result. Preview uses the current draft and does not publish it."))); .withHelpContent(help("Choose Preview layout from this record's actions to see the label that would print, with sample data, its longest values or a record; nothing is saved. "
+ "Generate retained preview file creates an audited file (PDF or ZPL) from a source record and the current draft, to open or download; it does not publish the draft.")));
table.withSection(new QFieldSection("layout", new QIcon("code"), Tier.T2, List.of("pdfSource", "zplSource")).withLabel("Layout") table.withSection(new QFieldSection("layout", new QIcon("code"), Tier.T2, List.of("pdfSource", "zplSource")).withLabel("Layout")
.withCollapsible(CollapsibleMetaData.INITIALLY_CLOSED) .withCollapsible(CollapsibleMetaData.INITIALLY_CLOSED)
.withHelpContent(help("Use Edit layout to change PDF HTML or the ZPL scene. Preview draft checks the result against a source record; Validate and publish draft makes an immutable revision available for generation."))); .withHelpContent(help("Use Edit layout to change PDF HTML or the ZPL scene. Preview layout shows the label and its warnings before anything is printed; "
+ "Validate and publish draft makes an immutable revision available for generation.")));
table.withSection(new QFieldSection("context", new QIcon("data_object"), Tier.T2, List.of("outputBaseName", "outputNameContextKey")).withLabel("Context & output") table.withSection(new QFieldSection("context", new QIcon("data_object"), Tier.T2, List.of("outputBaseName", "outputNameContextKey")).withLabel("Context & output")
.withHelpContent(help("Choose Select context script to select a published, context-tested script or explicitly clear it. Without a script, templates use the authorized source record under record. Use Edit output filename to configure naming."))); .withHelpContent(help("Choose Select context script to select a published, context-tested script or explicitly clear it. Without a script, templates use the authorized source record under record. Use Edit output filename to configure naming.")));
table.withSection(new QFieldSection("advanced", new QIcon("settings"), Tier.T3, List.of("id", "createDate", "scriptArtifact", "assetIds")).withLabel("Advanced references") table.withSection(new QFieldSection("advanced", new QIcon("settings"), Tier.T3, List.of("id", "createDate", "scriptArtifact", "assetIds")).withLabel("Advanced references")
@@ -144,7 +144,8 @@ class GenerationPortsContractTest
"INVALID_BARCODE_FIT_REQUEST", "BARCODE_SYMBOLOGY_NOT_ALLOWED", "SYMBOLOGY_ALLOWLIST_REQUIRED", "SCANNER_BARCODE_PROFILE_UNSUPPORTED", "SCANNER_BARCODE_PAYLOAD_UNSUPPORTED", "INVALID_BARCODE_FIT_REQUEST", "BARCODE_SYMBOLOGY_NOT_ALLOWED", "SYMBOLOGY_ALLOWLIST_REQUIRED", "SCANNER_BARCODE_PROFILE_UNSUPPORTED", "SCANNER_BARCODE_PAYLOAD_UNSUPPORTED",
"SCANNER_BARCODE_CHECKSUM_REQUIRED", "SCANNER_BARCODE_CHECKSUM_MISMATCH", "UNSUPPORTED_BARCODE_OPTION"), names.subList(0, 13)); "SCANNER_BARCODE_CHECKSUM_REQUIRED", "SCANNER_BARCODE_CHECKSUM_MISMATCH", "UNSUPPORTED_BARCODE_OPTION"), names.subList(0, 13));
assertEquals(List.of("SCENE_INVALID", "STOCK_MISMATCH", "TARGET_REQUIRES_SCENE_2", "ELEMENT_OUTSIDE_PRINTABLE_AREA", "TEXT_DOES_NOT_FIT", "VALUE_MISSING", "VALUE_TOO_LONG", assertEquals(List.of("SCENE_INVALID", "STOCK_MISMATCH", "TARGET_REQUIRES_SCENE_2", "ELEMENT_OUTSIDE_PRINTABLE_AREA", "TEXT_DOES_NOT_FIT", "VALUE_MISSING", "VALUE_TOO_LONG",
"FONT_UNKNOWN", "FONT_MISSING_GLYPH", "RESERVED_FONT_NAME", "BARCODE_DOES_NOT_FIT", "GS1_INVALID", "ASSET_UNKNOWN", "PREVIEW_TOO_LARGE", "RENDERER_TOO_OLD"), names.subList(13, names.size())); "FONT_UNKNOWN", "FONT_MISSING_GLYPH", "RESERVED_FONT_NAME", "BARCODE_DOES_NOT_FIT", "GS1_INVALID", "ASSET_UNKNOWN", "PREVIEW_TOO_LARGE", "RENDERER_TOO_OLD",
"VALUE_NOT_ENCODABLE", "QUIET_ZONE_INTRUDED"), names.subList(13, names.size()));
} }
/*************************************************************************** /***************************************************************************
@@ -258,7 +259,7 @@ class GenerationPortsContractTest
assertThrows(IllegalArgumentException.class, () -> new Diagnostic(code.name(), Severity.WARNING, null, null, null, null)); assertThrows(IllegalArgumentException.class, () -> new Diagnostic(code.name(), Severity.WARNING, null, null, null, null));
assertThrows(IllegalArgumentException.class, () -> new Diagnostic(code.name(), Severity.INFO, null, null, null, null)); assertThrows(IllegalArgumentException.class, () -> new Diagnostic(code.name(), Severity.INFO, null, null, null, null));
} }
for(String code : List.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", "BARCODE_MODULE_BELOW_RECOMMENDED", "QUIET_ZONE_INTRUDED", "ELEMENTS_OVERLAP", for(String code : List.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", "BARCODE_MODULE_BELOW_RECOMMENDED", "BARCODE_HEIGHT_BELOW_RECOMMENDED", "ELEMENTS_OVERLAP",
"IMAGE_UPSCALED", "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN")) "IMAGE_UPSCALED", "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN"))
{ {
assertEquals(Severity.WARNING, new Diagnostic(code, Severity.WARNING, null, null, null, null).severity()); assertEquals(Severity.WARNING, new Diagnostic(code, Severity.WARNING, null, null, null, null).severity());
@@ -76,19 +76,21 @@ class GenerationProcessesTest
void templateRecordSeparatesAuthoringFromAdvancedIdentities() void templateRecordSeparatesAuthoringFromAdvancedIdentities()
{ {
var table = instance.getTable(GenerationTables.TEMPLATE); var table = instance.getTable(GenerationTables.TEMPLATE);
assertThat(table.getSections()).extracting(section -> section.getName()).containsExactly("overview", "layout", "context", "advanced"); assertThat(table.getSections()).extracting(section -> section.getName()).containsExactly("overview", "labelPreview", "layout", "context", "advanced");
assertThat(table.getSections().get(1).getWidgetName()).isEqualTo(GenerationPreviewWidget.NAME);
assertThat(table.getSections().get(1).getFieldNames()).isNullOrEmpty();
assertThat(table.getSections().getFirst().getFieldNames()).contains("typeId", "stockId", "publishedRevisionId") assertThat(table.getSections().getFirst().getFieldNames()).contains("typeId", "stockId", "publishedRevisionId")
.doesNotContain("pdfSource", "zplSource", "scriptArtifact", "assetIds"); .doesNotContain("pdfSource", "zplSource", "scriptArtifact", "assetIds");
assertThat(table.getSections().get(1).getCollapsible().getInitiallyOpen()).isFalse(); assertThat(table.getSections().get(2).getCollapsible().getInitiallyOpen()).isFalse();
assertThat(table.getSections().get(3).getCollapsible().getInitiallyOpen()).isFalse(); assertThat(table.getSections().get(4).getCollapsible().getInitiallyOpen()).isFalse();
assertThat(table.getSections().stream().flatMap(section -> section.getFieldNames().stream()).toList()) assertThat(table.getSections().stream().filter(section -> section.getWidgetName() == null).flatMap(section -> section.getFieldNames().stream()).toList())
.containsExactlyInAnyOrderElementsOf(table.getFields().keySet()); .containsExactlyInAnyOrderElementsOf(table.getFields().keySet());
assertThat(table.getField("typeId").getPossibleValueSourceName()).isEqualTo(GenerationTables.TYPE); assertThat(table.getField("typeId").getPossibleValueSourceName()).isEqualTo(GenerationTables.TYPE);
assertThat(table.getField("stockId").getPossibleValueSourceName()).isEqualTo(GenerationTables.STOCK); assertThat(table.getField("stockId").getPossibleValueSourceName()).isEqualTo(GenerationTables.STOCK);
assertThat(table.getField("publishedRevisionId").getPossibleValueSourceName()).isEqualTo(GenerationTables.REVISION); assertThat(table.getField("publishedRevisionId").getPossibleValueSourceName()).isEqualTo(GenerationTables.REVISION);
assertThat(table.getField("scriptArtifact").getPossibleValueSourceName()).isNull(); assertThat(table.getField("scriptArtifact").getPossibleValueSourceName()).isNull();
var process = instance.getProcess(GenerationAuthoringProcesses.name(GenerationTables.TEMPLATE, "preview")); var process = instance.getProcess(GenerationAuthoringProcesses.name(GenerationTables.TEMPLATE, "preview"));
assertThat(process.getLabel()).isEqualTo("Preview draft"); assertThat(process.getLabel()).isEqualTo("Generate retained preview file");
assertThat(process.getFrontendStep("result").getLabel()).contains("open or download"); assertThat(process.getFrontendStep("result").getLabel()).contains("open or download");
assertThat(process.getFrontendStep("result").getViewFields()).anyMatch(field -> "downloadUrl".equals(field.getName())); assertThat(process.getFrontendStep("result").getViewFields()).anyMatch(field -> "downloadUrl".equals(field.getName()));
} }
@@ -34,16 +34,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
/******************************************************************************* /*******************************************************************************
** The registration points for the preview, asset and upgrade packages exist and ** The registration points for the preview, asset and upgrade packages exist and
** are called, and add nothing: a host that registers the QBit gets exactly the ** are called. The preview package has filled its own: a host that registers
** tables, processes, choices, widgets and template sections it got before. ** the QBit gets the "Preview layout" action on templates and revisions, its
** two choice lists, the preview widget and the "Label preview" section, and
** otherwise exactly what it got before. The asset and upgrade points still
** add nothing.
*******************************************************************************/ *******************************************************************************/
class GenerationRegistrationHooksTest class GenerationRegistrationHooksTest
{ {
/*************************************************************************** /***************************************************************************
** The complete default wiring, as the released foundation registers it. ** The complete default wiring: what the released foundation registered,
** plus the layout preview.
***************************************************************************/ ***************************************************************************/
@Test @Test
void theProducerRegistersExactlyWhatItDidBeforeTheHooks() throws Exception void theProducerRegistersWhatItDidBeforeTheHooksAndTheLayoutPreview() throws Exception
{ {
QInstance instance = instance(); QInstance instance = instance();
new DocumentGenerationQBitProducer().withQBitConfig(config()).produce(instance); new DocumentGenerationQBitProducer().withQBitConfig(config()).produce(instance);
@@ -54,40 +58,50 @@ class GenerationRegistrationHooksTest
assertEquals(List.of("document_generation_binding_author_create", "document_generation_queue_document_advance", "document_generation_queue_document_cancel", assertEquals(List.of("document_generation_binding_author_create", "document_generation_queue_document_advance", "document_generation_queue_document_cancel",
"document_generation_queue_document_reconcileItem", "document_generation_queue_document_recover", "document_generation_queue_document_status", "document_generation_queue_document_reconcileItem", "document_generation_queue_document_recover", "document_generation_queue_document_status",
"document_generation_request_document_download", "document_generation_request_document_reconcile", "document_generation_request_document_reprint", "document_generation_request_document_download", "document_generation_request_document_reconcile", "document_generation_request_document_reprint",
"document_generation_request_document_status", "document_generation_stock_author_create", "document_generation_stock_author_rename", "document_generation_request_document_status", "document_generation_revision_preview_layout", "document_generation_stock_author_create",
"document_generation_stock_author_rename",
"document_generation_template_author_asset", "document_generation_template_author_catalog", "document_generation_template_author_context", "document_generation_template_author_asset", "document_generation_template_author_catalog", "document_generation_template_author_context",
"document_generation_template_author_create", "document_generation_template_author_edit", "document_generation_template_author_naming", "document_generation_template_author_create", "document_generation_template_author_edit", "document_generation_template_author_naming",
"document_generation_template_author_packingSlip", "document_generation_template_author_preview", "document_generation_template_author_publish", "document_generation_template_author_packingSlip", "document_generation_template_author_preview", "document_generation_template_author_publish",
"document_generation_template_author_removeAsset", "document_generation_template_author_rename", "document_generation_template_author_replaceAsset", "document_generation_template_author_removeAsset", "document_generation_template_author_rename", "document_generation_template_author_replaceAsset",
"document_generation_type_author_create", "document_generation_type_author_rename", "orders_document_enqueue", "orders_document_generate"), "document_generation_template_preview_layout", "document_generation_type_author_create", "document_generation_type_author_rename", "orders_document_enqueue", "orders_document_generate"),
List.copyOf(new TreeSet<>(instance.getProcesses().keySet())), "processes"); List.copyOf(new TreeSet<>(instance.getProcesses().keySet())), "processes");
assertEquals(List.of("document_generation_asset", "document_generation_context_publications", "document_generation_formats", "document_generation_preview_source", assertEquals(List.of("document_generation_asset", "document_generation_context_publications", "document_generation_formats", "document_generation_preview_data",
"document_generation_preview_source_orders", "document_generation_retained_assets", "document_generation_revision", "document_generation_preview_resolution", "document_generation_preview_source", "document_generation_preview_source_orders", "document_generation_retained_assets",
"document_generation_revision",
"document_generation_source_tables", "document_generation_stock", "document_generation_template", "document_generation_type"), "document_generation_source_tables", "document_generation_stock", "document_generation_template", "document_generation_type"),
List.copyOf(new TreeSet<>(instance.getPossibleValueSources().keySet())), "possible value sources"); List.copyOf(new TreeSet<>(instance.getPossibleValueSources().keySet())), "possible value sources");
assertEquals(List.of(), assertEquals(List.of("document_generation_preview"),
List.copyOf(new TreeSet<>(instance.getWidgets().keySet())), "widgets"); List.copyOf(new TreeSet<>(instance.getWidgets().keySet())), "widgets");
assertEquals(List.of("overview", "layout", "context", "advanced"), assertEquals(List.of("overview", "labelPreview", "layout", "context", "advanced"),
instance.getTable(GenerationTables.TEMPLATE).getSections().stream().map(QFieldSection::getName).toList(), "template sections"); instance.getTable(GenerationTables.TEMPLATE).getSections().stream().map(QFieldSection::getName).toList(), "template sections");
} }
/*************************************************************************** /***************************************************************************
** Each registration point, called directly, changes nothing. ** The asset and upgrade points, called directly, change nothing. The
** preview point, called on a host that registered no record selectors,
** still defines the action, without the source table field.
***************************************************************************/ ***************************************************************************/
@Test @Test
void eachRegistrationPointAddsNothingYet() throws Exception void theAssetAndUpgradePointsAddNothingAndThePreviewPointStandsAlone() throws Exception
{ {
DocumentGenerationQBitConfig config = config(); DocumentGenerationQBitConfig config = config();
assertEquals(List.of(), GenerationAssetTables.tables(config)); assertEquals(List.of(), GenerationAssetTables.tables(config));
QInstance instance = instance(); QInstance instance = instance();
GenerationPreviewProcesses.register(instance, config);
GenerationAssetProcesses.register(instance, config); GenerationAssetProcesses.register(instance, config);
GenerationUpgradeProcesses.register(instance, config); GenerationUpgradeProcesses.register(instance, config);
assertEquals(List.of(), List.copyOf(instance.getProcesses().keySet())); assertEquals(List.of(), List.copyOf(instance.getProcesses().keySet()));
assertEquals(List.of("orders"), List.copyOf(instance.getTables().keySet())); assertEquals(List.of("orders"), List.copyOf(instance.getTables().keySet()));
GenerationPreviewProcesses.register(instance, config);
assertEquals(List.of("document_generation_revision_preview_layout", "document_generation_template_preview_layout"), List.copyOf(new TreeSet<>(instance.getProcesses().keySet())));
assertEquals(List.of("dataSource", "sampleName", "sourceRecordId", "stockId", "targetDpi"), instance.getProcess("document_generation_template_preview_layout")
.getFrontendStep("options").getFormFields().stream().map(QFieldMetaData::getName).toList());
assertEquals(List.of("document_generation_preview"), List.copyOf(instance.getWidgets().keySet()));
assertEquals(List.of("orders"), List.copyOf(instance.getTables().keySet()));
QTableMetaData table = new QTableMetaData().withName("template"); QTableMetaData table = new QTableMetaData().withName("template");
GenerationPreviewWidget.section(table); GenerationPreviewWidget.section(table);
assertEquals(new QTableMetaData().withName("template").getSections(), table.getSections()); assertEquals(List.of("labelPreview"), table.getSections().stream().map(QFieldSection::getName).toList());
assertEquals("document_generation_preview", table.getSections().getFirst().getWidgetName());
} }
/*************************************************************************** /***************************************************************************
+2
View File
@@ -4,6 +4,8 @@ Catalog `qqq-barcodes-9`, fit profile `qqq-barcode-fit/1`. This is a new source
## Finite capability ## Finite capability
This profile is what a version 1 scene and the PDF element use. A version 2 ZPL scene (`qqq-zpl-scene/2`) takes its symbols from the same encoders and the same thirteen symbologies but fits them by its own rule, in whole printer dots with a physical minimum module and bars the height of the box: see "ZPL scene 2" in [README.md](README.md).
Fit is supported for the default encoder profiles of `code128`, `code39`, `code93`, `itf`, `gs1-128`, `qr`, `ean13`, `ean8`, `upca`, `upce`, `datamatrix`, `pdf417` and `aztec`. Both PDF and ZPL use actual encoder rasters. The other 58 catalog IDs explicitly advertise `fit.supported=false`. This does not redefine the wider barcode requirement as completed. Fit is supported for the default encoder profiles of `code128`, `code39`, `code93`, `itf`, `gs1-128`, `qr`, `ean13`, `ean8`, `upca`, `upce`, `datamatrix`, `pdf417` and `aztec`. Both PDF and ZPL use actual encoder rasters. The other 58 catalog IDs explicitly advertise `fit.supported=false`. This does not redefine the wider barcode requirement as completed.
Options must be absent or `{}`; binary payloads, structured append, color, ECI and option-dependent geometry are not fit-qualified. Existing explicit non-fit APIs retain their capabilities. Canonical `gs1-128` accepts the existing explicit GS1 syntax; scanner GS1 modes are deliberately not inferred from ordinary text or a family name. Options must be absent or `{}`; binary payloads, structured append, color, ECI and option-dependent geometry are not fit-qualified. Existing explicit non-fit APIs retain their capabilities. Canonical `gs1-128` accepts the existing explicit GS1 syntax; scanner GS1 modes are deliberately not inferred from ordinary text or a family name.
+9
View File
@@ -26,3 +26,12 @@ The encoder and prime-field ECC helper retain the MIT license. See
META-INF/licenses/bwipp-code93i-MIT.txt and Code93i.java. Pinned corresponding META-INF/licenses/bwipp-code93i-MIT.txt and Code93i.java. Pinned corresponding
upstream source, helper, tests and provenance are retained under upstream source, helper, tests and provenance are retained under
src/test/resources/barcodes/code93i. src/test/resources/barcodes/code93i.
Bundled fonts (2026-11-12). This distribution contains, unmodified and as data,
IBM Plex Sans Regular and Bold and IBM Plex Sans Condensed Bold, Copyright (c)
2017 IBM Corp. with Reserved Font Name "Plex", and JetBrains Mono Regular and
Bold, Copyright 2020 The JetBrains Mono Project Authors
(https://github.com/JetBrains/JetBrainsMono). They are licensed under the SIL
Open Font License, Version 1.1, separately from the renderer's Apache license,
which does not replace it. Each font is in /fonts of the renderer JAR beside
the full license text and a provenance note; /fonts/SHA256SUMS lists the hashes.
+25 -1
View File
@@ -124,7 +124,31 @@ A source with schema `qqq-zpl-scene/2` is a layout in physical units that render
- **Coordinates** start at the top left of the printable area, the stock less its margins. In dots the printable area is `floor((width - left - right) x dpi)` wide and `floor((height - top - bottom) x dpi)` high, which is how a box size is rounded, and it starts at `ceil(left x dpi)`, `ceil(top x dpi)`, moved back by one dot where it would otherwise pass the page edge. So a box of exactly the printable width and height fits at 203, 300 and 600 dpi alike. No ink is ever a whole dot inside a margin; the right and bottom edges may pass theirs by a fraction of a dot (less than 0.125 mm at 203 dpi). `design` states the stock the layout was drawn for; the request's stock must match it within 0.5 mm on each side (`STOCK_MISMATCH`). - **Coordinates** start at the top left of the printable area, the stock less its margins. In dots the printable area is `floor((width - left - right) x dpi)` wide and `floor((height - top - bottom) x dpi)` high, which is how a box size is rounded, and it starts at `ceil(left x dpi)`, `ceil(top x dpi)`, moved back by one dot where it would otherwise pass the page edge. So a box of exactly the printable width and height fits at 203, 300 and 600 dpi alike. No ink is ever a whole dot inside a margin; the right and bottom edges may pass theirs by a fraction of a dot (less than 0.125 mm at 203 dpi). `design` states the stock the layout was drawn for; the request's stock must match it within 0.5 mm on each side (`STOCK_MISMATCH`).
- **Every element** has a unique `id` (`[A-Za-z][A-Za-z0-9_-]{0,31}`), a `type`, an `anchor` (one of nine points, default `top-left`: the same point of the box is placed on that point of its container), `x` and `y` (distances inward from the anchored edge; on a centred axis a shift that may be negative), `width` and `height` (omitted: the rest of the container), and `align` and `valign` (where content sits in the box). - **Every element** has a unique `id` (`[A-Za-z][A-Za-z0-9_-]{0,31}`), a `type`, an `anchor` (one of nine points, default `top-left`: the same point of the box is placed on that point of its container), `x` and `y` (distances inward from the anchored edge; on a centred axis a shift that may be negative), `width` and `height` (omitted: the rest of the container), and `align` and `valign` (where content sits in the box).
- **`box`** has `thickness` and optional `fill`; a line is a box whose width or height is its thickness. **`group`** has `children`, placed relative to its box; groups nest four deep. A scene holds at most 1000 elements, and its elements may paint at most sixteen times its printable area in all, an overlap counted each time: a filled box counts its area, an outline its four bars, a group nothing. The element that would pass that is refused as `SCENE_INVALID` at its pointer, with its box and `measured.paintedPercent` against `limit.paintedPercent` of 1600. A real label paints less than twice its area; the limit holds the worst scene to sixteen fills of the canvas where 1000 were possible. - **`box`** has `thickness` and optional `fill`; a line is a box whose width or height is its thickness. **`group`** has `children`, placed relative to its box; groups nest four deep. A scene holds at most 1000 elements, and its elements may paint at most sixteen times its printable area in all, an overlap counted each time: a filled box counts its area, an outline its four bars, a group nothing. The element that would pass that is refused as `SCENE_INVALID` at its pointer, with its box and `measured.paintedPercent` against `limit.paintedPercent` of 1600. A real label paints less than twice its area; the limit holds the worst scene to sixteen fills of the canvas where 1000 were possible.
- **`text`, `barcode` and `image`** are parsed and placed by renderer `0.2.0` and then refused as `RENDERER_TOO_OLD`, with the box they would have had, until their packages are in the renderer. - **`text`** draws one value in a face bundled with the renderer: `qqq-sans`, `qqq-sans-bold` (IBM Plex Sans), `qqq-condensed-bold` (IBM Plex Sans Condensed) and `qqq-mono`, `qqq-mono-bold` (JetBrains Mono). There is no printer font in version 2 and no installed font is used; any other `font` is `FONT_UNKNOWN`, and a request that supplies an asset whose name begins `qqq-` is refused as `RESERVED_FONT_NAME`. `font` and `size` may come from the scene's `defaults`. The value is `value` or, read from the record when rendering, `valuePath` (text as it is, `true` or `false`, or a number in plain decimal digits with no exponent and no fraction that is only zeros: `1.0E10` prints `10000000000`, `2.50` prints `2.5`; anything else is `VALUE_MISSING`); at most 1024 characters, each of which the face must draw as one glyph from left to right (no control or format characters, combining marks, shaping or right-to-left scripts: `FONT_MISSING_GLYPH`, with the count).
- **Size and measurement.** `size` is the em as a physical length from `1pt` to `1000pt`, not rounded to dots. A text is measured before it is drawn, by integer arithmetic on the face's own numbers, so the measurement is the same on every machine. A line's box is its pen advance widened to hold the ink of every character in it, plus two dots on each inked side for the rasteriser. A text whose ink the rasteriser puts outside that box is not printed in part and does not fail the render: the one element is refused as `TEXT_DOES_NOT_FIT` with `measured.glyphsOutsideMeasure` and `measured.dotsOutsideMeasure`, when the scene is validated if its value is a literal. No bundled face does so at any size from 1 pt to 1000 pt. The block of lines is placed in the element's box by `align` and `valign`, and each line in the block by `align`. `lineHeight` is the distance between baselines as a multiple of the size (default: the face's own). `rotation` turns the text clockwise in a box given as it appears on the label; `reverse` prints white letters on the box filled black.
- **Fit.** In this order: lay the value out at `size` within `fit.maxLines` (default 1); if it does not fit, take the largest size, in steps of 0.25 pt down to `fit.shrinkTo`, at which it does (`TEXT_SHRUNK`); if none does, apply `fit.overflow`. `shrinkTo` defaults to 70% of the size and not below 5 pt. `overflow` is `refuse` (the default: `TEXT_DOES_NOT_FIT`, with the measured width, height, lines and size against the box) or `truncate`, which cuts at a character, ends with an ellipsis and warns `TEXT_TRUNCATED`. At each size a line is broken between words while that fits and at any character when it does not, so a value with no space wraps and a larger size is preferred to whole words (`TEXT_WRAPPED`). A member of `fit` that is wrong is `SCENE_INVALID` at that member (`/elements/3/fit/maxLines`). The size chosen is exactly the one a search of every quarter-point step gives, found without making that search, and all the text of one scene is held to a stated amount of work: 64 million steps, where a character visited while fitting is one step, a character to be drawn is 16 and a glyph the scene draws for the first time at a size is 4096. A scene that passes it is refused as `SCENE_INVALID` at the element that did, with `measured.textWorkSteps` against `limit.textWorkSteps`, the same whether it is validated or rendered and on every machine. That is about a second of a worker; a label of a hundred values takes a few percent of it.
- **Proving the fit.** `maxLength` is the longest value in characters. When a scene is validated, that many of the face's widest character must fit whole, each taken to reach as far above, below and beside its advance as the furthest-reaching character of the face; otherwise the scene is refused as `TEXT_DOES_NOT_FIT`. The proof never cuts. An element with `overflow: truncate` whose stated length is not proven is still valid, since cutting is what its author chose, but every validation warns `FIT_NOT_PROVEN` with `measured.provenCharacters`, the longest length that is proven to fit whole, against `limit.characters`: longer values may be cut. A scene that passes cannot be refused at that render target because a value of up to that length does not fit, whichever of the face's characters it holds. The proof is therefore stricter than a typical value needs, and a box that is exactly `lines x lineHeight` high is not proven: leave room for an accent above a capital. When printing, a longer value is `VALUE_TOO_LONG` before any layout. A bound element without `maxLength` warns `FIT_NOT_PROVEN` with no number. Validation reads no record. The proof is for the render target of the request; validate at each resolution the document prints at.
- **Legibility.** Glyphs are drawn antialiased and a dot is ink when its grey is darker than `threshold` (1 to 254, default 128), so a higher value prints heavier. `TEXT_SMALL_FOR_DPI` warns when the capitals are under 12 dots high at the render target (about 6 pt at 203 dpi), `TEXT_LIGHT_FACE` when a regular weight is used with capitals under 20 dots (about 10 pt at 203 dpi). A literal is judged at the size it is drawn at; a bound value, when validated, at the size its `maxLength` is proven at, which is the smallest any value is printed at (the floor when the proof fails and the element cuts), and at its stated size when it has no `maxLength`. An override is how a scene answers for one resolution: a bold face or a higher `threshold` at 203 dpi.
- **`barcode`** draws one value in a fit-qualified symbology (`code128`, `code39`, `code93`, `itf`, `gs1-128`, `ean13`, `ean8`, `upca`, `upce`, `qr`, `datamatrix`, `pdf417`, `aztec`, default encoder options) into the picture of the label, in whole dots. It states `symbology`, or `symbologyPath` with the `allowedSymbologies` the record may name; and `value`, or `valuePath`. A `gs1-128` value is an element string with each application identifier in square brackets (`[01]00012345678905[21]TEST0001`); the encoder adds the leading FNC1 and the separators.
- **Module.** The module, the narrowest bar, is the largest whole number of dots at which the symbol fits its box with its quiet zones and its bars are as tall as its symbology asks. It is never under `minModule` and never over `maxModule`; both go up to a whole dot. Without `minModule` the smallest module is what `barcodeProfile` gives the symbology:
| `barcodeProfile` | `ean13`, `ean8`, `upca`, `upce` | `gs1-128`, `itf` | `code128`, `code39`, `code93` | `qr`, `datamatrix`, `pdf417`, `aztec` |
|---|---|---|---|---|
| `none`: the design's own minimum | 0.25 mm | 0.25 mm | 0.25 mm | 0.375 mm |
| `gs1-general`: GS1, general retail point of sale | 0.264 mm | 0.25 mm | 0.25 mm | 0.375 mm |
| `gs1-logistics`: GS1, general distribution and logistic units | 0.495 mm | 0.495 mm | 0.25 mm | 0.375 mm |
| not stated | as `gs1-general` | as `gs1-logistics` | as `none` | as `none` |
In dots at 203, 300 and 600 dpi: 0.25 mm is 2, 3 and 6; 0.264 mm is 3, 4 and 7; 0.375 mm is 3, 5 and 9; 0.495 mm is 4, 6 and 12. The GS1 numbers are those of the symbol specification tables of the GS1 General Specifications; 0.25 mm and 0.375 mm are this renderer's own and are to be confirmed by printing and scanning. Example: a 44-character GS1-128 (a GTIN, a date and a serial number) is 319 modules with its quiet zones. With no profile stated it is held to 4 dots at 203 dpi and needs 1276 dots, 160 mm: it fits no label 4 in wide (812 dots) and is refused. Named `gs1-general` or `none`, in a box of `90mm` (719 dots) its module is `719 / 319 = 2` dots (0.25 mm), the symbol is 638 dots, and in the middle of the box it leaves 40 and 41 dots.
- **Quiet zones.** Each symbology has its own, in modules before the first bar and after the last: 10 and 10 for `code128`, `gs1-128`, `code39`, `code93` and `itf`; 11 and 7 for `ean13`; 7 and 7 for `ean8`; 9 and 9 for `upca`; 9 and 7 for `upce`; 4 on every side of a two-dimensional symbol. `quiet` states one number for both sides: at least the larger of the two for every symbology the element may draw, at most 64.
- **Height.** The bars of a linear symbol take the whole height of the box across them, and that must be what the symbology asks of bars so wide: 15% of the width of the bars, first to last, and never under 5 mm, for `code128`, `gs1-128`, `code39`, `code93` and `itf` (ISO/IEC 15417, Annex G); 69.24 modules for `ean13`, `upca` and `upce` and 55.24 for `ean8` (GS1 General Specifications). A module that would make the symbol too wide for the height of its box is not chosen, and a box too short at the smallest module is `BARCODE_DOES_NOT_FIT`. The 44-character GS1-128 at 2 dots has bars 598 dots wide and needs 90 dots (11.3 mm at 203 dpi). An EAN-13 at 3 dots needs 208 dots (26 mm), more than a label 1 in high has. An author who accepts shorter bars states `minHeight`: the symbol is drawn, and the label carries the warning `BARCODE_HEIGHT_BELOW_RECOMMENDED` every time, with `measured.heightDots` against `limit.heightDots`.
- **Place.** The fitted symbol sits in the middle of its box: for a barcode, and only for a barcode, `align` and `valign` default to `center` and `middle`, so what the box has to spare is quiet zone, the same on both sides. A scene may still state them; the odd dot goes to the right and below. The symbol paints its own white ground, quiet zones included, so ink painted before it cannot close a space. `rotation` turns it clockwise in a box given as it appears on the label; a quarter turn fits the symbol along the height of the box, and the widths and heights in its diagnostics are those of the symbol.
- **Nothing over it.** An element later in the list whose ink would enter the symbol or its quiet zones is refused as `QUIET_ZONE_INTRUDED`, when the scene is validated as when it is rendered: `element` and `box` are the later element's, `pointer` is the barcode's, `measured` holds the edges of the ink (`leftDots`, `topDots`, `rightDots`, `bottomDots`) and `limit` the edges of what the barcode keeps. Ink is the box of the element, or the four bars of an outline; a group has none of its own. While the scene is only validated and the record gives the value or the symbology, the symbol is not known and the barcode keeps its whole box. Paint grounds and frames before a barcode, or beside it.
- **Does not fit.** A value that does not fit at the minimum module is never drawn smaller. It is `BARCODE_DOES_NOT_FIT`, when the scene is validated as when it is rendered, with `measured.modules`, `measured.quietLeftModules` and `measured.quietRightModules`, `measured.widthDots` and `measured.heightDots` (the dots needed at the minimum), `measured.moduleDots` (the largest module that would fit, which may be 0) against `limit.widthDots` and `limit.heightDots` (the box) and `limit.minModuleDots`. A symbol of more modules than the encoder draws carries `measured.characters` against `limit.modules` of 4096. An author who accepts a smaller module states it (`"minModule": "1dot"`, in an override for the resolution it is meant for): the symbol is drawn and the label carries the warning `BARCODE_MODULE_BELOW_RECOMMENDED` every time. A drawn symbol reports `BARCODE_MODULE` with the same numbers and `measured.moduleMicrometres`.
- **Values.** A bound value is text, or a number or true/false as JSON writes it; anything else, or nothing, is `VALUE_MISSING` at the pointer of the property that binds it (`valuePath`, `symbologyPath`, `scannerSymbologyPath`, `aimIdentifierPath`), and more than `maxLength` (or 4000) characters is `VALUE_TOO_LONG`. A label is scanned, so a symbol must never read as something other than its value, and four things the encoder would do are refused before it sees the value. (1) No value, literal or from the record, in any symbology, may hold the two characters `\<`: the encoder reads `\<FNC1>` to `\<FNC4>` as function characters, with which a record could make a GS1-128 of a plain Code 128, set the reader-programming flag or change a character. A function character enters a symbol only through its symbology: `gs1-128` adds its own FNC1. (2) `itf` takes an even number of digits; an odd number is never padded with a zero. (3) `ean13`, `ean8`, `upca` and `upce` take the whole number, check digit included (13, 8, 12 and 8 digits). The check digit is verified. A number without its check digit, or of any other length, is refused, never completed or padded. (4) In a `gs1-128` element string the check digit of every key is verified: application identifiers 00, 01, 02, 03, 253, 255, 402, 410 to 417, 8003, 8006, 8017, 8018 and 8026. A value refused by one of these, or that the symbology cannot hold, is `VALUE_NOT_ENCODABLE` (for `gs1-128`, `GS1_INVALID`) at `value` or `valuePath`, with numbers only and never the value: `measured.characters`; for an odd `itf`, `limit.charactersMultipleOf`; for a retail number, `limit.characters` and, when the check digit is wrong, `checkDigitMatches` 0 against 1; for a GS1 key, `measured.applicationIdentifier` and the same. A symbology the scene does not allow, and a scanner symbology and AIM identifier (`scannerSymbologyPath`, `aimIdentifierPath`, the version 1 scanner profile) that do not name the symbology drawn, are `SCENE_INVALID` at that property.
- **Proving the fit.** Validation reads no record. A literal value is fitted when the scene is validated, in every symbology the record may name. For a value bound to the record, `maxLength` is the longest value in characters, and validation fits the widest symbol a value of that length can need in a linear symbology (Code 128: 11 modules for each character and 35; Code 39: 13 and 25; Code 93: 18 and 37; `itf`: 9 for each digit and 9; `gs1-128`: 11 for each character of the element string, brackets included, and 24), refusing the scene as `BARCODE_DOES_NOT_FIT` when that does not fit. For Code 128 and Code 93 the widest is a value of characters from space to tilde. The EAN and UPC symbols are one width and need no length. A two-dimensional symbol is fitted for that many bytes, which refuses a box they cannot fit and proves no more: another value of the same length can need a larger symbol, so its `FIT_NOT_PROVEN` stays. A bound value with no `maxLength`, in a symbology of more than one width, warns `FIT_NOT_PROVEN`. The widest GS1-128 of a length is one of letters, far wider than a label of digits: a 44-character element string is proven only in a box that holds 528 modules.
- **Not yet.** `gs1` (an element string built from application identifiers) and `hri` (the human-readable line) are declared; an element that states either is refused as `RENDERER_TOO_OLD`.
- **`image`** is parsed and placed by renderer `0.2.0` and then refused as `RENDERER_TOO_OLD`, with the box it would have had, until its package is in the renderer.
- **`overrides`** replace properties of declared elements at the listed resolutions and are the only place a scene may depend on resolution. They are checked for all three resolutions whatever the request's target. **`samples`** are accepted and ignored by rendering. - **`overrides`** replace properties of declared elements at the listed resolutions and are the only place a scene may depend on resolution. They are checked for all three resolutions whatever the request's target. **`samples`** are accepted and ignored by rendering.
- **Output.** The whole label is composed on one 1-bit canvas and emitted as uncompressed `^GFA` fields: rows are cut into bands wherever eight or more blank rows separate ink, each band is trimmed to its inked columns, and a band is continued in a further field at 99,999 bytes. Only `^XA`, `^PW`, `^LL`, `^LH`, `^CI28`, `^FO`, `^GFA`, `^FS` and `^XZ` are emitted. - **Output.** The whole label is composed on one 1-bit canvas and emitted as uncompressed `^GFA` fields: rows are cut into bands wherever eight or more blank rows separate ink, each band is trimmed to its inked columns, and a band is continued in a further field at 99,999 bytes. Only `^XA`, `^PW`, `^LL`, `^LH`, `^CI28`, `^FO`, `^GFA`, `^FS` and `^XZ` are emitted.
- **Diagnostics.** A refusal is one diagnostic: `code`, `severity`, the `element` id, the element's `box` in dots from the top left of the printable area, and `measured` and `limit` as named integers. `SCENE_INVALID` also carries `pointer`, the JSON pointer of the offending place. A diagnostic names only an id the scene declares and points only through schema property names, array indexes and declared ids, so no record value, sample or unknown property name can leave the worker in one. A stock the printer language cannot address stays the opaque `RENDER_FAILED`, as for version 1. - **Diagnostics.** A refusal is one diagnostic: `code`, `severity`, the `element` id, the element's `box` in dots from the top left of the printable area, and `measured` and `limit` as named integers. `SCENE_INVALID` also carries `pointer`, the JSON pointer of the offending place. A diagnostic names only an id the scene declares and points only through schema property names, array indexes and declared ids, so no record value, sample or unknown property name can leave the worker in one. A stock the printer language cannot address stays the opaque `RENDER_FAILED`, as for version 1.
+29
View File
@@ -58,3 +58,32 @@ the Java file preserves the full license and identifies the dated port.
Unmodified source, tests, hashes and maintenance policy are retained in Unmodified source, tests, hashes and maintenance policy are retained in
`src/test/resources/barcodes/coop2of5`. No interpreter or additional runtime `src/test/resources/barcodes/coop2of5`. No interpreter or additional runtime
dependency is introduced. See [the capability contract](BARCODES.md#coop-2-of-5). dependency is introduced. See [the capability contract](BARCODES.md#coop-2-of-5).
## Bundled fonts for version 2 label text (2026-11-12)
Version 2 label scenes draw text in five TrueType faces shipped inside the renderer JAR under `/fonts`. They are
data, not code: unmodified files taken from each project's official release archive, each beside its licence text
and a provenance note, with their SHA-256 in `/fonts/SHA256SUMS`. A test (`FaceTest`) fails the build when a
licence, a provenance note or a hash is missing or a file's bytes change.
| Scene name | Family and style | File | Release | SHA-256 | Licence |
| --- | --- | --- | --- | --- | --- |
| `qqq-sans` | IBM Plex Sans Regular | `ibm-plex-sans/IBMPlexSans-Regular.ttf` | [`@ibm/plex-sans@1.1.0`](https://github.com/IBM/plex/releases/download/%40ibm/plex-sans%401.1.0/ibm-plex-sans.zip), font version 3.005 | `975dcda37d80f038dcd143c22e33ca2d97a0cc5a929aace1c749153b0fe1afa5` | SIL OFL 1.1 |
| `qqq-sans-bold` | IBM Plex Sans Bold | `ibm-plex-sans/IBMPlexSans-Bold.ttf` | the same archive, font version 3.005 | `9e6c74a889a700d707613d24548fe4ffa6bc59559a0689d2cf9e133bdcdafb2f` | SIL OFL 1.1 |
| `qqq-condensed-bold` | IBM Plex Sans Condensed Bold | `ibm-plex-sans-condensed/IBMPlexSansCondensed-Bold.ttf` | [`@ibm/plex-sans-condensed@2.0.0`](https://github.com/IBM/plex/releases/download/%40ibm/plex-sans-condensed%402.0.0/ibm-plex-sans-condensed.zip), font version 3.000 | `723e245902b45a49f8cf602d15891bae08c31309dce7c56d209d10cd471b88c7` | SIL OFL 1.1 |
| `qqq-mono` | JetBrains Mono Regular | `jetbrains-mono/JetBrainsMono-Regular.ttf` | [`v2.304`](https://github.com/JetBrains/JetBrainsMono/releases/download/v2.304/JetBrainsMono-2.304.zip), font version 2.304 | `a0bf60ef0f83c5ed4d7a75d45838548b1f6873372dfac88f71804491898d138f` | SIL OFL 1.1 |
| `qqq-mono-bold` | JetBrains Mono Bold | `jetbrains-mono/JetBrainsMono-Bold.ttf` | the same archive, font version 2.304 | `5590990c82e097397517f275f430af4546e1c45cff408bde4255dad142479dcb` | SIL OFL 1.1 |
Each licence was confirmed from the release archive itself and not from memory: the archive's own licence file
(`LICENSE.txt` for the two IBM Plex archives, `OFL.txt` for JetBrains Mono) states the SIL Open Font License,
Version 1.1 and carries its full text, the licence field of every font's name table says the same, and every
font's embedding bits are 0 (installable embedding). The licence files are shipped byte for byte. IBM Plex
declares the Reserved Font Name "Plex"; the files are neither modified nor renamed, and the scene names
(`qqq-sans` and so on) are names of the renderer's faces, not of derived fonts.
The SIL Open Font License 1.1 is not on the allowlist of `K22-DEP-02`. The maintainer approved one recorded
exception for unmodified OFL 1.1 fonts shipped as data on 2026-11-12. The register is kept in the standards
repository (`exceptions/register.md`), not here; the entry was proposed with the pull request that added the
fonts. The OFL permits bundling and redistribution with software provided the copyright and
licence notices accompany the fonts, the fonts are not sold by themselves and a Reserved Font Name is not used
for a modified version; it does not apply to documents made with the fonts.
+52 -8
View File
@@ -15,7 +15,7 @@
"properties": {"width": {"$ref": "#/$defs/physical"}, "height": {"$ref": "#/$defs/physical"}} "properties": {"width": {"$ref": "#/$defs/physical"}, "height": {"$ref": "#/$defs/physical"}}
}, },
"defaults": { "defaults": {
"description": "Defaults for text elements.", "description": "The face and size of a text element that states none.",
"type": "object", "type": "object",
"additionalProperties": false, "additionalProperties": false,
"properties": {"font": {"type": "string", "pattern": "^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,99}$"}, "size": {"$ref": "#/$defs/physical"}} "properties": {"font": {"type": "string", "pattern": "^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,99}$"}, "size": {"$ref": "#/$defs/physical"}}
@@ -76,8 +76,8 @@
"y": {"$ref": "#/$defs/length", "default": "0mm", "description": "Distance inward from the anchored edge; on a centred axis a shift down, which may be negative."}, "y": {"$ref": "#/$defs/length", "default": "0mm", "description": "Distance inward from the anchored edge; on a centred axis a shift down, which may be negative."},
"width": {"$ref": "#/$defs/size", "description": "Rounded down to whole dots. Omitted: the rest of the container."}, "width": {"$ref": "#/$defs/size", "description": "Rounded down to whole dots. Omitted: the rest of the container."},
"height": {"$ref": "#/$defs/size", "description": "Rounded down to whole dots. Omitted: the rest of the container."}, "height": {"$ref": "#/$defs/size", "description": "Rounded down to whole dots. Omitted: the rest of the container."},
"align": {"enum": ["left", "center", "right"], "default": "left"}, "align": {"enum": ["left", "center", "right"], "description": "Where the content sits across its box. Default `left`; for a `barcode`, `center`."},
"valign": {"enum": ["top", "middle", "bottom"], "default": "top"} "valign": {"enum": ["top", "middle", "bottom"], "description": "Where the content sits down its box. Default `top`; for a `barcode`, `middle`."}
} }
}, },
"element": { "element": {
@@ -98,16 +98,60 @@
}, },
{ {
"$ref": "#/$defs/placement", "$ref": "#/$defs/placement",
"description": "Text. Parsed and placed by renderer 0.2.0 and refused as RENDERER_TOO_OLD until the text package; the values of these properties are not yet read.", "description": "Text in a face bundled with the renderer, measured before it is drawn and placed in its box by `align` and `valign`. `font` and `size` may come from `defaults`. The renderer is the authority: it also enforces a size from 1pt to 1000pt, a `shrinkTo` from 1pt up to the size, at most three decimals in `lineHeight`, at most 1024 characters, only characters the face draws as one glyph each from left to right (FONT_MISSING_GLYPH), no supplied asset whose name begins `qqq-` (RESERVED_FONT_NAME), and a stated amount of work for all the text of one scene (SCENE_INVALID with `textWorkSteps`).",
"unevaluatedProperties": false, "unevaluatedProperties": false,
"properties": {"type": {"const": "text"}, "value": {}, "valuePath": {}, "font": {}, "size": {}, "lineHeight": {}, "fit": {}, "maxLength": {}, "threshold": {}, "reverse": {}, "rotation": {"enum": [0, 90, 180, 270]}} "oneOf": [{"required": ["value"]}, {"required": ["valuePath"]}],
"properties": {
"type": {"const": "text"},
"value": {"type": "string", "maxLength": 1024, "description": "The text itself."},
"valuePath": {"type": "string", "pattern": "^/", "maxLength": 256, "description": "A JSON pointer into the record. Text is printed as it is; true and false as those words; a number in plain decimal digits, with no exponent and no fraction that is only zeros (`1.0E10` prints `10000000000`, `2.50` prints `2.5`, `12.0` prints `12`). Anything else, a number that is not finite among them, is VALUE_MISSING. No record is read when a scene is validated."},
"font": {"enum": ["qqq-sans", "qqq-sans-bold", "qqq-condensed-bold", "qqq-mono", "qqq-mono-bold"], "description": "A bundled face: IBM Plex Sans Regular and Bold, IBM Plex Sans Condensed Bold, JetBrains Mono Regular and Bold. Any other name is FONT_UNKNOWN."},
"size": {"$ref": "#/$defs/physical", "description": "The em size. Type scales continuously: the size is not rounded to dots."},
"lineHeight": {"type": "number", "minimum": 0.5, "maximum": 5, "description": "The distance between baselines as a multiple of the size. Default: the face's own ascent, descent and line gap."},
"fit": {
"type": "object",
"additionalProperties": false,
"description": "What happens when the value does not fit the box. In order: lay out at `size` within `maxLines`; else the largest size, in steps of 0.25pt down to `shrinkTo`, that fits; else `overflow`. At each size a line is broken between words while that fits and at any character when it does not. A member that is wrong is SCENE_INVALID at that member (`/fit/maxLines`); a member `fit` does not have is SCENE_INVALID at `fit`.",
"properties": {
"maxLines": {"type": "integer", "minimum": 1, "maximum": 64, "default": 1, "description": "The most lines the value may take."},
"shrinkTo": {"$ref": "#/$defs/physical", "description": "The smallest size the text may be reduced to: from 1pt up to `size`, which the renderer enforces. Default: 70% of `size` and not below 5pt, or `size` itself when that is smaller."},
"overflow": {"enum": ["refuse", "truncate"], "default": "refuse", "description": "What is done with a value that fits at no size: `refuse` (TEXT_DOES_NOT_FIT), or `truncate` (cut at a character, end with an ellipsis, warn TEXT_TRUNCATED)."}
}
},
"maxLength": {"type": "integer", "minimum": 1, "maximum": 1024, "description": "The longest value, in characters. Validation proves that this many of the face's widest character fit whole, never cut, so a length refusal happens when the scene is published; a longer value is VALUE_TOO_LONG when printing. When the proof fails and `fit.overflow` is `truncate` the scene stands and warns FIT_NOT_PROVEN with the longest length that is proven (`provenCharacters`): longer values may be cut. Without `maxLength` a bound element warns FIT_NOT_PROVEN."},
"threshold": {"type": "integer", "minimum": 1, "maximum": 254, "default": 128, "description": "Glyphs are drawn antialiased; a dot is ink when its grey is darker than this. Higher prints heavier."},
"reverse": {"type": "boolean", "default": false, "description": "White letters on the element's box filled black."},
"rotation": {"enum": [0, 90, 180, 270], "description": "Clockwise. The box is given as it appears on the label; a text turned a quarter is fitted along the box's height."}
}
}, },
{ {
"$ref": "#/$defs/placement", "$ref": "#/$defs/placement",
"description": "A barcode. Parsed and placed by renderer 0.2.0 and refused as RENDERER_TOO_OLD until the barcode package; the values of these properties are not yet read.", "description": "A barcode, drawn into the picture of the label in whole dots. The module (the narrowest bar) is the largest whole number of dots at which the symbol, quiet zones included, fits the box, never under `minModule` and never over `maxModule`; a value that does not fit at the minimum is BARCODE_DOES_NOT_FIT, with the modules and dots it needs and the dots the box has, and is never drawn smaller. A linear symbol is fitted along its width and its bars take the whole height of the box, which must be the height its symbology asks of bars that wide (see `minHeight`); a two-dimensional symbol (`qr`, `datamatrix`, `pdf417`, `aztec`) is fitted on both axes. The fitted symbol sits in the middle of its box unless `align` or `valign` says otherwise (for a barcode they default to `center` and `middle`, so what the box has to spare is quiet zone on both sides), and paints its own white ground, quiet zones included, so an element painted before it does no harm. Nothing may be painted over it: an element later in the list whose ink would enter the symbol or its quiet zones is refused as QUIET_ZONE_INTRUDED, with the pointer of the barcode (while a value or symbology bound to the record is not known, the barcode keeps its whole box). The renderer is the authority on values, so that a symbol never reads as something other than its value: no value may hold the two characters `\\<`, with which the encoder's escapes for function characters begin; `itf` takes an even number of digits and is never padded; `ean13`, `ean8`, `upca` and `upce` take the whole number with its check digit (13, 8, 12 and 8 digits), which is verified, and never a shorter one; the check digit of every GS1 key in a `gs1-128` element string is verified. A value that breaks one of these, or that the symbology cannot hold, is VALUE_NOT_ENCODABLE (GS1_INVALID for `gs1-128`) at the value, with numbers only and never the value. The renderer also refuses a quiet zone under the symbology's own and a maximum module under the minimum.",
"unevaluatedProperties": false, "unevaluatedProperties": false,
"properties": {"type": {"const": "barcode"}, "symbology": {}, "symbologyPath": {}, "allowedSymbologies": {}, "value": {}, "valuePath": {}, "minModule": {}, "maxModule": {}, "quiet": {}, "gs1": {}, "hri": {}, "allOf": [
"scannerSymbologyPath": {}, "aimIdentifierPath": {}, "rotation": {"enum": [0, 90, 180, 270]}} {"oneOf": [{"required": ["symbology"], "not": {"anyOf": [{"required": ["symbologyPath"]}, {"required": ["allowedSymbologies"]}]}}, {"required": ["symbologyPath", "allowedSymbologies"], "not": {"required": ["symbology"]}}]},
{"oneOf": [{"required": ["value"]}, {"required": ["valuePath"]}]},
{"dependentRequired": {"scannerSymbologyPath": ["aimIdentifierPath"], "aimIdentifierPath": ["scannerSymbologyPath"]}}
],
"properties": {
"type": {"const": "barcode"},
"symbology": {"enum": ["code128", "code39", "code93", "itf", "gs1-128", "qr", "ean13", "ean8", "upca", "upce", "datamatrix", "pdf417", "aztec"], "description": "The symbology. These are the encoders qualified for fitting, with their default options."},
"symbologyPath": {"type": "string", "pattern": "^/", "maxLength": 256, "description": "A JSON pointer into the record for the symbology, which must be one of `allowedSymbologies`. Text only; anything else is VALUE_MISSING."},
"allowedSymbologies": {"type": "array", "minItems": 1, "uniqueItems": true, "items": {"enum": ["code128", "code39", "code93", "itf", "gs1-128", "qr", "ean13", "ean8", "upca", "upce", "datamatrix", "pdf417", "aztec"]}, "description": "The symbologies the record may name. Required with `symbologyPath` and not allowed without it."},
"value": {"type": "string", "minLength": 1, "maxLength": 4000, "description": "The value itself, without the characters `\\<`. For `gs1-128` an element string with each application identifier in square brackets, `[01]00012345678905[21]TEST0001`: the encoder adds the leading FNC1 and the separator after a field of variable length, and the check digit of each key is verified. For `ean13`, `ean8`, `upca` and `upce` the whole number, check digit included: 13, 8, 12 and 8 digits. For `itf` an even number of digits."},
"valuePath": {"type": "string", "pattern": "^/", "maxLength": 256, "description": "A JSON pointer into the record. Text is encoded as it is, a number or true/false as JSON writes it; anything else, and empty text, is VALUE_MISSING, and more than `maxLength` (or 4000) characters VALUE_TOO_LONG. The value is held to the same rules as `value`. No record is read when a scene is validated: see `maxLength`."},
"minModule": {"$ref": "#/$defs/absolute", "description": "The smallest module, more than nothing, taken up to a whole dot. Default: what `barcodeProfile` gives the symbology. A stated minimum that is fewer dots than that is drawn, with the warning BARCODE_MODULE_BELOW_RECOMMENDED every time the scene is validated or rendered."},
"maxModule": {"$ref": "#/$defs/absolute", "description": "The largest module, more than nothing, taken up to a whole dot as the minimum is, so the same length for both is one module at every resolution."},
"quiet": {"type": "integer", "minimum": 4, "maximum": 64, "description": "Blank modules on each side, inside the box and part of the fit. Default: the symbology's own, which is 10 on each side of `code128`, `gs1-128`, `code39`, `code93` and `itf`; 11 before and 7 after `ean13`; 7 and 7 for `ean8`; 9 and 9 for `upca`; 9 and 7 for `upce`; and 4 on every side of a two-dimensional symbol. A stated number is that many on both sides, and may not be under the larger of the two for any symbology the element may draw."},
"barcodeProfile": {"enum": ["none", "gs1-general", "gs1-logistics"], "description": "Which rule gives the smallest module when `minModule` is not stated. `none`: the design's own 0.25mm for a linear symbol and 0.375mm for a two-dimensional one (2 and 3 dots at 203 dpi, 3 and 5 at 300 dpi, 6 and 9 at 600 dpi). `gs1-general`: for `ean13`, `ean8`, `upca` and `upce` the GS1 minimum at general retail point of sale, 0.264mm (3, 4 and 7 dots); other symbologies as `none`. `gs1-logistics`: for `gs1-128`, `itf`, `ean13`, `ean8`, `upca` and `upce` the GS1 minimum in general distribution, 0.495mm (4, 6 and 12 dots); other symbologies as `none`. Default: the strictest GS1 rule written for the symbology's own use, which is `gs1-logistics` for `gs1-128` and `itf`, `gs1-general` for the EAN/UPC symbols and `none` for the rest. At 4 dots a GS1-128 of a GTIN, a date and a serial number is 160mm wide and fits no label 4in wide: such a label names `gs1-general` or `none`, or states `minModule`."},
"minHeight": {"$ref": "#/$defs/absolute", "description": "For a linear symbol: the least height of its bars, more than nothing and taken up to a whole dot, in place of the rule of its symbology. That rule is 15% of the width of the bars, first to last, and never under 5mm for `code128`, `gs1-128`, `code39`, `code93` and `itf`; and 69.24 modules for `ean13`, `upca` and `upce`, 55.24 for `ean8`. A box shorter than the rule asks at the smallest module is BARCODE_DOES_NOT_FIT, and a module that would make the symbol too wide for the height of its box is not chosen. With `minHeight` stated, bars shorter than the symbology's rule are drawn, with the warning BARCODE_HEIGHT_BELOW_RECOMMENDED every time. Not read for a two-dimensional symbol."},
"maxLength": {"type": "integer", "minimum": 1, "maximum": 4000, "description": "The longest value, in characters; a longer one is VALUE_TOO_LONG. For a value bound to the record in a linear symbology, validation fits the widest symbol a value of that length can need (for `code128` and `code93` a value of characters from space to tilde; for `gs1-128` the element string, brackets included), and a scene whose widest symbol does not fit is BARCODE_DOES_NOT_FIT. `ean13`, `ean8`, `upca` and `upce` are one width and need no length. A two-dimensional symbol is fitted for that many bytes, which refuses a box they cannot fit and proves no more, since another value of that length can need a larger symbol: its warning FIT_NOT_PROVEN stays. Without `maxLength`, a bound value in a symbology of more than one width warns FIT_NOT_PROVEN."},
"gs1": {"description": "Reserved for an element string built from application identifiers. An element that states it is refused as RENDERER_TOO_OLD by this renderer."},
"hri": {"description": "Reserved for the human-readable line. An element that states it is refused as RENDERER_TOO_OLD by this renderer."},
"scannerSymbologyPath": {"type": "string", "pattern": "^/", "maxLength": 256, "description": "With `aimIdentifierPath`, JSON pointers to the symbology name and AIM identifier a scanner reported. They must name the symbology drawn (else SCENE_INVALID here), and the value is held to what that profile reproduces (else VALUE_NOT_ENCODABLE at the value). They are read when a label is rendered, not when a scene is validated."},
"aimIdentifierPath": {"type": "string", "pattern": "^/", "maxLength": 256, "description": "See `scannerSymbologyPath`."},
"rotation": {"enum": [0, 90, 180, 270], "description": "Clockwise. The box is given as it appears on the label; a symbol turned a quarter is fitted along the height of the box, and the widths and heights in its diagnostics are those of the symbol."}
}
}, },
{ {
"$ref": "#/$defs/placement", "$ref": "#/$defs/placement",
@@ -21,6 +21,7 @@
package com.kingsrook.qbits.renderer.scene2; package com.kingsrook.qbits.renderer.scene2;
import java.util.List;
import java.util.Set; import java.util.Set;
import com.kingsrook.qbits.renderer.RenderInput; import com.kingsrook.qbits.renderer.RenderInput;
@@ -137,20 +138,29 @@ final class BoxElement implements SceneElement
/*************************************************************************** /***************************************************************************
** Four bars inside the box, or the whole box when it is filled or when the ** Four bars inside the box, or the whole box when it is filled or when the
** bars would meet. ** bars would meet. An outline may so be drawn around a barcode that was
** painted before it.
***************************************************************************/
@Override
public List<Frame> ink(Frame frame, int dpi)
{
int bar = bar(frame, dpi);
if(bar < 0)
{
return (List.of(frame));
}
return (List.of(new Frame(frame.x(), frame.y(), frame.width(), bar), new Frame(frame.x(), frame.bottom() - bar, frame.width(), bar), new Frame(frame.x(), frame.y(), bar, frame.height()),
new Frame(frame.right() - bar, frame.y(), bar, frame.height())));
}
/***************************************************************************
** Paint the ink of the box.
***************************************************************************/ ***************************************************************************/
@Override @Override
public void paint(Canvas canvas, Frame frame, RenderInput input, Diagnostics diagnostics) public void paint(Canvas canvas, Frame frame, RenderInput input, Diagnostics diagnostics)
{ {
int bar = bar(frame, canvas.dpi()); ink(frame, canvas.dpi()).forEach(part -> canvas.fill(part, true));
if(bar < 0)
{
canvas.fill(frame, true);
return;
}
canvas.fill(new Frame(frame.x(), frame.y(), frame.width(), bar), true);
canvas.fill(new Frame(frame.x(), frame.bottom() - bar, frame.width(), bar), true);
canvas.fill(new Frame(frame.x(), frame.y(), bar, frame.height()), true);
canvas.fill(new Frame(frame.right() - bar, frame.y(), bar, frame.height()), true);
} }
} }
@@ -40,8 +40,9 @@ import java.util.regex.Pattern;
public final class Diagnostic public final class Diagnostic
{ {
private static final Set<String> ERRORS = Set.of("SCENE_INVALID", "STOCK_MISMATCH", "TARGET_REQUIRES_SCENE_2", "ELEMENT_OUTSIDE_PRINTABLE_AREA", "TEXT_DOES_NOT_FIT", "VALUE_MISSING", private static final Set<String> ERRORS = Set.of("SCENE_INVALID", "STOCK_MISMATCH", "TARGET_REQUIRES_SCENE_2", "ELEMENT_OUTSIDE_PRINTABLE_AREA", "TEXT_DOES_NOT_FIT", "VALUE_MISSING",
"VALUE_TOO_LONG", "FONT_UNKNOWN", "FONT_MISSING_GLYPH", "RESERVED_FONT_NAME", "BARCODE_DOES_NOT_FIT", "GS1_INVALID", "ASSET_UNKNOWN", "PREVIEW_TOO_LARGE", "RENDERER_TOO_OLD"); "VALUE_TOO_LONG", "FONT_UNKNOWN", "FONT_MISSING_GLYPH", "RESERVED_FONT_NAME", "BARCODE_DOES_NOT_FIT", "GS1_INVALID", "ASSET_UNKNOWN", "PREVIEW_TOO_LARGE", "RENDERER_TOO_OLD",
private static final Set<String> WARNINGS = Set.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", "BARCODE_MODULE_BELOW_RECOMMENDED", "QUIET_ZONE_INTRUDED", "VALUE_NOT_ENCODABLE", "QUIET_ZONE_INTRUDED");
private static final Set<String> WARNINGS = Set.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", "BARCODE_MODULE_BELOW_RECOMMENDED", "BARCODE_HEIGHT_BELOW_RECOMMENDED",
"ELEMENTS_OVERLAP", "IMAGE_UPSCALED", "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN"); "ELEMENTS_OVERLAP", "IMAGE_UPSCALED", "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN");
private static final Set<String> INFORMATION = Set.of("TEXT_SHRUNK", "TEXT_WRAPPED", "BARCODE_MODULE", "IMAGE_SCALED"); private static final Set<String> INFORMATION = Set.of("TEXT_SHRUNK", "TEXT_WRAPPED", "BARCODE_MODULE", "IMAGE_SCALED");
private static final Pattern NAME = Pattern.compile("[a-z][A-Za-z0-9]{0,31}"); private static final Pattern NAME = Pattern.compile("[a-z][A-Za-z0-9]{0,31}");
@@ -50,10 +50,11 @@ public interface ElementFactory
Map<String, ElementFactory> FACTORIES = Map.of("box", new BoxElement.Factory(), "text", new TextFactory(), "barcode", new BarcodeFactory(), "image", new GraphicsFactory()); Map<String, ElementFactory> FACTORIES = Map.of("box", new BoxElement.Factory(), "text", new TextFactory(), "barcode", new BarcodeFactory(), "image", new GraphicsFactory());
/*************************************************************************** /***************************************************************************
** Every property name the version 2 schema declares. A diagnostic's pointer ** Every property name the version 2 schema declares, the members of a text
** is made only of these, of array indexes and of declared element ids. ** element's `fit` among them. A diagnostic's pointer is made only of these,
** of array indexes and of declared element ids.
***************************************************************************/ ***************************************************************************/
Set<String> VOCABULARY = Stream.concat(Stream.of("schema", "design", "defaults", "font", "size", "samples", "elements", "overrides", "when", "dpi", "set", "children"), Set<String> VOCABULARY = Stream.concat(Stream.of("schema", "design", "defaults", "font", "size", "samples", "elements", "overrides", "when", "dpi", "set", "children", "maxLines", "shrinkTo", "overflow"),
Stream.concat(COMMON.stream(), FACTORIES.values().stream().flatMap(factory -> factory.properties().stream()))).collect(Collectors.toUnmodifiableSet()); Stream.concat(COMMON.stream(), FACTORIES.values().stream().flatMap(factory -> factory.properties().stream()))).collect(Collectors.toUnmodifiableSet());
@@ -205,11 +205,23 @@ public final class ElementSource
/*************************************************************************** /***************************************************************************
** The refusal for a property the element states wrongly, or lacks. ** The refusal for a property the element states wrongly, or lacks. A member
** of a property that is an object is named with a slash: `fit/maxLines`.
***************************************************************************/ ***************************************************************************/
public Refusal invalid(String name) public Refusal invalid(String name)
{ {
return (diagnostics.refuse("SCENE_INVALID", id, pointer(name), null, null, null)); return (refuse("SCENE_INVALID", name));
}
/***************************************************************************
** The refusal, by its own code, for a property that is well formed but names
** something this renderer does not have, such as a font.
***************************************************************************/
public Refusal refuse(String code, String name)
{
return (diagnostics.refuse(code, id, pointer(name), null, null, null));
} }
@@ -230,12 +242,33 @@ public final class ElementSource
/*************************************************************************** /***************************************************************************
** Where a property is stated: in the override that set it, else in the ** Give the element the scene's `defaults` for the properties its type reads
** element. ** and it does not state. A default is reported where the scene states it.
***************************************************************************/
void inherit(JsonNode defaults, Set<String> properties)
{
for(Map.Entry<String, JsonNode> property : defaults.properties())
{
if(properties.contains(property.getKey()) && !values.containsKey(property.getKey()))
{
values.put(property.getKey(), property.getValue());
pointers.put(property.getKey(), "/defaults/" + property.getKey());
}
}
}
/***************************************************************************
** Where a property is stated: in the override that set it, in the scene's
** defaults, else in the element. A member of a property that is an object
** (`fit/maxLines`) is in that property, wherever the property is stated.
***************************************************************************/ ***************************************************************************/
private String pointer(String name) private String pointer(String name)
{ {
return (pointers.getOrDefault(name, pointer + "/" + name)); int member = name.indexOf('/');
String property = member < 0 ? name : name.substring(0, member);
return (pointers.getOrDefault(property, pointer + "/" + property) + (member < 0 ? "" : name.substring(member)));
} }
@@ -60,6 +60,16 @@ public record Frame(int x, int y, int width, int height)
/***************************************************************************
** Whether the two boxes share a dot.
***************************************************************************/
public boolean intersects(Frame other)
{
return (other.x < right() && x < other.right() && other.y < bottom() && y < other.bottom());
}
/*************************************************************************** /***************************************************************************
** The box as a diagnostic carries it: x, y, width and height. ** The box as a diagnostic carries it: x, y, width and height.
***************************************************************************/ ***************************************************************************/
@@ -83,6 +83,17 @@ final class GroupElement implements SceneElement
/***************************************************************************
** A group puts no ink anywhere; its children answer for theirs.
***************************************************************************/
@Override
public List<Frame> ink(Frame frame, int dpi)
{
return (List.of());
}
/*************************************************************************** /***************************************************************************
** A group has no ink of its own. ** A group has no ink of its own.
***************************************************************************/ ***************************************************************************/
@@ -22,6 +22,7 @@ package com.kingsrook.qbits.renderer.scene2;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
@@ -155,7 +156,7 @@ public final class Scene2
throw diagnostics.refuse("STOCK_MISMATCH", null, "/design", null, Map.of("widthMicrometres", stock.widthMicrons(), "heightMicrometres", stock.heightMicrons()), throw diagnostics.refuse("STOCK_MISMATCH", null, "/design", null, Map.of("widthMicrometres", stock.widthMicrons(), "heightMicrometres", stock.heightMicrons()),
Map.of("widthMicrometres", scene.width().micrometres(), "heightMicrometres", scene.height().micrometres(), "toleranceMicrometres", STOCK_TOLERANCE_MICROMETRES)); Map.of("widthMicrometres", scene.width().micrometres(), "heightMicrometres", scene.height().micrometres(), "toleranceMicrometres", STOCK_TOLERANCE_MICROMETRES));
} }
walk(scene.elements(), new Layout(new Frame(0, 0, canvas.width(), canvas.height()), page.dpi()), canvas, paint, input, diagnostics); walk(scene.elements(), new Layout(new Frame(0, 0, canvas.width(), canvas.height()), page.dpi()), canvas, paint, input, diagnostics, new ArrayList<>());
} }
catch(Refusal refusal) catch(Refusal refusal)
{ {
@@ -167,12 +168,30 @@ public final class Scene2
/*************************************************************************** /***************************************************************************
** Elements in list order: place, hold the box to the printable area, check, ** What an element painted earlier keeps clear of every later one: its
** count the dots it would paint against what one scene may paint, paint ** pointer in the scene and the area, in dots.
** when asked, then the children inside the box. The dots are counted when a
** scene is only validated too, so validation refuses what rendering would.
***************************************************************************/ ***************************************************************************/
private static void walk(List<SceneElement> elements, Layout layout, Canvas canvas, boolean paint, RenderInput input, Diagnostics diagnostics) private record Kept(String pointer, Frame area)
{
}
/***************************************************************************
** Elements in list order: place, hold the box to the printable area, check,
** hold its ink off every barcode painted before it, count the dots it would
** paint against what one scene may paint, paint when asked, then the
** children inside the box. The dots are counted when a scene is only
** validated too, so validation refuses what rendering would.
**
** A barcode painted later clears its own ground, so what lies under it does
** no harm; ink painted over a barcode or its quiet zone would change what a
** scanner reads, or stop it reading, and nothing would say so. The element
** that would put it there is refused as `QUIET_ZONE_INTRUDED`, with the
** pointer of the barcode, the edges of its own ink and the edges of the
** area the barcode keeps.
***************************************************************************/
private static void walk(List<SceneElement> elements, Layout layout, Canvas canvas, boolean paint, RenderInput input, Diagnostics diagnostics, List<Kept> kept)
{ {
Frame printable = new Frame(0, 0, canvas.width(), canvas.height()); Frame printable = new Frame(0, 0, canvas.width(), canvas.height());
for(SceneElement element : elements) for(SceneElement element : elements)
@@ -192,17 +211,33 @@ public final class Scene2
Map.of("leftDots", 0, "topDots", 0, "rightDots", printable.right(), "bottomDots", printable.bottom())); Map.of("leftDots", 0, "topDots", 0, "rightDots", printable.right(), "bottomDots", printable.bottom()));
} }
element.check(frame, input, diagnostics); element.check(frame, input, diagnostics);
for(Frame ink : element.ink(frame, layout.dpi()))
{
for(Kept earlier : kept)
{
if(ink.intersects(earlier.area()))
{
throw diagnostics.refuse("QUIET_ZONE_INTRUDED", element.id(), earlier.pointer(), frame, Map.of("leftDots", ink.x(), "topDots", ink.y(), "rightDots", ink.right(), "bottomDots", ink.bottom()),
Map.of("leftDots", earlier.area().x(), "topDots", earlier.area().y(), "rightDots", earlier.area().right(), "bottomDots", earlier.area().bottom()));
}
}
}
long dots = element.paintedDots(frame, layout.dpi()); long dots = element.paintedDots(frame, layout.dpi());
if(!canvas.admit(dots)) if(!canvas.admit(dots))
{ {
throw diagnostics.refuse("SCENE_INVALID", element.id(), diagnostics.pointer(element.id()), frame, Map.of("paintedPercent", canvas.paintedPercent(dots)), throw diagnostics.refuse("SCENE_INVALID", element.id(), diagnostics.pointer(element.id()), frame, Map.of("paintedPercent", canvas.paintedPercent(dots)),
Map.of("paintedPercent", Canvas.MAXIMUM_COATS * 100)); Map.of("paintedPercent", Canvas.MAXIMUM_COATS * 100));
} }
Frame area = element.clear(frame, input, diagnostics);
if(area != null)
{
kept.add(new Kept(diagnostics.pointer(element.id()), area));
}
if(paint) if(paint)
{ {
element.paint(canvas, frame, input, diagnostics); element.paint(canvas, frame, input, diagnostics);
} }
walk(element.children(), layout.within(frame), canvas, paint, input, diagnostics); walk(element.children(), layout.within(frame), canvas, paint, input, diagnostics, kept);
} }
catch(Refusal refusal) catch(Refusal refusal)
{ {
@@ -68,6 +68,30 @@ public interface SceneElement
/***************************************************************************
** Where in its box the element puts ink, as boxes that hold all of it: the
** whole box unless the element knows less. An element painted after a
** barcode may put none of these on the barcode.
***************************************************************************/
default List<Frame> ink(Frame frame, int dpi)
{
return (List.of(frame));
}
/***************************************************************************
** The part of the label that elements painted after this one must leave
** alone, or null: a barcode answers its symbol and quiet zones. Asked when
** a scene is validated as when it is painted, after `check`.
***************************************************************************/
default Frame clear(Frame frame, RenderInput input, Diagnostics diagnostics)
{
return (null);
}
/*************************************************************************** /***************************************************************************
** Draw the element in its box. ** Draw the element in its box.
***************************************************************************/ ***************************************************************************/
@@ -278,6 +278,7 @@ final class SceneParser
{ {
ElementFactory factory = ElementFactory.FACTORIES.get(source.type()); ElementFactory factory = ElementFactory.FACTORIES.get(source.type());
source.only(factory.properties()); source.only(factory.properties());
source.inherit(root.path("defaults"), factory.properties());
built.add(factory.create(source)); built.add(factory.create(source));
} }
} }
@@ -0,0 +1,682 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.kingsrook.qbits.renderer.Barcodes;
import com.kingsrook.qbits.renderer.RenderInput;
import com.kingsrook.qbits.renderer.ScannerSymbology;
import com.kingsrook.qbits.renderer.Wire;
import com.kingsrook.qbits.renderer.scene2.Canvas;
import com.kingsrook.qbits.renderer.scene2.Diagnostics;
import com.kingsrook.qbits.renderer.scene2.ElementSource;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.Layout;
import com.kingsrook.qbits.renderer.scene2.Length;
import com.kingsrook.qbits.renderer.scene2.Placement;
import com.kingsrook.qbits.renderer.scene2.SceneElement;
import uk.org.okapibarcode.backend.OkapiInputException;
/*******************************************************************************
** A `barcode` element: one value in one of the fit-qualified symbologies,
** drawn into the picture of the label. The encoder of version 1 gives the
** bars as modules; this element lays out the quiet zones of the symbology
** itself, `ModuleFit` chooses the module, a whole number of dots, and the
** symbol is placed in the box by `align` and `valign`, in the middle unless
** the scene says otherwise, and painted as a white ground and black bars, so
** that nothing painted under it can close a space or a quiet zone. Nothing
** may be painted over it: the scene refuses a later element that enters the
** area `clear` answers.
**
** The value is a literal (`value`) or is read from the record by a JSON
** pointer (`valuePath`). The symbology is stated, or read from the record
** (`symbologyPath`) and held to the list the scene allows. A scanner profile
** (`scannerSymbologyPath` with `aimIdentifierPath`) holds the value to what a
** scanner reported, as in version 1. `Payload` holds every value to the rules
** that keep a symbol from reading as something other than its value.
**
** Every refusal names the element and carries numbers only: modules, dots, a
** count of characters. The value itself never enters a diagnostic or an
** exception; what an encoder says about a value it rejects is dropped.
**
** Validation reads no record. It fits a literal value as it is, in every
** symbology the record may name. For a value bound to the record it fits the
** largest symbol a value of the declared `maxLength` can need, and warns
** `FIT_NOT_PROVEN` when no length is declared or the symbology has no such
** largest symbol, as no two-dimensional one has: that is then fitted for as
** many bytes, which refuses a box they cannot fit and proves no more. A
** symbology of one width needs no length.
*******************************************************************************/
final class BarcodeElement implements SceneElement
{
static final int MAXIMUM_CHARACTERS = 4000;
static final int MAXIMUM_POINTER = 256;
/////////////////////////////////////////////////////////////////////////////////////////////////
// the most modules across that the encoder path of version 1 draws (`BARCODE_BITMAP_LIMIT`) //
/////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXIMUM_MODULES = 4096;
private static final int MICROMETRES_PER_INCH = 25_400;
/////////////////////////////////////////////////////////////////////////////////////////////////
// one character that is one byte to every two-dimensional encoder here and that none of //
// their denser modes holds (e with an acute accent, Latin-1 233): a value of them is the //
// symbol of that many plain bytes //
/////////////////////////////////////////////////////////////////////////////////////////////////
private static final String BYTE = Character.toString(0xE9);
private final String id;
private final Placement placement;
private final Placement.Align align;
private final Placement.Valign valign;
private final int rotation;
private final List<Symbology> symbologies;
private final String symbologyPath;
private final String value;
private final String valuePath;
private final String scannerPath;
private final String aimPath;
private final Length minModule;
private final Length maxModule;
private final Length minHeight;
private final Integer quiet;
private final Integer maxLength;
private final Symbology.Profile profile;
private final ElementSource source;
/***************************************************************************
** One run of ink in a symbol, in modules from its first bar: `length`
** modules from column `column` of row `row`.
***************************************************************************/
private record Run(int column, int row, int length)
{
}
/***************************************************************************
** The bars of a symbol as the encoder gives them, without quiet zones:
** `columns` modules across and, for a two-dimensional symbol, `rows` down.
***************************************************************************/
private record Bars(int columns, int rows, List<Run> runs)
{
}
/***************************************************************************
** A fitted symbol on the label, in dots: the area it takes, quiet zones
** included, and its bars.
***************************************************************************/
private record Symbol(Frame area, List<Frame> bars)
{
}
/***************************************************************************
** Read the element. A property that is not what the schema says is
** `SCENE_INVALID` at that property.
***************************************************************************/
BarcodeElement(ElementSource source)
{
id = source.id();
placement = source.placement();
rotation = source.rotation();
this.source = source;
///////////////////////////////////////////////////////////////////////////////////////////
// a symbol sits in the middle of its box unless the scene says otherwise, so what the //
// box has to spare is more quiet zone, the same on both sides //
///////////////////////////////////////////////////////////////////////////////////////////
align = source.choice("align", Placement.Align.CENTER, Placement.Align::of);
valign = source.choice("valign", Placement.Valign.MIDDLE, Placement.Valign::of);
JsonNode stated = source.value("symbology");
JsonNode allowed = source.value("allowedSymbologies");
symbologyPath = path(source, "symbologyPath");
if((stated == null) == (symbologyPath == null))
{
throw source.invalid("symbology");
}
if(stated != null)
{
if(Symbology.of(stated.textValue()) == null)
{
throw source.invalid("symbology");
}
if(allowed != null)
{
throw source.invalid("allowedSymbologies");
}
symbologies = List.of(Symbology.of(stated.textValue()));
}
else
{
if(allowed == null || !allowed.isArray() || allowed.isEmpty())
{
throw source.invalid("allowedSymbologies");
}
List<Symbology> listed = new ArrayList<>();
for(JsonNode entry : allowed)
{
Symbology named = Symbology.of(entry.textValue());
if(named == null || listed.contains(named))
{
throw source.invalid("allowedSymbologies");
}
listed.add(named);
}
symbologies = List.copyOf(listed);
}
JsonNode literal = source.value("value");
valuePath = path(source, "valuePath");
if((literal == null) == (valuePath == null))
{
throw source.invalid("value");
}
if(literal != null && (!literal.isTextual() || literal.textValue().isEmpty() || literal.textValue().length() > MAXIMUM_CHARACTERS))
{
throw source.invalid("value");
}
value = literal == null ? null : literal.textValue();
scannerPath = path(source, "scannerSymbologyPath");
aimPath = path(source, "aimIdentifierPath");
if((scannerPath == null) != (aimPath == null))
{
throw source.invalid(scannerPath == null ? "scannerSymbologyPath" : "aimIdentifierPath");
}
minModule = more(source, "minModule");
maxModule = more(source, "maxModule");
minHeight = more(source, "minHeight");
profile = source.choice("barcodeProfile", null, Symbology.Profile::of);
int fewest = symbologies.stream().mapToInt(drawn -> Math.max(drawn.quietLeft(), drawn.quietRight())).max().orElseThrow();
quiet = whole(source, "quiet", fewest, Symbology.MAXIMUM_QUIET_MODULES);
maxLength = whole(source, "maxLength", 1, MAXIMUM_CHARACTERS);
}
/***************************************************************************
** A JSON pointer into the record, or null when the element states none.
***************************************************************************/
private static String path(ElementSource source, String name)
{
JsonNode stated = source.value(name);
if(stated == null)
{
return (null);
}
if(!stated.isTextual() || !stated.textValue().startsWith("/") || stated.textValue().length() > MAXIMUM_POINTER)
{
throw source.invalid(name);
}
return (stated.textValue());
}
/***************************************************************************
** A module size or a bar height, more than nothing, or null when the
** element states none.
***************************************************************************/
private static Length more(ElementSource source, String name)
{
Length stated = source.length(name, null, ElementSource.ABSOLUTE);
if(stated != null && stated.thousandths() <= 0)
{
throw source.invalid(name);
}
return (stated);
}
/***************************************************************************
** A whole number between two others, or null when the element states none.
***************************************************************************/
private static Integer whole(ElementSource source, String name, int least, int most)
{
JsonNode stated = source.value(name);
if(stated == null)
{
return (null);
}
if(!stated.isIntegralNumber() || !stated.canConvertToInt() || stated.intValue() < least || stated.intValue() > most)
{
throw source.invalid(name);
}
return (stated.intValue());
}
/***************************************************************************
** Where the scene states a property, in the element or in an override: the
** pointer of the refusal the source would raise for it. It is wanted for
** the refusals that are known only once the record is read or the
** resolution is chosen, which carry their own codes and numbers.
***************************************************************************/
private String pointer(String name)
{
return (source.invalid(name).diagnostic().pointer());
}
/***************************************************************************
** The id the scene declares for the barcode.
***************************************************************************/
@Override
public String id()
{
return (id);
}
/***************************************************************************
** The box of the element, by the standing rules.
***************************************************************************/
@Override
public Frame place(Layout layout)
{
return (layout.place(placement));
}
/***************************************************************************
** Everything that can refuse the barcode, with no ink: run when a scene is
** validated and again before it is painted.
***************************************************************************/
@Override
public void check(Frame frame, RenderInput input, Diagnostics diagnostics)
{
compose(frame, input, diagnostics);
}
/***************************************************************************
** What later elements must leave alone: the fitted symbol, quiet zones
** included. Where the symbol is not known, because the scene is only being
** validated and the record gives the value or the symbology, it is the
** whole box, since the symbol may be anywhere in it.
***************************************************************************/
@Override
public Frame clear(Frame frame, RenderInput input, Diagnostics diagnostics)
{
Symbol symbol = compose(frame, input, diagnostics);
return (symbol == null ? frame : symbol.area());
}
/***************************************************************************
** A symbol paints its ground and then its bars, each at most its box.
***************************************************************************/
@Override
public long paintedDots(Frame frame, int dpi)
{
return (2L * frame.width() * frame.height());
}
/***************************************************************************
** Draw the fitted symbol: its area white, quiet zones included, then its
** bars. The rest of the box is left as it was.
***************************************************************************/
@Override
public void paint(Canvas canvas, Frame frame, RenderInput input, Diagnostics diagnostics)
{
Symbol symbol = compose(frame, input, diagnostics);
canvas.fill(symbol.area(), false);
symbol.bars().forEach(bar -> canvas.fill(bar, true));
}
/***************************************************************************
** Resolve the symbology and the value, encode, fit and place. The answer is
** what to draw, or null when the record gives the value or the symbology
** and the scene is only being validated: every symbol the record could ask
** for is then fitted as far as it is known.
***************************************************************************/
private Symbol compose(Frame frame, RenderInput input, Diagnostics diagnostics)
{
int dpi = input.targetDpi == null ? input.stock.dpi() : input.targetDpi;
boolean validating = "VALIDATE".equals(input.operation);
if(valuePath != null && symbologies.stream().anyMatch(drawn -> !drawn.fixed() && (maxLength == null || !drawn.provable())))
{
diagnostics.warn("FIT_NOT_PROVEN", id, null, frame, null, null);
}
if(validating && (symbologyPath != null || valuePath != null))
{
limits(symbologies, dpi, frame, diagnostics);
for(Symbology drawn : symbologies)
{
if(valuePath == null)
{
String text = text(frame, input, diagnostics);
fit(drawn, encode(drawn, payload(drawn, text, frame, null, diagnostics), text.length(), frame, diagnostics), dpi, frame, false, diagnostics);
}
else if(drawn.fixed() || maxLength != null)
{
fit(drawn, longest(drawn, frame, diagnostics), dpi, frame, false, diagnostics);
}
}
return (null);
}
Symbology symbology = symbology(frame, input, diagnostics);
limits(List.of(symbology), dpi, frame, diagnostics);
String text = text(frame, input, diagnostics);
Bars bars = encode(symbology, payload(symbology, text, frame, validating ? null : input, diagnostics), text.length(), frame, diagnostics);
ModuleFit.Fit fit = fit(symbology, bars, dpi, frame, true, diagnostics);
boolean upright = rotation % 180 == 0;
boolean matrix = symbology.matrix();
int before = quiet == null ? symbology.quietLeft() : quiet;
Frame area = Layout.align(frame, upright ? fit.width() : fit.height(), upright ? fit.height() : fit.width(), align, valign);
List<Frame> drawn = new ArrayList<>();
for(Run run : bars.runs())
{
int x = (before + run.column()) * fit.module();
int y = matrix ? (before + run.row()) * fit.module() : 0;
int width = run.length() * fit.module();
int height = matrix ? fit.module() : fit.height();
drawn.add(switch(rotation)
{
case 90 -> new Frame(area.x() + fit.height() - y - height, area.y() + x, height, width);
case 180 -> new Frame(area.x() + fit.width() - x - width, area.y() + fit.height() - y - height, width, height);
case 270 -> new Frame(area.x() + y, area.y() + fit.width() - x - width, height, width);
default -> new Frame(area.x() + x, area.y() + y, width, height);
});
}
return (new Symbol(area, drawn));
}
/***************************************************************************
** The smallest module a symbology is drawn at here, in dots: what the
** scene states, else what the symbology's profile asks.
***************************************************************************/
private int minimum(Symbology symbology, int dpi)
{
return (minModule == null ? symbology.narrowest(profile, dpi) : minModule.module(dpi));
}
/***************************************************************************
** What the scene's module limits come to at this resolution, for the
** symbologies that may be drawn. A minimum the scene states below what one
** of them asks for is the choice of its author and is drawn, with a
** warning every time. A maximum goes up to a whole dot as the minimum
** does, so stating the same length for both is one module at every
** resolution; a maximum under the minimum is a mistake in the scene.
***************************************************************************/
private void limits(List<Symbology> drawn, int dpi, Frame frame, Diagnostics diagnostics)
{
int recommended = drawn.stream().mapToInt(symbology -> symbology.narrowest(profile, dpi)).max().orElseThrow();
int minimum = minModule == null ? recommended : minModule.module(dpi);
if(minimum < recommended)
{
diagnostics.warn("BARCODE_MODULE_BELOW_RECOMMENDED", id, null, frame, Map.of("minModuleDots", minimum), Map.of("minModuleDots", recommended));
}
if(maxModule != null && maxModule.module(dpi) < minimum)
{
throw diagnostics.refuse("SCENE_INVALID", id, pointer("maxModule"), frame, Map.of("maxModuleDots", maxModule.module(dpi)), Map.of("minModuleDots", minimum));
}
}
/***************************************************************************
** The symbology to draw: the one the scene states, or the one the record
** names, which must be one the scene allows.
***************************************************************************/
private Symbology symbology(Frame frame, RenderInput input, Diagnostics diagnostics)
{
if(symbologyPath == null)
{
return (symbologies.getFirst());
}
JsonNode named = input.context.at(symbologyPath);
if(!named.isTextual())
{
throw diagnostics.refuse("VALUE_MISSING", id, pointer("symbologyPath"), frame, null, null);
}
Symbology symbology = Symbology.of(named.textValue());
if(symbology == null || !symbologies.contains(symbology))
{
throw diagnostics.refuse("SCENE_INVALID", id, pointer("symbologyPath"), frame, null, null);
}
return (symbology);
}
/***************************************************************************
** The value: the literal, or the text, number or true/false of the record
** as JSON writes it, and no longer than the scene declares.
***************************************************************************/
private String text(Frame frame, RenderInput input, Diagnostics diagnostics)
{
String text = value;
if(valuePath != null)
{
JsonNode bound = input.context.at(valuePath);
if((!bound.isTextual() && !bound.isNumber() && !bound.isBoolean()) || bound.asText().isEmpty())
{
throw diagnostics.refuse("VALUE_MISSING", id, pointer("valuePath"), frame, null, null);
}
text = bound.asText();
}
int most = maxLength == null ? MAXIMUM_CHARACTERS : maxLength;
if(text.length() > most)
{
throw diagnostics.refuse("VALUE_TOO_LONG", id, null, frame, Map.of("characters", text.length()), Map.of("characters", most));
}
return (text);
}
/***************************************************************************
** What the encoder is given for a value, held to the rules of its
** symbology and, when the scene names a scanner profile and a record is
** being read, to that profile. A value that would not read back as itself
** is refused at the property that gives it, with only its numbers. An
** element string built from `gs1` entries would enter here.
***************************************************************************/
private String payload(Symbology symbology, String text, Frame frame, RenderInput input, Diagnostics diagnostics)
{
String code = symbology == Symbology.GS1_128 ? "GS1_INVALID" : "VALUE_NOT_ENCODABLE";
String at = pointer(valuePath == null ? "value" : "valuePath");
Payload.Checked checked = Payload.of(symbology, text);
if(checked.encoded() == null)
{
throw diagnostics.refuse(code, id, at, frame, checked.measured(), checked.limit());
}
if(scannerPath == null || input == null)
{
return (checked.encoded());
}
JsonNode label = input.context.at(scannerPath);
JsonNode identifier = input.context.at(aimPath);
if(!label.isTextual() || !identifier.isTextual())
{
throw diagnostics.refuse("VALUE_MISSING", id, pointer(label.isTextual() ? "aimIdentifierPath" : "scannerSymbologyPath"), frame, null, null);
}
try
{
return (ScannerSymbology.payload(symbology.id(), text, label.textValue(), identifier.textValue()));
}
catch(IllegalArgumentException rejected)
{
////////////////////////////////////////////////////////////////////////////////////////
// the closed codes of the profile: what the scanner reported does not name this //
// symbology, or the value is not one the profile can hold //
////////////////////////////////////////////////////////////////////////////////////////
if("SCANNER_BARCODE_PROFILE_UNSUPPORTED".equals(rejected.getMessage()))
{
throw diagnostics.refuse("SCENE_INVALID", id, pointer("scannerSymbologyPath"), frame, null, null);
}
throw diagnostics.refuse(code, id, at, frame, Map.of("characters", text.length()), null);
}
}
/***************************************************************************
** The bars of a value, from the encoder of version 1 at one dot to the
** module, with the quiet zones it was asked for taken off again. A symbol
** of more modules than that encoder draws does not fit any box. Anything
** else the encoder refuses is a value the symbology cannot hold; what it
** says may quote the value, so nothing of it is kept: the refusal is the
** count of characters.
***************************************************************************/
private Bars encode(Symbology symbology, String payload, int characters, Frame frame, Diagnostics diagnostics)
{
int margin = symbology.matrix() ? 4 : 10;
BufferedImage modules;
try
{
modules = Barcodes.renderForFormat("ZPL", symbology.id(), payload, 1, margin, Wire.JSON.createObjectNode());
}
catch(IllegalArgumentException | OkapiInputException rejected)
{
if("BARCODE_BITMAP_LIMIT".equals(rejected.getMessage()))
{
throw diagnostics.refuse("BARCODE_DOES_NOT_FIT", id, null, frame, Map.of("characters", characters), Map.of("modules", MAXIMUM_MODULES));
}
throw diagnostics.refuse(symbology == Symbology.GS1_128 ? "GS1_INVALID" : "VALUE_NOT_ENCODABLE", id, pointer(valuePath == null ? "value" : "valuePath"), frame, Map.of("characters", characters), null);
}
///////////////////////////////////////////////////////////////////////////////////////////
// a linear symbol is the runs of one row through its middle, since every bar is the //
// whole height; a two-dimensional symbol is the runs of every row //
///////////////////////////////////////////////////////////////////////////////////////////
boolean matrix = symbology.matrix();
int columns = modules.getWidth() - 2 * margin;
int rows = matrix ? modules.getHeight() - 2 * margin : 0;
List<Run> runs = new ArrayList<>();
int first = matrix ? margin : modules.getHeight() / 2;
int last = matrix ? margin + rows - 1 : first;
for(int row = first; row <= last; row++)
{
int start = -1;
for(int column = 0; column <= columns; column++)
{
boolean ink = column < columns && (modules.getRGB(margin + column, row) & 0xFFFFFF) == 0;
if(ink && start < 0)
{
start = column;
}
if(!ink && start >= 0)
{
runs.add(new Run(start, row - first, column - start));
start = -1;
}
}
}
return (new Bars(columns, rows, runs));
}
/***************************************************************************
** The symbol to fit for a value that is not known yet. A linear symbology
** has the largest a value of the declared length can need, by arithmetic. A
** two-dimensional one is asked for that many bytes, which is not its
** largest and so proves nothing; when it cannot hold them, the length the
** scene declares does not fit.
***************************************************************************/
private Bars longest(Symbology symbology, Frame frame, Diagnostics diagnostics)
{
if(!symbology.matrix())
{
return (new Bars(symbology.widest(maxLength == null ? 0 : maxLength), 0, List.of()));
}
try
{
BufferedImage modules = Barcodes.renderForFormat("ZPL", symbology.id(), BYTE.repeat(maxLength), 1, 4, Wire.JSON.createObjectNode());
return (new Bars(modules.getWidth() - 8, modules.getHeight() - 8, List.of()));
}
catch(IllegalArgumentException | OkapiInputException tooLong)
{
throw diagnostics.refuse("BARCODE_DOES_NOT_FIT", id, pointer("maxLength"), frame, Map.of("characters", maxLength), null);
}
}
/***************************************************************************
** Fit a symbol of these bars to the box, with its quiet zones, and refuse
** one that does not fit at the smallest module with the numbers that say
** why. A symbol that is drawn reports the module chosen. Bars shorter than
** the symbology asks are drawn only when the scene states its own
** `minHeight`, and then with a warning every time.
***************************************************************************/
private ModuleFit.Fit fit(Symbology symbology, Bars bars, int dpi, Frame frame, boolean drawn, Diagnostics diagnostics)
{
int before = quiet == null ? symbology.quietLeft() : quiet;
int after = quiet == null ? symbology.quietRight() : quiet;
ModuleFit.Height asked = symbology.height(bars.columns(), dpi);
ModuleFit.Height height = symbology.matrix() ? null : minHeight == null ? asked : new ModuleFit.Height(bars.columns(), minHeight.module(dpi), 0, 1);
boolean upright = rotation % 180 == 0;
ModuleFit.Request request = new ModuleFit.Request(before + bars.columns() + after, symbology.matrix() ? bars.rows() + 2 * before : 0, upright ? frame.width() : frame.height(),
upright ? frame.height() : frame.width(), minimum(symbology, dpi), maxModule == null ? Integer.MAX_VALUE : maxModule.module(dpi), height);
ModuleFit.Fit fit = ModuleFit.fit(request);
Map<String, Integer> measured = Map.of("modules", request.columns(), "quietLeftModules", before, "quietRightModules", after, "moduleDots", fit.module(), "widthDots", fit.width(),
"heightDots", fit.height(), "moduleMicrometres", Math.toIntExact(((long) fit.module() * MICROMETRES_PER_INCH + dpi / 2) / dpi));
Map<String, Integer> limit = Map.of("widthDots", request.along(), "heightDots", request.across(), "minModuleDots", request.minimum());
if(!fit.fits())
{
throw diagnostics.refuse("BARCODE_DOES_NOT_FIT", id, null, frame, measured, limit);
}
if(height != null && fit.height() < asked.at(fit.module()))
{
diagnostics.warn("BARCODE_HEIGHT_BELOW_RECOMMENDED", id, null, frame, Map.of("heightDots", fit.height()), Map.of("heightDots", asked.at(fit.module())));
}
if(drawn)
{
diagnostics.inform("BARCODE_MODULE", id, null, frame, measured, limit);
}
return (fit);
}
}
@@ -30,32 +30,38 @@ import com.kingsrook.qbits.renderer.scene2.UnavailableElement;
/******************************************************************************* /*******************************************************************************
** Barcodes: a symbol fitted to its box in whole-dot modules, never below its ** Barcodes: a symbol fitted to its box in whole-dot modules, never below its
** stated minimum. ** stated minimum, and placed in the box by `align` and `valign`, in the
** middle unless the scene says otherwise.
** **
** This is the placeholder of the scene 2 core: a `barcode` element is parsed and ** `gs1` (an element string built from application identifiers) and `hri` (the
** placed, then refused as `RENDERER_TOO_OLD`. The package that draws it ** human-readable line) are declared and not yet read: an element that states
** replaces this class and nothing else. ** either is parsed and placed, then refused as `RENDERER_TOO_OLD`, so it is
** never drawn without what it asked for.
*******************************************************************************/ *******************************************************************************/
public final class BarcodeFactory implements ElementFactory public final class BarcodeFactory implements ElementFactory
{ {
/*************************************************************************** /***************************************************************************
** The property names the design gives a `barcode` element. Their values are ** The property names the design gives a `barcode` element.
** not read yet.
***************************************************************************/ ***************************************************************************/
@Override @Override
public Set<String> properties() public Set<String> properties()
{ {
return (Set.of("symbology", "symbologyPath", "allowedSymbologies", "value", "valuePath", "minModule", "maxModule", "quiet", "gs1", "hri", "scannerSymbologyPath", "aimIdentifierPath", "rotation")); return (Set.of("symbology", "symbologyPath", "allowedSymbologies", "value", "valuePath", "minModule", "maxModule", "quiet", "gs1", "hri", "scannerSymbologyPath", "aimIdentifierPath", "rotation",
"barcodeProfile", "minHeight", "maxLength"));
} }
/*************************************************************************** /***************************************************************************
** The element, placed and then refused by name. ** The barcode, or the placeholder for one this renderer cannot draw yet.
***************************************************************************/ ***************************************************************************/
@Override @Override
public SceneElement create(ElementSource source) public SceneElement create(ElementSource source)
{ {
return (new UnavailableElement(source)); if(source.value("gs1") != null || source.value("hri") != null)
{
return (new UnavailableElement(source));
}
return (new BarcodeElement(source));
} }
} }
@@ -0,0 +1,124 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
/*******************************************************************************
** The module of a barcode in its box. A module is the width of the narrowest
** bar, and on a label composed as one picture it is a whole number of printer
** dots. The rule: the module is the largest whole number of dots at which the
** symbol, its quiet zones included, fits the box, never more than the stated
** maximum, and the symbol does not fit when that is less than the minimum.
**
** A two-dimensional symbol is fitted on both axes. A linear symbol is fitted
** along its width, and its bars take the whole height of the box; that height
** must be what the symbology asks of bars as wide as these, so a module that
** would make the symbol too wide for its height is not taken either. Integer
** arithmetic only: no fraction of a dot takes part.
**
** The numbers of each symbology (quiet zones, narrowest bar, bar height) are
** in `Symbology`.
*******************************************************************************/
final class ModuleFit
{
/***************************************************************************
** Utility class.
***************************************************************************/
private ModuleFit()
{
}
/***************************************************************************
** How tall the bars of a linear symbol must be: at least `least` dots, and
** at least `numerator / denominator` of the width of its `bars` modules,
** first bar to last. A numerator of nothing leaves only the length.
***************************************************************************/
record Height(int bars, int least, int numerator, int denominator)
{
/************************************************************************
** The dots the bars must be tall when a module is this many dots, the
** share of the width taken up to a whole dot.
************************************************************************/
int at(int module)
{
return (Math.max(least, Math.toIntExact(((long) bars * module * numerator + denominator - 1) / denominator)));
}
}
/***************************************************************************
** What is fitted: a symbol of `columns` modules across, quiet zones
** included, in a box of `along` dots on the width of the symbol and
** `across` dots on its height, with the module held between two whole
** numbers of dots. A two-dimensional symbol is `rows` modules down, quiet
** zones included, and has no `height`; a linear symbol has no rows and the
** rule for the height of its bars.
***************************************************************************/
record Request(int columns, int rows, int along, int across, int minimum, int maximum, Height height)
{
}
/***************************************************************************
** The answer. `module` is the largest module that fits, in dots, and may be
** less than the minimum, or nothing. `width` and `height` are the dots the
** symbol takes at that module when it fits, and the dots it would need at
** the minimum when it does not: for a linear symbol that fits, the height
** is the whole of the box across its bars.
***************************************************************************/
record Fit(int module, int width, int height, boolean fits)
{
}
/***************************************************************************
** Fit one symbol. The largest module is the box divided by the modules,
** rounded down, so the symbol and its quiet zones never leave the box; for
** a linear symbol it is also the largest at which the box is as tall as
** bars of that width must be.
***************************************************************************/
static Fit fit(Request request)
{
int module = Math.min(request.maximum(), request.along() / request.columns());
Height height = request.height();
if(height == null)
{
module = Math.min(module, request.across() / request.rows());
}
else if(height.least() > request.across())
{
module = 0;
}
else if(height.numerator() > 0)
{
module = (int) Math.min(module, (long) request.across() * height.denominator() / ((long) height.bars() * height.numerator()));
}
boolean fits = module >= request.minimum();
int drawn = fits ? module : request.minimum();
int tall = height == null ? request.rows() * drawn : fits ? request.across() : height.at(drawn);
return (new Fit(module, request.columns() * drawn, tall, fits));
}
}
@@ -0,0 +1,200 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.util.Map;
/*******************************************************************************
** What the encoder is given for a value, or why the value is not drawn. A
** barcode on a label is scanned, so the one failure that matters most is a
** symbol that reads as something other than the value it was given. The
** encoder would make one in four ways, and each is refused here before the
** encoder sees the value:
**
** - It reads `\<FNC1>` to `\<FNC4>` in a value as function characters. A
** record could so turn a plain Code 128 into a GS1-128 of its own choosing,
** set the reader-programming flag, or change a character; and where a
** symbology has no such character the escape is dropped, so the symbol
** differs from the value. No value may hold the two characters that begin
** an escape, in any symbology. A function character enters a symbol only
** through its symbology: `gs1-128` adds its own FNC1.
** - It pads Interleaved 2 of 5 of an odd number of digits with a zero in
** front. An odd number of digits is not drawn.
** - It takes an EAN or UPC value without its check digit, works the digit out
** and pads a short value with zeros in front, so a mistyped number prints
** as a valid symbol for another product. Here the value is the whole
** number, check digit included (13 digits for `ean13`, 8 for `ean8`, 12
** for `upca`, 8 for `upce`); the check digit is verified, and the encoder
** is given the digits before it.
** - It checks the lengths of a GS1 element string and not its check digits.
** The key of each application identifier that ends in a check digit is
** verified.
**
** A refusal carries numbers only: how many characters, which application
** identifier of the fixed list below, and that a check digit does not match.
** Nothing of the value is in it.
*******************************************************************************/
final class Payload
{
/////////////////////////////////////////////////////////////////////////////////////////////////
// the two characters every escape of the encoder begins with (`Symbol.FNC1_STRING` and its //
// three siblings of OkapiBarcode 0.5.7), refused whatever follows them //
/////////////////////////////////////////////////////////////////////////////////////////////////
static final String ESCAPE = "\\<";
/////////////////////////////////////////////////////////////////////////////////////////////////
// the application identifiers whose data begins with a key that ends in a GS1 check digit, //
// each with where its key starts and how many digits it is. The list is the `csum` entries //
// of the GS1 Syntax Dictionary as the bundled Zint 2.16.0 carries them //
// (`backend/gs1_lint.h`, generated from gs1-syntax-dictionary.txt): SSCC (00), GTIN (01, 02, //
// 03), GDTI (253), GCN (255), GSIN (402), the GLNs (410 to 417), GRAI (8003, after its //
// leading zero), ITIP (8006, 8026) and GSRN (8017, 8018). The identifiers 8013 and 8014 end //
// in a pair of check characters of another kind, which is not verified here. //
/////////////////////////////////////////////////////////////////////////////////////////////////
private static final Map<String, int[]> KEYS = Map.ofEntries(Map.entry("00", new int[] {0, 18}), Map.entry("01", new int[] {0, 14}), Map.entry("02", new int[] {0, 14}), Map.entry("03", new int[] {0, 14}),
Map.entry("253", new int[] {0, 13}), Map.entry("255", new int[] {0, 13}), Map.entry("402", new int[] {0, 17}), Map.entry("410", new int[] {0, 13}), Map.entry("411", new int[] {0, 13}),
Map.entry("412", new int[] {0, 13}), Map.entry("413", new int[] {0, 13}), Map.entry("414", new int[] {0, 13}), Map.entry("415", new int[] {0, 13}), Map.entry("416", new int[] {0, 13}),
Map.entry("417", new int[] {0, 13}), Map.entry("8003", new int[] {1, 13}), Map.entry("8006", new int[] {0, 14}), Map.entry("8026", new int[] {0, 14}), Map.entry("8017", new int[] {0, 18}),
Map.entry("8018", new int[] {0, 18}));
private static final Map<Symbology, Integer> RETAIL = Map.of(Symbology.EAN13, 13, Symbology.EAN8, 8, Symbology.UPCA, 12, Symbology.UPCE, 8);
/***************************************************************************
** Utility class.
***************************************************************************/
private Payload()
{
}
/***************************************************************************
** The answer for one value: what the encoder is given, or, when that is
** null, the numbers of the refusal.
***************************************************************************/
record Checked(String encoded, Map<String, Integer> measured, Map<String, Integer> limit)
{
}
/***************************************************************************
** Whether a value holds the beginning of an escape the encoder reads.
***************************************************************************/
static boolean escapes(String value)
{
return (value.contains(ESCAPE));
}
/***************************************************************************
** Hold a value to the rules of its symbology.
***************************************************************************/
static Checked of(Symbology symbology, String value)
{
Map<String, Integer> characters = Map.of("characters", value.length());
if(escapes(value))
{
return (new Checked(null, characters, null));
}
if(symbology == Symbology.ITF && value.length() % 2 != 0)
{
return (new Checked(null, characters, Map.of("charactersMultipleOf", 2)));
}
Integer whole = RETAIL.get(symbology);
if(whole != null)
{
if(value.length() != whole)
{
return (new Checked(null, characters, Map.of("characters", whole)));
}
String body = value.substring(0, whole - 1);
if(!checked((symbology == Symbology.UPCE ? expanded(body) : body) + value.charAt(whole - 1)))
{
return (new Checked(null, Map.of("characters", value.length(), "checkDigitMatches", 0), Map.of("characters", whole, "checkDigitMatches", 1)));
}
return (new Checked(body, null, null));
}
if(symbology == Symbology.GS1_128)
{
for(String element : value.split("\\[", -1))
{
int close = element.indexOf(']');
int[] key = close < 0 ? null : KEYS.get(element.substring(0, close));
if(key != null && (element.length() < close + 1 + key[0] + key[1] || !checked(element.substring(close + 1 + key[0], close + 1 + key[0] + key[1]))))
{
return (new Checked(null, Map.of("characters", value.length(), "applicationIdentifier", Integer.parseInt(element.substring(0, close)), "checkDigitMatches", 0), Map.of("checkDigitMatches", 1)));
}
}
}
return (new Checked(value, null, null));
}
/***************************************************************************
** Whether text is digits that end in their own GS1 check digit: from the
** right the digits weigh 1, 3, 1, 3 and so on, the check digit first, and
** the weighted sum is a multiple of ten. It is the one rule of GTIN, SSCC,
** GLN and the other keys, whatever their length.
***************************************************************************/
static boolean checked(String digits)
{
int sum = 0;
for(int index = 0; index < digits.length(); index++)
{
char digit = digits.charAt(index);
if(digit < '0' || digit > '9')
{
return (false);
}
sum += (digit - '0') * ((digits.length() - index) % 2 == 0 ? 3 : 1);
}
return (sum % 10 == 0);
}
/***************************************************************************
** The eleven digits of the UPC-A number that the seven digits of a UPC-E
** number stand for (the number system, then six): the check digit of a
** UPC-E symbol is that of the longer number. The last of the six says
** where the zeros were taken out.
***************************************************************************/
static String expanded(String body)
{
String six = body.substring(1);
char last = six.charAt(5);
String ten = switch(last)
{
case '0', '1', '2' -> six.substring(0, 2) + last + "0000" + six.substring(2, 5);
case '3' -> six.substring(0, 3) + "00000" + six.substring(3, 5);
case '4' -> six.substring(0, 4) + "00000" + six.charAt(4);
default -> six.substring(0, 5) + "0000" + last;
};
return (body.charAt(0) + ten);
}
}
@@ -0,0 +1,320 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import com.kingsrook.qbits.renderer.scene2.Length;
/*******************************************************************************
** The rules of each fit-qualified symbology, in one reviewed place: its quiet
** zones, the narrowest bar it is drawn at by default, how tall its bars must
** be, and the widest symbol a value of a stated length can need. Every number
** has its source beside it. A number that was chosen here, and is not taken
** from a specification, says so.
**
** Sources, by the short names the table uses:
**
** - GS1: the GS1 General Specifications. Section 5.2.3.4 gives the quiet zones
** of the EAN/UPC symbols in modules (EAN-13: 11 left, 7 right; EAN-8: 7 and
** 7; UPC-A: 9 and 9; UPC-E: 9 and 7). Section 5.2.3.2 gives their height at
** the nominal 0.330 mm module: 22.85 mm for EAN-13, UPC-A and UPC-E, which
** is 69.24 modules, and 18.23 mm for EAN-8, 55.24 modules; the height scales
** with the module. The symbol specification tables of section 5.12 give the
** narrowest bar: 0.264 mm for EAN/UPC at general retail point of sale
** (table 1) and 0.495 mm for ITF-14 and GS1-128 scanned in general
** distribution, logistic units among them (table 5). EAN/UPC scanned in
** general distribution is given the same 0.495 mm here, as the tables for
** general distribution are remembered to; those were not read again.
** - ISO/IEC 15417 (Code 128, and so GS1-128): a quiet zone of 10 modules on
** each side, and in Annex G a bar height of at least 5 mm or 15% of the
** length of the symbol, whichever is greater.
** - ISO/IEC 16388 (Code 39), ISO/IEC 16390 (Interleaved 2 of 5) and the AIM
** specification of Code 93: a quiet zone of 10 modules on each side. Their
** bar heights were not read for this table; they are held to the rule of
** ISO/IEC 15417, the one the same scanners are specified against.
** - ISO/IEC 18004 (QR Code): a quiet zone of 4 modules on every side. Data
** Matrix (ISO/IEC 16022) asks for 1, PDF417 (ISO/IEC 15438) for 2 and Aztec
** Code (ISO/IEC 24778) for none; all three keep the 4 that version 1 gives
** every two-dimensional symbol, which is more than each asks.
** - design: section 4.3 of the layout design, 0.25 mm for a linear symbol and
** 0.375 mm for a two-dimensional one. They are the design's own proposals,
** to be confirmed by printing and scanning before a final release.
**
** Read again when this table was written: the 0.495 mm and 0.264 mm of GS1,
** the quiet zones of EAN-13 and EAN-8, the EAN/UPC heights, and the 5 mm and
** 15% of ISO/IEC 15417. The quiet zones of UPC-A and UPC-E and the 10 modules
** of Code 39, Code 93 and Interleaved 2 of 5 are as remembered.
**
** The width of a symbol in modules was measured from the encoder and is held
** to it by test: Code 128, and so GS1-128, is 11 modules for each symbol
** character and 35 for its start, check and stop; Code 39 is 13 for each
** character and 25; Code 93 is 9 for each symbol character, two of which a
** lower-case letter needs, and 37; Interleaved 2 of 5 is 9 for each digit and
** 9; the EAN/UPC symbols are 95, 67, 95 and 51 modules whatever their digits.
*******************************************************************************/
enum Symbology
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// the columns, in order: the id; whether the symbology is two-dimensional; the quiet zone in modules, //
// left (every side of a two-dimensional symbol) and right; the narrowest bar in micrometres under the //
// profiles `none` (design), `gs1-general` (GS1 table 1) and `gs1-logistics` (GS1 general distribution); //
// the profile taken when the scene names none; the height of the bars as a share of their width //
// (numerator, denominator) and as a least length in micrometres; the modules of the widest symbol for //
// each character and besides //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
CODE128("code128", false, 10, 10, 250, 250, 250, Profile.NONE, 15, 100, 5000, 11, 35),
CODE39("code39", false, 10, 10, 250, 250, 250, Profile.NONE, 15, 100, 5000, 13, 25),
CODE93("code93", false, 10, 10, 250, 250, 250, Profile.NONE, 15, 100, 5000, 18, 37),
ITF("itf", false, 10, 10, 250, 250, 495, Profile.GS1_LOGISTICS, 15, 100, 5000, 9, 9),
GS1_128("gs1-128", false, 10, 10, 250, 250, 495, Profile.GS1_LOGISTICS, 15, 100, 5000, 11, 24),
EAN13("ean13", false, 11, 7, 250, 264, 495, Profile.GS1_GENERAL, 6924, 9500, 0, 0, 95),
EAN8("ean8", false, 7, 7, 250, 264, 495, Profile.GS1_GENERAL, 5524, 6700, 0, 0, 67),
UPCA("upca", false, 9, 9, 250, 264, 495, Profile.GS1_GENERAL, 6924, 9500, 0, 0, 95),
UPCE("upce", false, 9, 7, 250, 264, 495, Profile.GS1_GENERAL, 6924, 5100, 0, 0, 51),
QR("qr", true, 4, 4, 375, 375, 375, Profile.NONE, 0, 1, 0, 0, 0),
DATAMATRIX("datamatrix", true, 4, 4, 375, 375, 375, Profile.NONE, 0, 1, 0, 0, 0),
PDF417("pdf417", true, 4, 4, 375, 375, 375, Profile.NONE, 0, 1, 0, 0, 0),
AZTEC("aztec", true, 4, 4, 375, 375, 375, Profile.NONE, 0, 1, 0, 0, 0);
/////////////////////////////////////////////////////////////////////////////////////////////////
// the most blank modules a scene may ask for on a side, the limit version 1 gives its encoders //
/////////////////////////////////////////////////////////////////////////////////////////////////
static final int MAXIMUM_QUIET_MODULES = 64;
private final String id;
private final boolean matrix;
private final int quietLeft;
private final int quietRight;
private final int none;
private final int general;
private final int logistics;
private final Profile standard;
private final int heightNumerator;
private final int heightDenominator;
private final int heightMicrometres;
private final int widestEach;
private final int widestFixed;
/***************************************************************************
** Which rule gives the narrowest bar a symbol is drawn at when the scene
** states no `minModule`: none beyond the design's own, the GS1 rule for
** general retail, or the GS1 rule for general distribution and logistic
** units. A scene names one with `barcodeProfile`; without it each
** symbology takes its `standard` profile, the strictest GS1 rule written
** for that symbology's own use: general distribution for GS1-128 and
** Interleaved 2 of 5 (the carrier of ITF-14), general retail for EAN/UPC.
***************************************************************************/
enum Profile
{
NONE("none"), GS1_GENERAL("gs1-general"), GS1_LOGISTICS("gs1-logistics");
private final String word;
/************************************************************************
** The word a scene writes.
************************************************************************/
Profile(String word)
{
this.word = word;
}
/************************************************************************
** The profile a scene word names, or null.
************************************************************************/
static Profile of(String word)
{
for(Profile profile : values())
{
if(profile.word.equals(word))
{
return (profile);
}
}
return (null);
}
}
/***************************************************************************
** One row of the table.
***************************************************************************/
Symbology(String id, boolean matrix, int quietLeft, int quietRight, int none, int general, int logistics, Profile standard, int heightNumerator, int heightDenominator, int heightMicrometres,
int widestEach, int widestFixed)
{
this.id = id;
this.matrix = matrix;
this.quietLeft = quietLeft;
this.quietRight = quietRight;
this.none = none;
this.general = general;
this.logistics = logistics;
this.standard = standard;
this.heightNumerator = heightNumerator;
this.heightDenominator = heightDenominator;
this.heightMicrometres = heightMicrometres;
this.widestEach = widestEach;
this.widestFixed = widestFixed;
}
/***************************************************************************
** The symbology a scene or a record names, or null.
***************************************************************************/
static Symbology of(String id)
{
for(Symbology symbology : values())
{
if(symbology.id.equals(id))
{
return (symbology);
}
}
return (null);
}
/***************************************************************************
** The name a scene writes and the encoder is asked for.
***************************************************************************/
String id()
{
return (id);
}
/***************************************************************************
** Whether the symbology is two-dimensional: fitted on both axes, with a
** quiet zone on all four sides and no bar height of its own.
***************************************************************************/
boolean matrix()
{
return (matrix);
}
/***************************************************************************
** The blank modules before the first bar, and for a two-dimensional symbol
** on every side.
***************************************************************************/
int quietLeft()
{
return (quietLeft);
}
/***************************************************************************
** The blank modules after the last bar.
***************************************************************************/
int quietRight()
{
return (quietRight);
}
/***************************************************************************
** The narrowest bar at a resolution, in dots, when the scene states no
** `minModule`: the physical minimum of the profile, or of the symbology's
** standard profile when the scene names none, taken up to a whole dot.
***************************************************************************/
int narrowest(Profile profile, int dpi)
{
int micrometres = switch(profile == null ? standard : profile)
{
case NONE -> none;
case GS1_GENERAL -> general;
case GS1_LOGISTICS -> logistics;
};
return (new Length(Length.Unit.MM, micrometres).module(dpi));
}
/***************************************************************************
** How tall the bars of a linear symbol of `bars` modules, first bar to
** last, must be at a resolution: the stated share of their own width and
** never less than the stated length, which is taken up to a whole dot. A
** two-dimensional symbol has no such rule.
***************************************************************************/
ModuleFit.Height height(int bars, int dpi)
{
return (new ModuleFit.Height(bars, heightMicrometres == 0 ? 0 : new Length(Length.Unit.MM, heightMicrometres).module(dpi), heightNumerator, heightDenominator));
}
/***************************************************************************
** The most modules, first bar to last, that a value of up to `characters`
** characters needs in a linear symbology. For Code 128 and Code 93 that is
** a value of characters from space to tilde, each of which is at most one
** symbol character of Code 128 and two of Code 93; Code 39 and Interleaved
** 2 of 5 hold nothing else, and an odd digit of Interleaved 2 of 5 is
** never drawn. A GS1-128 element string of that many characters, brackets
** included, is at most one symbol character fewer than its characters:
** its brackets are not drawn, and the leading FNC1 and the separators are
** fewer than they. An EAN/UPC symbol is one width whatever it holds.
***************************************************************************/
int widest(int characters)
{
return (widestEach * (this == ITF ? characters - characters % 2 : characters) + widestFixed);
}
/***************************************************************************
** Whether every value has the same width, so that no length need be
** declared to know it.
***************************************************************************/
boolean fixed()
{
return (!matrix && widestEach == 0);
}
/***************************************************************************
** Whether the largest symbol of a declared length is known, which it is by
** the arithmetic of `widest` for a linear symbology and for no
** two-dimensional one. The default `datamatrix` and `pdf417` encoders
** choose among shapes, so a shorter value may be the wider; and the `qr`
** and `aztec` encoders change mode within a value, at a cost that makes
** some values larger than as many plain bytes. So no one value of a length
** stands for the rest. Each of these statements is held to the encoder by
** test.
***************************************************************************/
boolean provable()
{
return (!matrix);
}
}
@@ -0,0 +1,345 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/*******************************************************************************
** The faces bundled with the renderer, by the name a scene writes. Each is an
** unmodified TrueType file under the SIL Open Font License 1.1, shipped in the
** jar beside its licence, provenance and hash (`/fonts`). No installed font is
** ever used and there is no fallback between faces.
**
** Every number here is in thousandths of the em, read once from the face at a
** reference size of 1000, where the bundled faces (1000 units to the em) give
** whole numbers. Layout multiplies those integers by the size and never asks
** the font for a measurement at the size it draws, so a measurement is the
** same on every machine.
**
** The four numbers after the widest character are the most any character of
** the face reaches past its own advance on the left and on the right, above
** the baseline and below it. They bound every character, so a value that was
** never seen can be proven to fit; a test recomputes them from the font file.
*******************************************************************************/
public final class Face
{
public static final Face SANS = new Face("qqq-sans", "ibm-plex-sans/IBMPlexSans-Regular.ttf", false, 0x2030, 203, 203, 1119, 245);
public static final Face SANS_BOLD = new Face("qqq-sans-bold", "ibm-plex-sans/IBMPlexSans-Bold.ttf", true, 0x2030, 245, 245, 1150, 275);
public static final Face CONDENSED_BOLD = new Face("qqq-condensed-bold", "ibm-plex-sans-condensed/IBMPlexSansCondensed-Bold.ttf", true, 0x2030, 241, 241, 1150, 275);
public static final Face MONO = new Face("qqq-mono", "jetbrains-mono/JetBrainsMono-Regular.ttf", false, 0x21, 165, 165, 1120, 400);
public static final Face MONO_BOLD = new Face("qqq-mono-bold", "jetbrains-mono/JetBrainsMono-Bold.ttf", true, 0x21, 165, 165, 1120, 400);
static final FontRenderContext CONTEXT = new FontRenderContext(null, true, true);
static final int REFERENCE = 1000;
private static final List<Face> ALL = List.of(SANS, SANS_BOLD, CONDENSED_BOLD, MONO, MONO_BOLD);
/////////////////////////////////////////////////////////////////////////////////////////////////
// characters that cannot be drawn one glyph each from left to right: controls and formats //
// (which would print nothing), marks (which need placing on the letter before) and the like //
/////////////////////////////////////////////////////////////////////////////////////////////////
private static final Set<Integer> UNDRAWN = Set.of((int) Character.CONTROL, (int) Character.FORMAT, (int) Character.SURROGATE, (int) Character.PRIVATE_USE, (int) Character.UNASSIGNED,
(int) Character.LINE_SEPARATOR, (int) Character.PARAGRAPH_SEPARATOR, (int) Character.NON_SPACING_MARK, (int) Character.ENCLOSING_MARK, (int) Character.COMBINING_SPACING_MARK);
private final String scene;
private final String file;
private final boolean bold;
private final int widest;
private final int left;
private final int right;
private final int top;
private final int bottom;
private final Map<Integer, Glyph> glyphs = new ConcurrentHashMap<>();
private Font font;
/***************************************************************************
** One character of a face: how far the pen moves, and the box its outline
** fills, from the pen (`left`, `right`) and from the baseline (`top` above,
** `bottom` below), rounded outward. A space has no ink; only U+0020 is a
** `space`, the one place a line may be broken between words.
***************************************************************************/
public record Glyph(int advance, int left, int right, int top, int bottom, boolean ink, boolean space)
{
}
/***************************************************************************
** A face, where its file is, and the bounds a test holds it to.
***************************************************************************/
private Face(String scene, String file, boolean bold, int widest, int left, int right, int top, int bottom)
{
this.scene = scene;
this.file = file;
this.bold = bold;
this.widest = widest;
this.left = left;
this.right = right;
this.top = top;
this.bottom = bottom;
}
/***************************************************************************
** The bundled set: a proportional sans in regular and bold, a condensed bold
** for long values on narrow labels, and a monospace in regular and bold.
***************************************************************************/
public static List<Face> all()
{
return (ALL);
}
/***************************************************************************
** The face a scene names, or null.
***************************************************************************/
public static Face of(String scene)
{
for(Face face : ALL)
{
if(face.scene.equals(scene))
{
return (face);
}
}
return (null);
}
/***************************************************************************
** The name a scene writes.
***************************************************************************/
public String scene()
{
return (scene);
}
/***************************************************************************
** The font file, under `/fonts` in the jar.
***************************************************************************/
public String file()
{
return (file);
}
/***************************************************************************
** Whether the strokes are bold. A regular face prints light when small.
***************************************************************************/
public boolean bold()
{
return (bold);
}
/***************************************************************************
** The character with the greatest advance, the lowest when several share it.
***************************************************************************/
public int widest()
{
return (widest);
}
/***************************************************************************
** A character no real one exceeds in any direction: the greatest advance and
** the greatest reach on each side. A line of these is at least as wide and
** as tall as a line of the same number of any characters of the face.
***************************************************************************/
public Glyph worst()
{
int advance = glyph(widest).advance();
return (new Glyph(advance, -left, advance + right, top, bottom, true, false));
}
/***************************************************************************
** The face at a size in dots, for drawing only.
***************************************************************************/
Font font(float size)
{
return (reference().deriveFont(size));
}
/***************************************************************************
** Height above the baseline that a line reserves.
***************************************************************************/
public int ascent()
{
return (Math.round(metrics().getAscent()));
}
/***************************************************************************
** Depth below the baseline that a line reserves.
***************************************************************************/
public int descent()
{
return (Math.round(metrics().getDescent()));
}
/***************************************************************************
** Extra space the face asks for between lines.
***************************************************************************/
public int leading()
{
return (Math.round(metrics().getLeading()));
}
/***************************************************************************
** The height of a capital letter, which is what legibility is judged by.
***************************************************************************/
public int capHeight()
{
return (glyph('H').top());
}
/***************************************************************************
** Whether the face can draw a character as one glyph, left to right.
***************************************************************************/
public boolean draws(int codePoint)
{
return (codePoint <= Character.MAX_VALUE && !UNDRAWN.contains(Character.getType(codePoint)) && reference().canDisplay(codePoint)
&& !Font.textRequiresLayout(new char[] {(char) codePoint}, 0, 1));
}
/***************************************************************************
** How many characters of a text the face cannot draw.
***************************************************************************/
public int missing(String text)
{
return (Math.toIntExact(text.codePoints().filter(codePoint -> !draws(codePoint)).count()));
}
/***************************************************************************
** The measurements of one character the face draws.
***************************************************************************/
public Glyph glyph(int codePoint)
{
return (glyphs.computeIfAbsent(codePoint, this::measure));
}
/***************************************************************************
** The measurements of a text the face draws, one for each character.
***************************************************************************/
public Glyph[] glyphs(String text)
{
return (text.codePoints().mapToObj(this::glyph).toArray(Glyph[]::new));
}
/***************************************************************************
** Read one character from the face at the reference size.
***************************************************************************/
private Glyph measure(int codePoint)
{
GlyphVector vector = reference().createGlyphVector(CONTEXT, new char[] {(char) codePoint});
int advance = Math.round(vector.getGlyphMetrics(0).getAdvanceX());
Rectangle2D bounds = vector.getGlyphOutline(0).getBounds2D();
if(bounds.isEmpty())
{
return (new Glyph(advance, 0, 0, 0, 0, false, codePoint == ' '));
}
return (new Glyph(advance, (int) Math.floor(bounds.getMinX()), (int) Math.ceil(bounds.getMaxX()), (int) Math.ceil(-bounds.getMinY()), (int) Math.ceil(bounds.getMaxY()), true, false));
}
/***************************************************************************
** The line metrics of the face at the reference size.
***************************************************************************/
private LineMetrics metrics()
{
return (reference().getLineMetrics("H", CONTEXT));
}
/***************************************************************************
** The face at the reference size, read from the jar the first time.
***************************************************************************/
private synchronized Font reference()
{
if(font == null)
{
font = load("/fonts/" + file);
}
return (font);
}
/***************************************************************************
** Read a TrueType file from the jar. A file that is not a font is a broken
** build, not a mistake in a scene, so it is an illegal state.
***************************************************************************/
static Font load(String resource)
{
try(InputStream stream = Face.class.getResourceAsStream(resource))
{
return (Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont((float) REFERENCE));
}
catch(IOException | FontFormatException broken)
{
throw new IllegalStateException("BUNDLED_FONT_UNREADABLE", broken);
}
}
}
@@ -0,0 +1,565 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.kingsrook.qbits.renderer.RenderInput;
import com.kingsrook.qbits.renderer.scene2.Canvas;
import com.kingsrook.qbits.renderer.scene2.Diagnostics;
import com.kingsrook.qbits.renderer.scene2.ElementSource;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.Layout;
import com.kingsrook.qbits.renderer.scene2.Length;
import com.kingsrook.qbits.renderer.scene2.Placement;
import com.kingsrook.qbits.renderer.scene2.SceneElement;
/*******************************************************************************
** A `text` element: one value in one bundled face, measured before it is
** drawn, placed in its box by `align` and `valign`, and fitted by the rule the
** element states (`TextFit`). The value is a literal (`value`) or is read from
** the record by a JSON pointer (`valuePath`).
**
** Every refusal names the element and carries numbers only: a width, a line
** count, a size, a count of characters. The value itself never enters a
** diagnostic or an exception.
**
** A bound value is not known when a scene is validated, so validation reads no
** record. With `maxLength` it proves instead that the longest value fits whole:
** that many of the face's widest character, each taken to reach as far in
** every direction as the furthest-reaching character of the face. The proof
** never cuts. When it fails the scene is refused, unless the element asked for
** cutting: then the scene stands, with the warning `FIT_NOT_PROVEN` and the
** longest length that is proven. Without `maxLength` it warns `FIT_NOT_PROVEN`
** with no number. When rendering, a value longer than `maxLength` is refused
** before any layout.
**
** The text of one scene is held to a stated amount of work (`SCENE_WORK_STEPS`):
** every character visited while fitting counts one step, every character of
** a text that is to be drawn counts `TextRaster.PEN_STEPS`, and every glyph
** the scene draws for the first time at a size, which the runtime must
** rasterise, counts `TextRaster.GLYPH_STEPS`. A scene that passes it is
** refused by name at the element that did, and so is every text after it.
** The count is integer arithmetic, the same on every machine, and the same
** whether the scene is validated or rendered.
*******************************************************************************/
final class TextElement implements SceneElement
{
static final int MAXIMUM_CHARACTERS = 1024;
static final int MAXIMUM_LINES = 64;
static final int MINIMUM_MILLIPOINTS = 1000;
static final int MAXIMUM_MILLIPOINTS = 1_000_000;
static final int DEFAULT_FLOOR_PERCENT = 70;
static final int DEFAULT_FLOOR_MILLIPOINTS = 5000;
static final int DEFAULT_THRESHOLD = 128;
/////////////////////////////////////////////////////////////////////////////////////////////////
// capital heights in dots below which thermal print is hard to read: any face under 12 (about //
// 6 pt at 203 dpi), a regular weight under 20 (about 10 pt at 203 dpi). Starting values, to //
// be confirmed on the printed specimen //
/////////////////////////////////////////////////////////////////////////////////////////////////
static final int SMALL_CAPITAL_DOTS = 12;
static final int LIGHT_CAPITAL_DOTS = 20;
/////////////////////////////////////////////////////////////////////////////////////////////////
// the work the text of one scene may take, in steps. A value of forty characters costs //
// about a hundred thousand at a size its scene has not drawn, nearly all of it for the //
// glyphs the runtime must rasterise, and under two thousand at a size it has. The //
// allowance is fifteen thousand glyphs rasterised, or three thousand fits of the longest //
// value over the widest range of sizes: about a second of the worker, where one hostile //
// scene took minutes //
/////////////////////////////////////////////////////////////////////////////////////////////////
static final int SCENE_WORK_STEPS = 64_000_000;
private static final Set<String> FIT = Set.of("maxLines", "shrinkTo", "overflow");
/////////////////////////////////////////////////////////////////////////////////////////////////
// the work of each scene, by the collector of its one render or validation, which is all a //
// text element is given that belongs to the scene; it is forgotten with the collector //
/////////////////////////////////////////////////////////////////////////////////////////////////
private static final Map<Diagnostics, Scene> SCENES = Collections.synchronizedMap(new WeakHashMap<>());
private final String id;
private final Placement placement;
private final int rotation;
private final boolean reverse;
private final Face face;
private final int size;
private final int floor;
private final Integer lineHeight;
private final int maxLines;
private final boolean truncate;
private final Integer maxLength;
private final int threshold;
private final String value;
private final String path;
private Composed composed;
/***************************************************************************
** What the text of one scene has cost so far: the steps counted, and the
** glyphs it has drawn, each a face, a size and a character in one number.
** There are never more of those than the steps allow.
***************************************************************************/
private record Scene(TextFit.Work work, Set<Long> glyphs)
{
}
/***************************************************************************
** What `check` composed, kept for the `paint` of the same pass, so a text
** is fitted once.
***************************************************************************/
private record Composed(Frame frame, RenderInput input, Diagnostics diagnostics, TextRaster.Drawing drawing)
{
/************************************************************************
** Whether this is the answer for the same box of the same pass.
************************************************************************/
boolean of(Frame other, RenderInput request, Diagnostics collector)
{
return (frame.equals(other) && input == request && diagnostics == collector);
}
}
/***************************************************************************
** Read the element. A property that is not what the schema says is
** `SCENE_INVALID` at that property, a member of `fit` at that member; a
** member `fit` does not have is reported at `fit`, since only names the
** schema declares leave the renderer. A face this renderer does not bundle
** is `FONT_UNKNOWN`.
***************************************************************************/
TextElement(ElementSource source)
{
id = source.id();
placement = source.placement();
rotation = source.rotation();
reverse = source.flag("reverse", false);
JsonNode font = source.value("font");
if(font == null || !font.isTextual())
{
throw source.invalid("font");
}
face = Face.of(font.textValue());
if(face == null)
{
throw source.refuse("FONT_UNKNOWN", "font");
}
Length stated = source.length("size", null, ElementSource.PHYSICAL);
size = stated == null ? 0 : milliPoints(stated);
if(size < MINIMUM_MILLIPOINTS || size > MAXIMUM_MILLIPOINTS)
{
throw source.invalid("size");
}
lineHeight = lineHeight(source);
threshold = integer(source, "threshold", source.value("threshold"), 1, 254, DEFAULT_THRESHOLD);
maxLength = source.value("maxLength") == null ? null : Integer.valueOf(integer(source, "maxLength", source.value("maxLength"), 1, MAXIMUM_CHARACTERS, 0));
JsonNode fit = source.value("fit") == null ? JsonNodeFactory.instance.objectNode() : source.value("fit");
if(!fit.isObject() || fit.properties().stream().anyMatch(property -> !FIT.contains(property.getKey())))
{
throw source.invalid("fit");
}
maxLines = integer(source, "fit/maxLines", fit.get("maxLines"), 1, MAXIMUM_LINES, 1);
floor = floor(source, fit.get("shrinkTo"));
String overflow = fit.has("overflow") ? fit.get("overflow").textValue() : "refuse";
if(!"refuse".equals(overflow) && !"truncate".equals(overflow))
{
throw source.invalid("fit/overflow");
}
truncate = "truncate".equals(overflow);
JsonNode literal = source.value("value");
JsonNode pointer = source.value("valuePath");
if((literal == null) == (pointer == null))
{
throw source.invalid("value");
}
if(literal != null && (!literal.isTextual() || literal.textValue().codePointCount(0, literal.textValue().length()) > MAXIMUM_CHARACTERS))
{
throw source.invalid("value");
}
if(pointer != null && (!pointer.isTextual() || pointer.textValue().length() > 256 || !pointer.textValue().startsWith("/")))
{
throw source.invalid("valuePath");
}
value = literal == null ? null : literal.textValue();
path = pointer == null ? null : pointer.textValue();
}
/***************************************************************************
** A type size in thousandths of a point. A point is a 72nd of an inch and an
** inch is 25400 micrometres, so a micrometre is 360/127 of a millipoint.
***************************************************************************/
private static int milliPoints(Length length)
{
long thousandths = length.thousandths();
return (Math.toIntExact(switch(length.unit())
{
case IN -> thousandths * 72;
case MM -> Math.floorDiv(thousandths * 360 + 63, 127);
default -> thousandths;
}));
}
/***************************************************************************
** A whole number in a range, or the fallback when the scene states none.
***************************************************************************/
private static int integer(ElementSource source, String name, JsonNode stated, int minimum, int maximum, int fallback)
{
if(stated == null)
{
return (fallback);
}
if(!stated.isIntegralNumber() || !stated.canConvertToInt() || stated.intValue() < minimum || stated.intValue() > maximum)
{
throw source.invalid(name);
}
return (stated.intValue());
}
/***************************************************************************
** The distance between baselines as a multiple of the size, in thousandths:
** a number from 0.5 to 5 with at most three decimals. Null is the face's own.
** A number too large to be a number at all (`1e400`) is refused like any
** other, not left to fail as arithmetic.
***************************************************************************/
private static Integer lineHeight(ElementSource source)
{
JsonNode stated = source.value("lineHeight");
if(stated == null)
{
return (null);
}
BigDecimal thousandths = stated.isNumber() && Double.isFinite(stated.doubleValue()) ? stated.decimalValue().movePointRight(3) : BigDecimal.ZERO;
if(thousandths.stripTrailingZeros().scale() > 0 || thousandths.compareTo(BigDecimal.valueOf(500)) < 0 || thousandths.compareTo(BigDecimal.valueOf(5000)) > 0)
{
throw source.invalid("lineHeight");
}
return (thousandths.intValueExact());
}
/***************************************************************************
** The smallest size the text may be reduced to. Stated, it is a physical
** length from one point up to the size. Otherwise it is 70% of the size and
** not below 5 pt, or the size itself when that is smaller still.
***************************************************************************/
private int floor(ElementSource source, JsonNode stated)
{
if(stated == null)
{
return (Math.min(size, Math.max(size * DEFAULT_FLOOR_PERCENT / 100, DEFAULT_FLOOR_MILLIPOINTS)));
}
try
{
Length length = Length.parse(stated.textValue());
if(length.physical() && milliPoints(length) >= MINIMUM_MILLIPOINTS && milliPoints(length) <= size)
{
return (milliPoints(length));
}
}
catch(IllegalArgumentException expected)
{
// Refused below, at the property; the cause holds nothing more.
}
throw source.invalid("fit/shrinkTo");
}
/***************************************************************************
** The id the scene declares for the text.
***************************************************************************/
@Override
public String id()
{
return (id);
}
/***************************************************************************
** The element's box, by the standing rules.
***************************************************************************/
@Override
public Frame place(Layout layout)
{
return (layout.place(placement));
}
/***************************************************************************
** Everything that can refuse the text, with no ink: run when a scene is
** validated and before it is painted. What it composed is kept for the
** paint that follows.
***************************************************************************/
@Override
public void check(Frame frame, RenderInput input, Diagnostics diagnostics)
{
composed = null;
composed = new Composed(frame, input, diagnostics, compose(frame, input, diagnostics));
}
/***************************************************************************
** Reverse text paints its box and then clears its letters, so it is counted
** twice against what one scene may paint.
***************************************************************************/
@Override
public long paintedDots(Frame frame, int dpi)
{
return ((reverse ? 2L : 1L) * frame.width() * frame.height());
}
/***************************************************************************
** Draw the text as `check` fitted it, or not at all: a text whose ink the
** rasteriser put outside what was measured is refused and leaves the label
** as it was. Reverse text is white letters on its own box filled black.
***************************************************************************/
@Override
public void paint(Canvas canvas, Frame frame, RenderInput input, Diagnostics diagnostics)
{
Composed checked = composed;
composed = null;
TextRaster.Drawing drawing = checked != null && checked.of(frame, input, diagnostics) ? checked.drawing() : compose(frame, input, diagnostics);
measured(diagnostics, id, frame, TextRaster.paint(canvas, frame, drawing, TextRaster.BAND_DOTS), drawing.block().milliPoints());
}
/***************************************************************************
** Refuse a text whose ink is not where it was measured: the element, by
** name, with how many glyphs and dots strayed and at what size. The label
** holds none of it.
***************************************************************************/
static void measured(Diagnostics diagnostics, String id, Frame frame, TextRaster.Stray stray, int milliPoints)
{
if(stray.any())
{
throw diagnostics.refuse("TEXT_DOES_NOT_FIT", id, null, frame, Map.of("glyphsOutsideMeasure", stray.glyphs(), "dotsOutsideMeasure", stray.dots(), "sizeCentipoints", milliPoints / 10),
Map.of("glyphsOutsideMeasure", 0, "dotsOutsideMeasure", 0));
}
}
/***************************************************************************
** Compose the text within the work its scene may take, or refuse the
** element by name with the steps counted against the steps allowed.
***************************************************************************/
private TextRaster.Drawing compose(Frame frame, RenderInput input, Diagnostics diagnostics)
{
Scene scene = SCENES.computeIfAbsent(diagnostics, collector -> new Scene(new TextFit.Work(SCENE_WORK_STEPS), new HashSet<>()));
try
{
return (compose(frame, input, diagnostics, scene));
}
catch(TextFit.Exhausted exhausted)
{
throw diagnostics.refuse("SCENE_INVALID", id, diagnostics.pointer(id), frame, Map.of("textWorkSteps", Math.toIntExact(Math.min(scene.work().spent(), Integer.MAX_VALUE))), Map.of("textWorkSteps", SCENE_WORK_STEPS));
}
}
/***************************************************************************
** Resolve the value, hold it to its length and to the face, and fit it. The
** answer is what to draw, or null when a bound value is only being
** validated. A text that is only validated is also held to what the
** rasteriser would do with it, glyph by glyph, with no ink.
***************************************************************************/
private TextRaster.Drawing compose(Frame frame, RenderInput input, Diagnostics diagnostics, Scene scene)
{
TextFit.Work work = scene.work();
int reserved = input.reservedAssetNames().size();
if(reserved > 0)
{
throw diagnostics.refuse("RESERVED_FONT_NAME", id, null, frame, Map.of("reservedAssets", reserved), Map.of("reservedAssets", 0));
}
int dpi = input.targetDpi == null ? input.stock.dpi() : input.targetDpi;
boolean upright = rotation % 180 == 0;
boolean validate = "VALIDATE".equals(input.operation);
TextFit.Request request = new TextFit.Request(face, upright ? frame.width() : frame.height(), upright ? frame.height() : frame.width(), dpi, size, floor, lineHeight, maxLines, truncate);
if(path != null && maxLength == null)
{
diagnostics.warn("FIT_NOT_PROVEN", id, null, frame, null, null);
}
if(path != null && validate)
{
legibility(maxLength == null ? size : proven(request, frame, diagnostics, work), dpi, frame, diagnostics);
return (null);
}
String text = path == null ? value : bound(input.context.at(path), frame, diagnostics);
int characters = text.codePointCount(0, text.length());
int longest = maxLength == null ? MAXIMUM_CHARACTERS : maxLength;
if(characters > longest)
{
throw diagnostics.refuse("VALUE_TOO_LONG", id, null, frame, Map.of("characters", characters), Map.of("characters", longest));
}
int missing = face.missing(text);
if(missing > 0)
{
throw diagnostics.refuse("FONT_MISSING_GLYPH", id, null, frame, Map.of("missingGlyphs", missing, "characters", characters), Map.of("missingGlyphs", 0));
}
TextFit.Block block = fitted(request, face.glyphs(text), frame, diagnostics, work);
long drawn = (long) Face.all().indexOf(face) << 48 | (long) block.milliPoints() << 16;
long fresh = text.codePoints().filter(codePoint -> scene.glyphs().add(drawn | codePoint)).count();
work.spend(fresh * TextRaster.GLYPH_STEPS + (long) characters * TextRaster.PEN_STEPS);
if(block.milliPoints() < size)
{
diagnostics.inform("TEXT_SHRUNK", id, null, frame, Map.of("sizeCentipoints", block.milliPoints() / 10), Map.of("sizeCentipoints", size / 10, "floorCentipoints", floor / 10));
}
if(block.lines().size() > 1)
{
diagnostics.inform("TEXT_WRAPPED", id, null, frame, Map.of("lines", block.lines().size()), Map.of("lines", maxLines));
}
if(block.truncated())
{
diagnostics.warn("TEXT_TRUNCATED", id, null, frame, Map.of("characters", block.characters(), "shownCharacters", block.shown(), "lines", block.lines().size()), Map.of("lines", maxLines));
}
legibility(block.milliPoints(), dpi, frame, diagnostics);
TextRaster.Drawing drawing = new TextRaster.Drawing(face, text, block, placement.align(), placement.valign(), rotation, threshold, !reverse);
measured(diagnostics, id, frame, new TextRaster.Stray(validate ? TextRaster.outside(drawing, dpi) : 0, 0), block.milliPoints());
return (drawing);
}
/***************************************************************************
** The value the record holds at the element's pointer, as it is printed.
** Text is printed as it is and a truth value as `true` or `false`. A number
** is printed in plain decimal digits, as the schema says: no exponent, and
** no fraction that is only zeros, so `1.0E10` prints `10000000000`, `2.50`
** prints `2.5` and `12.0` prints `12`. Anything else, a number that is not
** finite among them, is `VALUE_MISSING`.
***************************************************************************/
private String bound(JsonNode bound, Frame frame, Diagnostics diagnostics)
{
if(bound.isTextual() || bound.isBoolean())
{
return (bound.asText());
}
if(bound.isIntegralNumber())
{
return (bound.bigIntegerValue().toString());
}
if(bound.isNumber() && Double.isFinite(bound.doubleValue()))
{
return (BigDecimal.valueOf(bound.doubleValue()).stripTrailingZeros().toPlainString());
}
throw diagnostics.refuse("VALUE_MISSING", id, null, frame, null, null);
}
/***************************************************************************
** Prove that the longest value fits whole, and answer the size it is
** proven at, which is the smallest any value is printed at. The proof never
** cuts: a cut value is not a value that fits. When it fails, an element
** that did not ask for cutting is refused; one that did stands, since
** cutting is what its author chose, with a warning that says how many
** characters are proven to fit whole. Fewer characters never fit worse, so
** that number is found by halving. The size is then the floor, where a cut
** value is printed.
***************************************************************************/
private int proven(TextFit.Request request, Frame frame, Diagnostics diagnostics, TextFit.Work work)
{
TextFit.Request whole = new TextFit.Request(face, request.width(), request.height(), request.dpi(), size, floor, lineHeight, maxLines, false);
Face.Glyph[] worst = new Face.Glyph[maxLength];
Arrays.fill(worst, face.worst());
TextFit.Block proof = truncate ? TextFit.fit(whole, worst, null, work) : fitted(whole, worst, frame, diagnostics, work);
if(!proof.fits())
{
int low = 0;
int high = maxLength - 1;
while(low < high)
{
int middle = (low + high + 1) >>> 1;
if(TextFit.fit(whole, Arrays.copyOf(worst, middle), null, work).fits())
{
low = middle;
}
else
{
high = middle - 1;
}
}
diagnostics.warn("FIT_NOT_PROVEN", id, null, frame, Map.of("provenCharacters", low), Map.of("characters", maxLength));
}
return (proof.milliPoints());
}
/***************************************************************************
** Fit, or refuse with what was measured at the floor size against the box.
***************************************************************************/
private TextFit.Block fitted(TextFit.Request request, Face.Glyph[] glyphs, Frame frame, Diagnostics diagnostics, TextFit.Work work)
{
TextFit.Block block = TextFit.fit(request, glyphs, face.glyph(TextFit.MARK), work);
if(!block.fits())
{
throw diagnostics.refuse("TEXT_DOES_NOT_FIT", id, null, frame,
Map.of("widthDots", block.width(), "heightDots", block.height(), "lines", block.lines().size(), "sizeCentipoints", block.milliPoints() / 10, "characters", block.characters()),
Map.of("widthDots", request.width(), "heightDots", request.height(), "lines", maxLines));
}
return (block);
}
/***************************************************************************
** Warn when the type is small for the printer: any face whose capitals are
** under 12 dots, and a regular weight whose capitals are under 20.
***************************************************************************/
private void legibility(int milliPoints, int dpi, Frame frame, Diagnostics diagnostics)
{
int capitals = new TextFit.Scale(milliPoints, dpi).floor(face.capHeight());
if(capitals < SMALL_CAPITAL_DOTS)
{
diagnostics.warn("TEXT_SMALL_FOR_DPI", id, null, frame, Map.of("capHeightDots", capitals, "sizeCentipoints", milliPoints / 10), Map.of("capHeightDots", SMALL_CAPITAL_DOTS));
}
if(!face.bold() && capitals < LIGHT_CAPITAL_DOTS)
{
diagnostics.warn("TEXT_LIGHT_FACE", id, null, frame, Map.of("capHeightDots", capitals, "sizeCentipoints", milliPoints / 10), Map.of("capHeightDots", LIGHT_CAPITAL_DOTS));
}
}
}
@@ -25,22 +25,18 @@ import java.util.Set;
import com.kingsrook.qbits.renderer.scene2.ElementFactory; import com.kingsrook.qbits.renderer.scene2.ElementFactory;
import com.kingsrook.qbits.renderer.scene2.ElementSource; import com.kingsrook.qbits.renderer.scene2.ElementSource;
import com.kingsrook.qbits.renderer.scene2.SceneElement; import com.kingsrook.qbits.renderer.scene2.SceneElement;
import com.kingsrook.qbits.renderer.scene2.UnavailableElement;
/******************************************************************************* /*******************************************************************************
** Text: a TrueType face rasterised by the renderer, with size, fit and legibility ** Text: a TrueType face bundled with the renderer, rasterised by it, with
** rules. ** size, fit and legibility rules. Version 2 has no printer font: a face the
** ** renderer cannot measure can be neither fitted nor previewed truthfully.
** This is the placeholder of the scene 2 core: a `text` element is parsed and
** placed, then refused as `RENDERER_TOO_OLD`. The package that draws it
** replaces this class and nothing else.
*******************************************************************************/ *******************************************************************************/
public final class TextFactory implements ElementFactory public final class TextFactory implements ElementFactory
{ {
/*************************************************************************** /***************************************************************************
** The property names the design gives a `text` element. Their values are ** The properties of a `text` element beyond the common ones. `font` and
** not read yet. ** `size` may come from the scene's `defaults`.
***************************************************************************/ ***************************************************************************/
@Override @Override
public Set<String> properties() public Set<String> properties()
@@ -51,11 +47,11 @@ public final class TextFactory implements ElementFactory
/*************************************************************************** /***************************************************************************
** The element, placed and then refused by name. ** Build one text element.
***************************************************************************/ ***************************************************************************/
@Override @Override
public SceneElement create(ElementSource source) public SceneElement create(ElementSource source)
{ {
return (new UnavailableElement(source)); return (new TextElement(source));
} }
} }
@@ -0,0 +1,661 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.util.ArrayList;
import java.util.List;
import com.kingsrook.qbits.renderer.scene2.text.Face.Glyph;
/*******************************************************************************
** Measurement and fit of one text in one box, in whole dots, by integer
** arithmetic on the face's own numbers. Nothing is drawn here, and what is
** drawn later is drawn from this answer: the pen position of every character
** and the box of every line are decided once.
**
** The order is fixed. Lay the text out at the nominal size within the allowed
** lines. If it does not fit, take the largest size, in steps of a quarter of
** a point down to the floor, at which it does. If none does, the text is
** refused, or, only when the element asked for it, cut at a character and
** ended with an ellipsis at the floor size.
**
** The answer is the one a search of every step from the nominal size down
** gives, and is found without making it. A count that errs only toward yes
** (`possible`) says whether a size could hold the text; it never says no to a
** size that fits and never says yes to a larger size after no to a smaller,
** so the largest size it allows is found by halving, and no size above that
** one fits. From there the steps are laid out one by one as before; the count
** is within a few dots of the layout, so they are few. When one line at the
** floor is higher than the box, no size fits and none is searched.
**
** Every character visited is counted against the `Work` the caller gives, so
** a caller can hold all the fitting of one scene to a stated amount.
**
** At each size a line is first broken between words only. If that does not
** fit, it is broken at any character. So a value with no spaces wraps, a
** sentence keeps its words while it can, and a larger size is preferred to
** whole words. Breaking at any character is also what makes a length provable:
** a text of n characters needs no more lines than n of the face's widest.
**
** A line's box is its pen advance, widened to hold the ink of every character
** in it (a `j` that starts left of the pen, an accent above the ascent) plus
** `SLOP` dots on each inked side. The drawn glyph is the font's outline fitted
** to the dot grid by the rasteriser, which moves an edge by less than two dots
** from the outline scaled exactly; the slop is that allowance, and a test
** holds every character of every bundled face to it.
*******************************************************************************/
public final class TextFit
{
public static final int SLOP = 2;
public static final int STEP_MILLIPOINTS = 250;
public static final int MARK = 0x2026;
/***************************************************************************
** Utility class.
***************************************************************************/
private TextFit()
{
}
/***************************************************************************
** What is asked: a face, a box in dots as the text reads (before any
** rotation), the resolution, the nominal size and the floor in thousandths
** of a point, the line pitch in thousandths of the size (null for the
** face's own), the most lines, and whether a text that fits at no size is
** cut short rather than refused.
***************************************************************************/
public record Request(Face face, int width, int height, int dpi, int nominal, int floor, Integer lineHeight, int maxLines, boolean truncate)
{
}
/***************************************************************************
** One line: the characters `from` to `to` of the text, followed by the
** ellipsis when `marked`. `left` (never positive) and `right` are the sides
** of its box measured from the pen at the start of the line; `above` and
** `below` are how far its ink reaches from the baseline.
***************************************************************************/
public record Line(int from, int to, boolean marked, int left, int right, int above, int below)
{
/************************************************************************
** The width of the line's box.
************************************************************************/
public int width()
{
return (right - left);
}
}
/***************************************************************************
** The answer: the size chosen, the lines, the size of the block they make,
** the baseline of the first line from the top of the block, the distance
** between baselines, how many characters there were (trailing spaces never
** print and are not counted), how many are shown, and whether it fits. When
** it does not, the numbers are those of the text broken at any character at
** the floor size, which is what a refusal reports.
***************************************************************************/
public record Block(int milliPoints, List<Line> lines, int width, int height, int baseline, int pitch, int characters, int shown, boolean fits)
{
/************************************************************************
** Whether the text was cut short.
************************************************************************/
public boolean truncated()
{
return (shown < characters);
}
}
/***************************************************************************
** Dots from thousandths of the em at one size and resolution. A size of
** `milliPoints` is `milliPoints * dpi / 72000` dots to the em, so a length
** of `units` is `units * milliPoints * dpi / 72000000` dots, rounded as the
** use says. The products stay far inside a long.
***************************************************************************/
public record Scale(int milliPoints, int dpi)
{
private static final long DIVISOR = 72_000_000L;
/************************************************************************
** Rounded down.
************************************************************************/
public int floor(long units)
{
return (Math.toIntExact(Math.floorDiv(units * milliPoints * dpi, DIVISOR)));
}
/************************************************************************
** Rounded up.
************************************************************************/
public int ceil(long units)
{
return (-floor(-units));
}
/************************************************************************
** To the nearest dot, a half upward.
************************************************************************/
public int round(long units)
{
return (Math.toIntExact(Math.floorDiv(units * milliPoints * dpi + DIVISOR / 2, DIVISOR)));
}
/************************************************************************
** The size of the em in dots, for the font that draws.
************************************************************************/
public float size()
{
return ((float) ((double) milliPoints * dpi / 72_000));
}
}
/***************************************************************************
** The work fitting may do, in characters visited, shared by as many fits
** as the caller wants held to one amount. It is counted by integer
** arithmetic alone, so it is the same on every machine.
***************************************************************************/
public static final class Work
{
private final long limit;
private long spent;
/************************************************************************
** An allowance of this many steps.
************************************************************************/
public Work(long limit)
{
this.limit = limit;
}
/************************************************************************
** Count steps, and end the work when the allowance is passed. It stays
** passed: whatever is asked next ends at once.
************************************************************************/
public void spend(long steps)
{
spent += steps;
if(spent > limit)
{
throw new Exhausted();
}
}
/************************************************************************
** The steps counted so far.
************************************************************************/
public long spent()
{
return (spent);
}
}
/***************************************************************************
** The allowance of a `Work` was passed. It says nothing else: what was
** being fitted is not in it.
***************************************************************************/
public static final class Exhausted extends RuntimeException
{
private static final long serialVersionUID = 1L;
/************************************************************************
** No message beyond the name, no cause and no stack.
************************************************************************/
Exhausted()
{
super("TEXT_WORK_EXHAUSTED", null, false, false);
}
}
/***************************************************************************
** What a line reserves, in thousandths of the em, read from the face once
** for a fit: the ascent above the baseline, the descent below it, and the
** distance between baselines.
***************************************************************************/
record Leading(int ascent, int descent, int pitch)
{
/************************************************************************
** The face's own, with the line height the request states if it does.
************************************************************************/
static Leading of(Request request)
{
Face face = request.face();
return (new Leading(face.ascent(), face.descent(), request.lineHeight() == null ? face.ascent() + face.descent() + face.leading() : request.lineHeight()));
}
/************************************************************************
** The distance between baselines in dots, never less than one.
************************************************************************/
int pitch(Scale scale)
{
return (Math.max(1, scale.ceil(pitch)));
}
/************************************************************************
** The least a block of this many lines is high: one ascent, the pitches
** between and one descent. Ink that reaches further makes it higher.
************************************************************************/
int height(Scale scale, int lines)
{
return (scale.ceil(ascent) + (lines - 1) * pitch(scale) + scale.ceil(descent));
}
}
/***************************************************************************
** The box of a line as characters are added to it from the left.
***************************************************************************/
private static final class Extent
{
private final Scale scale;
private long units;
private int left;
private int right;
private int above;
private int below;
/************************************************************************
** An empty line at one size.
************************************************************************/
Extent(Scale scale)
{
this.scale = scale;
}
/************************************************************************
** Add the next character at the pen. A space moves the pen and widens
** nothing, so spaces at the end of a line take no room.
************************************************************************/
void add(Glyph glyph)
{
int pen = scale.round(units);
units += glyph.advance();
if(!glyph.space())
{
right = Math.max(right, scale.ceil(units));
}
if(glyph.ink())
{
left = Math.min(left, pen + scale.floor(glyph.left()) - SLOP);
right = Math.max(right, pen + scale.ceil(glyph.right()) + SLOP);
above = Math.max(above, scale.ceil(glyph.top()) + SLOP);
below = Math.max(below, scale.ceil(glyph.bottom()) + SLOP);
}
}
/************************************************************************
** The width of the box so far.
************************************************************************/
int width()
{
return (right - left);
}
}
/***************************************************************************
** Fit a text, given as the measurements of its characters, by the fixed
** order, with no limit on the work. `mark` is the face's ellipsis, used
** only when the request allows cutting.
***************************************************************************/
public static Block fit(Request request, Glyph[] glyphs, Glyph mark)
{
return (fit(request, glyphs, mark, new Work(Long.MAX_VALUE)));
}
/***************************************************************************
** Fit a text by the fixed order, counting the work against an allowance
** and ending as `Exhausted` when it is passed. The floor is never above
** the nominal size and no character has a negative advance.
***************************************************************************/
public static Block fit(Request request, Glyph[] glyphs, Glyph mark, Work work)
{
int count = glyphs.length;
while(count > 0 && glyphs[count - 1].space())
{
count--;
}
Leading leading = Leading.of(request);
int last = (request.nominal() - request.floor() + STEP_MILLIPOINTS - 1) / STEP_MILLIPOINTS;
Block block = at(request, leading, request.nominal(), glyphs, count, mark, work);
int step = block.fits() || last == 0 ? last + 1 : first(request, leading, glyphs, count, last, work);
while(step <= last)
{
block = at(request, leading, size(request, step), glyphs, count, mark, work);
step = block.fits() ? last + 1 : step + 1;
}
return (block);
}
/***************************************************************************
** The size a number of quarter-point steps below the nominal, which is the
** floor once the steps reach it.
***************************************************************************/
private static int size(Request request, int step)
{
return (Math.max(request.floor(), request.nominal() - step * STEP_MILLIPOINTS));
}
/***************************************************************************
** The answer at one size: the text broken between words if that fits, else
** broken at any character; and at the floor, when that does not fit either
** and the request allows it, cut. This is one step of the search of every
** size, which a test makes in full to hold `fit` to it.
***************************************************************************/
static Block at(Request request, Leading leading, int size, Glyph[] glyphs, int count, Glyph mark, Work work)
{
Scale scale = new Scale(size, request.dpi());
Block words = block(request, leading, scale, lines(request, scale, glyphs, count, true, work), count, count);
if(words.fits())
{
return (words);
}
Block characters = block(request, leading, scale, lines(request, scale, glyphs, count, false, work), count, count);
return (characters.fits() || size > request.floor() || !request.truncate() ? characters : cut(request, leading, scale, glyphs, mark, characters, work));
}
/***************************************************************************
** The fewest steps below the nominal, from one, at which the text could
** fit; `last`, the floor, when it could at none above it. No size above the
** answer fits, because `possible` never refuses a size that fits and, once
** it allows a size, allows every smaller one. One line at the floor higher
** than the box settles it for every text without a count.
***************************************************************************/
private static int first(Request request, Leading leading, Glyph[] glyphs, int count, int last, Work work)
{
if(leading.height(new Scale(request.floor(), request.dpi()), 1) > request.height())
{
return (last);
}
int low = 1;
int high = last;
while(low < high)
{
int middle = (low + high) >>> 1;
if(possible(request, leading, new Scale(size(request, middle), request.dpi()), glyphs, count, work))
{
high = middle;
}
else
{
low = middle + 1;
}
}
return (low);
}
/***************************************************************************
** Whether a text could fit at one size, erring only toward yes. Lines are
** filled at any character, each held to a width no layout of it can be
** under: its advance to the end of its last character that is not a space,
** or, when wider, the span of its ink scaled exactly and the allowance at
** both ends less the one dot two roundings can give back. A line of a real
** layout, by words or by characters, is never narrower than this, and a
** line that holds more is never narrower than one that holds less, so no
** layout has fewer lines than are counted here; and a block is never lower
** than its lines' ascent, pitches and descent. Every one of these numbers
** grows with the size, so a yes at one size is a yes at every smaller one.
***************************************************************************/
private static boolean possible(Request request, Leading leading, Scale scale, Glyph[] glyphs, int count, Work work)
{
work.spend(count);
int lines = 0;
int index = 0;
while(index < count)
{
lines++;
if(lines > request.maxLines() || leading.height(scale, lines) > request.height())
{
return (false);
}
int from = index;
long units = 0;
long end = 0;
long reach = Long.MIN_VALUE;
long lead = Long.MAX_VALUE;
while(index < count)
{
Glyph glyph = glyphs[index];
long after = units + glyph.advance();
long ended = glyph.space() ? end : after;
long reached = glyph.ink() ? Math.max(reach, units + glyph.right()) : reach;
long led = glyph.ink() ? Math.min(lead, units + glyph.left()) : lead;
int width = Math.max(scale.ceil(ended), reached < led ? 0 : scale.ceil(reached - led) + 2 * SLOP - 1);
if(width > request.width() && index > from)
{
break;
}
if(width > request.width())
{
return (false);
}
units = after;
end = ended;
reach = reached;
lead = led;
index++;
}
}
return (true);
}
/***************************************************************************
** Break a text into lines at one size, between words or at any character.
** Spaces where a line is broken are dropped. A line is measured twice, to
** find its end and to box it, and is counted so.
***************************************************************************/
private static List<Line> lines(Request request, Scale scale, Glyph[] glyphs, int count, boolean words, Work work)
{
List<Line> lines = new ArrayList<>();
int from = 0;
while(from < count)
{
int to = end(request, scale, glyphs, from, count, words);
work.spend(2L * (to - from) + 1);
lines.add(line(scale, glyphs, from, to, null));
from = to;
while(from < count && glyphs[from].space())
{
from++;
}
}
return (lines);
}
/***************************************************************************
** Where the line that starts at `from` ends: after the last word, or the
** last character, that still fits the width. The first one is taken even
** when it is too wide, so the line is then wider than the box and the
** layout does not fit. Broken at any character, a line may end after a
** space, which takes no room; so spaces at the start of a text cannot push
** its first letter out of the box.
***************************************************************************/
private static int end(Request request, Scale scale, Glyph[] glyphs, int from, int count, boolean words)
{
Extent extent = new Extent(scale);
int accepted = from;
for(int index = from; index < count; index++)
{
extent.add(glyphs[index]);
if(!words || (!glyphs[index].space() && (index + 1 == count || glyphs[index + 1].space())))
{
boolean wide = extent.width() > request.width();
if(wide && accepted > from)
{
return (accepted);
}
accepted = index + 1;
if(wide)
{
return (accepted);
}
}
}
return (accepted);
}
/***************************************************************************
** Measure one line, with the ellipsis after it when one is given.
***************************************************************************/
private static Line line(Scale scale, Glyph[] glyphs, int from, int to, Glyph mark)
{
Extent extent = new Extent(scale);
for(int index = from; index < to; index++)
{
extent.add(glyphs[index]);
}
if(mark != null)
{
extent.add(mark);
}
return (new Line(from, to, mark != null, extent.left, extent.right, extent.above, extent.below));
}
/***************************************************************************
** Stack lines into a block and hold it against the box. A line reserves the
** face's ascent above its baseline and its descent below; the block grows
** where the ink of a line reaches further.
***************************************************************************/
private static Block block(Request request, Leading leading, Scale scale, List<Line> lines, int characters, int shown)
{
if(lines.isEmpty())
{
return (new Block(scale.milliPoints(), lines, 0, 0, 0, 0, characters, shown, true));
}
int ascent = scale.ceil(leading.ascent());
int pitch = leading.pitch(scale);
int top = 0;
int bottom = leading.height(scale, lines.size());
int width = 0;
for(int index = 0; index < lines.size(); index++)
{
Line line = lines.get(index);
int baseline = ascent + index * pitch;
top = Math.min(top, baseline - line.above());
bottom = Math.max(bottom, baseline + line.below());
width = Math.max(width, line.width());
}
boolean fits = lines.size() <= request.maxLines() && width <= request.width() && bottom - top <= request.height();
return (new Block(scale.milliPoints(), lines, width, bottom - top, ascent - top, pitch, characters, shown, fits));
}
/***************************************************************************
** Cut a text that fits at no size: keep as many lines as the box holds, and
** end the last of them with the ellipsis after as many of its characters as
** still fit with it, down to the ellipsis alone. Something is always left
** out, so the ellipsis always stands for text, and spaces before it are
** dropped. When not even the ellipsis fits, the answer is the refusal that
** was passed in. A box lower than a number of lines holds no cut of that
** many, which is known without trying; so one lower than a single line
** holds no ellipsis at all.
***************************************************************************/
private static Block cut(Request request, Leading leading, Scale scale, Glyph[] glyphs, Glyph mark, Block refused, Work work)
{
int all = refused.lines().size();
int most = Math.min(request.maxLines(), all);
while(most > 0 && leading.height(scale, most) > request.height())
{
most--;
}
for(int kept = most; kept > 0; kept--)
{
List<Line> lines = new ArrayList<>(refused.lines().subList(0, kept));
int from = lines.get(kept - 1).from();
for(int to = lines.get(kept - 1).to() - (kept == all ? 1 : 0); to >= from; to--)
{
if(to > from && glyphs[to - 1].space())
{
continue;
}
work.spend(to - from + 1L + kept);
lines.set(kept - 1, line(scale, glyphs, from, to, mark));
Block block = block(request, leading, scale, lines, refused.characters(), to);
if(block.fits())
{
return (block);
}
}
}
return (refused);
}
}
@@ -0,0 +1,291 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.font.GlyphVector;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.util.BitSet;
import com.kingsrook.qbits.renderer.scene2.Canvas;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.Layout;
import com.kingsrook.qbits.renderer.scene2.Placement;
/*******************************************************************************
** Draws a fitted text onto the label. Each glyph is drawn antialiased at the
** whole-dot pen position the fit decided, by the same Java rasteriser version 1
** raster text uses, and a dot is ink when its grey is darker than the
** element's threshold, so a higher threshold prints heavier.
**
** A line is drawn on a strip: its measured box and a guard of `GUARD` dots all
** round. Ink found in the guard, or a glyph whose bitmap the runtime places
** anywhere outside the measured box, means the measurement was wrong. Such
** ink is never clipped away and never printed outside the box, and a text is
** never printed in part: the dots of a text are gathered first and reach the
** label only when none strayed. What strayed is counted (`Stray`), for the
** element to be refused by name.
**
** A strip of more than `BAND_DOTS` dots (very large type) is drawn in bands of
** whole rows, so one line never needs more grey than that. Where the bands
** fall depends only on the box of the line, so the picture is the same on
** every machine; the rasteriser may shade an edge dot at the border of a band
** differently than it would in one piece.
*******************************************************************************/
final class TextRaster
{
static final int GUARD = 2;
static final int BAND_DOTS = 1 << 23;
/////////////////////////////////////////////////////////////////////////////////////////////////
// what drawing counts against the work of a scene, in characters visited while fitting, //
// which take about 15 ns each. A glyph the runtime has not drawn at a size is rasterised //
// once, in 20 to 50 microseconds; after that, asking for it and for where its bitmap //
// falls takes about a quarter of a microsecond //
/////////////////////////////////////////////////////////////////////////////////////////////////
static final int GLYPH_STEPS = 4096;
static final int PEN_STEPS = 16;
/***************************************************************************
** Utility class.
***************************************************************************/
private TextRaster()
{
}
/***************************************************************************
** What to draw and how: the face, the text, its fitted block, where lines
** sit across the block, the clockwise rotation, the grey below which a dot
** is ink, and whether the dots are ink or (for reverse text) cleared from
** the element's box filled black.
***************************************************************************/
record Drawing(Face face, String text, TextFit.Block block, Placement.Align align, Placement.Valign valign, int rotation, int threshold, boolean ink)
{
}
/***************************************************************************
** What the rasteriser put outside the measure: glyphs whose bitmap is not
** wholly inside the box of their line, and dots of ink found in the guard
** round a line or outside the element's box.
***************************************************************************/
record Stray(int glyphs, int dots)
{
/************************************************************************
** Whether anything strayed.
************************************************************************/
boolean any()
{
return (glyphs > 0 || dots > 0);
}
}
/***************************************************************************
** How many glyphs of a fitted text the runtime would place outside the box
** measured for their line at this resolution, without drawing any: what
** can be known of a text when a scene is only validated.
***************************************************************************/
static int outside(Drawing drawing, int dpi)
{
TextFit.Scale scale = new TextFit.Scale(drawing.block().milliPoints(), dpi);
Font font = drawing.face().font(scale.size());
int outside = 0;
for(TextFit.Line line : drawing.block().lines())
{
outside += glyphs(drawing, scale, font, line, null, 0);
}
return (outside);
}
/***************************************************************************
** Draw into the element's box, which is given as it appears on the label:
** a text turned a quarter reads along the box's height. The answer is what
** strayed; when anything did, the label is left as it was.
***************************************************************************/
static Stray paint(Canvas canvas, Frame frame, Drawing drawing, int bandDots)
{
TextFit.Block block = drawing.block();
boolean upright = drawing.rotation() % 180 == 0;
Frame reading = new Frame(0, 0, upright ? frame.width() : frame.height(), upright ? frame.height() : frame.width());
Frame content = Layout.align(reading, block.width(), block.height(), drawing.align(), drawing.valign());
TextFit.Scale scale = new TextFit.Scale(block.milliPoints(), canvas.dpi());
Font font = drawing.face().font(scale.size());
BitSet ink = new BitSet();
int glyphs = 0;
int dots = 0;
for(int index = 0; index < block.lines().size(); index++)
{
TextFit.Line line = block.lines().get(index);
int left = content.x() + drawing.align().position().place(block.width(), line.width(), 0);
int top = content.y() + block.baseline() + index * block.pitch() - line.above();
Stray stray = strip(ink, reading, drawing, scale, font, line, left, top, bandDots);
glyphs += stray.glyphs();
dots += stray.dots();
}
Stray stray = new Stray(glyphs, dots);
if(!stray.any())
{
if(!drawing.ink())
{
canvas.fill(frame, true);
}
for(int dot = ink.nextSetBit(0); dot >= 0; dot = ink.nextSetBit(dot + 1))
{
dot(canvas, frame, reading, drawing, dot % reading.width(), dot / reading.width());
}
}
return (stray);
}
/***************************************************************************
** Gather the ink of one line whose box has its top left at `left`, `top` of
** the reading frame, a band of rows at a time, and count what strayed.
***************************************************************************/
private static Stray strip(BitSet ink, Frame reading, Drawing drawing, TextFit.Scale scale, Font font, TextFit.Line line, int left, int top, int bandDots)
{
int width = line.width() + 2 * GUARD;
int height = line.above() + line.below() + 2 * GUARD;
int rows = Math.max(1, bandDots / width);
int glyphs = 0;
int dots = 0;
for(int first = 0; first < height; first += rows)
{
BufferedImage band = new BufferedImage(width, Math.min(rows, height - first), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D graphics = band.createGraphics();
try
{
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, band.getWidth(), band.getHeight());
graphics.setColor(Color.BLACK);
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//////////////////////////////////////////////////////////////////////////////////
// ink that fell wholly beyond the guard is clipped by the strip and leaves no //
// dot to find; the bounds of its glyph say so, and they are the same for every //
// band, so those of the first are the count //
//////////////////////////////////////////////////////////////////////////////////
int beyond = glyphs(drawing, scale, font, line, graphics, first);
glyphs = first == 0 ? beyond : glyphs;
}
finally
{
graphics.dispose();
}
byte[] grey = ((DataBufferByte) band.getRaster().getDataBuffer()).getData();
for(int y = 0; y < band.getHeight(); y++)
{
for(int x = 0; x < width; x++)
{
if((grey[y * width + x] & 255) < drawing.threshold())
{
int row = first + y;
int dotX = left + x - GUARD;
int dotY = top + row - GUARD;
if(x < GUARD || x >= width - GUARD || row < GUARD || row >= height - GUARD || dotX < 0 || dotY < 0 || dotX >= reading.width() || dotY >= reading.height())
{
dots++;
}
else
{
ink.set(dotY * reading.width() + dotX);
}
}
}
}
}
return (new Stray(glyphs, dots));
}
/***************************************************************************
** The glyphs of one line at their pens on its strip: how many the runtime
** places outside the line's measured box, drawing each on a band of the
** strip whose first row is `first` when one is given.
***************************************************************************/
private static int glyphs(Drawing drawing, TextFit.Scale scale, Font font, TextFit.Line line, Graphics2D band, int first)
{
int width = line.width() + 2 * GUARD;
int height = line.above() + line.below() + 2 * GUARD;
int outside = 0;
long units = 0;
for(int index = line.from(); index < line.to() + (line.marked() ? 1 : 0); index++)
{
char character = index < line.to() ? drawing.text().charAt(index) : (char) TextFit.MARK;
Face.Glyph glyph = drawing.face().glyph(character);
if(glyph.ink())
{
GlyphVector vector = font.createGlyphVector(Face.CONTEXT, new char[] {character});
int pen = GUARD - line.left() + scale.round(units);
Rectangle pixels = vector.getGlyphPixelBounds(0, Face.CONTEXT, pen, GUARD + line.above());
outside += !pixels.isEmpty() && (pixels.x < GUARD || pixels.y < GUARD || pixels.x + pixels.width > width - GUARD || pixels.y + pixels.height > height - GUARD) ? 1 : 0;
if(band != null)
{
band.drawGlyphVector(vector, pen, GUARD + line.above() - first);
}
}
units += glyph.advance();
}
return (outside);
}
/***************************************************************************
** Put one dot of the reading frame on the label, turned clockwise.
***************************************************************************/
private static void dot(Canvas canvas, Frame frame, Frame reading, Drawing drawing, int x, int y)
{
int turnedX = switch(drawing.rotation())
{
case 90 -> reading.height() - 1 - y;
case 180 -> reading.width() - 1 - x;
case 270 -> y;
default -> x;
};
int turnedY = switch(drawing.rotation())
{
case 90 -> x;
case 180 -> reading.height() - 1 - y;
case 270 -> reading.width() - 1 - x;
default -> y;
};
canvas.set(frame.x() + turnedX, frame.y() + turnedY, drawing.ink());
}
}
@@ -0,0 +1,8 @@
9e6c74a889a700d707613d24548fe4ffa6bc59559a0689d2cf9e133bdcdafb2f ibm-plex-sans/IBMPlexSans-Bold.ttf
975dcda37d80f038dcd143c22e33ca2d97a0cc5a929aace1c749153b0fe1afa5 ibm-plex-sans/IBMPlexSans-Regular.ttf
7e6b2818edbd8f6a01ae80641cc8f16a51080d08fb4e532be3a0b6f74adb07da ibm-plex-sans/LICENSE.txt
723e245902b45a49f8cf602d15891bae08c31309dce7c56d209d10cd471b88c7 ibm-plex-sans-condensed/IBMPlexSansCondensed-Bold.ttf
7e6b2818edbd8f6a01ae80641cc8f16a51080d08fb4e532be3a0b6f74adb07da ibm-plex-sans-condensed/LICENSE.txt
5590990c82e097397517f275f430af4546e1c45cff408bde4255dad142479dcb jetbrains-mono/JetBrainsMono-Bold.ttf
a0bf60ef0f83c5ed4d7a75d45838548b1f6873372dfac88f71804491898d138f jetbrains-mono/JetBrainsMono-Regular.ttf
30f0c136e3c88e422d0791acd97238870f9054a9729bc34cf2ff0d4ed8cac4ad jetbrains-mono/OFL.txt
@@ -0,0 +1,93 @@
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,23 @@
# IBM Plex Sans Condensed (Bold)
An unmodified file from the official release of the IBM Plex project, retrieved 2026-11-12.
| | |
| --- | --- |
| Project | https://github.com/IBM/plex |
| Release | `@ibm/plex-sans-condensed@2.0.0` |
| Archive | https://github.com/IBM/plex/releases/download/%40ibm/plex-sans-condensed%402.0.0/ibm-plex-sans-condensed.zip |
| Archive SHA-256 | `f86ba73abbeed7cf7690ead863192a87211dfc2b0cef0ac6bf4700533ec5ab9e` |
| Licence | SIL Open Font License 1.1, `LICENSE.txt` in this directory (the archive's `ibm-plex-sans-condensed/LICENSE.txt`, byte for byte) |
| Reserved Font Name | "Plex" (the file is not modified and not renamed) |
| File here | Path in the archive | Font version (name table) | SHA-256 |
| --- | --- | --- | --- |
| `IBMPlexSansCondensed-Bold.ttf` | `ibm-plex-sans-condensed/fonts/complete/ttf/IBMPlexSansCondensed-Bold.ttf` | Version 3.000 | `723e245902b45a49f8cf602d15891bae08c31309dce7c56d209d10cd471b88c7` |
| `LICENSE.txt` | `ibm-plex-sans-condensed/LICENSE.txt` | | `7e6b2818edbd8f6a01ae80641cc8f16a51080d08fb4e532be3a0b6f74adb07da` |
The licence was confirmed from the release archive itself: its `LICENSE.txt` states "This Font Software is
licensed under the SIL Open Font License, Version 1.1" and carries the full text; the licence field of the
font's name table says the same, and the font's embedding bits (`OS/2.fsType`) are 0, installable embedding.
Scene name: `qqq-condensed-bold`.
@@ -0,0 +1,93 @@
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,24 @@
# IBM Plex Sans (Regular, Bold)
Unmodified files from the official release of the IBM Plex project, retrieved 2026-11-12.
| | |
| --- | --- |
| Project | https://github.com/IBM/plex |
| Release | `@ibm/plex-sans@1.1.0` |
| Archive | https://github.com/IBM/plex/releases/download/%40ibm/plex-sans%401.1.0/ibm-plex-sans.zip |
| Archive SHA-256 | `fb365d910566e6d199cc2c15579a7dd9a267128e18431a394ed81f1970c69200` |
| Licence | SIL Open Font License 1.1, `LICENSE.txt` in this directory (the archive's `ibm-plex-sans/LICENSE.txt`, byte for byte) |
| Reserved Font Name | "Plex" (the files are not modified and not renamed) |
| File here | Path in the archive | Font version (name table) | SHA-256 |
| --- | --- | --- | --- |
| `IBMPlexSans-Regular.ttf` | `ibm-plex-sans/fonts/complete/ttf/IBMPlexSans-Regular.ttf` | Version 3.005 | `975dcda37d80f038dcd143c22e33ca2d97a0cc5a929aace1c749153b0fe1afa5` |
| `IBMPlexSans-Bold.ttf` | `ibm-plex-sans/fonts/complete/ttf/IBMPlexSans-Bold.ttf` | Version 3.005 | `9e6c74a889a700d707613d24548fe4ffa6bc59559a0689d2cf9e133bdcdafb2f` |
| `LICENSE.txt` | `ibm-plex-sans/LICENSE.txt` | | `7e6b2818edbd8f6a01ae80641cc8f16a51080d08fb4e532be3a0b6f74adb07da` |
The licence was confirmed from the release archive itself: its `LICENSE.txt` states "This Font Software is
licensed under the SIL Open Font License, Version 1.1" and carries the full text; the licence field of each
font's name table says the same, and each font's embedding bits (`OS/2.fsType`) are 0, installable embedding.
Scene names: `qqq-sans` (Regular), `qqq-sans-bold` (Bold).
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,24 @@
# JetBrains Mono (Regular, Bold)
Unmodified files from the official release of the JetBrains Mono project, retrieved 2026-11-12.
| | |
| --- | --- |
| Project | https://github.com/JetBrains/JetBrainsMono |
| Release | `v2.304` |
| Archive | https://github.com/JetBrains/JetBrainsMono/releases/download/v2.304/JetBrainsMono-2.304.zip |
| Archive SHA-256 | `6f6376c6ed2960ea8a963cd7387ec9d76e3f629125bc33d1fdcd7eb7012f7bbf` |
| Licence | SIL Open Font License 1.1, `OFL.txt` in this directory (the archive's `OFL.txt`, byte for byte) |
| Reserved Font Name | none declared |
| File here | Path in the archive | Font version (name table) | SHA-256 |
| --- | --- | --- | --- |
| `JetBrainsMono-Regular.ttf` | `fonts/ttf/JetBrainsMono-Regular.ttf` | Version 2.304; ttfautohint (v1.8.4.7-5d5b) | `a0bf60ef0f83c5ed4d7a75d45838548b1f6873372dfac88f71804491898d138f` |
| `JetBrainsMono-Bold.ttf` | `fonts/ttf/JetBrainsMono-Bold.ttf` | Version 2.304; ttfautohint (v1.8.4.7-5d5b) | `5590990c82e097397517f275f430af4546e1c45cff408bde4255dad142479dcb` |
| `OFL.txt` | `OFL.txt` | | `30f0c136e3c88e422d0791acd97238870f9054a9729bc34cf2ff0d4ed8cac4ad` |
The licence was confirmed from the release archive itself: its `OFL.txt` states "This Font Software is
licensed under the SIL Open Font License, Version 1.1" and carries the full text; the licence field of each
font's name table says the same, and each font's embedding bits (`OS/2.fsType`) are 0, installable embedding.
Scene names: `qqq-mono` (Regular), `qqq-mono-bold` (Bold).
@@ -22,6 +22,8 @@ package com.kingsrook.qbits.renderer;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -31,6 +33,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.exc.StreamConstraintsException; import com.fasterxml.jackson.core.exc.StreamConstraintsException;
@@ -80,9 +83,15 @@ class MutationCampaignTest
// having reached the canvas and the emitter // // having reached the canvas and the emitter //
///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////
private static final AtomicInteger LABELS = new AtomicInteger(); private static final AtomicInteger LABELS = new AtomicInteger();
private static final AtomicInteger BARCODES = new AtomicInteger();
private static final Pattern LENGTH = Pattern.compile("-?[0-9]{1,5}(\\.[0-9]{1,3})?(mm|in|pt|%|dot)"); private static final Pattern LENGTH = Pattern.compile("-?[0-9]{1,5}(\\.[0-9]{1,3})?(mm|in|pt|%|dot)");
private static final Pattern ELEMENT_ID = Pattern.compile("[A-Za-z][A-Za-z0-9_-]{0,31}"); private static final Pattern ELEMENT_ID = Pattern.compile("[A-Za-z][A-Za-z0-9_-]{0,31}");
private static final Pattern TYPE_SIZE = Pattern.compile("([0-9]{1,5}(?:\\.[0-9]{1,3})?)(mm|in|pt)");
private static final Set<String> FACES = Set.of("qqq-sans", "qqq-sans-bold", "qqq-condensed-bold", "qqq-mono", "qqq-mono-bold");
private static final Pattern MODULE = Pattern.compile("[0-9]{1,5}(\\.[0-9]{1,3})?(mm|in|pt)|[0-9]{1,5}dot");
private static final Pattern NOTHING = Pattern.compile("[0.]+[a-z]+");
private static final Set<String> FIT_QUALIFIED = Set.of("code128", "code39", "code93", "itf", "gs1-128", "qr", "ean13", "ean8", "upca", "upce", "datamatrix", "pdf417", "aztec");
@@ -305,22 +314,28 @@ class MutationCampaignTest
** second parser, either a version 1 scene (as above) or a version 2 scene ** second parser, either a version 1 scene (as above) or a version 2 scene
** that keeps every rule this checks on its own: only the declared top-level ** that keeps every rule this checks on its own: only the declared top-level
** properties, a physical design size, at most 1000 elements with unique ids ** properties, a physical design size, at most 1000 elements with unique ids
** of the fixed pattern, only boxes and groups (the types this renderer ** of the fixed pattern, only boxes, groups, text and barcodes (the types
** draws), groups at most four deep, every length a number and a unit, and ** this renderer draws), groups at most four deep, every length a number and
** overrides only for the three resolutions and for declared ids. About one ** a unit, every text in a bundled face at a physical size with one value
** version 2 input in four is rendered instead of validated: its label must ** and only documented fit, length and legibility settings at each
** then be the commands and graphic fields a version 2 label is made of, with ** resolution, every barcode in a fit-qualified symbology with one value and
** no ink outside the printable area, and validation must give the same ** only documented module, quiet zone, height, length, profile and rotation
** answer. Every other input is refused with a `Refusal`, which carries a ** settings at each resolution, and overrides only for the three resolutions
** and for declared ids. About one version 2 input in four is rendered
** instead of validated: its label must then be the commands and graphic
** fields a version 2 label is made of, with no ink outside the printable
** area, and validation must give the same answer (but for a text or a
** barcode bound to the record, which has no value here). Every other input
** is refused with a `Refusal`, which carries a
** diagnostic (or, for a version 1 source, with that parser's own refusal). ** diagnostic (or, for a version 1 source, with that parser's own refusal).
** Any other exception, an `IllegalArgumentException` of the package's own ** Any other exception, an `IllegalArgumentException` of the package's own
** invariants among them, is a finding. ** invariants or of a barcode encoder among them, is a finding.
***************************************************************************/ ***************************************************************************/
@Test @Test
void theVersionTwoSceneParserAcceptsOnlyVersionTwoScenes() throws Exception void theVersionTwoSceneParserAcceptsOnlyVersionTwoScenes() throws Exception
{ {
List<byte[]> corpus = new ArrayList<>(); List<byte[]> corpus = new ArrayList<>();
for(String name : List.of("anchors", "rules", "groups")) for(String name : List.of("anchors", "rules", "groups", "text-faces", "text-fit", "text-turned", "barcode-linear", "barcode-matrix", "barcode-gs1"))
{ {
try(InputStream stream = MutationCampaignTest.class.getResourceAsStream("/scene2/cases/" + name + ".json")) try(InputStream stream = MutationCampaignTest.class.getResourceAsStream("/scene2/cases/" + name + ".json"))
{ {
@@ -329,16 +344,24 @@ class MutationCampaignTest
} }
MutationCampaign campaign = new MutationCampaign(corpus, List.of("\"schema\"", "\"qqq-zpl-scene/2\"", "\"qqq-zpl-scene/1\"", "\"design\"", "\"elements\"", "\"overrides\"", "\"when\"", "\"dpi\"", "\"set\"", MutationCampaign campaign = new MutationCampaign(corpus, List.of("\"schema\"", "\"qqq-zpl-scene/2\"", "\"qqq-zpl-scene/1\"", "\"design\"", "\"elements\"", "\"overrides\"", "\"when\"", "\"dpi\"", "\"set\"",
"\"children\"", "\"group\"", "\"box\"", "\"text\"", "\"barcode\"", "\"image\"", "\"id\"", "\"type\"", "\"anchor\"", "\"thickness\"", "\"fill\"", "\"rotation\"", "\"center\"", "true", "false", "null", "\"children\"", "\"group\"", "\"box\"", "\"text\"", "\"barcode\"", "\"image\"", "\"id\"", "\"type\"", "\"anchor\"", "\"thickness\"", "\"fill\"", "\"rotation\"", "\"center\"", "true", "false", "null",
"\"defaults\"", "\"font\"", "\"size\"", "\"value\"", "\"valuePath\"", "\"lineHeight\"", "\"fit\"", "\"maxLines\"", "\"shrinkTo\"", "\"overflow\"", "\"truncate\"", "\"refuse\"", "\"maxLength\"", "\"threshold\"",
"\"reverse\"", "\"qqq-sans\"", "\"qqq-mono-bold\"", "\"qqq-\"", "\"/record/name\"", "90", "180", "270", "1000pt", "0.5", "1e400", "\\u0301", "\\t", "\\uD83D",
"\"symbology\"", "\"symbologyPath\"", "\"allowedSymbologies\"", "\"minModule\"", "\"maxModule\"", "\"quiet\"", "\"gs1\"", "\"hri\"", "\"scannerSymbologyPath\"", "\"aimIdentifierPath\"",
"\"code128\"", "\"gs1-128\"", "\"itf\"", "\"ean13\"", "\"qr\"", "\"pdf417\"", "\"codabar\"", "\"/record/code\"", "\"[01]00012345678905\"", "\"1dot\"", "[21]", "\\u00e9", "\\u2603", "4", "9", "64", "65",
"\"barcodeProfile\"", "\"gs1-logistics\"", "\"gs1-general\"", "\"none\"", "\"minHeight\"", "\\\\<FNC1>", "\\\\<", "\"0012345678905\"", "7", "11",
"mm", "in", "pt", "%", "dot", "-", ".", "203", "300", "600", "99999999999", "4294967499", "{", "}", "[", "]", ":", ",", "\\u0000")); "mm", "in", "pt", "%", "dot", "-", ".", "203", "300", "600", "99999999999", "4294967499", "{", "}", "[", "]", ":", ",", "\\u0000"));
int iterations = MutationCampaign.iterations(ITERATIONS); int iterations = MutationCampaign.iterations(ITERATIONS);
for(long seed : MutationCampaign.seeds(SEEDS)) for(long seed : MutationCampaign.seeds(SEEDS))
{ {
LABELS.set(0); LABELS.set(0);
BARCODES.set(0);
MutationCampaign.Result result = campaign.run(seed, iterations, MutationCampaignTest::checkLabelSource, MutationCampaignTest::labelRefusal); MutationCampaign.Result result = campaign.run(seed, iterations, MutationCampaignTest::checkLabelSource, MutationCampaignTest::labelRefusal);
assertEquals(List.of(), result.findings(), "replay with -Dfuzz.seed=" + seed + " -Dfuzz.iterations=" + iterations); assertEquals(List.of(), result.findings(), "replay with -Dfuzz.seed=" + seed + " -Dfuzz.iterations=" + iterations);
assertFalse(result.accepted() == 0 || result.refused() == 0, "the campaign must reach both acceptance and refusal: " + result); assertFalse(result.accepted() == 0 || result.refused() == 0, "the campaign must reach both acceptance and refusal: " + result);
assertTrue(LABELS.get() > 0, "the campaign must render labels as well as validate scenes: " + result); assertTrue(LABELS.get() > 0, "the campaign must render labels as well as validate scenes: " + result);
System.out.println("version 2 campaign, seed " + seed + ": " + result.accepted() + " accepted (" + LABELS.get() + " labels rendered and read back), " + result.refused() + " refused"); assertTrue(BARCODES.get() > 0, "the campaign must render labels that hold a barcode: " + result);
System.out.println("version 2 campaign, seed " + seed + ": " + result.accepted() + " accepted (" + LABELS.get() + " labels rendered and read back, " + BARCODES.get() + " of them with a barcode), "
+ result.refused() + " refused");
} }
} }
@@ -402,11 +425,17 @@ class MutationCampaignTest
} }
assertEquals(answer.get("diagnostics"), RendererMain.process(SceneFixture.request("VALIDATE", stock, source)).get("diagnostics"), "rendered what validation finds otherwise"); assertEquals(answer.get("diagnostics"), RendererMain.process(SceneFixture.request("VALIDATE", stock, source)).get("diagnostics"), "rendered what validation finds otherwise");
LABELS.incrementAndGet(); LABELS.incrementAndGet();
BARCODES.addAndGet(String.valueOf(answer.get("diagnostics")).contains("code=BARCODE_MODULE,") ? 1 : 0);
} }
} }
catch(Refusal refusal) catch(Refusal refusal)
{ {
if(render) ///////////////////////////////////////////////////////////////////////////////////////
// a text or a barcode bound to the record has no value here, since the campaign's //
// record is empty: that is the one refusal a render gives that validation, which //
// reads no record, cannot //
///////////////////////////////////////////////////////////////////////////////////////
if(render && !"VALUE_MISSING".equals(refusal.diagnostic().code()))
{ {
Refusal validated = assertThrows(Refusal.class, () -> RendererMain.process(SceneFixture.request("VALIDATE", stock, source)), "refused to render what validation accepts"); Refusal validated = assertThrows(Refusal.class, () -> RendererMain.process(SceneFixture.request("VALIDATE", stock, source)), "refused to render what validation accepts");
assertEquals(refusal.diagnostic().wire(), validated.diagnostic().wire()); assertEquals(refusal.diagnostic().wire(), validated.diagnostic().wire());
@@ -436,7 +465,7 @@ class MutationCampaignTest
assertTrue(length != null && LENGTH.matcher(length).matches() && !length.startsWith("-") && !length.endsWith("%") && !length.endsWith("dot"), () -> "accepted design " + side + " " + length); assertTrue(length != null && LENGTH.matcher(length).matches() && !length.startsWith("-") && !length.endsWith("%") && !length.endsWith("dot"), () -> "accepted design " + side + " " + length);
} }
Set<String> ids = new HashSet<>(); Set<String> ids = new HashSet<>();
assertVersionTwoElements(accepted.path("elements"), 1, ids); assertVersionTwoElements(accepted.path("elements"), 1, ids, accepted);
assertTrue(ids.size() <= 1000, () -> "accepted " + ids.size() + " elements"); assertTrue(ids.size() <= 1000, () -> "accepted " + ids.size() + " elements");
for(JsonNode override : accepted.path("overrides")) for(JsonNode override : accepted.path("overrides"))
{ {
@@ -451,7 +480,7 @@ class MutationCampaignTest
/*************************************************************************** /***************************************************************************
** The independent reading of a version 2 element list. ** The independent reading of a version 2 element list.
***************************************************************************/ ***************************************************************************/
private static void assertVersionTwoElements(JsonNode elements, int depth, Set<String> ids) private static void assertVersionTwoElements(JsonNode elements, int depth, Set<String> ids, JsonNode scene)
{ {
assertTrue(elements.isArray(), "accepted elements that are not a list"); assertTrue(elements.isArray(), "accepted elements that are not a list");
for(JsonNode element : elements) for(JsonNode element : elements)
@@ -459,23 +488,190 @@ class MutationCampaignTest
String id = element.path("id").textValue(); String id = element.path("id").textValue();
assertTrue(id != null && ELEMENT_ID.matcher(id).matches() && ids.add(id), () -> "accepted element id " + element.path("id")); assertTrue(id != null && ELEMENT_ID.matcher(id).matches() && ids.add(id), () -> "accepted element id " + element.path("id"));
String type = element.path("type").textValue(); String type = element.path("type").textValue();
assertTrue("box".equals(type) || "group".equals(type), () -> "accepted element type " + element.path("type")); assertTrue("box".equals(type) || "group".equals(type) || "text".equals(type) || "barcode".equals(type), () -> "accepted element type " + element.path("type"));
for(String name : List.of("x", "y", "width", "height", "thickness")) for(String name : List.of("x", "y", "width", "height", "thickness"))
{ {
assertTrue(!element.has(name) || (element.get(name).isTextual() && LENGTH.matcher(element.get(name).textValue()).matches()), () -> "accepted " + name + " " + element.get(name)); assertTrue(!element.has(name) || (element.get(name).isTextual() && LENGTH.matcher(element.get(name).textValue()).matches()), () -> "accepted " + name + " " + element.get(name));
} }
Set<String> allowed = "box".equals(type) ? Set.of("id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "thickness", "fill") Set<String> allowed = "box".equals(type) ? Set.of("id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "thickness", "fill")
: "text".equals(type) ? Set.of("id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "value", "valuePath", "font", "size", "lineHeight", "fit", "maxLength", "threshold", "reverse", "rotation")
: "barcode".equals(type) ? Set.of("id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "symbology", "symbologyPath", "allowedSymbologies", "value", "valuePath", "minModule", "maxModule", "quiet",
"scannerSymbologyPath", "aimIdentifierPath", "rotation", "barcodeProfile", "minHeight", "maxLength")
: Set.of("id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "children"); : Set.of("id", "type", "anchor", "x", "y", "width", "height", "align", "valign", "children");
element.fieldNames().forEachRemaining(name -> assertTrue(allowed.contains(name), () -> "accepted " + type + " property " + name)); element.fieldNames().forEachRemaining(name -> assertTrue(allowed.contains(name), () -> "accepted " + type + " property " + name));
if("group".equals(type)) if("group".equals(type))
{ {
assertTrue(depth <= 4, "accepted groups more than four deep"); assertTrue(depth <= 4, "accepted groups more than four deep");
assertVersionTwoElements(element.path("children"), depth + 1, ids); assertVersionTwoElements(element.path("children"), depth + 1, ids, scene);
}
if("text".equals(type))
{
assertVersionTwoText(element, scene);
}
if("barcode".equals(type))
{
assertVersionTwoBarcode(element, scene);
} }
} }
} }
/***************************************************************************
** The independent reading of an accepted barcode element, as it stands at
** each resolution: the element, then the overrides for that resolution in
** order. It states one fit-qualified symbology, or a pointer into the
** record with a list of distinct fit-qualified symbologies; exactly one of
** a literal value of 1 to 4000 characters and a pointer; a scanner
** symbology and identifier together or not at all; module sizes and a bar
** height that are more than nothing in a physical unit or dots; a quiet
** zone of at least the widest that any symbology it may draw asks for (11
** modules for EAN-13, 10 for the other linear symbols but 9 for the UPCs
** and 7 for EAN-8, 4 for a two-dimensional one) and at most 64; a longest
** length of 1 to 4000; one of the three profiles; and a quarter-turn
** rotation. An element that asks for `gs1` or `hri` is never accepted, nor
** at the resolution the campaign renders at, where the value is read, is a
** literal that holds the beginning of an escape of the encoder.
***************************************************************************/
private static void assertVersionTwoBarcode(JsonNode element, JsonNode scene)
{
for(int dpi : List.of(203, 300, 600))
{
ObjectNode stated = INDEPENDENT.createObjectNode();
element.properties().forEach(property -> stated.set(property.getKey(), property.getValue()));
for(JsonNode override : scene.path("overrides"))
{
boolean applies = false;
for(JsonNode resolution : override.path("when").path("dpi"))
{
applies |= resolution.intValue() == dpi;
}
if(applies)
{
override.path("set").path(element.path("id").textValue()).properties().forEach(property -> stated.set(property.getKey(), property.getValue()));
}
}
String about = "accepted barcode " + element.path("id") + " at " + dpi + " dpi with ";
assertFalse(stated.has("gs1") || stated.has("hri"), () -> about + "gs1 or hri");
assertTrue(stated.has("symbology") != stated.has("symbologyPath"), () -> about + "both or neither of symbology and symbologyPath");
List<String> drawn = new ArrayList<>();
if(stated.has("symbology"))
{
assertTrue(stated.get("symbology").isTextual() && FIT_QUALIFIED.contains(stated.get("symbology").textValue()) && !stated.has("allowedSymbologies"), () -> about + "symbology " + stated.get("symbology"));
drawn.add(stated.get("symbology").textValue());
}
else
{
assertTrue(stated.path("allowedSymbologies").isArray() && !stated.path("allowedSymbologies").isEmpty(), () -> about + "allowedSymbologies " + stated.path("allowedSymbologies"));
for(JsonNode allowed : stated.path("allowedSymbologies"))
{
assertTrue(allowed.isTextual() && FIT_QUALIFIED.contains(allowed.textValue()) && !drawn.contains(allowed.textValue()), () -> about + "allowed symbology " + allowed);
drawn.add(allowed.textValue());
}
}
assertTrue(stated.has("value") != stated.has("valuePath"), () -> about + "both or neither of value and valuePath");
assertTrue(!stated.has("value") || (stated.get("value").isTextual() && !stated.get("value").textValue().isEmpty() && stated.get("value").textValue().length() <= 4000), () -> about + "a value that is not text");
assertTrue(stated.has("scannerSymbologyPath") == stated.has("aimIdentifierPath"), () -> about + "half a scanner profile");
for(String path : List.of("symbologyPath", "valuePath", "scannerSymbologyPath", "aimIdentifierPath"))
{
assertTrue(!stated.has(path) || (stated.get(path).isTextual() && stated.get(path).textValue().startsWith("/") && stated.get(path).textValue().length() <= 256), () -> about + path + " " + stated.get(path));
}
assertFalse(dpi == 203 && stated.path("value").asText().contains(String.valueOf((char) 92) + "<"), () -> about + "an escape of the encoder in its value");
assertTrue(whole(stated.path("maxLength"), 1, 4000), () -> about + "maxLength " + stated.path("maxLength"));
assertTrue(!stated.has("barcodeProfile") || Set.of("none", "gs1-general", "gs1-logistics").contains(String.valueOf(stated.get("barcodeProfile").textValue())), () -> about + "barcodeProfile " + stated.get("barcodeProfile"));
for(String module : List.of("minModule", "maxModule", "minHeight"))
{
String size = stated.path(module).textValue();
assertTrue(!stated.has(module) || (size != null && MODULE.matcher(size).matches() && !NOTHING.matcher(size).matches()), () -> about + module + " " + stated.get(module));
}
int fewest = drawn.stream().mapToInt(symbology -> Map.of("ean13", 11, "upca", 9, "upce", 9, "ean8", 7, "qr", 4, "datamatrix", 4, "pdf417", 4, "aztec", 4).getOrDefault(symbology, 10)).max().orElseThrow();
assertTrue(!stated.has("quiet") || (stated.get("quiet").isInt() && stated.get("quiet").intValue() >= fewest && stated.get("quiet").intValue() <= 64), () -> about + "quiet " + stated.get("quiet"));
assertTrue(!stated.has("rotation") || (stated.get("rotation").isInt() && Set.of(0, 90, 180, 270).contains(stated.get("rotation").intValue())), () -> about + "rotation " + stated.get("rotation"));
}
}
/***************************************************************************
** The independent reading of an accepted text element, as it stands at each
** resolution: the scene's defaults, then the element, then the overrides
** for that resolution in order. It names a bundled face, has a physical
** size from 1 to 1000 pt, exactly one of a literal and a pointer into the
** record, and only fit, length, threshold, rotation, reverse and line
** height values of the documented kinds and ranges.
***************************************************************************/
private static void assertVersionTwoText(JsonNode element, JsonNode scene)
{
for(int dpi : List.of(203, 300, 600))
{
ObjectNode stated = INDEPENDENT.createObjectNode();
scene.path("defaults").properties().forEach(property -> stated.set(property.getKey(), property.getValue()));
element.properties().forEach(property -> stated.set(property.getKey(), property.getValue()));
for(JsonNode override : scene.path("overrides"))
{
boolean applies = false;
for(JsonNode resolution : override.path("when").path("dpi"))
{
applies |= resolution.intValue() == dpi;
}
if(applies)
{
override.path("set").path(element.path("id").textValue()).properties().forEach(property -> stated.set(property.getKey(), property.getValue()));
}
}
String about = "accepted text " + element.path("id") + " at " + dpi + " dpi with ";
assertTrue(stated.path("font").isTextual() && FACES.contains(stated.path("font").textValue()), () -> about + "font " + stated.path("font"));
assertTrue(typeSize(stated.path("size"), 1, 1000), () -> about + "size " + stated.path("size"));
assertTrue(stated.has("value") != stated.has("valuePath"), () -> about + "both or neither of value and valuePath");
assertTrue(!stated.has("value") || (stated.get("value").isTextual() && stated.get("value").textValue().codePointCount(0, stated.get("value").textValue().length()) <= 1024), () -> about + "a value that is not text");
assertTrue(!stated.has("valuePath") || (stated.get("valuePath").isTextual() && stated.get("valuePath").textValue().startsWith("/")), () -> about + "valuePath " + stated.path("valuePath"));
JsonNode fit = stated.path("fit");
assertTrue(fit.isMissingNode() || fit.isObject(), () -> about + "fit " + fit);
fit.fieldNames().forEachRemaining(name -> assertTrue(Set.of("maxLines", "shrinkTo", "overflow").contains(name), () -> about + "fit property " + name));
assertTrue(whole(fit.path("maxLines"), 1, 64) && whole(stated.path("threshold"), 1, 254) && whole(stated.path("maxLength"), 1, 1024), () -> about + "a count out of range");
assertTrue(fit.path("shrinkTo").isMissingNode() || typeSize(fit.path("shrinkTo"), 1, 1000), () -> about + "shrinkTo " + fit.path("shrinkTo"));
assertTrue(fit.path("overflow").isMissingNode() || Set.of("refuse", "truncate").contains(String.valueOf(fit.path("overflow").textValue())), () -> about + "overflow " + fit.path("overflow"));
assertTrue(stated.path("rotation").isMissingNode() || (stated.path("rotation").isInt() && Set.of(0, 90, 180, 270).contains(stated.path("rotation").intValue())), () -> about + "rotation " + stated.path("rotation"));
assertTrue(stated.path("reverse").isMissingNode() || stated.path("reverse").isBoolean(), () -> about + "reverse " + stated.path("reverse"));
JsonNode lineHeight = stated.path("lineHeight");
assertTrue(lineHeight.isMissingNode() || (lineHeight.isNumber() && lineHeight.doubleValue() >= 0.5 && lineHeight.doubleValue() <= 5), () -> about + "lineHeight " + lineHeight);
}
}
/***************************************************************************
** Whether a value is absent or a whole number in a range.
***************************************************************************/
private static boolean whole(JsonNode value, int minimum, int maximum)
{
return (value.isMissingNode() || (value.isInt() && value.intValue() >= minimum && value.intValue() <= maximum));
}
/***************************************************************************
** Whether a value is a type size: an unsigned physical length between two
** numbers of points, by decimal arithmetic with a hair of tolerance for the
** renderer's rounding to thousandths of a point.
***************************************************************************/
private static boolean typeSize(JsonNode value, int minimum, int maximum)
{
Matcher matcher = TYPE_SIZE.matcher(value.isTextual() ? value.textValue() : "");
if(!matcher.matches())
{
return (false);
}
BigDecimal points = new BigDecimal(matcher.group(1)).multiply(switch(matcher.group(2))
{
case "in" -> BigDecimal.valueOf(72);
case "mm" -> BigDecimal.valueOf(72).divide(new BigDecimal("25.4"), 12, RoundingMode.HALF_EVEN);
default -> BigDecimal.ONE;
});
return (points.compareTo(new BigDecimal(minimum).subtract(new BigDecimal("0.001"))) >= 0 && points.compareTo(new BigDecimal(maximum).add(new BigDecimal("0.001"))) <= 0);
}
/*************************************************************************** /***************************************************************************
** The target: static validation of one scene on a stock all corpus scenes fit. ** The target: static validation of one scene on a stock all corpus scenes fit.
***************************************************************************/ ***************************************************************************/
@@ -128,13 +128,14 @@ class DiagnosticsTest
{ {
Diagnostics diagnostics = new Diagnostics(true); Diagnostics diagnostics = new Diagnostics(true);
for(String code : List.of("SCENE_INVALID", "STOCK_MISMATCH", "TARGET_REQUIRES_SCENE_2", "ELEMENT_OUTSIDE_PRINTABLE_AREA", "TEXT_DOES_NOT_FIT", "VALUE_MISSING", "VALUE_TOO_LONG", "FONT_UNKNOWN", for(String code : List.of("SCENE_INVALID", "STOCK_MISMATCH", "TARGET_REQUIRES_SCENE_2", "ELEMENT_OUTSIDE_PRINTABLE_AREA", "TEXT_DOES_NOT_FIT", "VALUE_MISSING", "VALUE_TOO_LONG", "FONT_UNKNOWN",
"FONT_MISSING_GLYPH", "RESERVED_FONT_NAME", "BARCODE_DOES_NOT_FIT", "GS1_INVALID", "ASSET_UNKNOWN", "PREVIEW_TOO_LARGE", "RENDERER_TOO_OLD")) "FONT_MISSING_GLYPH", "RESERVED_FONT_NAME", "BARCODE_DOES_NOT_FIT", "GS1_INVALID", "ASSET_UNKNOWN", "PREVIEW_TOO_LARGE", "RENDERER_TOO_OLD",
"VALUE_NOT_ENCODABLE", "QUIET_ZONE_INTRUDED"))
{ {
assertEquals(code, diagnostics.refuse(code, null, null, null, null, null).getMessage()); assertEquals(code, diagnostics.refuse(code, null, null, null, null, null).getMessage());
assertThrows(IllegalStateException.class, () -> diagnostics.warn(code, null, null, null, null, null)); assertThrows(IllegalStateException.class, () -> diagnostics.warn(code, null, null, null, null, null));
assertThrows(IllegalStateException.class, () -> diagnostics.inform(code, null, null, null, null, null)); assertThrows(IllegalStateException.class, () -> diagnostics.inform(code, null, null, null, null, null));
} }
for(String code : List.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", "BARCODE_MODULE_BELOW_RECOMMENDED", "QUIET_ZONE_INTRUDED", "ELEMENTS_OVERLAP", "IMAGE_UPSCALED", for(String code : List.of("TEXT_TRUNCATED", "TEXT_SMALL_FOR_DPI", "TEXT_LIGHT_FACE", "FIT_NOT_PROVEN", "BARCODE_MODULE_BELOW_RECOMMENDED", "BARCODE_HEIGHT_BELOW_RECOMMENDED", "ELEMENTS_OVERLAP", "IMAGE_UPSCALED",
"DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN")) "DEVICE_UNIT_USED", "PRINTER_FONT_NOT_SHOWN"))
{ {
diagnostics.warn(code, null, null, null, null, null); diagnostics.warn(code, null, null, null, null, null);
@@ -508,9 +508,14 @@ class Scene2Test
/*************************************************************************** /***************************************************************************
** Text, barcodes and images are parsed and placed by this renderer and then ** An image is parsed and placed by this renderer and then refused by name,
** refused by name, with the box they would have had. The design's own ** with the box it would have had: text and barcodes are drawn, images not
** example scene is the case. ** yet. The design's own example scene with a logo beside it is the case.
** Validated, the logo is its first error. Rendered with an empty record,
** its barcode is refused first, for the value the record lacks, and its
** caption for the same; the barcode's standing warnings come with it: no
** length is declared, and the 0.25 mm the example states is under the
** 0.495 mm of a GS1-128 on a logistic unit.
***************************************************************************/ ***************************************************************************/
@Test @Test
void anElementThisRendererCannotDrawIsRefusedByName() throws Exception void anElementThisRendererCannotDrawIsRefusedByName() throws Exception
@@ -519,17 +524,21 @@ class Scene2Test
+ "\"samples\":{\"typical\":{\"record\":{\"humanReadable\":\"(01)00012345678905(10)L240611A\",\"rendererValue\":\"[01]00012345678905[10]L240611A\"}}}," + "\"samples\":{\"typical\":{\"record\":{\"humanReadable\":\"(01)00012345678905(10)L240611A\",\"rendererValue\":\"[01]00012345678905[10]L240611A\"}}},"
+ "\"elements\":[{\"id\":\"code\",\"type\":\"barcode\",\"symbology\":\"gs1-128\",\"valuePath\":\"/record/rendererValue\",\"anchor\":\"top-center\",\"y\":\"0.5mm\",\"width\":\"94mm\",\"height\":\"11mm\"," + "\"elements\":[{\"id\":\"code\",\"type\":\"barcode\",\"symbology\":\"gs1-128\",\"valuePath\":\"/record/rendererValue\",\"anchor\":\"top-center\",\"y\":\"0.5mm\",\"width\":\"94mm\",\"height\":\"11mm\","
+ "\"align\":\"center\",\"valign\":\"middle\",\"minModule\":\"0.25mm\",\"quiet\":10}," + "\"align\":\"center\",\"valign\":\"middle\",\"minModule\":\"0.25mm\",\"quiet\":10},"
+ "{\"id\":\"logo\",\"type\":\"image\",\"asset\":\"logo\",\"width\":\"0.5mm\",\"height\":\"10mm\"},"
+ "{\"id\":\"caption\",\"type\":\"text\",\"valuePath\":\"/record/humanReadable\",\"anchor\":\"bottom-center\",\"y\":\"0.5mm\",\"width\":\"94mm\",\"height\":\"6.5mm\"," + "{\"id\":\"caption\",\"type\":\"text\",\"valuePath\":\"/record/humanReadable\",\"anchor\":\"bottom-center\",\"y\":\"0.5mm\",\"width\":\"94mm\",\"height\":\"6.5mm\","
+ "\"align\":\"center\",\"valign\":\"middle\",\"size\":\"11pt\",\"maxLength\":48,\"fit\":{\"maxLines\":2,\"shrinkTo\":\"7pt\",\"overflow\":\"refuse\"}}]," + "\"align\":\"center\",\"valign\":\"middle\",\"size\":\"11pt\",\"maxLength\":48,\"fit\":{\"maxLines\":2,\"shrinkTo\":\"7pt\",\"overflow\":\"refuse\"}}],"
+ "\"overrides\":[{\"when\":{\"dpi\":[203]},\"set\":{\"caption\":{\"threshold\":144}}}]}"; + "\"overrides\":[{\"when\":{\"dpi\":[203]},\"set\":{\"caption\":{\"threshold\":144}}}]}";
Map<String, Object> code = Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "code", "box", List.of(6, 4, 751, 87)); Map<String, Object> code = Map.of("code", "VALUE_MISSING", "severity", "ERROR", "element", "code", "pointer", "/elements/0/valuePath", "box", List.of(6, 4, 751, 87));
Map<String, Object> caption = Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "caption", "box", List.of(6, 100, 751, 51)); Map<String, Object> caption = Map.of("code", "VALUE_MISSING", "severity", "ERROR", "element", "caption", "box", List.of(6, 100, 751, 51));
assertEquals(code, refused(example)); Map<String, Object> logo = Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "logo", "box", List.of(0, 0, 3, 79));
assertEquals(logo, refused(example));
assertEquals(code, SceneFixture.refusal(() -> RendererMain.process(SceneFixture.request("RENDER", example)))); assertEquals(code, SceneFixture.refusal(() -> RendererMain.process(SceneFixture.request("RENDER", example))));
Map<String, Object> answer = RendererMain.process(SceneFixture.request("RENDER", example).put("diagnostics", "COLLECT")); Map<String, Object> answer = RendererMain.process(SceneFixture.request("RENDER", example).put("diagnostics", "COLLECT"));
assertEquals("REFUSED", answer.get("outcome")); assertEquals("REFUSED", answer.get("outcome"));
assertEquals(List.of(code, caption), answer.get("diagnostics")); assertEquals(List.of(Map.of("code", "FIT_NOT_PROVEN", "severity", "WARNING", "element", "code", "box", List.of(6, 4, 751, 87)),
Map.of("code", "BARCODE_MODULE_BELOW_RECOMMENDED", "severity", "WARNING", "element", "code", "box", List.of(6, 4, 751, 87), "measured", Map.of("minModuleDots", 2), "limit", Map.of("minModuleDots", 4)),
code, logo, caption), answer.get("diagnostics"));
assertFalse(answer.containsKey("base64")); assertFalse(answer.containsKey("base64"));
assertEquals(Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "logo", "box", List.of(0, 0, 79, 79)), assertEquals(Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "logo", "box", List.of(0, 0, 79, 79)),
@@ -539,10 +548,10 @@ class Scene2Test
assertEquals(invalid("logo", "/elements/0/rotation"), refusedElements("{\"id\":\"logo\",\"type\":\"image\",\"asset\":\"logo\",\"rotation\":" + rotation + "}"), rotation); assertEquals(invalid("logo", "/elements/0/rotation"), refusedElements("{\"id\":\"logo\",\"type\":\"image\",\"asset\":\"logo\",\"rotation\":" + rotation + "}"), rotation);
} }
assertEquals(Map.of("code", "SCENE_INVALID", "severity", "ERROR", "element", "t", "pointer", "/elements/0", "measured", Map.of("unknownProperties", 1), "limit", Map.of("unknownProperties", 0)), assertEquals(Map.of("code", "SCENE_INVALID", "severity", "ERROR", "element", "t", "pointer", "/elements/0", "measured", Map.of("unknownProperties", 1), "limit", Map.of("unknownProperties", 0)),
refusedElements("{\"id\":\"t\",\"type\":\"text\",\"value\":\"TEST-0001\",\"symbology\":\"qr\"}")); refusedElements("{\"id\":\"t\",\"type\":\"text\",\"value\":\"TEST-0001\",\"font\":\"qqq-sans\",\"size\":\"9pt\",\"symbology\":\"qr\"}"));
assertEquals(Map.of("code", "SCENE_INVALID", "severity", "ERROR", "element", "t", "pointer", "/elements/0", "measured", Map.of("widthDots", 0, "heightDots", 155), "limit", Map.of("widthDots", 1, "heightDots", 1)), assertEquals(Map.of("code", "SCENE_INVALID", "severity", "ERROR", "element", "t", "pointer", "/elements/0", "measured", Map.of("widthDots", 0, "heightDots", 155), "limit", Map.of("widthDots", 1, "heightDots", 1)),
refusedElements("{\"id\":\"t\",\"type\":\"text\",\"value\":\"TEST-0001\",\"width\":\"0.1mm\"}")); refusedElements("{\"id\":\"t\",\"type\":\"text\",\"value\":\"TEST-0001\",\"font\":\"qqq-sans\",\"size\":\"9pt\",\"width\":\"0.1mm\"}"));
Diagnostics diagnostics = new Diagnostics(false); Diagnostics diagnostics = new Diagnostics(false);
diagnostics.declare("t", "/elements/0"); diagnostics.declare("t", "/elements/0");
@@ -554,7 +563,7 @@ class Scene2Test
assertEquals(144, source.value("threshold").intValue()); assertEquals(144, source.value("threshold").intValue());
assertNull(source.value("size")); assertNull(source.value("size"));
assertEquals(new Placement(Placement.Anchor.TOP_LEFT, Length.ZERO, Length.ZERO, null, null, Placement.Align.LEFT, Placement.Valign.TOP), source.placement()); assertEquals(new Placement(Placement.Anchor.TOP_LEFT, Length.ZERO, Length.ZERO, null, null, Placement.Align.LEFT, Placement.Valign.TOP), source.placement());
SceneElement placeholder = ElementFactory.FACTORIES.get("text").create(source); SceneElement placeholder = ElementFactory.FACTORIES.get("image").create(source);
assertEquals("t", placeholder.id()); assertEquals("t", placeholder.id());
assertEquals(List.of(), placeholder.children()); assertEquals(List.of(), placeholder.children());
assertEquals(Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "t", "box", List.of(1, 2, 3, 4)), assertEquals(Map.of("code", "RENDERER_TOO_OLD", "severity", "ERROR", "element", "t", "box", List.of(1, 2, 3, 4)),
@@ -574,8 +583,8 @@ class Scene2Test
{ {
String source = SceneFixture.scene("{\"id\":\"good\",\"type\":\"box\",\"x\":\"5dot\",\"width\":\"16dot\",\"height\":\"4dot\",\"fill\":true}," String source = SceneFixture.scene("{\"id\":\"good\",\"type\":\"box\",\"x\":\"5dot\",\"width\":\"16dot\",\"height\":\"4dot\",\"fill\":true},"
+ "{\"id\":\"wide\",\"type\":\"box\",\"x\":\"90mm\",\"width\":\"10mm\",\"height\":\"5mm\",\"thickness\":\"1pt\"}," + "{\"id\":\"wide\",\"type\":\"box\",\"x\":\"90mm\",\"width\":\"10mm\",\"height\":\"5mm\",\"thickness\":\"1pt\"},"
+ "{\"id\":\"g\",\"type\":\"group\",\"width\":\"0.1mm\",\"children\":[{\"id\":\"unseen\",\"type\":\"text\",\"value\":\"TEST-0001\"}]}," + "{\"id\":\"g\",\"type\":\"group\",\"width\":\"0.1mm\",\"children\":[{\"id\":\"unseen\",\"type\":\"image\",\"asset\":\"logo\"}]},"
+ "{\"id\":\"words\",\"type\":\"text\",\"value\":\"TEST-0001\",\"y\":\"10mm\",\"height\":\"5mm\"}," + "{\"id\":\"words\",\"type\":\"image\",\"asset\":\"logo\",\"y\":\"10mm\",\"height\":\"5mm\"},"
+ "{\"id\":\"also\",\"type\":\"box\",\"anchor\":\"bottom-left\",\"width\":\"8dot\",\"height\":\"2dot\",\"fill\":true}"); + "{\"id\":\"also\",\"type\":\"box\",\"anchor\":\"bottom-left\",\"width\":\"8dot\",\"height\":\"2dot\",\"fill\":true}");
List<Map<String, Object>> expected = List.of( List<Map<String, Object>> expected = List.of(
Map.of("code", "DEVICE_UNIT_USED", "severity", "WARNING", "element", "good", "pointer", "/elements/0/x"), Map.of("code", "DEVICE_UNIT_USED", "severity", "WARNING", "element", "good", "pointer", "/elements/0/x"),
@@ -48,8 +48,14 @@ import static org.junit.jupiter.api.Assertions.fail;
** Golden labels for the layout cases in `scene2/cases`, at 203, 300 and 600 ** Golden labels for the layout cases in `scene2/cases`, at 203, 300 and 600
** dpi. Each case has a picture (the page a printer would draw, compared dot ** dpi. Each case has a picture (the page a printer would draw, compared dot
** for dot) and the exact ZPL. A box is whole dots of pure ink, so both are ** for dot) and the exact ZPL. A box is whole dots of pure ink, so both are
** exact on every machine. A golden changes only with a reviewed change to the ** exact on every machine. Text is measured by integer arithmetic and drawn
** layout rules: what this build drew is left in `target/scene2-actual`. ** by the Java runtime's rasteriser from the bundled faces only; the text
** goldens were generated on Linux (Temurin 21.0.9, the CI image) and are the
** same bytes on Windows (Temurin 21.0.12), and they are compared exactly on
** both. A golden changes only with a reviewed change to the layout rules or
** the runtime: what this build drew is left in `target/scene2-actual`. The
** runtimes, and the FreeType each ships, are recorded beside the goldens
** (`scene2/README.md`).
*******************************************************************************/ *******************************************************************************/
class SceneGoldenTest class SceneGoldenTest
{ {
@@ -0,0 +1,359 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.IntFunction;
import java.util.function.UnaryOperator;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.kingsrook.qbits.renderer.RendererMain;
import com.kingsrook.qbits.renderer.Wire;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.Refusal;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** Decode tests: every fit-qualified symbology at 203, 300 and 600 dpi, for a
** short, a typical and the longest value its box holds. Each label is the
** emitted ZPL, its page rebuilt from the graphic fields and read by ZXing:
** the content, the symbology, the module in dots and the blank margins are
** all taken from what a printer would be sent. Code 128 is read three ways,
** since its encoder changes code set with the content: letters, digits alone
** (pairs of digits in code set C, of an even and of an odd count) and mixed
** content. A retail symbol is given its whole number, check digit included,
** and reads back as that number.
*******************************************************************************/
class BarcodeDecodeTest
{
private static final String LETTERS = "TEST0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String DIGITS = "0012345678";
private static final String MIXED = "Ab-1234567/cd 890.XY12z";
private static final String GTIN = "[01]00012345678905[11]260101";
private static final String UNIT = "00012345678901234";
private static final char SEPARATOR = (char) 29;
private static final List<Integer> DESIGN = List.of(2, 3, 6);
private static final List<Integer> RETAIL = List.of(3, 4, 7);
private static final List<Integer> DISTRIBUTION = List.of(4, 6, 12);
private static final List<Integer> MATRIX = List.of(3, 5, 9);
/***************************************************************************
** One symbology: how it is read back, its box, the profile the scene
** names, the quiet zones and narrowest bars it must then have (the bars in
** dots at 203, 300 and 600 dpi), the values to try by length (the lengths
** it is tried at lie between `fewest` and `most` in steps of `step`) and
** what a scanner reads for a value.
***************************************************************************/
private record Profile(String name, String symbology, BarcodeFormat format, String width, String height, String profile, int quietLeft, int quietRight, List<Integer> narrowest, IntFunction<String> value,
UnaryOperator<String> decoded, int fewest, int typical, int most, int step)
{
/************************************************************************
** The name of the profile in a test report.
************************************************************************/
@Override
public String toString()
{
return (name);
}
}
/***************************************************************************
** The first characters of a repeated alphabet.
***************************************************************************/
private static String repeated(String alphabet, int length)
{
return (alphabet.repeat(length / alphabet.length() + 1).substring(0, length));
}
/***************************************************************************
** A GS1 element string in the brackets the encoder reads: a GTIN, a date,
** then a serial number of up to 20 characters, and past 20 a lot as well,
** which is of variable length and so is followed by a separator.
***************************************************************************/
private static String elementString(int length)
{
return (GTIN + (length > 20 ? "[10]" + repeated(LETTERS, length - 20) : "") + "[21]" + repeated(LETTERS, Math.min(length, 20)));
}
/***************************************************************************
** What a scanner reads from a GS1-128: the `]C1` identifier for the leading
** FNC1, the identifiers and their data without brackets, and a separator
** where a field of variable length is followed by another.
***************************************************************************/
private static String scanned(String elementString)
{
String[] fields = elementString.substring(1).split("\\[", -1);
StringBuilder scanned = new StringBuilder("]C1");
for(int index = 0; index < fields.length; index++)
{
scanned.append(fields[index].replace("]", ""));
if(fields[index].startsWith("10]") && index < fields.length - 1)
{
scanned.append(SEPARATOR);
}
}
return (scanned.toString());
}
/***************************************************************************
** The thirteen fit-qualified symbologies. The retail symbols have one
** length and are tall, as their specification asks; their check digits
** here were worked out by hand. A GS1-128 is read under both of its
** profiles: as a serial shipping container code at the 0.495 mm of a
** logistic unit, which is all that fits 90 mm at that module, and as a
** GTIN with a date and a serial number at the design's 0.25 mm.
***************************************************************************/
private static List<Profile> profiles()
{
UnaryOperator<String> same = value -> value;
return (List.of(
new Profile("code128", "code128", BarcodeFormat.CODE_128, "90mm", "12mm", null, 10, 10, DESIGN, length -> repeated(LETTERS, length), same, 1, 12, 80, 1),
new Profile("code128 of digits", "code128", BarcodeFormat.CODE_128, "90mm", "12mm", null, 10, 10, DESIGN, length -> repeated(DIGITS, length), same, 1, 13, 120, 1),
new Profile("code128 of mixed content", "code128", BarcodeFormat.CODE_128, "90mm", "12mm", null, 10, 10, DESIGN, length -> repeated(MIXED, length), same, 1, 23, 80, 1),
new Profile("code39", "code39", BarcodeFormat.CODE_39, "90mm", "12mm", null, 10, 10, DESIGN, length -> repeated(LETTERS, length), same, 1, 10, 80, 1),
new Profile("code93", "code93", BarcodeFormat.CODE_93, "90mm", "12mm", null, 10, 10, DESIGN, length -> repeated(LETTERS, length), same, 1, 10, 80, 1),
new Profile("itf", "itf", BarcodeFormat.ITF, "90mm", "12mm", null, 10, 10, DISTRIBUTION, length -> repeated(DIGITS, length), same, 6, 14, 120, 2),
new Profile("itf of no profile", "itf", BarcodeFormat.ITF, "90mm", "12mm", "none", 10, 10, DESIGN, length -> repeated(DIGITS, length), same, 6, 14, 120, 2),
new Profile("gs1-128 of a logistic unit", "gs1-128", BarcodeFormat.CODE_128, "90mm", "13mm", null, 10, 10, DISTRIBUTION, length -> "[00]" + UNIT + BarcodeFixture.checkDigit(UNIT), BarcodeDecodeTest::scanned, 1, 1, 1, 1),
new Profile("gs1-128", "gs1-128", BarcodeFormat.CODE_128, "90mm", "12mm", "gs1-general", 10, 10, DESIGN, BarcodeDecodeTest::elementString, BarcodeDecodeTest::scanned, 1, 8, 40, 1),
new Profile("ean13", "ean13", BarcodeFormat.EAN_13, "45mm", "27mm", null, 11, 7, RETAIL, length -> "0012345678905", same, 13, 13, 13, 1),
new Profile("ean8", "ean8", BarcodeFormat.EAN_8, "45mm", "27mm", null, 7, 7, RETAIL, length -> "12345670", same, 8, 8, 8, 1),
new Profile("upca", "upca", BarcodeFormat.UPC_A, "45mm", "27mm", null, 9, 9, RETAIL, length -> "012345678905", same, 12, 12, 12, 1),
new Profile("upce", "upce", BarcodeFormat.UPC_E, "45mm", "27mm", null, 9, 7, RETAIL, length -> "04252614", same, 8, 8, 8, 1),
new Profile("ean13 in general distribution", "ean13", BarcodeFormat.EAN_13, "60mm", "36mm", "gs1-logistics", 11, 7, DISTRIBUTION, length -> "4006381333931", same, 13, 13, 13, 1),
new Profile("qr", "qr", BarcodeFormat.QR_CODE, "40mm", "40mm", null, 4, 4, MATRIX, length -> repeated(LETTERS, length), same, 1, 40, 2000, 1),
new Profile("datamatrix", "datamatrix", BarcodeFormat.DATA_MATRIX, "40mm", "40mm", null, 4, 4, MATRIX, length -> repeated(LETTERS, length), same, 1, 40, 2000, 1),
new Profile("pdf417", "pdf417", BarcodeFormat.PDF_417, "90mm", "30mm", null, 4, 4, MATRIX, length -> repeated(LETTERS, length), same, 1, 40, 1000, 1),
new Profile("aztec", "aztec", BarcodeFormat.AZTEC, "40mm", "40mm", null, 4, 4, MATRIX, length -> repeated(LETTERS, length), same, 1, 40, 2000, 1)));
}
/***************************************************************************
** A barcode in the middle of the label. Nothing says where the symbol sits
** in its box, so it sits in the middle of that too.
***************************************************************************/
private static String element(Profile profile, String value)
{
ObjectNode element = Wire.JSON.createObjectNode().put("id", "code").put("type", "barcode").put("symbology", profile.symbology()).put("value", value);
if(profile.profile() != null)
{
element.put("barcodeProfile", profile.profile());
}
return (element.put("anchor", "center").put("width", profile.width()).put("height", profile.height()).toString());
}
/***************************************************************************
** Whether a value of this length is accepted at every resolution.
***************************************************************************/
private static boolean fits(Profile profile, int length) throws Exception
{
for(int dpi : Scene2.RESOLUTIONS)
{
try
{
RendererMain.process(BarcodeFixture.request("VALIDATE", dpi, element(profile, profile.value().apply(length)), Map.of()));
}
catch(Refusal refusal)
{
return (false);
}
}
return (true);
}
/***************************************************************************
** The longest value of a profile that every resolution accepts, found by
** halving between a length that fits and one that does not.
***************************************************************************/
private static int longest(Profile profile) throws Exception
{
int fits = 0;
int refused = (profile.most() - profile.fewest()) / profile.step() + 1;
assertTrue(fits(profile, profile.fewest()), profile + " must hold its shortest value");
while(refused - fits > 1)
{
int middle = (fits + refused) / 2;
if(fits(profile, profile.fewest() + middle * profile.step()))
{
fits = middle;
}
else
{
refused = middle;
}
}
return (profile.fewest() + fits * profile.step());
}
/***************************************************************************
** Every profile.
***************************************************************************/
static List<Profile> everyProfile()
{
return (profiles());
}
/***************************************************************************
** A short, a typical and the longest value at each resolution: the label
** decodes to the value, in the symbology asked for, at a whole-dot module
** that is the largest the box holds and never under the minimum of its
** profile, with the quiet zones of its symbology blank, the symbol in the
** middle of its box within one dot and, for a linear symbol, bars as tall
** as its symbology asks.
***************************************************************************/
@ParameterizedTest(name = "{0}")
@MethodSource("everyProfile")
void theLabelDecodesToItsValueAtEveryResolution(Profile profile) throws Exception
{
int longest = longest(profile);
if(longest < profile.most())
{
int longer = longest + profile.step();
List<String> codes = new ArrayList<>();
for(int dpi : Scene2.RESOLUTIONS)
{
try
{
RendererMain.process(BarcodeFixture.request("RENDER", dpi, element(profile, profile.value().apply(longer)), Map.of()));
}
catch(Refusal refusal)
{
codes.add(refusal.diagnostic().code());
}
}
assertTrue(codes.contains("BARCODE_DOES_NOT_FIT"), profile + " one step past its longest value: " + codes);
}
Symbology rules = Symbology.of(profile.symbology());
StringBuilder report = new StringBuilder(profile.name());
for(int length : List.of(profile.fewest(), profile.typical(), longest))
{
String value = profile.value().apply(length);
for(int dpi : Scene2.RESOLUTIONS)
{
String about = profile + " of " + length + " characters at " + dpi + " dpi";
Map<String, Object> answer = BarcodeFixture.answer(BarcodeFixture.request("RENDER", dpi, element(profile, value), Map.of()));
Map<String, Object> chosen = BarcodeFixture.finding(answer, "BARCODE_MODULE");
boolean matrix = List.of("qr", "datamatrix", "pdf417", "aztec").contains(profile.symbology());
int module = BarcodeFixture.number(chosen, "measured", "moduleDots");
int modules = BarcodeFixture.number(chosen, "measured", "modules");
int quietLeft = BarcodeFixture.number(chosen, "measured", "quietLeftModules");
int quietRight = BarcodeFixture.number(chosen, "measured", "quietRightModules");
int width = BarcodeFixture.number(chosen, "measured", "widthDots");
int height = BarcodeFixture.number(chosen, "measured", "heightDots");
Frame box = BarcodeFixture.box(chosen, dpi);
//////////////////////////////////////////////////////////////////////////////////////
// the module: whole dots, at least the minimum for the resolution, and the largest //
// the box holds, since one dot more would not fit or would ask for taller bars //
//////////////////////////////////////////////////////////////////////////////////////
int minimum = profile.narrowest().get(Scene2.RESOLUTIONS.indexOf(dpi));
int bars = modules - quietLeft - quietRight;
assertEquals(List.of(profile.quietLeft(), profile.quietRight()), List.of(quietLeft, quietRight), about);
assertEquals(minimum, BarcodeFixture.number(chosen, "limit", "minModuleDots"), about);
assertTrue(module >= minimum, about + ": module " + module);
assertEquals(modules * module, width, about);
assertTrue(modules * (module + 1) > box.width() || (matrix ? height / module * (module + 1) > box.height() : rules.height(bars, dpi).at(module + 1) > box.height()), about + ": a larger module fits");
assertTrue(width <= box.width() && height <= box.height(), about + ": the symbol leaves its box");
assertTrue(matrix || rules.height(bars, dpi).at(module) <= box.height(), about + ": bars too short");
//////////////////////////////////////////////////////////////////////////////////////
// the picture: ink only inside the box less the quiet zones, the symbol with its //
// quiet zones in the middle within one dot, and every bar and space a whole number //
// of modules //
//////////////////////////////////////////////////////////////////////////////////////
boolean[][] page = BarcodeFixture.page(answer);
BarcodeFixture.Ink ink = BarcodeFixture.ink(page);
int left = ink.left() - box.x();
int right = box.right() - 1 - ink.right();
int top = ink.top() - box.y();
int bottom = box.bottom() - 1 - ink.bottom();
assertTrue(left >= quietLeft * module && right >= quietRight * module, about + ": quiet zones " + left + " and " + right);
boolean edged = !"aztec".equals(profile.symbology());
assertTrue(left >= (box.width() - width) / 2 + quietLeft * module && (!edged || left == (box.width() - width) / 2 + quietLeft * module), about + ": left margin " + left);
if(matrix)
{
assertTrue(top >= quietLeft * module && bottom >= quietLeft * module, about + ": quiet zones " + top + " and " + bottom);
assertTrue(top >= (box.height() - height) / 2 + quietLeft * module && (!edged || top == (box.height() - height) / 2 + quietLeft * module), about + ": top margin " + top);
}
else
{
assertTrue(Math.abs((left - quietLeft * module) - (right - quietRight * module)) <= 1, about + ": margins " + left + " and " + right);
assertEquals(box.height(), ink.height(), about);
assertEquals(0, top, about);
List<Integer> runs = BarcodeFixture.runs(page[(ink.top() + ink.bottom()) / 2]);
assertEquals(module, runs.stream().mapToInt(Integer::intValue).min().orElseThrow(), about);
assertEquals(bars * module, runs.stream().mapToInt(Integer::intValue).sum(), about);
}
for(int y = ink.top(); y <= ink.bottom(); y++)
{
for(int run : BarcodeFixture.runs(page[y]))
{
assertEquals(0, run % module, about + ": a run of " + run + " dots in row " + y);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// the content, read by a decoder that shares nothing with the encoder //
//////////////////////////////////////////////////////////////////////////////////////
boolean gs1 = "gs1-128".equals(profile.symbology());
Result decoded = BarcodeFixture.decode(page, profile.format(), gs1);
assertEquals(profile.format(), decoded.getBarcodeFormat(), about);
assertEquals(profile.decoded().apply(value), decoded.getText(), about);
if(gs1)
{
assertEquals("]C1", decoded.getResultMetadata().get(ResultMetadataType.SYMBOLOGY_IDENTIFIER), about);
assertTrue(decoded.getText().startsWith("]C1"), about);
}
report.append(' ').append(length).append('@').append(dpi).append('=').append(module);
}
}
System.out.println("decoded " + report);
}
}
@@ -0,0 +1,310 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Base64;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.kingsrook.qbits.renderer.RendererMain;
import com.kingsrook.qbits.renderer.Wire;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.SceneFixture;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*******************************************************************************
** Shared test support for barcodes in version 2 scenes. Every test here looks
** at the label a printer would be sent: the page is rebuilt from the graphic
** fields of the emitted ZPL and, where a test decodes, read by ZXing, a
** decoder that shares nothing with the encoder.
*******************************************************************************/
final class BarcodeFixture
{
////////////////////////////////////////////////////////////////////////////////////////////////
// a 4 x 2 in label with 3 mm margins: room for a long linear symbol and for a large matrix //
////////////////////////////////////////////////////////////////////////////////////////////////
static final int WIDTH = 101_600;
static final int HEIGHT = 50_800;
static final int MARGIN = 3000;
/***************************************************************************
** Utility class.
***************************************************************************/
private BarcodeFixture()
{
}
/***************************************************************************
** The ink of a page: the first and last inked column and row, and the
** narrowest and widest run of ink along the row through the middle.
***************************************************************************/
record Ink(int left, int top, int right, int bottom)
{
/************************************************************************
** Columns of ink, first to last.
************************************************************************/
int width()
{
return (right - left + 1);
}
/************************************************************************
** Rows of ink, first to last.
************************************************************************/
int height()
{
return (bottom - top + 1);
}
}
/***************************************************************************
** A request for a scene of these elements on the 4 x 2 in label, at a
** render target, with a record.
***************************************************************************/
static ObjectNode request(String operation, int dpi, String elements, Map<String, Object> record)
{
String source = "{\"schema\":\"qqq-zpl-scene/2\",\"design\":{\"width\":\"4in\",\"height\":\"2in\"},\"elements\":[" + elements + "]}";
ObjectNode request = SceneFixture.request(operation, SceneFixture.stock(WIDTH, HEIGHT, MARGIN, 203), source).put("targetDpi", dpi);
request.set("context", Wire.JSON.valueToTree(Map.of("record", record)));
return (request);
}
/***************************************************************************
** The GS1 check digit of the digits before it, worked as the General
** Specifications describe it: the digit nearest the check digit is
** multiplied by 3, the next by 1, and so on, and the check digit takes the
** sum up to a multiple of ten.
***************************************************************************/
static char checkDigit(String body)
{
int sum = 0;
int weight = 3;
for(int index = body.length() - 1; index >= 0; index--)
{
sum += Character.digit(body.charAt(index), 10) * weight;
weight = 4 - weight;
}
return ((char) ('0' + (10 - sum % 10) % 10));
}
/***************************************************************************
** The first column and row of the printable area on the page, in dots: the
** margin rounded up.
***************************************************************************/
static int origin(int dpi)
{
return ((MARGIN * dpi + 25_399) / 25_400);
}
/***************************************************************************
** The answer of the worker to a request that must succeed.
***************************************************************************/
static Map<String, Object> answer(JsonNode request) throws Exception
{
Map<String, Object> answer = RendererMain.process(request);
assertEquals("OK", answer.get("outcome"));
return (answer);
}
/***************************************************************************
** The page a printer would draw from an answer.
***************************************************************************/
static boolean[][] page(Map<String, Object> answer)
{
return (SceneFixture.raster(Base64.getDecoder().decode((String) answer.get("base64"))));
}
/***************************************************************************
** The one finding of a code in an answer.
***************************************************************************/
@SuppressWarnings("unchecked")
static Map<String, Object> finding(Map<String, Object> answer, String code)
{
List<Map<String, Object>> found = ((List<Map<String, Object>>) answer.get("diagnostics")).stream().filter(finding -> code.equals(finding.get("code"))).toList();
assertEquals(1, found.size(), code);
return (found.getFirst());
}
/***************************************************************************
** A named number of a finding, from `measured` or `limit`.
***************************************************************************/
@SuppressWarnings("unchecked")
static int number(Map<String, Object> finding, String part, String name)
{
return (((Map<String, Integer>) finding.get(part)).get(name));
}
/***************************************************************************
** The box of a finding, moved from the printable area onto the page.
***************************************************************************/
@SuppressWarnings("unchecked")
static Frame box(Map<String, Object> finding, int dpi)
{
List<Integer> box = (List<Integer>) finding.get("box");
return (new Frame(box.get(0) + origin(dpi), box.get(1) + origin(dpi), box.get(2), box.get(3)));
}
/***************************************************************************
** Where the ink of a page is.
***************************************************************************/
static Ink ink(boolean[][] page)
{
int left = Integer.MAX_VALUE;
int top = Integer.MAX_VALUE;
int right = -1;
int bottom = -1;
for(int y = 0; y < page.length; y++)
{
for(int x = 0; x < page[y].length; x++)
{
if(page[y][x])
{
left = Math.min(left, x);
top = Math.min(top, y);
right = Math.max(right, x);
bottom = Math.max(bottom, y);
}
}
}
return (new Ink(left, top, right, bottom));
}
/***************************************************************************
** The lengths of the runs of ink and of blank between the first and last
** ink of one row, in order, starting with ink.
***************************************************************************/
static List<Integer> runs(boolean[] row)
{
List<Integer> runs = new ArrayList<>();
int first = -1;
int last = -1;
for(int x = 0; x < row.length; x++)
{
if(row[x])
{
first = first < 0 ? x : first;
last = x;
}
}
int start = first;
for(int x = first + 1; first >= 0 && x <= last + 1; x++)
{
if(x > last || row[x] != row[x - 1])
{
runs.add(x - start);
start = x;
}
}
return (runs);
}
/***************************************************************************
** One column of a page as a row, for a symbol turned a quarter.
***************************************************************************/
static boolean[] column(boolean[][] page, int x)
{
boolean[] column = new boolean[page.length];
for(int y = 0; y < page.length; y++)
{
column[y] = page[y][x];
}
return (column);
}
/***************************************************************************
** Read the one symbol on a page with ZXing. A GS1 symbol is read as one, so
** its FNC1 comes back as the `]C1` identifier and as separators. (ZXing
** also reads a Code 128 check character whose value is that of FNC1 as one
** more separator at the end; a GS1 value chosen for a test must not have
** that check character. `[10]LOT[21]X` is one that does.)
***************************************************************************/
static Result decode(boolean[][] page, BarcodeFormat format, boolean gs1) throws Exception
{
BufferedImage picture = new BufferedImage(page[0].length, page.length, BufferedImage.TYPE_BYTE_GRAY);
for(int y = 0; y < page.length; y++)
{
for(int x = 0; x < page[y].length; x++)
{
picture.setRGB(x, y, page[y][x] ? 0x000000 : 0xFFFFFF);
}
}
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.POSSIBLE_FORMATS, List.of(format));
hints.put(DecodeHintType.TRY_HARDER, true);
if(gs1)
{
hints.put(DecodeHintType.ASSUME_GS1, true);
}
if(format == BarcodeFormat.QR_CODE || format == BarcodeFormat.DATA_MATRIX)
{
/////////////////////////////////////////////////////////////////////////////////////////
// read the modules straight off the grid: the page is a rendering, with no skew or //
// noise, and this reads a matrix of two dots to the module that the detector for //
// photographs does not find //
/////////////////////////////////////////////////////////////////////////////////////////
hints.put(DecodeHintType.PURE_BARCODE, true);
}
return (new MultiFormatReader().decode(new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(picture))), hints));
}
}
@@ -0,0 +1,238 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.NotFoundException;
import com.kingsrook.qbits.renderer.RendererMain;
import com.kingsrook.qbits.renderer.Wire;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.Refusal;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import com.kingsrook.qbits.renderer.scene2.SceneFixture;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** Properties of a fitted barcode, over seeded symbologies, values, boxes,
** resolutions, profiles, alignments and rotations, each read from the label a
** printer would be sent. No clock and a fixed seed, so a failure replays.
*******************************************************************************/
class BarcodePropertyTest
{
private static final String LETTERS = "TEST0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final List<String> SYMBOLOGIES = List.of("code128", "code39", "itf", "gs1-128", "qr", "datamatrix");
private static final Map<String, BarcodeFormat> FORMATS = Map.of("code128", BarcodeFormat.CODE_128, "code39", BarcodeFormat.CODE_39, "itf", BarcodeFormat.ITF, "gs1-128", BarcodeFormat.CODE_128,
"qr", BarcodeFormat.QR_CODE, "datamatrix", BarcodeFormat.DATA_MATRIX);
/***************************************************************************
** A picture turned a quarter clockwise.
***************************************************************************/
private static boolean[][] turned(boolean[][] picture)
{
boolean[][] turned = new boolean[picture[0].length][picture.length];
for(int y = 0; y < turned.length; y++)
{
for(int x = 0; x < turned[y].length; x++)
{
turned[y][x] = picture[picture.length - 1 - x][y];
}
}
return (turned);
}
/***************************************************************************
** Property: a barcode is either drawn or refused as not fitting, and
**
** - drawn, its module is a whole number of dots, never under the minimum,
** and under what its profile asks only when the scene states a smaller
** minimum, which is then warned of; every bar and space is a whole
** number of modules; the symbol and its quiet zones are inside the box;
** the alignment puts what is left over where it says, in the middle when
** it says nothing, and the middle leaves equal margins within one dot; a
** linear symbol takes the whole of the box across its bars, which are as
** tall as its symbology asks unless the scene states its own height,
** which is then warned of; and the label decodes to the value;
** - refused, the numbers say why: the dots needed at the minimum module are
** more than the box has on the axis that is short.
***************************************************************************/
@Test
void aBarcodeIsDrawnInWholeDotsInsideItsBoxOrRefusedWithItsNumbers() throws Exception
{
SplittableRandom random = new SplittableRandom(20261114L);
int drawn = 0;
int refused = 0;
int below = 0;
int low = 0;
for(int iteration = 0; iteration < 320; iteration++)
{
String symbology = SYMBOLOGIES.get(random.nextInt(SYMBOLOGIES.size()));
boolean matrix = "qr".equals(symbology) || "datamatrix".equals(symbology);
int length = matrix ? random.nextInt(1, 61) : random.nextInt(3, 11) * 2;
String text = LETTERS.repeat(2).substring(0, length);
String value = switch(symbology)
{
case "itf" -> "0012345678".repeat(2).substring(0, length);
case "gs1-128" -> "[01]00012345678905[21]" + text.substring(0, length / 2);
default -> text;
};
String scanned = "gs1-128".equals(symbology) ? "]C1" + "0100012345678905" + "21" + text.substring(0, length / 2) : value;
int dpi = Scene2.RESOLUTIONS.get(random.nextInt(3));
int rotation = random.nextInt(4) * 90;
boolean upright = rotation % 180 == 0;
boolean stated = random.nextInt(4) == 0;
boolean shorter = random.nextInt(4) == 0;
String profile = List.of("", "none", "gs1-general", "gs1-logistics").get(random.nextInt(4));
String align = List.of("", "left", "center", "right").get(random.nextInt(4));
String valign = List.of("", "top", "middle", "bottom").get(random.nextInt(4));
int along = random.nextInt(12_000, upright ? 94_000 : 43_000);
int across = random.nextInt(4000, shorter ? 12_000 : upright ? 43_000 : 94_000);
ObjectNode element = Wire.JSON.createObjectNode().put("id", "code").put("type", "barcode").put("symbology", symbology).put("value", value).put("anchor", "center");
element.put("width", (upright ? along : across) / 1000.0 + "mm").put("height", (upright ? across : along) / 1000.0 + "mm").put("rotation", rotation);
if(stated)
{
element.put("minModule", "1dot");
}
if(shorter)
{
element.put("minHeight", "3mm");
}
if(!profile.isEmpty())
{
element.put("barcodeProfile", profile);
}
if(!align.isEmpty())
{
element.put("align", align);
}
if(!valign.isEmpty())
{
element.put("valign", valign);
}
String about = "iteration " + iteration + ": " + element + " at " + dpi + " dpi";
Symbology rules = Symbology.of(symbology);
int recommended = rules.narrowest(Symbology.Profile.of(profile), dpi);
int quiet = matrix ? 4 : 10;
Map<String, Object> answer;
try
{
answer = BarcodeFixture.answer(BarcodeFixture.request("RENDER", dpi, element.toString(), Map.of()));
}
catch(Refusal refusal)
{
refused++;
Map<String, Object> wire = refusal.diagnostic().wire();
assertEquals("BARCODE_DOES_NOT_FIT", wire.get("code"), about);
int minimum = BarcodeFixture.number(wire, "limit", "minModuleDots");
assertEquals(stated ? 1 : recommended, minimum, about);
assertTrue(BarcodeFixture.number(wire, "measured", "moduleDots") < minimum, about);
assertEquals(BarcodeFixture.number(wire, "measured", "modules") * minimum, BarcodeFixture.number(wire, "measured", "widthDots"), about);
assertTrue(BarcodeFixture.number(wire, "measured", "widthDots") > BarcodeFixture.number(wire, "limit", "widthDots")
|| BarcodeFixture.number(wire, "measured", "heightDots") > BarcodeFixture.number(wire, "limit", "heightDots"), about + ": " + wire);
assertEquals(wire, SceneFixture.refusal(() -> RendererMain.process(BarcodeFixture.request("VALIDATE", dpi, element.toString(), Map.of()))), about);
continue;
}
drawn++;
Map<String, Object> chosen = BarcodeFixture.finding(answer, "BARCODE_MODULE");
int module = BarcodeFixture.number(chosen, "measured", "moduleDots");
assertTrue(module >= (stated ? 1 : recommended), about + ": module " + module);
assertEquals(stated, ((List<?>) answer.get("diagnostics")).stream().anyMatch(finding -> "BARCODE_MODULE_BELOW_RECOMMENDED".equals(((Map<?, ?>) finding).get("code"))), about);
below += module < recommended ? 1 : 0;
//////////////////////////////////////////////////////////////////////////////////////////
// the symbol with its quiet zones, as the label shows it: the ink, widened by the //
// quiet zones on the axes the module was fitted on //
//////////////////////////////////////////////////////////////////////////////////////////
boolean[][] page = BarcodeFixture.page(answer);
Frame box = BarcodeFixture.box(chosen, dpi);
BarcodeFixture.Ink ink = BarcodeFixture.ink(page);
int marginX = matrix || upright ? quiet * module : 0;
int marginY = matrix || !upright ? quiet * module : 0;
Frame area = new Frame(ink.left() - marginX, ink.top() - marginY, ink.width() + 2 * marginX, ink.height() + 2 * marginY);
assertTrue(box.contains(area), about + ": " + area + " leaves " + box);
int symbolWidth = BarcodeFixture.number(chosen, "measured", "widthDots");
int symbolHeight = BarcodeFixture.number(chosen, "measured", "heightDots");
assertEquals(List.of(upright ? symbolWidth : symbolHeight, upright ? symbolHeight : symbolWidth), List.of(area.width(), area.height()), about);
assertEquals(BarcodeFixture.number(chosen, "measured", "modules") * module, symbolWidth, about);
int spareX = box.width() - area.width();
int spareY = box.height() - area.height();
assertEquals(Map.of("left", 0, "", spareX / 2, "center", spareX / 2, "right", spareX).get(align), area.x() - box.x(), about);
assertEquals(Map.of("top", 0, "", spareY / 2, "middle", spareY / 2, "bottom", spareY).get(valign), area.y() - box.y(), about);
assertTrue(!List.of("", "center").contains(align) || Math.abs((area.x() - box.x()) - (box.right() - area.right())) <= 1, about);
assertTrue(!List.of("", "middle").contains(valign) || Math.abs((area.y() - box.y()) - (box.bottom() - area.bottom())) <= 1, about);
assertFalse(!matrix && (upright ? spareY : spareX) != 0, about + ": the bars do not take the whole box");
if(!matrix)
{
int asked = rules.height(BarcodeFixture.number(chosen, "measured", "modules") - 2 * quiet, dpi).at(module);
boolean warned = ((List<?>) answer.get("diagnostics")).stream().anyMatch(finding -> "BARCODE_HEIGHT_BELOW_RECOMMENDED".equals(((Map<?, ?>) finding).get("code")));
assertEquals(symbolHeight < asked, warned, about + ": bars of " + symbolHeight + " dots where " + asked + " are asked");
assertTrue(shorter || !warned, about);
low += warned ? 1 : 0;
}
for(int y = ink.top(); y <= ink.bottom(); y++)
{
for(int run : BarcodeFixture.runs(page[y]))
{
assertEquals(0, (matrix || upright ? run : 0) % module, about + ": a run of " + run + " dots in row " + y);
}
}
for(int x = ink.left(); x <= ink.right(); x++)
{
for(int run : BarcodeFixture.runs(BarcodeFixture.column(page, x)))
{
assertEquals(0, (matrix || !upright ? run : 0) % module, about + ": a run of " + run + " dots in column " + x);
}
}
boolean[][] symbol = new boolean[area.height()][area.width()];
for(int y = 0; y < symbol.length; y++)
{
System.arraycopy(page[area.y() + y], area.x(), symbol[y], 0, area.width());
}
for(int turn = rotation; turn % 360 != 0; turn += 90)
{
symbol = turned(symbol);
}
try
{
assertEquals(scanned, BarcodeFixture.decode(symbol, FORMATS.get(symbology), "gs1-128".equals(symbology)).getText(), about);
}
catch(NotFoundException unread)
{
throw new AssertionError(about + ": module " + module + ", the label does not decode", unread);
}
}
assertTrue(drawn > 80 && refused > 40 && below > 5 && low > 2, drawn + " drawn, " + refused + " refused, " + below + " below the module asked, " + low + " with bars shorter than asked");
}
}
@@ -0,0 +1,224 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.util.ArrayList;
import java.util.List;
import java.util.SplittableRandom;
import com.kingsrook.qbits.renderer.scene2.Length;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The module-fit rule as arithmetic: the largest whole-dot module that holds
** the symbol and its quiet zones in the box, never under the minimum, and for
** a linear symbol never one that makes it too wide for the height of its box.
*******************************************************************************/
class ModuleFitTest
{
private static final int MICROMETRES_PER_INCH = 25_400;
private static final int NO_MAXIMUM = Integer.MAX_VALUE;
/***************************************************************************
** A linear symbol with no rule for the height of its bars.
***************************************************************************/
private static ModuleFit.Request linear(int columns, int along, int across, int minimum, int maximum)
{
return (new ModuleFit.Request(columns, 0, along, across, minimum, maximum, new ModuleFit.Height(columns, 0, 0, 1)));
}
/***************************************************************************
** The worked example: a GS1-128 of 319 modules, quiet zones included, in a
** box 719 dots wide (90 mm at 203 dpi) is drawn at 2 dots, 638 dots wide;
** 3 dots would need 957. In a box of 637 dots it does not fit: the largest
** module is 1 dot, under the minimum, and the answer states the 638 dots
** the minimum needs.
***************************************************************************/
@Test
void aLinearSymbolTakesTheLargestModuleThatFitsItsWidth()
{
assertEquals(new ModuleFit.Fit(2, 638, 87, true), ModuleFit.fit(linear(319, 719, 87, 2, NO_MAXIMUM)));
assertEquals(new ModuleFit.Fit(2, 638, 87, true), ModuleFit.fit(linear(319, 638, 87, 2, NO_MAXIMUM)));
assertEquals(new ModuleFit.Fit(1, 638, 0, false), ModuleFit.fit(linear(319, 637, 87, 2, NO_MAXIMUM)));
assertEquals(new ModuleFit.Fit(0, 638, 0, false), ModuleFit.fit(linear(319, 318, 87, 2, NO_MAXIMUM)));
assertEquals(new ModuleFit.Fit(1, 319, 87, true), ModuleFit.fit(linear(319, 637, 87, 1, NO_MAXIMUM)));
assertEquals(new ModuleFit.Fit(7, 2233, 1, true), ModuleFit.fit(linear(319, 2400, 1, 6, NO_MAXIMUM)));
assertEquals(new ModuleFit.Fit(3, 957, 87, true), ModuleFit.fit(linear(319, 2400, 87, 2, 3)));
}
/***************************************************************************
** A two-dimensional symbol is held on both axes, so the shorter side of
** the box decides; a stated maximum caps either kind.
***************************************************************************/
@Test
void aMatrixSymbolIsHeldOnBothAxesAndAMaximumCaps()
{
assertEquals(new ModuleFit.Fit(5, 145, 145, true), ModuleFit.fit(new ModuleFit.Request(29, 29, 319, 147, 3, NO_MAXIMUM, null)));
assertEquals(new ModuleFit.Fit(11, 319, 319, true), ModuleFit.fit(new ModuleFit.Request(29, 29, 319, 400, 3, NO_MAXIMUM, null)));
assertEquals(new ModuleFit.Fit(4, 116, 116, true), ModuleFit.fit(new ModuleFit.Request(29, 29, 319, 400, 3, 4, null)));
assertEquals(new ModuleFit.Fit(2, 87, 87, false), ModuleFit.fit(new ModuleFit.Request(29, 29, 319, 86, 3, NO_MAXIMUM, null)));
}
/***************************************************************************
** The bars of a linear symbol must be as tall as their own width asks: here
** the rule of Code 128, 15% of the width of the bars and never under 5 mm,
** which is 40 dots at 203 dpi. A 44-character GS1-128 has 299 modules of
** bars: at 2 dots they are 598 dots wide and must be 90 dots tall (89.7,
** taken up); at 3 dots, 135. So a module the width would allow is not
** taken when the box is too short for it, and when even the minimum module
** needs more height than the box has, the answer states the height it
** needs. A box under the 5 mm holds no module at all.
***************************************************************************/
@Test
void theBarsOfALinearSymbolAreAsTallAsTheirWidthAsks()
{
ModuleFit.Height asked = new ModuleFit.Height(299, 40, 15, 100);
assertEquals(List.of(40, 45, 90, 135, 180), List.of(asked.at(0), asked.at(1), asked.at(2), asked.at(3), asked.at(4)));
assertEquals(new ModuleFit.Fit(2, 638, 95, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 719, 95, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(2, 638, 95, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 1000, 95, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(3, 957, 135, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 1000, 135, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(2, 638, 134, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 1000, 134, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(2, 638, 90, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 719, 90, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(1, 638, 90, false), ModuleFit.fit(new ModuleFit.Request(319, 0, 719, 89, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(1, 319, 89, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 719, 89, 1, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(0, 638, 90, false), ModuleFit.fit(new ModuleFit.Request(319, 0, 719, 39, 2, NO_MAXIMUM, asked)));
assertEquals(new ModuleFit.Fit(0, 319, 45, false), ModuleFit.fit(new ModuleFit.Request(319, 0, 719, 39, 1, NO_MAXIMUM, asked)));
///////////////////////////////////////////////////////////////////////////////////////////
// a height the scene states itself is a length and nothing more: no share of the width //
///////////////////////////////////////////////////////////////////////////////////////////
ModuleFit.Height stated = new ModuleFit.Height(299, 60, 0, 1);
assertEquals(60, stated.at(7));
assertEquals(new ModuleFit.Fit(3, 957, 60, true), ModuleFit.fit(new ModuleFit.Request(319, 0, 1000, 60, 2, NO_MAXIMUM, stated)));
assertEquals(new ModuleFit.Fit(0, 638, 60, false), ModuleFit.fit(new ModuleFit.Request(319, 0, 1000, 59, 2, NO_MAXIMUM, stated)));
}
/***************************************************************************
** Property, over seeded symbols, boxes and limits: the module is whole
** dots; when the symbol fits it is inside its box at a module between the
** minimum and the maximum, its bars are as tall as that module asks, and
** one dot more would not fit or would ask for taller bars; when it does
** not, the dots it needs at the minimum are more than the box has, on the
** axis that refused it.
***************************************************************************/
@Test
void theFittedSymbolIsInsideItsBoxAtTheLargestModuleOrTheNumbersSayWhyNot()
{
SplittableRandom random = new SplittableRandom(20261112L);
int fitted = 0;
int refused = 0;
int low = 0;
for(int iteration = 0; iteration < 20_000; iteration++)
{
boolean matrix = random.nextBoolean();
int bars = random.nextInt(21, 600);
int columns = bars + random.nextInt(8, 40);
int rows = matrix ? random.nextInt(9, 200) : 0;
int along = random.nextInt(1, 4000);
int across = random.nextInt(1, 2000);
int minimum = random.nextInt(1, 10);
int maximum = random.nextInt(4) == 0 ? minimum + random.nextInt(0, 6) : NO_MAXIMUM;
ModuleFit.Height height = matrix ? null : new ModuleFit.Height(bars, random.nextInt(0, 80), random.nextInt(3) == 0 ? 0 : random.nextInt(1, 80), 100);
ModuleFit.Request request = new ModuleFit.Request(columns, rows, along, across, minimum, maximum, height);
ModuleFit.Fit fit = ModuleFit.fit(request);
String about = request + " gave " + fit;
if(fit.fits())
{
fitted++;
assertTrue(fit.module() >= minimum && fit.module() <= maximum, about);
assertEquals(columns * fit.module(), fit.width(), about);
assertEquals(matrix ? rows * fit.module() : across, fit.height(), about);
assertTrue(fit.width() <= along && fit.height() <= across, about);
assertTrue(matrix || height.at(fit.module()) <= across, about);
assertTrue(fit.module() == maximum || columns * (fit.module() + 1) > along || (matrix ? rows * (fit.module() + 1) > across : height.at(fit.module() + 1) > across), about);
}
else
{
refused++;
assertTrue(fit.module() < minimum && fit.module() >= 0, about);
assertEquals(columns * minimum, fit.width(), about);
assertEquals(matrix ? rows * minimum : height.at(minimum), fit.height(), about);
assertTrue(fit.width() > along || fit.height() > across, about);
low += fit.width() <= along ? 1 : 0;
}
}
assertTrue(fitted > 2000 && refused > 2000 && low > 500, fitted + " fitted, " + refused + " refused, " + low + " for their height alone");
}
/***************************************************************************
** Property, over seeded symbols and physical boxes at the design's minimum
** modules: a symbol with room to spare is refused at no resolution. The
** room is what rounding can cost: the minimum goes up to a whole dot, which
** at most makes 0.25 mm into 0.254 mm (and 0.375 mm into 0.424 mm, five
** dots at 300 dpi), and the box goes down to a whole dot, which at most
** loses one dot of 203 dpi. Where a symbol with less room fits at one
** resolution and not at another, the refusal states the dots it needs and
** the dots the box has.
***************************************************************************/
@Test
void aSymbolWithRoomIsRefusedAtNoResolutionAndARoundingRefusalStatesItsNumbers()
{
SplittableRandom random = new SplittableRandom(20261113L);
int roomy = 0;
int divided = 0;
for(int iteration = 0; iteration < 20_000; iteration++)
{
boolean matrix = random.nextBoolean();
int columns = random.nextInt(21, 500);
Length minimum = new Length(Length.Unit.MM, matrix ? 375 : 250);
int exact = columns * minimum.micrometres();
Length box = new Length(Length.Unit.MM, exact + random.nextInt(-exact / 5, exact / 4));
int dotAt203 = (MICROMETRES_PER_INCH + 202) / 203;
boolean room = columns * (matrix ? 424 : 254) + dotAt203 <= box.micrometres();
List<ModuleFit.Fit> fits = new ArrayList<>();
for(int dpi : Scene2.RESOLUTIONS)
{
int along = box.size(dpi, 0);
ModuleFit.Fit fit = ModuleFit.fit(matrix ? new ModuleFit.Request(columns, columns, along, along, minimum.module(dpi), NO_MAXIMUM, null) : linear(columns, along, along, minimum.module(dpi), NO_MAXIMUM));
fits.add(fit);
String about = columns + " modules in " + box.micrometres() + " micrometres at " + dpi + " dpi gave " + fit;
assertFalse(room && !fit.fits(), about);
assertTrue(fit.fits() || (fit.width() == columns * minimum.module(dpi) && fit.width() > along), about);
assertTrue(!fit.fits() || (long) fit.module() * MICROMETRES_PER_INCH >= (long) minimum.micrometres() * dpi, about + ": a module under the physical minimum");
}
roomy += room ? 1 : 0;
divided += fits.stream().map(ModuleFit.Fit::fits).distinct().count() > 1 ? 1 : 0;
}
assertTrue(roomy > 2000 && divided > 100, roomy + " with room, " + divided + " refused at one resolution only");
}
}
@@ -0,0 +1,313 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import com.kingsrook.qbits.renderer.BarcodeFit;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The rules that keep a symbol from reading as something other than its
** value: no escape of the encoder in any value, no odd Interleaved 2 of 5, an
** EAN or UPC number whole and with its own check digit, and the check digit
** of every GS1 key that has one. Values are obviously fake, and a refusal is
** numbers only.
*******************************************************************************/
class PayloadTest
{
private static final String BACKSLASH = String.valueOf((char) 92);
/***************************************************************************
** The GS1 check digit of some digits, worked the way the General
** Specifications describe it and not the way `Payload` does: the digit
** nearest the check digit is multiplied by 3, the next by 1, and so on,
** and the check digit takes the sum up to a multiple of ten.
***************************************************************************/
private static char checkDigit(String body)
{
int sum = 0;
int weight = 3;
for(int index = body.length() - 1; index >= 0; index--)
{
sum += Character.digit(body.charAt(index), 10) * weight;
weight = 4 - weight;
}
return ((char) ('0' + (10 - sum % 10) % 10));
}
/***************************************************************************
** Seeded digits.
***************************************************************************/
private static String digits(SplittableRandom random, int length)
{
StringBuilder digits = new StringBuilder();
for(int index = 0; index < length; index++)
{
digits.append((char) ('0' + random.nextInt(10)));
}
return (digits.toString());
}
/***************************************************************************
** A number of a length with any check digit but its own.
***************************************************************************/
private static String mistyped(String body)
{
return (body + (char) ('0' + (checkDigit(body) - '0' + 3) % 10));
}
/***************************************************************************
** The check digit is the one rule of every GS1 key. Published numbers
** first (the GTIN-13 and UPC-A of the usual textbook examples, an EAN-8,
** the GTIN-14 these tests use), then every length a key has, against the
** rule worked the other way round; one digit changed, or anything that is
** not a digit, does not pass.
***************************************************************************/
@Test
void aCheckDigitIsVerifiedByTheGs1Rule()
{
for(String published : List.of("4006381333931", "036000291452", "73513537", "00012345678905", "0012345678905", "012345678905", "12345670"))
{
assertTrue(Payload.checked(published), published);
assertEquals(published.charAt(published.length() - 1), checkDigit(published.substring(0, published.length() - 1)), published);
}
SplittableRandom random = new SplittableRandom(20261118L);
for(int iteration = 0; iteration < 2000; iteration++)
{
String body = digits(random, List.of(7, 11, 12, 13, 16, 17).get(random.nextInt(6)));
String whole = body + checkDigit(body);
assertTrue(Payload.checked(whole), whole);
for(int other = 1; other < 10; other++)
{
assertFalse(Payload.checked(body + (char) ('0' + (whole.charAt(body.length()) - '0' + other) % 10)), whole + " with another check digit");
}
int changed = random.nextInt(body.length());
assertFalse(Payload.checked(whole.substring(0, changed) + (char) ('0' + (whole.charAt(changed) - '0' + 1 + random.nextInt(9)) % 10) + whole.substring(changed + 1)), whole + " with digit " + changed + " changed");
}
assertFalse(Payload.checked("001234567890S"));
assertFalse(Payload.checked("00123 5678905"));
assertFalse(Payload.checked("0012345678905".replace('0', (char) 0xFF10)));
assertFalse(Payload.checked("-012345678905"));
}
/***************************************************************************
** A UPC-E number stands for a UPC-A number, whose check digit it carries.
** The last of its six digits says where the zeros were taken out.
***************************************************************************/
@Test
void aUpcENumberIsCheckedAsTheNumberItStandsFor()
{
assertEquals("04210000526", Payload.expanded("0425261"));
assertEquals("01200000345", Payload.expanded("0123450"));
assertEquals("01220000345", Payload.expanded("0123452"));
assertEquals("01230000045", Payload.expanded("0123453"));
assertEquals("01234000005", Payload.expanded("0123454"));
assertEquals("01234500005", Payload.expanded("0123455"));
assertEquals("11234500009", Payload.expanded("1123459"));
assertEquals('4', checkDigit("04210000526"));
assertEquals(new Payload.Checked("0425261", null, null), Payload.of(Symbology.UPCE, "04252614"));
assertEquals(new Payload.Checked(null, Map.of("characters", 8, "checkDigitMatches", 0), Map.of("characters", 8, "checkDigitMatches", 1)), Payload.of(Symbology.UPCE, "04252615"));
}
/***************************************************************************
** The encoder reads `\<FNC1>` to `\<FNC4>` in a value as function
** characters: a record could so make a GS1-128 of a plain Code 128, set
** the reader-programming flag or change a character, and where a symbology
** has no such character the escape is dropped. No value holding the two
** characters an escape begins with is drawn, in any symbology, wherever
** they stand; the refusal is the count of characters. A backslash, or a
** less-than sign, alone is a character like any other.
***************************************************************************/
@Test
void noValueHoldsAnEscapeOfTheEncoder()
{
assertEquals(BACKSLASH + "<", Payload.ESCAPE);
for(String id : BarcodeFit.TYPES)
{
Symbology symbology = Symbology.of(id);
for(String function : List.of("FNC1>", "FNC2>", "FNC3>", "FNC4>", "", "fnc1>", "FNC5>", "<"))
{
for(String value : List.of(BACKSLASH + "<" + function + "0112345678901231", "TEST" + BACKSLASH + "<" + function + "A", "0012" + BACKSLASH + "<" + function, "[01]00012345678905[21]" + BACKSLASH + "<" + function))
{
assertTrue(Payload.escapes(value), id);
assertEquals(new Payload.Checked(null, Map.of("characters", value.length()), null), Payload.of(symbology, value), id + " with " + function);
}
}
}
for(String plain : List.of(BACKSLASH, "<", BACKSLASH + " <", "<" + BACKSLASH, "TEST" + BACKSLASH + "FNC1>", "<FNC1>", BACKSLASH + BACKSLASH + "TEST"))
{
assertFalse(Payload.escapes(plain), plain);
assertEquals(new Payload.Checked(plain, null, null), Payload.of(Symbology.CODE128, plain), plain);
assertEquals(new Payload.Checked(plain, null, null), Payload.of(Symbology.QR, plain), plain);
}
}
/***************************************************************************
** Interleaved 2 of 5 draws digits in pairs, and the encoder puts a zero in
** front of an odd number of them, which a scanner then reads. An odd
** number of digits is refused by its count; an even number goes to the
** encoder as it is.
***************************************************************************/
@Test
void interleavedTwoOfFiveOfAnOddLengthIsRefused()
{
for(int length = 1; length <= 41; length += 2)
{
String odd = "0012345678".repeat(5).substring(0, length);
assertEquals(new Payload.Checked(null, Map.of("characters", length), Map.of("charactersMultipleOf", 2)), Payload.of(Symbology.ITF, odd), odd);
assertEquals(new Payload.Checked(odd + "0", null, null), Payload.of(Symbology.ITF, odd + "0"), odd);
assertEquals(new Payload.Checked(odd, null, null), Payload.of(Symbology.CODE128, odd), odd);
}
}
/***************************************************************************
** An EAN or UPC value is the whole number, check digit included: 13 digits
** for `ean13`, 8 for `ean8`, 12 for `upca`, 8 for `upce`. The check digit
** is verified and the encoder is given the digits before it. A number
** without its check digit, or of any other length, is refused with the
** length it must have, and never padded; a wrong check digit, and anything
** that is not a digit, is refused as a check digit that does not match.
***************************************************************************/
@Test
void aRetailNumberIsWholeAndCarriesItsOwnCheckDigit()
{
Map<Symbology, String> numbers = Map.of(Symbology.EAN13, "0012345678905", Symbology.EAN8, "12345670", Symbology.UPCA, "012345678905", Symbology.UPCE, "04252614");
for(Map.Entry<Symbology, String> number : numbers.entrySet())
{
String whole = number.getValue();
String body = whole.substring(0, whole.length() - 1);
String about = number.getKey().id();
assertEquals(new Payload.Checked(body, null, null), Payload.of(number.getKey(), whole), about);
for(String other : List.of(body, body.substring(1), "0" + whole, whole + "0", "1", whole + "+12", "0".repeat(40)))
{
assertEquals(new Payload.Checked(null, Map.of("characters", other.length()), Map.of("characters", whole.length())), Payload.of(number.getKey(), other), about + " of " + other.length());
}
Payload.Checked mismatch = new Payload.Checked(null, Map.of("characters", whole.length(), "checkDigitMatches", 0), Map.of("characters", whole.length(), "checkDigitMatches", 1));
for(char digit = '0'; digit <= '9'; digit++)
{
assertEquals(digit == whole.charAt(body.length()) ? new Payload.Checked(body, null, null) : mismatch, Payload.of(number.getKey(), body + digit), about + " ending " + digit);
}
assertEquals(mismatch, Payload.of(number.getKey(), "A" + whole.substring(1)), about);
assertEquals(mismatch, Payload.of(number.getKey(), body + "+"), about);
assertEquals(mismatch, Payload.of(number.getKey(), " ".repeat(whole.length())), about);
}
SplittableRandom random = new SplittableRandom(20261119L);
for(int iteration = 0; iteration < 500; iteration++)
{
String thirteen = digits(random, 12);
assertEquals(thirteen, Payload.of(Symbology.EAN13, thirteen + checkDigit(thirteen)).encoded());
assertNull(Payload.of(Symbology.EAN13, mistyped(thirteen)).encoded());
String twelve = digits(random, 11);
assertEquals(twelve, Payload.of(Symbology.UPCA, twelve + checkDigit(twelve)).encoded());
assertNull(Payload.of(Symbology.UPCA, mistyped(twelve)).encoded());
String eight = digits(random, 7);
assertEquals(eight, Payload.of(Symbology.EAN8, eight + checkDigit(eight)).encoded());
assertNull(Payload.of(Symbology.EAN8, mistyped(eight)).encoded());
assertEquals(eight, Payload.of(Symbology.UPCE, eight + checkDigit(Payload.expanded(eight))).encoded());
assertNull(Payload.of(Symbology.UPCE, mistyped(Payload.expanded(eight)).substring(11).transform(check -> eight + check)).encoded());
}
}
/***************************************************************************
** The encoder checks the lengths of a GS1 element string, not its check
** digits, so a GTIN with a wrong check digit would print as a label that
** scans as another item. Every application identifier whose data begins
** with a key that ends in a check digit is verified: SSCC, GTIN, GDTI,
** GCN, GSIN, the GLNs, GRAI after its leading zero, ITIP and GSRN. The
** refusal names the identifier, from that fixed list, and nothing of the
** value. Data of an identifier outside the list is left to the encoder.
***************************************************************************/
@Test
void theCheckDigitOfEveryGs1KeyIsVerified()
{
String typical = "[01]00012345678905[11]260101[21]TEST00010002";
assertEquals(new Payload.Checked(typical, null, null), Payload.of(Symbology.GS1_128, typical));
assertEquals(new Payload.Checked(null, Map.of("characters", 44, "applicationIdentifier", 1, "checkDigitMatches", 0), Map.of("checkDigitMatches", 1)),
Payload.of(Symbology.GS1_128, typical.replace("678905", "678906")));
assertEquals(new Payload.Checked(null, Map.of("characters", 44, "applicationIdentifier", 1, "checkDigitMatches", 0), Map.of("checkDigitMatches", 1)),
Payload.of(Symbology.GS1_128, "[11]260101[21]TEST00010002[01]00012345678995"));
Map<String, List<Integer>> keys = Map.ofEntries(Map.entry("00", List.of(0, 18)), Map.entry("01", List.of(0, 14)), Map.entry("02", List.of(0, 14)), Map.entry("03", List.of(0, 14)),
Map.entry("253", List.of(0, 13)), Map.entry("255", List.of(0, 13)), Map.entry("402", List.of(0, 17)), Map.entry("410", List.of(0, 13)), Map.entry("411", List.of(0, 13)),
Map.entry("412", List.of(0, 13)), Map.entry("413", List.of(0, 13)), Map.entry("414", List.of(0, 13)), Map.entry("415", List.of(0, 13)), Map.entry("416", List.of(0, 13)),
Map.entry("417", List.of(0, 13)), Map.entry("8003", List.of(1, 13)), Map.entry("8006", List.of(0, 14)), Map.entry("8026", List.of(0, 14)), Map.entry("8017", List.of(0, 18)),
Map.entry("8018", List.of(0, 18)));
SplittableRandom random = new SplittableRandom(20261120L);
for(Map.Entry<String, List<Integer>> key : keys.entrySet())
{
for(int iteration = 0; iteration < 50; iteration++)
{
String body = digits(random, key.getValue().get(1) - 1);
String before = "0".repeat(key.getValue().get(0));
String after = List.of("", "0101", "TEST01").get(random.nextInt(3));
String good = "[" + key.getKey() + "]" + before + body + checkDigit(body) + after;
String bad = "[" + key.getKey() + "]" + before + mistyped(body) + after;
String about = "(" + key.getKey() + ")";
assertEquals(good, Payload.of(Symbology.GS1_128, good).encoded(), about);
assertEquals(good + "[10]TEST", Payload.of(Symbology.GS1_128, good + "[10]TEST").encoded(), about);
Payload.Checked refused = new Payload.Checked(null, Map.of("characters", bad.length(), "applicationIdentifier", Integer.parseInt(key.getKey()), "checkDigitMatches", 0), Map.of("checkDigitMatches", 1));
assertEquals(refused, Payload.of(Symbology.GS1_128, bad), about);
assertNull(Payload.of(Symbology.GS1_128, "[10]TEST" + bad).encoded(), about);
assertNull(Payload.of(Symbology.GS1_128, good + bad).encoded(), about);
}
assertNull(Payload.of(Symbology.GS1_128, "[" + key.getKey() + "]123").encoded(), key.getKey());
assertNull(Payload.of(Symbology.GS1_128, "[" + key.getKey() + "]").encoded(), key.getKey());
assertNull(Payload.of(Symbology.GS1_128, "[" + key.getKey() + "]" + "A".repeat(18)).encoded(), key.getKey());
}
///////////////////////////////////////////////////////////////////////////////////////////
// identifiers with no such key, and strings the encoder will refuse for their shape, //
// pass here as they are; and the rule is for element strings only //
///////////////////////////////////////////////////////////////////////////////////////////
for(String other : List.of("[21]00012345678906", "[10]1", "[8013]TEST", "[401]00012345678906", "[01", "[", "(01)00012345678906", "[1]00012345678906", "[001]00012345678906"))
{
assertEquals(new Payload.Checked(other, null, null), Payload.of(Symbology.GS1_128, other), other);
}
assertEquals("[01]00012345678906", Payload.of(Symbology.CODE128, "[01]00012345678906").encoded());
assertEquals("[01]00012345678906", Payload.of(Symbology.QR, "[01]00012345678906").encoded());
}
}
@@ -0,0 +1,291 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.barcode;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import com.kingsrook.qbits.renderer.BarcodeFit;
import com.kingsrook.qbits.renderer.Barcodes;
import com.kingsrook.qbits.renderer.Wire;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The table of the symbologies: its numbers written out a second time here,
** so that a change to one is a change to both, and what it says of the
** encoder held to the encoder.
*******************************************************************************/
class SymbologyTest
{
private static final String ACCENTED = Character.toString(0xE9);
private static final List<String> LINEAR = List.of("code128", "code39", "code93", "itf", "gs1-128", "ean13", "ean8", "upca", "upce");
private static final List<String> RETAIL = List.of("ean13", "ean8", "upca", "upce");
/***************************************************************************
** The modules of a symbol as the encoder of version 1 draws it, without
** its quiet zones: across, and down.
***************************************************************************/
private static List<Integer> modules(String symbology, String value)
{
int margin = LINEAR.contains(symbology) ? 10 : 4;
BufferedImage image = Barcodes.renderForFormat("ZPL", symbology, value, 1, margin, Wire.JSON.createObjectNode());
return (List.of(image.getWidth() - 2 * margin, image.getHeight() - 2 * margin));
}
/***************************************************************************
** The narrowest bar of a symbology under a profile, in dots at 203, 300 and
** 600 dpi.
***************************************************************************/
private static List<Integer> narrowest(String symbology, Symbology.Profile profile)
{
return (Scene2.RESOLUTIONS.stream().map(dpi -> Symbology.of(symbology).narrowest(profile, dpi)).toList());
}
/***************************************************************************
** Seeded text of a length from an alphabet.
***************************************************************************/
private static String text(SplittableRandom random, String alphabet, int length)
{
StringBuilder text = new StringBuilder();
for(int index = 0; index < length; index++)
{
text.append(alphabet.charAt(random.nextInt(alphabet.length())));
}
return (text.toString());
}
/***************************************************************************
** Every character from space to tilde.
***************************************************************************/
private static String printable()
{
StringBuilder printable = new StringBuilder();
for(char character = ' '; character <= '~'; character++)
{
printable.append(character);
}
return (printable.toString());
}
/***************************************************************************
** The table names exactly the fit-qualified symbologies of version 1. Quiet
** zones are each symbology's own: 10 modules on each side of Code 128, Code
** 39, Code 93 and Interleaved 2 of 5; 11 and 7 for EAN-13, 7 and 7 for
** EAN-8, 9 and 9 for UPC-A, 9 and 7 for UPC-E; 4 on every side of a
** two-dimensional symbol.
***************************************************************************/
@Test
void theQuietZonesAreThoseOfEachSymbology()
{
Map<String, List<Integer>> quiet = Map.ofEntries(Map.entry("code128", List.of(10, 10)), Map.entry("code39", List.of(10, 10)), Map.entry("code93", List.of(10, 10)), Map.entry("itf", List.of(10, 10)),
Map.entry("gs1-128", List.of(10, 10)), Map.entry("ean13", List.of(11, 7)), Map.entry("ean8", List.of(7, 7)), Map.entry("upca", List.of(9, 9)), Map.entry("upce", List.of(9, 7)),
Map.entry("qr", List.of(4, 4)), Map.entry("datamatrix", List.of(4, 4)), Map.entry("pdf417", List.of(4, 4)), Map.entry("aztec", List.of(4, 4)));
assertEquals(BarcodeFit.TYPES.size(), Symbology.values().length);
for(String id : BarcodeFit.TYPES)
{
Symbology symbology = Symbology.of(id);
assertEquals(id, symbology.id());
assertEquals(quiet.get(id), List.of(symbology.quietLeft(), symbology.quietRight()), id);
assertEquals(!LINEAR.contains(id), symbology.matrix(), id);
assertEquals(RETAIL.contains(id), symbology.fixed(), id);
assertEquals(LINEAR.contains(id), symbology.provable(), id);
}
assertNull(Symbology.of("codabar"));
assertNull(Symbology.of(null));
assertEquals(64, Symbology.MAXIMUM_QUIET_MODULES);
}
/***************************************************************************
** The narrowest bar by profile, taken up to whole dots at 203, 300 and 600
** dpi. The design's own 0.25 mm is 2, 3 and 6 dots and its 0.375 mm for a
** two-dimensional symbol 3, 5 and 9. The GS1 minimum for EAN/UPC at general
** retail, 0.264 mm, is 3, 4 and 7 dots; the GS1 minimum in general
** distribution, 0.495 mm, is 4, 6 and 12 dots. With no profile named, each
** symbology takes the strictest rule written for its own use: general
** distribution for GS1-128 and Interleaved 2 of 5, general retail for
** EAN/UPC, and the design's for the rest.
***************************************************************************/
@Test
void theNarrowestBarIsThatOfTheProfile()
{
List<Integer> design = List.of(2, 3, 6);
List<Integer> retail = List.of(3, 4, 7);
List<Integer> distribution = List.of(4, 6, 12);
for(String id : BarcodeFit.TYPES)
{
boolean matrix = !LINEAR.contains(id);
boolean logistic = List.of("itf", "gs1-128").contains(id);
assertEquals(matrix ? List.of(3, 5, 9) : design, narrowest(id, Symbology.Profile.NONE), id);
assertEquals(matrix ? List.of(3, 5, 9) : RETAIL.contains(id) ? retail : design, narrowest(id, Symbology.Profile.GS1_GENERAL), id);
assertEquals(matrix ? List.of(3, 5, 9) : RETAIL.contains(id) || logistic ? distribution : design, narrowest(id, Symbology.Profile.GS1_LOGISTICS), id);
assertEquals(matrix ? List.of(3, 5, 9) : RETAIL.contains(id) ? retail : logistic ? distribution : design, narrowest(id, null), id);
}
assertEquals(Symbology.Profile.NONE, Symbology.Profile.of("none"));
assertEquals(Symbology.Profile.GS1_GENERAL, Symbology.Profile.of("gs1-general"));
assertEquals(Symbology.Profile.GS1_LOGISTICS, Symbology.Profile.of("gs1-logistics"));
assertNull(Symbology.Profile.of("retail"));
assertNull(Symbology.Profile.of(null));
}
/***************************************************************************
** How tall bars must be. Code 128 and the symbologies held to its rule: 15%
** of the width of the bars and never under 5 mm, which is 40, 60 and 119
** dots. EAN-13, UPC-A and UPC-E: 69.24 modules, so 208 dots at a module of
** 3 dots (207.72, taken up); EAN-8: 55.24 modules, 166 dots. A
** two-dimensional symbol has no such rule.
***************************************************************************/
@Test
void theHeightOfTheBarsIsThatOfEachSymbology()
{
for(String id : List.of("code128", "code39", "code93", "itf", "gs1-128"))
{
assertEquals(new ModuleFit.Height(299, 40, 15, 100), Symbology.of(id).height(299, 203), id);
assertEquals(List.of(60, 119), List.of(Symbology.of(id).height(299, 300).least(), Symbology.of(id).height(299, 600).least()), id);
}
assertEquals(new ModuleFit.Height(95, 0, 6924, 9500), Symbology.EAN13.height(95, 203));
assertEquals(List.of(208, 208, 208, 166), List.of(Symbology.EAN13.height(95, 203).at(3), Symbology.UPCA.height(95, 203).at(3), Symbology.UPCE.height(51, 203).at(3), Symbology.EAN8.height(67, 203).at(3)));
assertEquals(0, Symbology.QR.height(21, 600).at(9));
}
/***************************************************************************
** The widest symbol of a length is what the encoder draws for the widest
** value of that length, and no value from space to tilde is wider: Code 128
** in lower-case letters, Code 39, Code 93 in lower-case letters (two symbol
** characters each), Interleaved 2 of 5 in pairs of digits, where the widest
** of an odd length is that of the even length below it. The EAN/UPC symbols
** are one width.
***************************************************************************/
@Test
void theWidestSymbolOfALengthIsTheWidestTheEncoderDraws()
{
for(int length = 1; length <= 48; length++)
{
assertEquals(Symbology.CODE128.widest(length), modules("code128", "a".repeat(length)).getFirst(), "code128 of " + length);
assertEquals(Symbology.CODE39.widest(length), modules("code39", "A".repeat(length)).getFirst(), "code39 of " + length);
assertEquals(Symbology.CODE93.widest(length), modules("code93", "a".repeat(length)).getFirst(), "code93 of " + length);
assertEquals(Symbology.ITF.widest(2 * length), modules("itf", "12".repeat(length)).getFirst(), "itf of " + 2 * length);
assertEquals(Symbology.ITF.widest(2 * length), Symbology.ITF.widest(2 * length + 1), "itf of " + (2 * length + 1));
}
assertEquals(9, Symbology.ITF.widest(1));
assertEquals(List.of(95, 67, 95, 51), List.of(modules("ean13", "001234567890").getFirst(), modules("ean8", "1234567").getFirst(), modules("upca", "01234567890").getFirst(), modules("upce", "0425261").getFirst()));
assertEquals(List.of(95, 67, 95, 51), List.of(Symbology.EAN13.widest(0), Symbology.EAN8.widest(8), Symbology.UPCA.widest(12), Symbology.UPCE.widest(4000)));
SplittableRandom random = new SplittableRandom(20261115L);
String printable = printable();
for(int iteration = 0; iteration < 3000; iteration++)
{
int length = random.nextInt(1, 49);
String mixed = text(random, random.nextBoolean() ? printable : "0123456789Aa", length);
assertTrue(modules("code128", mixed).getFirst() <= Symbology.CODE128.widest(length), "code128 of " + length + " characters");
assertTrue(modules("code93", mixed).getFirst() <= Symbology.CODE93.widest(length), "code93 of " + length + " characters");
assertEquals(Symbology.CODE39.widest(length), modules("code39", text(random, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%", length)).getFirst(), "code39 of " + length + " characters");
}
}
/***************************************************************************
** A GS1-128 element string of a length, brackets included, is never wider
** than the table says: each application identifier costs two brackets that
** are not drawn and at most one separator that is. The widest are strings
** of one identifier and letters; a real label, mostly digits, is far
** narrower, which is why a declared length proves little for GS1-128.
***************************************************************************/
@Test
void aGs1ElementStringIsNoWiderThanItsLength()
{
assertEquals(11 * 24 + 24, Symbology.GS1_128.widest(24));
assertEquals(Symbology.GS1_128.widest(24), modules("gs1-128", "[21]" + "a".repeat(20)).getFirst());
assertEquals(299, modules("gs1-128", "[01]00012345678905[11]260101[21]TEST00010002").getFirst());
assertEquals(11 * 44 + 24, Symbology.GS1_128.widest(44));
SplittableRandom random = new SplittableRandom(20261116L);
for(int iteration = 0; iteration < 3000; iteration++)
{
StringBuilder elements = new StringBuilder();
for(int element = random.nextInt(1, 5); element > 0; element--)
{
switch(random.nextInt(5))
{
case 0 -> elements.append("[01]0001234567890").append(5);
case 1 -> elements.append("[11]").append(text(random, "0123456789", 6));
case 2 -> elements.append("[10]").append(text(random, "0123456789ABCabc-", random.nextInt(1, 21)));
case 3 -> elements.append("[21]").append(text(random, "a1", random.nextInt(1, 21)));
default -> elements.append("[21]").append(text(random, "abcXYZ0123456789", random.nextInt(1, 21)));
}
}
assertTrue(modules("gs1-128", elements.toString()).getFirst() <= Symbology.GS1_128.widest(elements.length()), elements.length() + " characters of element string");
}
}
/***************************************************************************
** No two-dimensional symbology has one value of a length that is its
** largest symbol, which is why a declared length proves nothing for them.
** Data Matrix and PDF417 choose among shapes, so a shorter value can be the
** wider: seven bytes of Data Matrix are 32 by 8 modules where six are 14 by
** 14, and eleven of PDF417 are 120 wide and 21 high where ten are 103 and
** 30. QR and Aztec change mode within a value, and that costs: here values
** of ordinary characters that need a larger symbol than as many plain
** bytes.
***************************************************************************/
@Test
void noTwoDimensionalSymbologyHasALargestSymbolOfALength()
{
SplittableRandom random = new SplittableRandom(20261117L);
String printable = printable();
int square = 0;
int target = 0;
for(int iteration = 0; iteration < 1500; iteration++)
{
int length = random.nextInt(150, 401);
String value = text(random, List.of(printable, "0123456789abcdefABCDEF $%*+-./:").get(random.nextInt(2)), length);
square += modules("qr", value).getFirst() > modules("qr", ACCENTED.repeat(length)).getFirst() ? 1 : 0;
target += modules("aztec", value).getFirst() > modules("aztec", ACCENTED.repeat(length)).getFirst() ? 1 : 0;
}
assertTrue(square > 0 && target > 0, square + " qr and " + target + " aztec symbols larger than as many bytes");
assertEquals(List.of(List.of(14, 14), List.of(32, 8)), List.of(modules("datamatrix", ACCENTED.repeat(6)), modules("datamatrix", ACCENTED.repeat(7))));
assertEquals(List.of(List.of(103, 30), List.of(120, 21)), List.of(modules("pdf417", ACCENTED.repeat(10)), modules("pdf417", ACCENTED.repeat(11))));
}
}
@@ -0,0 +1,311 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.awt.Font;
import java.awt.Rectangle;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The bundled faces: what ships, under which licence, with which hash, and
** that the numbers layout relies on are the font files' own.
*******************************************************************************/
class FaceTest
{
/***************************************************************************
** A resource of the renderer jar, or null.
***************************************************************************/
private static byte[] resource(String path) throws Exception
{
try(InputStream stream = Face.class.getResourceAsStream(path))
{
return (stream == null ? null : stream.readAllBytes());
}
}
/***************************************************************************
** The lowercase hexadecimal SHA-256 of some bytes.
***************************************************************************/
private static String sha256(byte[] bytes) throws Exception
{
return (HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)));
}
/***************************************************************************
** Every character of the Basic Multilingual Plane a face draws.
***************************************************************************/
static List<Integer> drawn(Face face)
{
List<Integer> drawn = new ArrayList<>();
for(int codePoint = 0; codePoint <= Character.MAX_VALUE; codePoint++)
{
if(face.draws(codePoint))
{
drawn.add(codePoint);
}
}
return (drawn);
}
/***************************************************************************
** The set is the five faces the design names, by the names it gives them,
** and no other name is a face.
***************************************************************************/
@Test
void theBundledSetIsFiveNamedFaces()
{
assertEquals(List.of("qqq-sans", "qqq-sans-bold", "qqq-condensed-bold", "qqq-mono", "qqq-mono-bold"), Face.all().stream().map(Face::scene).toList());
assertEquals(List.of(false, true, true, false, true), Face.all().stream().map(Face::bold).toList());
for(Face face : Face.all())
{
assertEquals(face, Face.of(face.scene()));
assertTrue(face.scene().startsWith("qqq-"), "a bundled face has the reserved prefix");
}
for(String other : List.of("", "qqq-", "qqq-serif", "QQQ-SANS", "qqq-sans ", "Abel", "IBM Plex Sans"))
{
assertNull(Face.of(other), other);
}
assertNull(Face.of(null));
}
/***************************************************************************
** Every bundled face ships with its licence text, a provenance note and a
** hash, and the bytes in the jar are the bytes that were hashed. The build
** fails when any of the three is missing or a file changes.
***************************************************************************/
@Test
void everyBundledFaceHasItsLicenceProvenanceAndAMatchingHash() throws Exception
{
Map<String, String> sums = new HashMap<>();
for(String line : new String(resource("/fonts/SHA256SUMS"), StandardCharsets.US_ASCII).lines().toList())
{
assertTrue(line.matches("[0-9a-f]{64} [A-Za-z0-9./-]+"), line);
assertNull(sums.put(line.substring(66), line.substring(0, 64)), "listed twice: " + line);
}
Set<String> licences = Set.of("ibm-plex-sans/LICENSE.txt", "ibm-plex-sans-condensed/LICENSE.txt", "jetbrains-mono/OFL.txt");
assertEquals(Face.all().size() + licences.size(), sums.size(), "the list is exactly the faces and their licences");
for(Face face : Face.all())
{
String directory = face.file().substring(0, face.file().indexOf('/') + 1);
byte[] font = resource("/fonts/" + face.file());
assertNotNull(font, face.file());
assertTrue(font[0] == 0 && font[1] == 1 && font[2] == 0 && font[3] == 0, "static TrueType outlines: " + face.file());
assertEquals(sums.get(face.file()), sha256(font), face.file());
String licence = licences.stream().filter(name -> name.startsWith(directory)).findFirst().orElseThrow();
byte[] text = resource("/fonts/" + licence);
assertNotNull(text, licence);
assertEquals(sums.get(licence), sha256(text), licence);
String words = new String(text, StandardCharsets.UTF_8);
assertTrue(words.contains("This Font Software is licensed under the SIL Open Font License, Version 1.1."), licence);
assertTrue(words.contains("SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007") && words.contains("PERMISSION & CONDITIONS") && words.contains("TERMINATION"), "the whole licence text: " + licence);
byte[] provenance = resource("/fonts/" + directory + "SOURCE.md");
assertNotNull(provenance, "provenance of " + face.file());
String note = new String(provenance, StandardCharsets.UTF_8);
String name = face.file().substring(directory.length());
assertTrue(note.contains("`" + name + "`") && note.contains(sums.get(face.file())) && note.contains(sums.get(licence)), "the provenance names the file and both hashes: " + name);
assertTrue(note.contains("https://github.com/") && note.contains("/releases/download/") && note.contains("Archive SHA-256") && (note.contains("Unmodified") || note.contains("unmodified")), name);
assertTrue(note.contains("`" + face.scene() + "`"), "the provenance gives the scene name " + face.scene());
}
}
/***************************************************************************
** A file that is not a font is a broken build and says so; it is never a
** silent fallback to another face.
***************************************************************************/
@Test
void aFileThatIsNotAFontIsABrokenBuild()
{
assertEquals("BUNDLED_FONT_UNREADABLE", assertThrows(IllegalStateException.class, () -> Face.load("/fonts/SHA256SUMS")).getMessage());
}
/***************************************************************************
** The bounds each face states are the font file's: the widest character
** (the lowest of those that share the greatest advance, among characters
** with ink), and the furthest any character reaches past its advance on the
** left and right, above the baseline and below it. They are what a length
** is proven against, so they are recomputed here from every character.
**
** A character with no ink still moves the pen (a no-break space, an em
** quad), so the greatest advance is taken over every character the face
** draws, inked or not, and the widest inked character must have it: were a
** font ever to carry a blank wider than its widest letter, a line of that
** blank would be wider than the proof allows, and this fails.
***************************************************************************/
@Test
void theBoundsOfAFaceAreThoseOfItsFontFile()
{
for(Face face : Face.all())
{
int widest = -1;
int advance = 0;
int inked = 0;
int blanks = 0;
int left = 0;
int right = 0;
int top = 0;
int bottom = 0;
List<Integer> drawn = drawn(face);
for(int codePoint : drawn)
{
Face.Glyph glyph = face.glyph(codePoint);
assertTrue(glyph.advance() >= 0 && glyph.advance() <= 2 * Face.REFERENCE, "advance of " + codePoint);
assertEquals(glyph.space(), codePoint == ' ');
advance = Math.max(advance, glyph.advance());
if(!glyph.ink())
{
assertEquals(new Face.Glyph(glyph.advance(), 0, 0, 0, 0, false, codePoint == ' '), glyph);
blanks++;
continue;
}
if(glyph.advance() > inked)
{
inked = glyph.advance();
widest = codePoint;
}
left = Math.max(left, -glyph.left());
right = Math.max(right, glyph.right() - glyph.advance());
top = Math.max(top, glyph.top());
bottom = Math.max(bottom, glyph.bottom());
}
assertTrue(drawn.size() > 800, face.scene() + " draws " + drawn.size() + " characters");
assertTrue(blanks >= 2 && face.draws(0xA0) && !face.glyph(0xA0).ink() && face.glyph(0xA0).advance() > 0, face.scene() + " draws " + blanks + " characters with no ink, the no-break space among them");
assertEquals(advance, inked, face.scene() + ": no character without ink advances further than the widest with ink");
assertEquals(new Face.Glyph(advance, -left, advance + right, top, bottom, true, false), face.worst(), face.scene());
assertEquals(widest, face.widest(), face.scene());
assertEquals(face.glyph(face.widest()).advance(), face.worst().advance());
/////////////////////////////////////////////////////////////////////////////////////
// the faces have 1000 units to the em, so the reference size reads whole numbers //
/////////////////////////////////////////////////////////////////////////////////////
assertTrue(face.ascent() > 900 && face.ascent() < 1100 && face.descent() > 200 && face.descent() < 350 && face.leading() == 0, face.scene());
assertTrue(face.capHeight() > 650 && face.capHeight() < 760, face.scene());
}
assertEquals(List.of(1025, 275, 698), List.of(Face.SANS.ascent(), Face.SANS.descent(), Face.SANS.capHeight()));
assertEquals(List.of(1020, 300, 730), List.of(Face.MONO_BOLD.ascent(), Face.MONO_BOLD.descent(), Face.MONO_BOLD.capHeight()));
assertEquals(new Face.Glyph(600, 0, 0, 0, 0, false, true), Face.MONO.glyph(' '));
assertEquals(Set.of(600), drawn(Face.MONO).stream().map(codePoint -> Face.MONO.glyph(codePoint).advance()).collect(Collectors.toSet()), "the monospace has one advance");
}
/***************************************************************************
** A face draws a character only as one glyph of its own, left to right.
** Controls, formats (which would print nothing), marks that must be placed
** on another letter, scripts that need shaping, and characters outside the
** Basic Multilingual Plane are not drawn; nor is a character the face lacks.
***************************************************************************/
@Test
void aFaceDrawsOnlyWhatItCanDrawFaithfully()
{
for(Face face : Face.all())
{
for(int codePoint = 0x20; codePoint < 0x7F; codePoint++)
{
assertTrue(face.draws(codePoint), face.scene() + " draws " + codePoint);
}
assertTrue(face.draws(TextFit.MARK), "the ellipsis that marks a cut");
assertTrue(face.draws(0xE9) && face.draws(0xC5) && face.draws(0xA0) && face.draws(0x20AC));
for(int codePoint : List.of(0x00, 0x09, 0x0A, 0x0D, 0x7F, 0x85, 0xAD, 0x200B, 0x200D, 0x202E, 0x2028, 0x2029, 0xFEFF, 0x0301, 0x0627, 0x05D0, 0x0915, 0x4E2D, 0xD83D, 0xE0A0, 0xFFFF, 0x1F600, 0x10FFFF))
{
assertFalse(face.draws(codePoint), face.scene() + " must not draw " + Integer.toHexString(codePoint));
}
assertEquals(0, face.missing("TEST-0001 (01)00012345678905 café")); // e acute
assertEquals(0, face.missing(""));
assertEquals(4, face.missing("A\tB́😀C中")); // a tab, a combining acute, one emoji (two units, one character), a CJK ideograph
assertEquals(3, face.glyphs("A B").length);
assertTrue(face.glyphs("A B")[1].space() && !face.glyphs("A B")[0].space());
}
}
/***************************************************************************
** The rasteriser keeps every glyph inside the box layout measures for it:
** the outline at the reference size, scaled exactly, and `TextFit.SLOP`
** dots. Held for every character of every face over the sizes and
** resolutions labels use, and at the ends of what the renderer accepts:
** 1 pt and 2 pt, where a glyph is a few dots, and 300 pt and 1000 pt,
** where it is drawn from its outline. (That the ink itself stays inside is
** held where text is drawn: `TextRasterTest`.)
***************************************************************************/
@Test
void everyGlyphIsRasterisedInsideItsMeasuredBox()
{
for(Face face : Face.all())
{
List<Integer> drawn = drawn(face);
for(int dpi : Scene2.RESOLUTIONS)
{
for(int milliPoints : List.of(1000, 2000, 5000, 6250, 7000, 8000, 9000, 10_500, 12_000, 18_000, 36_000, 72_000, 300_000, 1_000_000))
{
TextFit.Scale scale = new TextFit.Scale(milliPoints, dpi);
Font font = face.font(scale.size());
for(int codePoint : drawn)
{
Face.Glyph glyph = face.glyph(codePoint);
Rectangle pixels = font.createGlyphVector(Face.CONTEXT, new char[] {(char) codePoint}).getGlyphPixelBounds(0, Face.CONTEXT, 0, 0);
if(!glyph.ink())
{
assertTrue(pixels.isEmpty(), "ink where none is measured");
continue;
}
boolean inside = pixels.x >= scale.floor(glyph.left()) - TextFit.SLOP && pixels.x + pixels.width <= scale.ceil(glyph.right()) + TextFit.SLOP
&& -pixels.y <= scale.ceil(glyph.top()) + TextFit.SLOP && pixels.y + pixels.height <= scale.ceil(glyph.bottom()) + TextFit.SLOP;
assertTrue(inside, () -> face.scene() + " U+" + Integer.toHexString(codePoint) + " at " + milliPoints + " millipoints, " + dpi + " dpi: " + pixels + " outside " + glyph);
}
}
}
}
}
}
@@ -0,0 +1,871 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** The fit rules, by example and as properties over seeded, deterministic
** generators (fixed seeds, no clock): text, face, box, size, floor, lines and
** resolution.
*******************************************************************************/
class TextFitTest
{
static final long[] SEEDS = {20261112L, 7L, 4242L};
static final int CASES = 600;
/***************************************************************************
** One generated case.
***************************************************************************/
record Case(TextFit.Request request, String text)
{
/************************************************************************
** The same case with another nominal size and floor, and no cutting.
************************************************************************/
Case at(int nominal, int floor)
{
TextFit.Request from = request;
return (new Case(new TextFit.Request(from.face(), from.width(), from.height(), from.dpi(), nominal, floor, from.lineHeight(), from.maxLines(), false), text));
}
/************************************************************************
** The same case for another text.
************************************************************************/
Case of(String other)
{
return (new Case(request, other));
}
/************************************************************************
** Fit it.
************************************************************************/
TextFit.Block fit()
{
return (TextFit.fit(request, request.face().glyphs(text), request.face().glyph(TextFit.MARK)));
}
}
/***************************************************************************
** A request in a box, with the face's own line pitch, one line, no cutting.
***************************************************************************/
static TextFit.Request request(Face face, int width, int height, int nominal, int floor)
{
return (new TextFit.Request(face, width, height, 203, nominal, floor, null, 1, false));
}
/***************************************************************************
** The same request with more lines, and cutting or not.
***************************************************************************/
static TextFit.Request lines(TextFit.Request request, int maxLines, boolean truncate)
{
return (new TextFit.Request(request.face(), request.width(), request.height(), request.dpi(), request.nominal(), request.floor(), request.lineHeight(), maxLines, truncate));
}
/***************************************************************************
** Fit a text of a face's own characters.
***************************************************************************/
static TextFit.Block fit(TextFit.Request request, String text)
{
return (new Case(request, text).fit());
}
/***************************************************************************
** The characters of each line, with `~` where the ellipsis is.
***************************************************************************/
static List<String> shown(TextFit.Block block, String text)
{
return (block.lines().stream().map(line -> text.substring(line.from(), line.to()) + (line.marked() ? "~" : "")).toList());
}
/***************************************************************************
** A generated case: labels are small boxes, short values and type from 5 to
** 30 pt. A third of the texts have no space, as identifiers do.
***************************************************************************/
static Case generate(Random random)
{
Face face = Face.all().get(random.nextInt(Face.all().size()));
int dpi = Scene2.RESOLUTIONS.get(random.nextInt(3));
int nominal = 5000 + random.nextInt(101) * 250 + (random.nextInt(4) == 0 ? random.nextInt(250) : 0);
int floor = switch(random.nextInt(4))
{
case 0 -> nominal;
case 1 -> Math.max(1000, nominal * 7 / 10);
default -> 1000 + random.nextInt(nominal - 999);
};
Integer lineHeight = random.nextInt(3) == 0 ? Integer.valueOf(700 + random.nextInt(1500)) : null;
int width = (20 + random.nextInt(700)) * dpi / 203;
int height = (8 + random.nextInt(160)) * dpi / 203;
String alphabet = switch(random.nextInt(3))
{
case 0 -> "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()/.";
case 1 -> "abcdefghijklmnopqrstuvwxyzWMfjgyÅé‰ "; // A ring, e acute, per mille
default -> "il1.,' WM@‰⁄ǺĢ "; // per mille, fraction slash, A ring acute, G cedilla: the widest and furthest-reaching
};
StringBuilder text = new StringBuilder();
int length = random.nextInt(48);
boolean spaces = random.nextInt(3) != 0;
for(int index = 0; index < length; index++)
{
text.append(spaces && random.nextInt(6) == 0 ? ' ' : alphabet.charAt(random.nextInt(alphabet.length())));
}
return (new Case(new TextFit.Request(face, width, height, dpi, nominal, floor, lineHeight, 1 + random.nextInt(4), random.nextInt(3) == 0), text.toString()));
}
/***************************************************************************
** The search `fit` must agree with, made in full: every quarter-point step
** from the nominal size down to the floor, each laid out between words and
** then at any character, the first that fits taken. This is the search the
** fit was first written as. It shares with `fit` only the layout at one
** size (`TextFit.at`), and none of what `fit` uses to skip sizes.
***************************************************************************/
static TextFit.Block linear(TextFit.Request request, Face.Glyph[] glyphs, Face.Glyph mark, TextFit.Work work)
{
int count = glyphs.length;
while(count > 0 && glyphs[count - 1].space())
{
count--;
}
int size = request.nominal();
while(true)
{
TextFit.Block block = TextFit.at(request, TextFit.Leading.of(request), size, glyphs, count, mark, work);
if(block.fits() || size == request.floor())
{
return (block);
}
size = Math.max(request.floor(), size - TextFit.STEP_MILLIPOINTS);
}
}
/***************************************************************************
** A generated case over everything a scene may state: type from 1 pt to
** 1000 pt with a floor anywhere under it, boxes from a few dots to a large
** label, up to 64 lines, any line height, and texts of up to 160
** characters, some without a space, some of the widest and
** furthest-reaching characters, some led or followed by spaces.
***************************************************************************/
static Case wide(Random random)
{
Face face = Face.all().get(random.nextInt(Face.all().size()));
int dpi = Scene2.RESOLUTIONS.get(random.nextInt(3));
int nominal = switch(random.nextInt(4))
{
case 0 -> 1000 + random.nextInt(9001);
case 1 -> 5000 + random.nextInt(30_001);
case 2 -> 20_000 + random.nextInt(280_001);
default -> 1000 + random.nextInt(999_001);
};
int floor = switch(random.nextInt(4))
{
case 0 -> 1000;
case 1 -> Math.max(1000, nominal / 10);
case 2 -> Math.max(1000, nominal - random.nextInt(4000));
default -> 1000 + random.nextInt(nominal - 999);
};
Integer lineHeight = random.nextInt(3) == 0 ? Integer.valueOf(500 + random.nextInt(4501)) : null;
int width = switch(random.nextInt(3))
{
case 0 -> 1 + random.nextInt(60);
case 1 -> 20 + random.nextInt(700);
default -> 200 + random.nextInt(6000);
};
int height = switch(random.nextInt(3))
{
case 0 -> 1 + random.nextInt(40);
case 1 -> 8 + random.nextInt(300);
default -> 100 + random.nextInt(4000);
};
String alphabet = switch(random.nextInt(4))
{
case 0 -> "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()/.";
case 1 -> "abcdefghijklmnopqrstuvwxyzWMfjgyÅé‰ "; // A ring, e acute, per mille
case 2 -> "il1.,' WM@‰⁄ǺĢ "; // per mille, fraction slash, A ring acute, G cedilla: the widest and furthest-reaching
default -> new String(Character.toChars(face.widest())) + "j "; // the widest, a letter that starts left of the pen, a no-break space
};
StringBuilder text = new StringBuilder(random.nextInt(5) == 0 ? " " : "");
int length = random.nextInt(4) == 0 ? random.nextInt(160) : random.nextInt(40);
int spaces = random.nextInt(3);
for(int index = 0; index < length; index++)
{
text.append(spaces > 0 && random.nextInt(spaces == 1 ? 6 : 2) == 0 ? ' ' : alphabet.charAt(random.nextInt(alphabet.length())));
}
return (new Case(new TextFit.Request(face, width, height, dpi, nominal, floor, lineHeight, 1 + random.nextInt(random.nextInt(3) == 0 ? 64 : 4), random.nextInt(3) == 0), text.toString()));
}
/***************************************************************************
** Dots are thousandths of the em times the size times the resolution over
** 72 000 000, rounded down, up or to the nearest: checked against exact
** decimal arithmetic, negative lengths included.
***************************************************************************/
@Test
void theScaleRoundsExactly()
{
Random random = new Random(SEEDS[0]);
for(int index = 0; index < 5000; index++)
{
TextFit.Scale scale = new TextFit.Scale(1000 + random.nextInt(999_001), Scene2.RESOLUTIONS.get(random.nextInt(3)));
long units = random.nextInt(3_000_001) - 1_500_000L;
BigDecimal exact = BigDecimal.valueOf(units).multiply(BigDecimal.valueOf(scale.milliPoints())).multiply(BigDecimal.valueOf(scale.dpi())).divide(BigDecimal.valueOf(72_000_000L), 12, RoundingMode.HALF_EVEN);
assertEquals(exact.setScale(0, RoundingMode.FLOOR).intValueExact(), scale.floor(units));
assertEquals(exact.setScale(0, RoundingMode.CEILING).intValueExact(), scale.ceil(units));
assertEquals(exact.add(new BigDecimal("0.5")).setScale(0, RoundingMode.FLOOR).intValueExact(), scale.round(units));
}
assertEquals(25.375f, new TextFit.Scale(9000, 203).size());
assertEquals(100f, new TextFit.Scale(12_000, 600).size());
assertEquals(List.of(25, 26, 25), List.of(new TextFit.Scale(9000, 203).floor(1000), new TextFit.Scale(9000, 203).ceil(1000), new TextFit.Scale(9000, 203).round(1000)));
assertEquals(List.of(-26, -25, -25), List.of(new TextFit.Scale(9000, 203).floor(-1000), new TextFit.Scale(9000, 203).ceil(-1000), new TextFit.Scale(9000, 203).round(-1000)));
}
/***************************************************************************
** The default: one line. A text that fits at its size keeps it; one that
** does not is reduced a quarter point at a time to the largest size that
** fits; one that does not fit at the floor is refused with what it
** measured there.
***************************************************************************/
@Test
void oneLineShrinksToTheLargestSizeThatFitsThenRefuses()
{
////////////////////////////////////////////////////////////////////////////////////////////
// 9 pt at 203 dpi is 25.375 dots to the em and the monospace advances 0.6 em: 12 letters //
// are 183 dots, and the line is 2 dots wider on each inked side //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Block fits = fit(request(Face.MONO_BOLD, 200, 40, 9000, 6300), "ABCDEFGHIJKL");
assertTrue(fits.fits() && !fits.truncated());
assertEquals(9000, fits.milliPoints());
assertEquals(List.of("ABCDEFGHIJKL"), shown(fits, "ABCDEFGHIJKL"));
assertEquals(12, fits.characters());
assertTrue(fits.width() >= 183 && fits.width() <= 187, "width " + fits.width());
assertEquals(fits.width(), fits.lines().get(0).width());
assertEquals(List.of(26, 34), List.of(fits.baseline(), fits.height()), "ascent 1.02 em and descent 0.3 em, each rounded up");
TextFit.Block shrunk = fit(request(Face.MONO_BOLD, 160, 40, 9000, 6300), "ABCDEFGHIJKL");
assertTrue(shrunk.fits() && shrunk.milliPoints() < 9000 && shrunk.milliPoints() >= 6300 && shrunk.milliPoints() % 250 == 0);
assertTrue(shrunk.width() <= 160);
assertFalse(fit(request(Face.MONO_BOLD, 160, 40, shrunk.milliPoints() + 250, shrunk.milliPoints() + 250), "ABCDEFGHIJKL").fits(), "a quarter point larger does not fit");
TextFit.Block refused = fit(request(Face.MONO_BOLD, 100, 40, 9000, 6300), "ABCDEFGHIJKL");
assertFalse(refused.fits());
assertEquals(6300, refused.milliPoints());
assertTrue(refused.lines().size() > 1 && refused.width() <= 100, "measured broken at any character: " + refused);
assertEquals(12, refused.shown());
////////////////////////////////////////////////////////////////////////////////////////////
// the floor need not be on the quarter-point grid from the size: it is the last size //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Block floor = fit(request(Face.MONO_BOLD, 134, 40, 9000, 6400), "ABCDEFGHIJKL");
assertTrue(floor.fits());
assertEquals(6400, floor.milliPoints());
////////////////////////////////////////////////////////////////////////////////////////////
// too tall is refused as too wide is: the box is 20 dots high and the floor needs 25 //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Block tall = fit(request(Face.MONO_BOLD, 400, 20, 9000, 6300), "ABC");
assertFalse(tall.fits());
assertTrue(tall.height() > 20 && tall.lines().size() == 1);
}
/***************************************************************************
** Nothing to draw always fits: an empty value, or one of spaces only.
** Spaces at the end of a text take no room; spaces at its start do.
***************************************************************************/
@Test
void spacesAtTheEndTakeNoRoom()
{
for(String blank : List.of("", " ", " "))
{
TextFit.Block block = fit(request(Face.SANS, 1, 1, 9000, 9000), blank);
assertTrue(block.fits() && block.lines().isEmpty() && !block.truncated());
assertEquals(List.of(0, 0, 0, 0), List.of(block.width(), block.height(), block.characters(), block.shown()));
}
TextFit.Request request = request(Face.SANS_BOLD, 300, 40, 9000, 9000);
TextFit.Block plain = fit(request, "AB");
assertEquals(plain, fit(request, "AB "));
TextFit.Block led = fit(request, " AB");
int shift = new TextFit.Scale(9000, 203).round(2L * Face.SANS_BOLD.glyph(' ').advance());
assertTrue(shift > 8 && led.width() >= plain.width() + shift - 2 * TextFit.SLOP && led.width() <= plain.width() + shift + 1, plain.width() + " then " + led.width());
assertEquals(4, led.characters());
}
/***************************************************************************
** With more lines allowed, a line is broken between words while that fits,
** and at any character when it does not: a larger size is preferred to
** whole words, and a value with no space wraps.
***************************************************************************/
@Test
void linesBreakBetweenWordsAndThenAtAnyCharacter()
{
////////////////////////////////////////////////////////////////////////////////////////////
// the monospace at 9 pt, 203 dpi advances 15.225 dots: a 100 dot box holds 6 letters //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Request box = request(Face.MONO, 100, 200, 9000, 9000);
assertEquals(List.of("AAA", "BBB", "CCC"), shown(fit(lines(box, 3, false), "AAA BBB CCC"), "AAA BBB CCC"));
assertEquals(List.of("AAA BB", "CCC"), shown(fit(lines(box, 2, false), "AAA BB CCC"), "AAA BB CCC"), "spaces at a break are dropped");
assertEquals(List.of("AAA BB", "B CCC"), shown(fit(lines(box, 2, false), "AAA BBB CCC"), "AAA BBB CCC"), "two lines only when broken at any character");
assertEquals(List.of("L24061", "1A-RET", "URNED"), shown(fit(lines(box, 3, false), "L240611A-RETURNED"), "L240611A-RETURNED"));
assertEquals(9000, fit(lines(box, 2, false), "AAA BBB CCC").milliPoints());
TextFit.Block refused = fit(lines(box, 2, false), "L240611A-RETURNED");
assertFalse(refused.fits());
assertEquals(3, refused.lines().size());
////////////////////////////////////////////////////////////////////////////////////////////
// a stated line height sets the distance between baselines; the block is one ascent, //
// the pitches between, and one descent //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Block natural = fit(lines(box, 3, false), "AAA BBB CCC");
assertEquals(List.of(34, 26, 26 + 2 * 34 + 8), List.of(natural.pitch(), natural.baseline(), natural.height()));
TextFit.Block tight = TextFit.fit(new TextFit.Request(Face.MONO, 100, 200, 203, 9000, 9000, 1000, 3, false), Face.MONO.glyphs("AAA BBB CCC"), null);
assertEquals(List.of(26, 26, 26 + 2 * 26 + 8), List.of(tight.pitch(), tight.baseline(), tight.height()));
////////////////////////////////////////////////////////////////////////////////////////////
// a character wider than the box stands alone on a line that does not fit //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Block narrow = fit(lines(request(Face.MONO, 10, 200, 9000, 9000), 4, false), "AB");
assertFalse(narrow.fits());
assertEquals(List.of("A", "B"), shown(narrow, "AB"));
assertTrue(narrow.width() > 10);
}
/***************************************************************************
** Cutting happens only when the element asked for it and only when the text
** fits at no size down to the floor. The last line that fits ends with the
** ellipsis after as many characters as fit beside it; when not even the
** ellipsis fits, the text is refused.
***************************************************************************/
@Test
void truncationIsOnlyWhenAskedAndAlwaysShowsTheMark()
{
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
TextFit.Request box = request(Face.MONO, 100, 80, 9000, 9000);
assertFalse(fit(box, text).fits());
assertFalse(fit(lines(box, 2, false), text).truncated());
TextFit.Block cut = fit(lines(box, 1, true), text);
assertTrue(cut.fits() && cut.truncated());
assertEquals(List.of("ABCDE~"), shown(cut, text));
assertEquals(List.of(26, 5), List.of(cut.characters(), cut.shown()));
assertTrue(cut.width() <= 100);
TextFit.Block two = fit(lines(box, 2, true), text);
assertEquals(List.of("ABCDEF", "GHIJK~"), shown(two, text));
assertEquals(11, two.shown());
////////////////////////////////////////////////////////////////////////////////////////////
// the box is high enough for one line only: the second is given up for the mark //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Block low = fit(lines(request(Face.MONO, 100, 40, 9000, 9000), 3, true), text);
assertEquals(List.of("ABCDE~"), shown(low, text));
////////////////////////////////////////////////////////////////////////////////////////////
// a text that fits is not cut and has no mark, though cutting is allowed; one that fits //
// after shrinking is shrunk, not cut //
////////////////////////////////////////////////////////////////////////////////////////////
assertEquals(List.of("ABCDEF"), shown(fit(lines(box, 1, true), "ABCDEF"), "ABCDEF"));
TextFit.Block shrunk = fit(lines(request(Face.MONO, 100, 80, 9000, 6000), 1, true), "ABCDEFGH");
assertTrue(shrunk.fits() && !shrunk.truncated() && shrunk.milliPoints() < 9000);
////////////////////////////////////////////////////////////////////////////////////////////
// spaces before the mark are dropped; the mark may stand alone; and where it cannot //
// stand at all, or a line is too high, the answer is the refusal //
////////////////////////////////////////////////////////////////////////////////////////////
assertEquals(List.of("ABC~"), shown(fit(lines(box, 1, true), "ABC DEFGHIJKL"), "ABC DEFGHIJKL"));
assertEquals(List.of("~"), shown(fit(lines(request(Face.MONO, 22, 80, 9000, 9000), 1, true), text), text));
assertFalse(fit(lines(request(Face.MONO, 12, 80, 9000, 9000), 1, true), text).fits());
assertFalse(fit(lines(request(Face.MONO, 100, 20, 9000, 9000), 1, true), text).fits());
assertFalse(fit(lines(request(Face.MONO, 400, 20, 9000, 9000), 1, true), "ABC").fits(), "a line that is too high is too high with the mark");
////////////////////////////////////////////////////////////////////////////////////////////
// the last line of a text is cut too when the text fits at no size: here one letter is //
// wider than the box and the mark is not, and here an accent above the ascent is too //
// high for the box and is given up for the mark //
////////////////////////////////////////////////////////////////////////////////////////////
assertEquals(List.of("~"), shown(fit(lines(request(Face.SANS, 26, 80, 9000, 9000), 1, true), "\u2030"), "\u2030")); // per mille
TextFit.Request shallow = lines(request(Face.SANS_BOLD, 200, 36, 9000, 9000), 1, true);
assertTrue(fit(shallow, "ABC").fits() && !fit(shallow, "ABC").truncated());
assertEquals(List.of("AB~"), shown(fit(shallow, "AB\u01FA"), "AB\u01FA")); // A ring acute
assertFalse(fit(lines(shallow, 1, false), "AB\u01FA").fits()); // A ring acute
////////////////////////////////////////////////////////////////////////////////////////////
// broken at any character, spaces at the start of a text stay on a line of their own //
// rather than push the first letter out of the box //
////////////////////////////////////////////////////////////////////////////////////////////
assertEquals(List.of(" ", "ABCDE"), shown(fit(lines(box, 2, false), " ABCDE"), " ABCDE"));
assertEquals(List.of(" ABCD", "E"), shown(fit(lines(box, 2, false), " ABCDE"), " ABCDE"));
}
/***************************************************************************
** Property: the answer is a layout inside the box or a refusal whose
** measurement exceeds its limit. The size is never above the nominal and
** never below the floor; it is on the quarter-point steps from the nominal
** or is the floor. The lines are the text in order, whole unless cut, and
** never more than allowed. A text is cut only when asked, only at the
** floor, and then its last line carries the mark.
***************************************************************************/
@Test
void theAnswerIsALayoutInsideTheBoxOrARefusalThatMeasuresMore()
{
int fitted = 0;
int refused = 0;
int cut = 0;
for(long seed : SEEDS)
{
Random random = new Random(seed);
for(int index = 0; index < CASES; index++)
{
Case generated = generate(random);
TextFit.Request request = generated.request();
TextFit.Block block = generated.fit();
String about = "seed " + seed + " case " + index + ": " + request + " for " + generated.text().length() + " characters gave " + block;
String trimmed = generated.text().stripTrailing();
assertEquals(trimmed.length(), block.characters(), about);
assertTrue(block.milliPoints() <= request.nominal() && block.milliPoints() >= request.floor(), about);
assertTrue(block.milliPoints() == request.floor() || (request.nominal() - block.milliPoints()) % TextFit.STEP_MILLIPOINTS == 0, about);
int next = 0;
for(int line = 0; line < block.lines().size(); line++)
{
TextFit.Line each = block.lines().get(line);
assertTrue(trimmed.substring(next, each.from()).isBlank() && each.to() >= each.from() && each.left() <= 0 && each.width() <= block.width(), about);
assertTrue(each.to() > each.from() || each.marked(), about);
assertTrue(each.to() == each.from() || trimmed.charAt(each.to() - 1) != ' ' || !each.marked(), about + ": a space before the mark");
assertEquals(each.marked(), block.truncated() && line == block.lines().size() - 1, about);
next = each.to();
}
assertEquals(block.shown(), next, about);
if(block.fits())
{
fitted++;
assertTrue(block.lines().size() <= request.maxLines() && block.width() <= request.width() && block.height() <= request.height(), about);
}
else
{
refused++;
assertTrue(block.lines().size() > request.maxLines() || block.width() > request.width() || block.height() > request.height(), about);
assertEquals(request.floor(), block.milliPoints(), about);
assertFalse(block.truncated(), about);
}
if(block.truncated())
{
cut++;
assertTrue(request.truncate() && block.fits() && block.milliPoints() == request.floor() && block.shown() < block.characters(), about);
assertFalse(generated.at(request.floor(), request.floor()).fit().fits(), about);
}
else
{
assertEquals(trimmed.length(), block.shown(), about);
}
}
}
assertTrue(fitted > 300 && refused > 300 && cut > 50, "the cases must reach every outcome: " + fitted + " fitted, " + refused + " refused, " + cut + " cut");
}
/***************************************************************************
** Property: a text that fits at its nominal size is never shrunk, and the
** size chosen is the largest that fits: the step above it does not.
***************************************************************************/
@Test
void aTextThatFitsIsNeverShrunkAndTheChosenSizeIsTheLargestThatFits()
{
int kept = 0;
int shrunk = 0;
for(long seed : SEEDS)
{
Random random = new Random(seed);
for(int index = 0; index < CASES; index++)
{
Case generated = generate(random);
TextFit.Request request = generated.request();
TextFit.Block block = generated.fit();
String about = "seed " + seed + " case " + index + ": " + request + " gave " + block;
TextFit.Block nominal = generated.at(request.nominal(), request.nominal()).fit();
if(nominal.fits())
{
kept++;
assertEquals(nominal, block, about);
assertEquals(request.nominal(), block.milliPoints(), about);
}
else if(block.fits() && !block.truncated())
{
shrunk++;
assertTrue(block.milliPoints() < request.nominal(), about);
int steps = (request.nominal() - block.milliPoints() - 1) / TextFit.STEP_MILLIPOINTS;
int above = request.nominal() - steps * TextFit.STEP_MILLIPOINTS;
assertTrue(above > block.milliPoints() && above - block.milliPoints() <= TextFit.STEP_MILLIPOINTS, about);
assertFalse(generated.at(above, above).fit().fits(), about + ", yet it fits at " + above);
assertEquals(block, generated.at(block.milliPoints(), block.milliPoints()).fit(), about);
}
}
}
assertTrue(kept > 200 && shrunk > 100, "the cases must reach both: " + kept + " kept, " + shrunk + " shrunk");
}
/***************************************************************************
** Property: in the same box a shorter text never gets a smaller size than a
** longer one that starts with it, and fits whenever the longer one does.
***************************************************************************/
@Test
void aShorterTextNeverGetsASmallerSizeThanALongerOne()
{
int compared = 0;
for(long seed : SEEDS)
{
Random random = new Random(seed);
for(int index = 0; index < CASES; index++)
{
Case generated = generate(random);
if(generated.text().isEmpty())
{
continue;
}
Case all = generated.at(generated.request().nominal(), generated.request().floor());
TextFit.Block longer = all.fit();
TextFit.Block shorter = all.of(generated.text().substring(0, random.nextInt(generated.text().length()))).fit();
String about = "seed " + seed + " case " + index + ": " + all.request() + " gave " + shorter + " and then " + longer;
if(longer.fits())
{
compared++;
assertTrue(shorter.fits() && shorter.milliPoints() >= longer.milliPoints() && shorter.lines().size() <= longer.lines().size(), about);
}
else
{
assertTrue(!shorter.fits() || shorter.milliPoints() >= longer.milliPoints(), about);
}
}
}
assertTrue(compared > 300, "compared " + compared);
}
/***************************************************************************
** Property: when the longest value is proven to fit (that many of the
** face's worst character), no text of up to that many characters is
** refused, whatever its characters, with spaces or without, cut or not.
***************************************************************************/
@Test
void aProvenLengthImpliesNoRefusalForAnyTextUpToThatLength()
{
int proven = 0;
int tried = 0;
for(long seed : SEEDS)
{
Random random = new Random(seed);
for(int index = 0; index < CASES; index++)
{
Case generated = generate(random);
TextFit.Request request = generated.request();
Face face = request.face();
int maxLength = 1 + random.nextInt(40);
Face.Glyph[] worst = new Face.Glyph[maxLength];
Arrays.fill(worst, face.worst());
TextFit.Block proof = TextFit.fit(request, worst, face.glyph(TextFit.MARK));
if(!proof.fits())
{
continue;
}
proven++;
List<Integer> drawn = FaceTest.drawn(face);
for(int attempt = 0; attempt < 12; attempt++)
{
StringBuilder text = new StringBuilder();
int length = attempt == 0 ? maxLength : 1 + random.nextInt(maxLength);
for(int character = 0; character < length; character++)
{
int choice = attempt % 4;
text.appendCodePoint(choice == 0 ? face.widest() : choice == 1 && random.nextInt(5) == 0 ? ' ' : choice == 3 ? "⁄Ǻ̉Wj".charAt(random.nextInt(6)) : drawn.get(random.nextInt(drawn.size())));
}
tried++;
TextFit.Block block = generated.of(text.toString()).fit();
assertTrue(block.fits(), () -> "seed " + seed + ": " + request + " proves " + maxLength + " characters with " + proof + " yet refuses " + text.length() + " as " + block);
assertTrue(block.milliPoints() >= proof.milliPoints(), "a real text is never smaller than the proof");
}
}
}
assertTrue(proven > 150 && tried > 1500, "proven " + proven + ", tried " + tried);
}
/***************************************************************************
** The proof agrees with rendering for the widest character: the longest
** length it proves is drawn, and it is short of the longest that is really
** drawn by no more than one character a line, which is the room the proof
** keeps for characters that reach past their advance.
***************************************************************************/
@Test
void theProofAgreesWithTheWidestCharacters()
{
for(Face face : Face.all())
{
for(int dpi : Scene2.RESOLUTIONS)
{
for(int maxLines : List.of(1, 2, 3))
{
TextFit.Request request = new TextFit.Request(face, 700 * dpi / 203, 150 * dpi / 203, dpi, 11_000, 7000, null, maxLines, false);
int proven = 0;
int drawn = 0;
for(int length = 1; length <= 200; length++)
{
Face.Glyph[] worst = new Face.Glyph[length];
Arrays.fill(worst, face.worst());
proven = TextFit.fit(request, worst, null).fits() ? length : proven;
drawn = fit(request, new String(Character.toChars(face.widest())).repeat(length)).fits() ? length : drawn;
}
String about = face.scene() + " at " + dpi + " dpi on " + maxLines + " lines: proven " + proven + ", drawn " + drawn;
assertTrue(proven >= 20 * maxLines && drawn < 200, about);
assertTrue(proven <= drawn && drawn - proven <= maxLines, about);
}
}
}
}
/***************************************************************************
** Property: the answer is exactly the one the search of every size gives:
** the same size, the same lines, the same numbers, fitted, refused or cut.
** Held over the cases labels use and over everything a scene may state,
** and for a proof of the face's worst character as for a text. The search
** of every size visits far more characters than `fit` does.
***************************************************************************/
@Test
void theAnswerIsExactlyThatOfTheSearchOfEverySize()
{
int fitted = 0;
int shrunk = 0;
int refused = 0;
int cut = 0;
int deep = 0;
long spent = 0;
long searched = 0;
for(long seed : SEEDS)
{
Random random = new Random(seed);
for(int index = 0; index < 2 * CASES; index++)
{
Case generated = index < CASES ? generate(random) : wide(random);
TextFit.Request request = generated.request();
Face face = request.face();
Face.Glyph[] glyphs = face.glyphs(generated.text());
if(index % 7 == 0)
{
glyphs = new Face.Glyph[1 + random.nextInt(60)];
Arrays.fill(glyphs, face.worst());
}
TextFit.Work work = new TextFit.Work(Long.MAX_VALUE);
TextFit.Work every = new TextFit.Work(Long.MAX_VALUE);
TextFit.Block block = TextFit.fit(request, glyphs, face.glyph(TextFit.MARK), work);
TextFit.Block expected = linear(request, glyphs, face.glyph(TextFit.MARK), every);
int length = glyphs.length;
assertEquals(expected, block, () -> "seed " + seed + " case " + request + " for " + length + " characters");
assertEquals(block, TextFit.fit(request, glyphs, face.glyph(TextFit.MARK)), "the same with no allowance stated");
spent += work.spent();
searched += every.spent();
fitted += block.fits() && !block.truncated() ? 1 : 0;
shrunk += block.fits() && !block.truncated() && block.milliPoints() < request.nominal() ? 1 : 0;
deep += block.fits() && request.nominal() - block.milliPoints() > 40 * TextFit.STEP_MILLIPOINTS ? 1 : 0;
refused += block.fits() ? 0 : 1;
cut += block.truncated() ? 1 : 0;
}
}
assertTrue(fitted > 900 && shrunk > 300 && deep > 100 && refused > 500 && cut > 150, "the cases must reach every outcome: " + fitted + " fitted, " + shrunk + " shrunk, " + deep + " by more than 10 pt, " + refused + " refused, " + cut + " cut");
assertTrue(searched > 20L * spent, "the search of every size visited " + searched + " characters, the fit " + spent);
System.out.println("3600 fits: " + spent + " characters visited, where the search of every size visits " + searched);
}
/***************************************************************************
** The case an independent review measured at 140 to 250 ms a fit: 1024
** characters at 600 dpi, type of 1000 pt that may shrink to 1 pt (four
** thousand sizes), in boxes it fits at no size, at a small size, or only
** cut. The answer is the one the search of every size gives, for under
** forty times the characters of the text where that search visits more
** than ten thousand times them. The time is printed; the count is held,
** because it is the same on every machine.
***************************************************************************/
@Test
void theWorstCaseOfTheShrinkSearchIsHeldToAStatedWork()
{
String wide = "W".repeat(1024);
String words = "The quick brown fox jumps over the lazy dog 0123456789 ".repeat(19).substring(0, 1024);
long most = 0;
long least = Long.MAX_VALUE;
long nanoseconds = 0;
long linearNanoseconds = 0;
int fits = 0;
for(int[] box : new int[][] {{20, 20, 64}, {20, 20, 1}, {40, 40, 64}, {200, 30, 1}, {600, 300, 64}, {2400, 1200, 64}, {2400, 1200, 1}, {9000, 30_000, 64}, {9000, 30_000, 2}})
{
for(String text : List.of(wide, words))
{
for(boolean truncate : List.of(false, true))
{
TextFit.Request request = new TextFit.Request(Face.SANS, box[0], box[1], 600, 1_000_000, 1000, null, box[2], truncate);
Face.Glyph[] glyphs = Face.SANS.glyphs(text);
TextFit.Work work = new TextFit.Work(Long.MAX_VALUE);
TextFit.Work every = new TextFit.Work(Long.MAX_VALUE);
long start = System.nanoTime();
TextFit.Block block = TextFit.fit(request, glyphs, Face.SANS.glyph(TextFit.MARK), work);
nanoseconds += System.nanoTime() - start;
start = System.nanoTime();
assertEquals(linear(request, glyphs, Face.SANS.glyph(TextFit.MARK), every), block, () -> "in " + request);
linearNanoseconds += System.nanoTime() - start;
assertTrue(work.spent() <= 40L * 1024, "in " + request + ": " + work.spent() + " characters visited");
most = Math.max(most, work.spent());
least = Math.min(least, every.spent());
fits += block.fits() ? 1 : 0;
}
}
}
assertTrue(least > 10_000L * 1024, "the search of every size visited at least " + least + " characters");
assertTrue(fits > 20 && fits < 36, fits + " of 36 fit or are cut");
System.out.println("1024 characters, 1000 pt to 1 pt at 600 dpi, 36 fits: at most " + most + " characters visited in a fit and " + nanoseconds / 36_000 + " microseconds a fit; the search of every size visited at least "
+ least + " and took " + linearNanoseconds / 36_000 + " microseconds a fit");
}
/***************************************************************************
** When one line at the floor is higher than the box, no text fits at any
** size, and that is known without searching: the text is laid out once at
** its size and once at the floor, for the numbers a refusal reports, and
** nothing is tried for a cut. The answer is still that of the search of
** every size.
***************************************************************************/
@Test
void aBoxLowerThanOneLineAtTheFloorIsRefusedWithoutASearch()
{
String text = "The quick brown fox jumps over the lazy dog 0123456789 ".repeat(19).substring(0, 1024);
Face.Glyph[] glyphs = Face.MONO.glyphs(text);
for(boolean truncate : List.of(false, true))
{
for(int maxLines : List.of(1, 64))
{
////////////////////////////////////////////////////////////////////////////////////////
// 1 pt at 600 dpi is 8.3 dots to the em: a line reserves 9 dots above its baseline //
// and 3 below, and the box is 11 high //
////////////////////////////////////////////////////////////////////////////////////////
TextFit.Request request = new TextFit.Request(Face.MONO, 5000, 11, 600, 1_000_000, 1000, null, maxLines, truncate);
TextFit.Work work = new TextFit.Work(Long.MAX_VALUE);
TextFit.Block block = TextFit.fit(request, glyphs, Face.MONO.glyph(TextFit.MARK), work);
assertFalse(block.fits() || block.truncated());
assertEquals(List.of(1000, 1024, 1024), List.of(block.milliPoints(), block.characters(), block.shown()));
assertTrue(block.height() > 11 && block.width() <= 5000, "measured at the floor: " + block);
assertEquals(linear(request, glyphs, Face.MONO.glyph(TextFit.MARK), new TextFit.Work(Long.MAX_VALUE)), block);
assertTrue(work.spent() <= 12L * 1024, "two layouts at each of two sizes, each at most three times the text, and no more: " + work.spent());
}
}
assertTrue(fit(new TextFit.Request(Face.MONO, 5000, 12, 600, 1_000_000, 1000, null, 1, true), text).truncated(), "one dot higher holds a line, and so a cut");
}
/***************************************************************************
** Fitting counts the characters it visits against the allowance it is
** given and ends, by name and with nothing of the text, when the allowance
** is passed: at once when it is already passed, however little is asked.
** The count is the same every time.
***************************************************************************/
@Test
void fittingEndsWhenItsAllowanceIsPassed()
{
String text = "The quick brown fox jumps over the lazy dog";
Face.Glyph[] glyphs = Face.SANS.glyphs(text);
TextFit.Request request = new TextFit.Request(Face.SANS, 300, 60, 203, 40_000, 5000, null, 2, true);
TextFit.Work measure = new TextFit.Work(Long.MAX_VALUE);
TextFit.Block block = TextFit.fit(request, glyphs, Face.SANS.glyph(TextFit.MARK), measure);
assertTrue(block.fits() && block.milliPoints() < 40_000 && measure.spent() > 500 && measure.spent() < 2000, measure.spent() + " characters visited for " + block);
TextFit.Work exact = new TextFit.Work(measure.spent());
assertEquals(block, TextFit.fit(request, glyphs, Face.SANS.glyph(TextFit.MARK), exact));
assertEquals(measure.spent(), exact.spent());
for(long allowance : List.of(0L, 1L, 43L, 200L, measure.spent() - 1))
{
TextFit.Work work = new TextFit.Work(allowance);
TextFit.Exhausted exhausted = assertThrows(TextFit.Exhausted.class, () -> TextFit.fit(request, glyphs, Face.SANS.glyph(TextFit.MARK), work));
assertEquals("TEXT_WORK_EXHAUSTED", exhausted.getMessage());
assertEquals(0, exhausted.getStackTrace().length);
assertTrue(work.spent() > allowance && work.spent() <= allowance + 2L * text.length() + 1, "passed by no more than one line: " + work.spent() + " of " + allowance);
long passed = work.spent();
assertThrows(TextFit.Exhausted.class, () -> TextFit.fit(request, Face.SANS.glyphs("A"), null, work));
assertThrows(TextFit.Exhausted.class, () -> work.spend(0));
assertTrue(work.spent() >= passed);
}
////////////////////////////////////////////////////////////////////////////////////////////
// a cut is counted too: every try of the last line with the mark //
////////////////////////////////////////////////////////////////////////////////////////////
TextFit.Request narrow = new TextFit.Request(Face.SANS, 120, 40, 203, 9000, 9000, null, 1, true);
TextFit.Work cutting = new TextFit.Work(Long.MAX_VALUE);
TextFit.Work whole = new TextFit.Work(Long.MAX_VALUE);
assertTrue(TextFit.fit(narrow, glyphs, Face.SANS.glyph(TextFit.MARK), cutting).truncated());
assertFalse(TextFit.fit(lines(narrow, 1, false), glyphs, null, whole).fits());
assertTrue(cutting.spent() > whole.spent(), cutting.spent() + " with a cut, " + whole.spent() + " without");
assertThrows(TextFit.Exhausted.class, () -> TextFit.fit(narrow, glyphs, Face.SANS.glyph(TextFit.MARK), new TextFit.Work(whole.spent())));
}
}
@@ -0,0 +1,482 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2025. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.renderer.scene2.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.kingsrook.qbits.renderer.scene2.Canvas;
import com.kingsrook.qbits.renderer.scene2.Frame;
import com.kingsrook.qbits.renderer.scene2.Layout;
import com.kingsrook.qbits.renderer.scene2.Placement;
import com.kingsrook.qbits.renderer.scene2.Scene2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*******************************************************************************
** What is drawn is what was measured: the ink of every line is inside the
** line's measured box, the block is where `align` and `valign` put it, and
** nothing is clipped. These read the canvas the renderer composes. Every
** text drawn here is also held to have nothing stray from its measure.
*******************************************************************************/
class TextRasterTest
{
private static final int MARGIN = 8;
/***************************************************************************
** Fit a text and draw it in a box that sits `MARGIN` dots inside a canvas,
** so that ink outside the box would be seen. The box is given as the text
** reads; turned a quarter, it is laid on its side.
***************************************************************************/
private static Canvas draw(TextFit.Request request, String text, Placement.Align align, Placement.Valign valign, int rotation, int threshold, int bandDots)
{
TextFit.Block block = TextFit.fit(request, request.face().glyphs(text), request.face().glyph(TextFit.MARK));
assertTrue(block.fits(), "the case must fit: " + request);
boolean upright = rotation % 180 == 0;
Frame frame = new Frame(MARGIN, MARGIN, upright ? request.width() : request.height(), upright ? request.height() : request.width());
Canvas canvas = new Canvas(frame.width() + 2 * MARGIN, frame.height() + 2 * MARGIN, request.dpi());
TextRaster.Drawing drawing = new TextRaster.Drawing(request.face(), text, block, align, valign, rotation, threshold, true);
assertEquals(new TextRaster.Stray(0, 0), TextRaster.paint(canvas, frame, drawing, bandDots), "nothing strays from the measure: " + request);
assertEquals(0, TextRaster.outside(drawing, request.dpi()));
return (canvas);
}
/***************************************************************************
** The box of the ink on a canvas: left, top, right and bottom (the last two
** exclusive), or null when it is blank.
***************************************************************************/
private static Frame ink(Canvas canvas)
{
int left = Integer.MAX_VALUE;
int top = -1;
int right = -1;
int bottom = -1;
for(int y = 0; y < canvas.height(); y++)
{
int first = canvas.firstInk(y);
if(first >= 0)
{
top = top < 0 ? y : top;
bottom = y + 1;
left = Math.min(left, first);
right = Math.max(right, canvas.lastInk(y) + 1);
}
}
return (top < 0 ? null : new Frame(left, top, right - left, bottom - top));
}
/***************************************************************************
** How many dots of a canvas hold ink.
***************************************************************************/
private static int dots(Canvas canvas)
{
int dots = 0;
for(int y = 0; y < canvas.height(); y++)
{
for(int x = 0; x < canvas.width(); x++)
{
dots += canvas.get(x, y) ? 1 : 0;
}
}
return (dots);
}
/***************************************************************************
** Whether two canvases hold the same picture.
***************************************************************************/
private static void assertSamePicture(Canvas expected, Canvas actual, String about)
{
assertEquals(expected.width(), actual.width(), about);
assertEquals(expected.height(), actual.height(), about);
for(int y = 0; y < expected.height(); y++)
{
for(int x = 0; x < expected.width(); x++)
{
if(expected.get(x, y) != actual.get(x, y))
{
assertEquals(expected.get(x, y), actual.get(x, y), about + ": dot " + x + ", " + y);
}
}
}
}
/***************************************************************************
** Every character of every bundled face, at sizes and resolutions labels
** use, is drawn with all of its ink inside the box that was measured for
** its line. The renderer itself fails a render whose ink leaves that box
** (the guard round each line), so drawing them all is the test; the ink is
** then also read back from the canvas and held to the line's box.
***************************************************************************/
@Test
void everyCharacterOfEveryFaceIsDrawnInsideItsMeasuredLine()
{
int[][] sizes = {{203, 6000}, {203, 9000}, {203, 14_250}, {300, 7000}, {300, 11_000}, {600, 5000}, {600, 12_250}};
for(Face face : Face.all())
{
List<Integer> drawn = FaceTest.drawn(face);
for(int[] size : sizes)
{
TextFit.Scale scale = new TextFit.Scale(size[1], size[0]);
int inked = 0;
for(int start = 0; start < drawn.size(); start += 16)
{
StringBuilder text = new StringBuilder();
drawn.subList(start, Math.min(drawn.size(), start + 16)).forEach(text::appendCodePoint);
TextFit.Request request = new TextFit.Request(face, scale.ceil(1500) * 16 + 16, scale.ceil(2000), size[0], size[1], size[1], null, 1, false);
Canvas canvas = draw(request, text.toString(), Placement.Align.LEFT, Placement.Valign.TOP, 0, 128, TextRaster.BAND_DOTS);
TextFit.Block block = TextFit.fit(request, face.glyphs(text.toString()), null);
Frame ink = ink(canvas);
if(ink != null)
{
inked++;
TextFit.Line line = block.lines().get(0);
Frame measured = new Frame(MARGIN, MARGIN + block.baseline() - line.above(), line.width(), line.above() + line.below());
assertTrue(measured.contains(ink), () -> face.scene() + " at " + size[1] + " millipoints, " + size[0] + " dpi: ink " + ink + " outside the measured " + measured);
assertTrue(new Frame(MARGIN, MARGIN, block.width(), block.height()).contains(measured));
}
}
assertTrue(inked >= drawn.size() / 16 - 4, face.scene() + " drew " + inked + " lines");
}
}
}
/***************************************************************************
** Property: for generated texts, faces, boxes, sizes and resolutions, at
** every rotation, no ink is outside the element's box and none is clipped,
** and the upright picture turned is the turned picture. Up to 100 dots to
** the em, where glyphs are drawn as bitmaps, the picture is also exactly
** the same drawn a row at a time, so bands lose and repeat nothing.
***************************************************************************/
@Test
void inkIsNeverOutsideTheBoxAndNeverClipped()
{
Random random = new Random(TextFitTest.SEEDS[0]);
List<Placement.Align> aligns = List.of(Placement.Align.values());
List<Placement.Valign> valigns = List.of(Placement.Valign.values());
int drawn = 0;
int banded = 0;
for(int index = 0; drawn < 160; index++)
{
TextFitTest.Case generated = TextFitTest.generate(random);
if(!generated.fit().fits() || generated.text().isBlank())
{
continue;
}
drawn++;
TextFit.Request request = generated.request();
Placement.Align align = aligns.get(random.nextInt(3));
Placement.Valign valign = valigns.get(random.nextInt(3));
int threshold = 1 + random.nextInt(254);
String about = "case " + index + ": " + request;
Canvas upright = draw(request, generated.text(), align, valign, 0, threshold, TextRaster.BAND_DOTS);
Frame ink = ink(upright);
Frame box = new Frame(MARGIN, MARGIN, request.width(), request.height());
assertTrue(ink == null || box.contains(ink), about + ": ink " + ink + " outside " + box);
if(new TextFit.Scale(generated.fit().milliPoints(), request.dpi()).size() <= 100)
{
banded++;
assertSamePicture(upright, draw(request, generated.text(), align, valign, 0, threshold, 1), about + ", row by row");
}
for(int rotation : List.of(90, 180, 270))
{
Canvas turned = draw(request, generated.text(), align, valign, rotation, threshold, TextRaster.BAND_DOTS);
Canvas expected = new Canvas(turned.width(), turned.height(), request.dpi());
for(int y = 0; y < request.height(); y++)
{
for(int x = 0; x < request.width(); x++)
{
if(upright.get(MARGIN + x, MARGIN + y))
{
int turnedX = rotation == 90 ? request.height() - 1 - y : rotation == 180 ? request.width() - 1 - x : y;
int turnedY = rotation == 90 ? x : rotation == 180 ? request.height() - 1 - y : request.width() - 1 - x;
expected.set(MARGIN + turnedX, MARGIN + turnedY, true);
}
}
}
assertSamePicture(expected, turned, about + ", turned " + rotation);
}
}
assertTrue(banded > 60, "drawn row by row: " + banded);
}
/***************************************************************************
** The block sits in the box where `align` and `valign` say, a centred block
** within one dot of the middle, and each line sits in the block the same
** way. Read from the ink of a two-line text.
***************************************************************************/
@Test
void theBlockIsPlacedByAlignAndValignAndCentredWithinOneDot()
{
String text = "HHHHHHHH HH";
TextFit.Request request = new TextFit.Request(Face.SANS_BOLD, 241, 151, 203, 12_000, 12_000, null, 2, false);
TextFit.Block block = TextFit.fit(request, Face.SANS_BOLD.glyphs(text), null);
assertEquals(List.of("HHHHHHHH", "HH"), TextFitTest.shown(block, text));
TextFit.Line wide = block.lines().get(0);
TextFit.Line narrow = block.lines().get(1);
for(Placement.Align align : Placement.Align.values())
{
for(Placement.Valign valign : Placement.Valign.values())
{
Canvas canvas = draw(request, text, align, valign, 0, 128, TextRaster.BAND_DOTS);
Frame content = Layout.align(new Frame(MARGIN, MARGIN, 241, 151), block.width(), block.height(), align, valign);
Frame ink = ink(canvas);
assertTrue(content.contains(ink), align + " " + valign + ": ink " + ink + " outside the block " + content);
int slackLeft = content.x() - MARGIN;
int slackRight = MARGIN + 241 - content.right();
int slackTop = content.y() - MARGIN;
int slackBottom = MARGIN + 151 - content.bottom();
switch(align)
{
case LEFT -> assertEquals(0, slackLeft);
case CENTER -> assertTrue(slackLeft >= 0 && Math.abs(slackLeft - slackRight) <= 1);
default -> assertEquals(0, slackRight);
}
switch(valign)
{
case TOP -> assertEquals(0, slackTop);
case MIDDLE -> assertTrue(slackTop >= 0 && Math.abs(slackTop - slackBottom) <= 1);
default -> assertEquals(0, slackBottom);
}
//////////////////////////////////////////////////////////////////////////////////////
// the ink of each line, read from the rows of its own baseline, is in the line's //
// box, and that box is against the same side of the block (or in its middle) //
//////////////////////////////////////////////////////////////////////////////////////
int capitals = new TextFit.Scale(12_000, 203).floor(Face.SANS_BOLD.capHeight());
int first = content.y() + block.baseline() - capitals / 2;
int second = first + block.pitch();
int narrowLeft = content.x() + align.position().place(block.width(), narrow.width(), 0);
assertTrue(canvas.firstInk(first) >= content.x() && canvas.lastInk(first) < content.x() + wide.width(), "the widest line fills the block");
assertTrue(canvas.firstInk(second) >= narrowLeft && canvas.lastInk(second) < narrowLeft + narrow.width(), align + ": the short line " + canvas.firstInk(second) + " to " + canvas.lastInk(second));
int gapLeft = canvas.firstInk(second) - canvas.firstInk(first);
int gapRight = canvas.lastInk(first) - canvas.lastInk(second);
switch(align)
{
case LEFT -> assertTrue(Math.abs(gapLeft) <= 1 && gapRight > 50);
case CENTER -> assertTrue(Math.abs(gapLeft - gapRight) <= 2 && gapLeft > 25);
default -> assertTrue(Math.abs(gapRight) <= 1 && gapLeft > 50);
}
}
}
}
/***************************************************************************
** A dot is ink when its grey is darker than the threshold, so a higher
** threshold prints every dot a lower one prints and more: heavier strokes,
** which is the control for small type on a thermal head.
***************************************************************************/
@Test
void aHigherThresholdPrintsHeavier()
{
TextFit.Request request = new TextFit.Request(Face.SANS, 500, 60, 203, 14_000, 14_000, null, 1, false);
List<Canvas> pictures = new ArrayList<>();
for(int threshold : List.of(1, 60, 128, 200, 254))
{
pictures.add(draw(request, "Lot L240611A 0O1lI", Placement.Align.LEFT, Placement.Valign.TOP, 0, threshold, TextRaster.BAND_DOTS));
}
for(int index = 1; index < pictures.size(); index++)
{
Canvas lighter = pictures.get(index - 1);
Canvas heavier = pictures.get(index);
assertTrue(dots(heavier) > dots(lighter), "threshold step " + index + ": " + dots(lighter) + " then " + dots(heavier));
for(int y = 0; y < lighter.height(); y++)
{
for(int x = 0; x < lighter.width(); x++)
{
assertFalse(lighter.get(x, y) && !heavier.get(x, y), "a dot printed at the lower threshold is printed at the higher");
}
}
}
assertTrue(dots(pictures.get(0)) > 100, "full ink is black at every threshold");
}
/***************************************************************************
** The ends of what the renderer accepts. At 1 pt and 2 pt, where a letter
** is a few dots, every character of every face is drawn inside its
** measured line. At 300 pt and 1000 pt, where a letter is drawn from its
** outline in bands, the characters of each face that reach furthest are:
** its widest, and those that reach furthest left, right, up and down.
***************************************************************************/
@Test
void theSmallestAndTheLargestTypeAreDrawnInsideTheirMeasuredLine()
{
for(Face face : Face.all())
{
List<Integer> drawn = FaceTest.drawn(face);
for(int[] size : new int[][] {{203, 1000}, {300, 1000}, {600, 1000}, {203, 2000}, {600, 2000}})
{
TextFit.Scale scale = new TextFit.Scale(size[1], size[0]);
for(int start = 0; start < drawn.size(); start += 16)
{
StringBuilder text = new StringBuilder();
drawn.subList(start, Math.min(drawn.size(), start + 16)).forEach(text::appendCodePoint);
TextFit.Request request = new TextFit.Request(face, scale.ceil(1500) * 16 + 16 * 2 * TextFit.SLOP, scale.ceil(2000) + 2 * TextFit.SLOP, size[0], size[1], size[1], null, 1, false);
Canvas canvas = draw(request, text.toString(), Placement.Align.LEFT, Placement.Valign.TOP, 0, 128, TextRaster.BAND_DOTS);
TextFit.Line line = TextFit.fit(request, face.glyphs(text.toString()), null).lines().get(0);
Frame ink = ink(canvas);
assertTrue(ink == null || new Frame(MARGIN, MARGIN, line.width(), request.height()).contains(ink), () -> face.scene() + " at " + size[1] + " millipoints, " + size[0] + " dpi: ink " + ink);
}
}
Face.Glyph worst = face.worst();
StringBuilder extremes = new StringBuilder().appendCodePoint(face.widest());
for(int codePoint : drawn)
{
Face.Glyph glyph = face.glyph(codePoint);
if(glyph.ink() && extremes.length() < 5 && (glyph.left() == worst.left() || glyph.right() - glyph.advance() == worst.right() - worst.advance() || glyph.top() == worst.top() || glyph.bottom() == worst.bottom()))
{
extremes.appendCodePoint(codePoint);
}
}
assertTrue(extremes.length() >= 3, face.scene() + " has " + extremes.length() + " furthest-reaching characters");
for(int milliPoints : List.of(300_000, 1_000_000))
{
TextFit.Scale scale = new TextFit.Scale(milliPoints, 203);
for(int index = 0; index < (milliPoints == 300_000 ? extremes.length() : 2); index++)
{
String text = extremes.substring(index, index + 1);
TextFit.Request request = new TextFit.Request(face, scale.ceil(2000), scale.ceil(2000), 203, milliPoints, milliPoints, null, 1, false);
Canvas canvas = draw(request, text, Placement.Align.CENTER, Placement.Valign.MIDDLE, 0, 128, TextRaster.BAND_DOTS);
Frame ink = ink(canvas);
assertTrue(ink.width() > scale.floor(100) && ink.height() > scale.floor(100), () -> face.scene() + " U+" + Integer.toHexString(text.codePointAt(0)) + " at " + milliPoints + " millipoints: ink " + ink);
}
}
}
}
/***************************************************************************
** Ink outside the measured line is never clipped away and never printed,
** and a text is never printed in part: what strayed is counted and the
** label is left as it was, reverse text included, whose box is not filled.
** Forced here with lines whose boxes are stated too small: one that ends in
** the gap between two letters, so the second letter is wholly beyond the
** guard and only its bounds tell, and two that cut through the letters,
** whose ink is found in the guard. The bounds alone, which is what a
** validation asks, count the same glyphs. Ink that would fall outside the
** element's box is counted too, and none of that text is printed.
***************************************************************************/
@Test
void inkOutsideTheMeasuredLineIsCountedAndNothingIsPainted()
{
TextFit.Request request = new TextFit.Request(Face.SANS_BOLD, 200, 60, 203, 12_000, 12_000, null, 1, false);
TextFit.Block honest = TextFit.fit(request, Face.SANS_BOLD.glyphs("HH"), null);
TextFit.Line line = honest.lines().get(0);
Canvas canvas = new Canvas(220, 80, 203);
Frame frame = new Frame(10, 10, 200, 60);
List<TextFit.Line> wrong = List.of(new TextFit.Line(0, 2, false, line.left(), line.right() / 2, line.above(), line.below()), new TextFit.Line(0, 2, false, line.left(), line.right(), line.above() / 3, line.below()),
new TextFit.Line(0, 2, false, line.left(), line.right(), line.above(), -line.above() / 2));
List<TextRaster.Stray> strays = new ArrayList<>();
for(TextFit.Line each : wrong)
{
TextFit.Block forged = new TextFit.Block(honest.milliPoints(), List.of(each), each.width(), honest.height(), honest.baseline(), honest.pitch(), 2, 2, true);
for(boolean reverse : List.of(false, true))
{
TextRaster.Drawing drawing = new TextRaster.Drawing(Face.SANS_BOLD, "HH", forged, Placement.Align.LEFT, Placement.Valign.TOP, 0, 128, !reverse);
TextRaster.Stray stray = TextRaster.paint(canvas, frame, drawing, TextRaster.BAND_DOTS);
assertTrue(stray.any() && stray.glyphs() > 0, "strayed: " + stray);
assertEquals(stray.glyphs(), TextRaster.outside(drawing, 203));
assertEquals(stray, TextRaster.paint(canvas, frame, drawing, 1 << 10), "the same count drawn in bands");
assertEquals(null, ink(canvas), "nothing of a text that strayed is on the label");
strays.add(stray);
}
}
assertEquals(List.of(new TextRaster.Stray(1, 0), new TextRaster.Stray(1, 0)), strays.subList(0, 2), "the second letter is wholly beyond the guard: only its bounds tell");
assertTrue(strays.get(2).glyphs() == 2 && strays.get(2).dots() > 20 && strays.get(4).glyphs() == 2 && strays.get(4).dots() > 20, "ink in the guard: " + strays);
assertFalse(new TextRaster.Stray(0, 0).any());
assertTrue(new TextRaster.Stray(0, 1).any() && new TextRaster.Stray(1, 0).any());
////////////////////////////////////////////////////////////////////////////////////////////
// a block measured honestly but handed a box too small for it: its ink would fall //
// outside the element, to the right and below //
////////////////////////////////////////////////////////////////////////////////////////////
TextRaster.Drawing whole = new TextRaster.Drawing(Face.SANS_BOLD, "HH", honest, Placement.Align.LEFT, Placement.Valign.TOP, 0, 128, true);
for(Frame small : List.of(new Frame(10, 10, 20, 60), new Frame(10, 10, 200, 12)))
{
TextRaster.Stray stray = TextRaster.paint(canvas, small, whole, TextRaster.BAND_DOTS);
assertTrue(stray.glyphs() == 0 && stray.dots() > 20, "outside the element: " + stray);
assertEquals(null, ink(canvas));
}
Canvas clean = new Canvas(220, 80, 203);
assertEquals(new TextRaster.Stray(0, 0), TextRaster.paint(clean, frame, whole, TextRaster.BAND_DOTS));
assertEquals(0, TextRaster.outside(whole, 203));
assertTrue(new Frame(10, 10, honest.width(), honest.height()).contains(ink(clean)));
}
/***************************************************************************
** Very large type is drawn in bands of whole rows, so a line never needs
** more grey than the band allows. 200 pt at 600 dpi is 1667 dots to the em.
** The bands lose no row and repeat none: the picture is the one drawn in
** one piece, but for a few edge dots where the rasteriser, given a band,
** shades a curve differently: fewer than one ink dot in ten thousand (4 of
** 121 thousand, 5 of 265 thousand and 40 of 1.06 million were seen).
***************************************************************************/
@Test
void veryLargeTypeIsDrawnInBands()
{
for(int dpi : Scene2.RESOLUTIONS)
{
TextFit.Request request = new TextFit.Request(Face.CONDENSED_BOLD, 2400 * dpi / 600, 2400 * dpi / 600, dpi, 200_000, 200_000, null, 1, false);
Canvas whole = draw(request, "7g", Placement.Align.CENTER, Placement.Valign.MIDDLE, 0, 128, Integer.MAX_VALUE);
assertSamePicture(whole, draw(request, "7g", Placement.Align.CENTER, Placement.Valign.MIDDLE, 0, 128, TextRaster.BAND_DOTS), "200 pt at " + dpi + " dpi fits one band");
Canvas banded = draw(request, "7g", Placement.Align.CENTER, Placement.Valign.MIDDLE, 0, 128, 1 << 16);
int different = 0;
for(int y = 0; y < whole.height(); y++)
{
for(int x = 0; x < whole.width(); x++)
{
different += whole.get(x, y) == banded.get(x, y) ? 0 : 1;
}
}
assertTrue(different * 10_000L <= dots(whole), "200 pt at " + dpi + " dpi: " + different + " dots differ of " + dots(whole));
System.out.println("200 pt at " + dpi + " dpi in bands: " + different + " of " + dots(whole) + " ink dots differ from the picture drawn in one piece");
assertEquals(ink(whole), ink(banded));
int capitals = new TextFit.Scale(200_000, dpi).floor(Face.CONDENSED_BOLD.capHeight());
assertTrue(ink(banded).height() > capitals && ink(banded).height() < 2 * capitals && ink(banded).width() > capitals, "the digits are the size asked: " + ink(banded));
}
}
}
@@ -0,0 +1,31 @@
# Golden labels of version 2 scenes
Each case in `cases` has, in `golden`, at 203, 300 and 600 dpi, the exact ZPL the renderer emits
(`<case>-<dpi>.zpl`) and the page a printer draws from it (`<case>-<dpi>.png`). `SceneGoldenTest` compares both
exactly, on every machine, and holds `golden` to exactly those files, which is why this note is beside it.
## What the pictures depend on
A box is whole dots of ink and depends on the scene alone. Text is measured by integer arithmetic on the bundled
faces, which is the same everywhere, but its glyph bitmaps are drawn by the Java runtime: the Java 2D rasteriser
and the FreeType library that the JDK itself ships (`lib/libfreetype.so` on Linux, `bin/freetype.dll` on
Windows). The system's FreeType is not used: in the images below `libfontmanager.so` loads the JDK's own copy.
The version of that copy is the one the JDK states in `legal/java.desktop/freetype.md`.
The text goldens (`text-*`) were generated and compared on these runtimes, all x86-64:
| Where | JDK | FreeType in the JDK | The goldens there |
|---|---|---|---|
| CI image `maven:3.9.11-eclipse-temurin-21` (Ubuntu 24.04) | Temurin 21.0.9+10 | 2.13.3 | generated here; compared exactly by the build |
| Windows 11 | Temurin 21.0.12.1+1 | 2.14.3 | the same bytes; compared exactly by the build |
| The worker image's runtime (`renderer/Dockerfile` requires `jdk-21.0.13+9` on Ubuntu 24.04), as `eclipse-temurin:21-jre-noble` | Temurin 21.0.13+9 | 2.14.3 | the same bytes; the 21 labels were rendered there and compared by hand, not by a build |
So the same bytes came from two FreeType versions and three JDK builds. That is an observation about these
versions, not a promise about the next: a golden that changes with a runtime is a reviewed change.
## Changing a golden
A golden changes only with a reviewed change to the layout rules or to the runtime. Run `SceneGoldenTest` in the
CI image; what the build drew is left in `renderer/target/scene2-actual`. Copy the files to `golden`, then run the
test on Windows as well: it must pass there on the same bytes. Say in the change which goldens changed and why, and
update the table above when a runtime changes.
@@ -0,0 +1,11 @@
{
"stock": {"widthMicrons": 101600, "heightMicrons": 25400, "topMicrons": 3000, "rightMicrons": 3000, "bottomMicrons": 3000, "leftMicrons": 3000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "4in", "height": "1in"},
"elements": [
{"id": "code", "type": "barcode", "symbology": "gs1-128", "value": "[01]00012345678905[11]260101[21]TEST0001", "anchor": "top-center", "y": "0.5mm", "width": "94mm", "height": "13mm", "barcodeProfile": "gs1-general"},
{"id": "rule", "type": "box", "anchor": "bottom-center", "y": "1mm", "width": "94mm", "height": "0.5pt", "thickness": "0.5pt"}
]
}
}
@@ -0,0 +1,16 @@
{
"stock": {"widthMicrons": 50800, "heightMicrons": 25400, "topMicrons": 2000, "rightMicrons": 2000, "bottomMicrons": 2000, "leftMicrons": 2000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "2in", "height": "1in"},
"elements": [
{"id": "ground", "type": "box", "y": "11mm", "width": "38mm", "height": "10mm", "fill": true},
{"id": "code", "type": "barcode", "symbology": "code128", "value": "TEST-0001", "width": "38mm", "height": "9mm"},
{"id": "capped", "type": "barcode", "symbology": "code39", "value": "T1", "x": "1mm", "y": "12mm", "width": "36mm", "height": "8mm", "align": "right", "maxModule": "0.4mm", "quiet": 12},
{"id": "side", "type": "barcode", "symbology": "itf", "value": "0012", "anchor": "top-right", "width": "7mm", "height": "21mm", "rotation": 90, "barcodeProfile": "none"}
],
"overrides": [
{"when": {"dpi": [600]}, "set": {"capped": {"maxModule": "0.3mm"}}}
]
}
}
@@ -0,0 +1,12 @@
{
"stock": {"widthMicrons": 50800, "heightMicrons": 25400, "topMicrons": 2000, "rightMicrons": 2000, "bottomMicrons": 2000, "leftMicrons": 2000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "2in", "height": "1in"},
"elements": [
{"id": "square", "type": "barcode", "symbology": "qr", "value": "TEST-0001", "y": "2mm", "width": "14mm", "height": "14mm"},
{"id": "turned", "type": "barcode", "symbology": "datamatrix", "value": "TEST-0001-0002", "anchor": "top-center", "y": "2mm", "width": "9mm", "height": "18mm", "align": "left", "valign": "bottom", "rotation": 90},
{"id": "target", "type": "barcode", "symbology": "aztec", "value": "TEST-0001", "anchor": "top-right", "y": "2mm", "width": "14mm", "height": "14mm", "align": "right", "valign": "top", "quiet": 5}
]
}
}
@@ -0,0 +1,12 @@
{
"stock": {"widthMicrons": 101600, "heightMicrons": 25400, "topMicrons": 3000, "rightMicrons": 3000, "bottomMicrons": 3000, "leftMicrons": 3000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "4in", "height": "1in"},
"elements": [
{"id": "retail", "type": "barcode", "symbology": "ean13", "value": "0012345678905", "width": "45mm", "minHeight": "15mm"},
{"id": "small", "type": "barcode", "symbology": "upce", "value": "04252614", "anchor": "top-right", "width": "26mm", "height": "16mm", "minHeight": "15mm", "align": "left", "valign": "bottom"},
{"id": "rule", "type": "box", "anchor": "bottom-right", "width": "26mm", "height": "0.5pt", "thickness": "0.5pt"}
]
}
}
@@ -0,0 +1,15 @@
{
"stock": {"widthMicrons": 50800, "heightMicrons": 25400, "topMicrons": 2000, "rightMicrons": 2000, "bottomMicrons": 2000, "leftMicrons": 2000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "2in", "height": "1in"},
"defaults": {"size": "8pt"},
"elements": [
{"id": "sans", "type": "text", "value": "Sans 0O 1lI 5S 8B Åéj", "font": "qqq-sans", "y": "0mm", "height": "4.2mm"},
{"id": "sans-bold", "type": "text", "value": "Bold 0O 1lI 5S 8B Åéj", "font": "qqq-sans-bold", "y": "4.2mm", "height": "4.2mm"},
{"id": "condensed-bold", "type": "text", "value": "Condensed 0O 1lI 5S 8B Åéj", "font": "qqq-condensed-bold", "y": "8.4mm", "height": "4.2mm"},
{"id": "mono", "type": "text", "value": "Mono 0O 1lI 5S 8B Åéj", "font": "qqq-mono", "y": "12.6mm", "height": "4.2mm"},
{"id": "mono-bold", "type": "text", "value": "Bold 0O 1lI 5S 8B Åéj", "font": "qqq-mono-bold", "y": "16.8mm", "height": "4.2mm"}
]
}
}
@@ -0,0 +1,21 @@
{
"stock": {"widthMicrons": 50800, "heightMicrons": 25400, "topMicrons": 2000, "rightMicrons": 2000, "bottomMicrons": 2000, "leftMicrons": 2000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "2in", "height": "1in"},
"defaults": {"font": "qqq-sans-bold", "size": "10pt"},
"elements": [
{"id": "kept-box", "type": "box", "width": "22mm", "height": "5mm", "thickness": "0.1mm"},
{"id": "kept", "type": "text", "value": "LOT 240611", "width": "22mm", "height": "5mm", "align": "center", "valign": "middle"},
{"id": "right-box", "type": "box", "anchor": "top-right", "width": "22mm", "height": "5mm", "thickness": "0.1mm"},
{"id": "right", "type": "text", "value": "9.5 kg", "font": "qqq-condensed-bold", "size": "11pt", "anchor": "top-right", "width": "22mm", "height": "5mm", "align": "right", "valign": "bottom"},
{"id": "shrunk-box", "type": "box", "y": "5.5mm", "width": "44mm", "height": "4mm", "thickness": "0.1mm"},
{"id": "shrunk", "type": "text", "value": "(01)00012345678905(10)L240611A", "font": "qqq-mono-bold", "size": "9pt", "y": "5.5mm", "width": "44mm", "height": "4mm", "valign": "middle"},
{"id": "wrapped-box", "type": "box", "y": "10mm", "width": "36mm", "height": "7.5mm", "thickness": "0.1mm"},
{"id": "wrapped", "type": "text", "value": "(01)00012345678905(10)L240611A-RETURNED-000123", "font": "qqq-mono", "size": "7pt", "y": "10mm", "width": "36mm", "height": "7.5mm", "align": "center", "valign": "middle",
"maxLength": 46, "fit": {"maxLines": 2}},
{"id": "cut-box", "type": "box", "anchor": "bottom-left", "width": "30mm", "height": "3.6mm", "thickness": "0.1mm"},
{"id": "cut", "type": "text", "value": "A description of the item that is too long", "font": "qqq-sans", "size": "7pt", "anchor": "bottom-left", "width": "30mm", "height": "3.6mm", "fit": {"overflow": "truncate", "shrinkTo": "7pt"}}
]
}
}
@@ -0,0 +1,18 @@
{
"stock": {"widthMicrons": 50800, "heightMicrons": 25400, "topMicrons": 2000, "rightMicrons": 2000, "bottomMicrons": 2000, "leftMicrons": 2000, "dpi": 203},
"scene": {
"schema": "qqq-zpl-scene/2",
"design": {"width": "2in", "height": "1in"},
"defaults": {"font": "qqq-sans-bold", "size": "10pt"},
"elements": [
{"id": "up", "type": "text", "value": "TEST-0001", "font": "qqq-mono-bold", "rotation": 90, "width": "5mm", "align": "center"},
{"id": "down", "type": "text", "value": "TEST-0001", "font": "qqq-mono-bold", "rotation": 270, "anchor": "top-right", "width": "5mm", "align": "center"},
{"id": "flip", "type": "text", "value": "THIS WAY UP", "rotation": 180, "x": "7mm", "width": "30mm", "height": "5mm", "align": "center"},
{"id": "panel", "type": "text", "value": "ZONE 7", "font": "qqq-condensed-bold", "size": "16pt", "reverse": true, "x": "7mm", "y": "6mm", "width": "30mm", "height": "8mm", "align": "center", "valign": "middle"},
{"id": "fine", "type": "text", "value": "Best before 2027-06-11", "font": "qqq-sans", "size": "6.5pt", "x": "7mm", "y": "15mm", "width": "32mm", "height": "5mm", "valign": "bottom"}
],
"overrides": [
{"when": {"dpi": [203]}, "set": {"fine": {"font": "qqq-sans-bold", "threshold": 150}}}
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 271 B

@@ -0,0 +1,4 @@
^XA^PW812^LL203^LH0,0^CI28
^FO128,28^GFA,7210,7210,70,F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3C3CF0F3F0C33FCFCF3F03303CC0F3F303CFC0CCFCFF3CF0F0F0F3C30303CF03F33C0F30FC3FCCFCF0F3C3CF0F0F0F3C3F3CFCCFCF0300CF0F3CFF3030F0F030C3F0C3CF0F3C3Line truncated
^FO30,170^GFA,94,94,94,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE^FS
^XZ
Binary file not shown.

After

Width:  |  Height:  |  Size: 487 B

@@ -0,0 +1,4 @@
^XA^PW1200^LL300^LH0,0^CI28
^FO184,42^GFA,15912,15912,104,FC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03F1F81C01C01F8FC01FF1C7EFC703FE07FF8E3FE3F03F1F81F8FC0FC0FC0FC7E07FC7E3FE38FF8FC01C0038FC0FC7E3FFC700703F03F0070381FF0381F8FC0FC7E07E07E3F03F1FF0381C7FF8FF8FC7FC01C7007E3803F1FF1C01F8FF8038E3FE3FFC7E3F03F03F03Line truncated
^FO45,251^GFA,278,278,139,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFCFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC^FS
^XZ
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1,4 @@
^XA^PW2400^LL600^LH0,0^CI28
^FO230,83^GFA,74601,74601,243,FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03FFFFE03F80FFFFF80FFFC00001FC0000003F80FFFC000FFFC07FFE03FFFFFFC07F000007F0003FFF0003FFF000007F0003F8001FFFFF0003F8001FFF80FFFC000FFFC07FFE0007FFE0007FFE03FFF0003FFF01FFFFF0003F8001FC07FFFFFF80FFFFF80FFFC07FFFFC00001FC07F000007FFE03F800003FFF01FFFFF01FC00001FFF80FFFFF800003F80FE03FFFFE03FFFFFFC07FFE03FFF0003FFF0003FFF0003FFF01FFF8001FC00001FC00001FFF80FFFC00001FFFFF01FC07FFE0FFFC07F0003FFFFE0007FFFFFF80FE03FFFFE03FFF0003FFF01FFF8001FFF80FFFC000FFFC000FFFC000FFFC07FFE0007FFFFC07FFE03Line truncated
^FO90,501^GFA,1112,1112,278,FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0^FS
^XZ
Binary file not shown.

After

Width:  |  Height:  |  Size: 295 B

Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more