# Golden-output test suite for the REBOL/View 2 clone

This directory contains a **golden-output conformance suite** for the clone.
Every case is a small, deterministic REBOL 2 script.  The expected output is
generated by running the original **REBOL/View 2.7.8.3.1** executable
(`reference-rebol-view-278-3-1.exe`) under Wine, so the goldens are an
oracle, not hand-written expectations.

Current result: **103/103 cases pass** on both the native Linux build and the
Windows PE build under Wine (demo34).

## Layout

```
tests/
  cases/      103 *.r cases (no REBOL header, no quit)
  expected/   golden output for each case
  tools/run.py  runner / golden generator
  fixtures/   files copied into each case's temporary working directory
  README.md   this file
```

## Running

From the repository root:

```bash
# compare the native Linux clone against the goldens
python3 tests/tools/run.py test

# show unified diffs for failures
python3 tests/tools/run.py test --diff

# compare the Windows build under Wine
python3 tests/tools/run.py test --wine --diff

# regenerate the goldens from the reference binary (requires Wine + Xvfb)
python3 tests/tools/run.py gen
```

A bundled-example smoke test runs every script in `examples/` (console and
VID windows, on Linux and Wine):

```bash
python3 tools/examples_smoke.py
python3 tools/examples_smoke.py --wine
```

A **GUI screenshot regression** renders static VID layouts and diffs them
against stored baselines (needs Wine, Xvfb and Pillow):

```bash
python3 tools/gui_shots.py            # compare with tests/gui-baseline/
python3 tools/gui_shots.py --update   # rewrite the baselines
python3 tools/gui_shots.py --only widgets --keep
```

`tests/gui/*.r` are deliberately static (no timers, no animation) and call
`view`, so the window stays open until the harness kills the interpreter.
The harness finds the window with `xwininfo`, crops it with `ffmpeg`, and
compares with `PIL`: a shot passes when no more than 2% of pixels differ by
more than 12/255 per channel (Wine font antialiasing can shift by a step).
`tests/gui-baseline/` is the expected set (widgets, image effects, text
list).

A separate local-server smoke test covers URL networking (HTTP redirects,
`load` of an image URL, FTP read/write/list/`dir?`, POP3/IMAP reads and SMTP
sending):

```bash
python3 tools/net_smoke.py
python3 tools/net_smoke.py --wine
```

Useful options:

```
--only 23          run/regenerate cases whose name contains "23"
--timeout 80       per-run timeout in seconds
--no-retry         do not retry a timed-out run
--all              (gen) regenerate every golden, including existing ones
```

The runner wraps each case as:

```rebol
REBOL []
out: copy ""
print: func [value] [... append to out ...]
prin:  func [value] [...]
probe: func [value] [...]
either error? try [
    <case body>
] [append out "ERROR" append out newline] []
write %result.txt out
quit
```

The wrapper deliberately uses `either error? try [...]` rather than
`err: try [...]`: in R2 a raw error value stored in a word is re-raised.
Errors are normalised to a single `ERROR` line.

Cases must be deterministic.  Do not use `now`, `random`, `alert`,
`request-*`, `editor`, `browse`, external network reads, `view`, `call` or
unbounded `wait`s.  `layout` alone is fine.  File cases use relative paths
because the runner changes the working directory to a fresh temp dir.

Port cases (70-75) are allowed but must be **self-contained loopback** and
must be written the way the reference needs them:

* use a fixed high port (19xxx) and always `close` every port so the next
  run can bind it again; a timed-out run can leave a reference process
  holding the port (`pkill -9 -x rebol-view.exe`, `pkill -9 -x wine`,
  `pkill -9 -x wineserver`),
* the reference only flushes TCP data written by a port when that port is
  closed, so `insert port data` must be followed by `close port` (or by an
  event-loop `wait`) before the other end can `copy` it,
* `copy port` returns `none` at EOF and `read port` raises in R2 — use
  `copy`,
* never set `port/state/misc` (or other internals) on a port you then
  `close`: R2 hangs.  Inspect such a port after the script ends instead,
* do not read a file image twice through `copy` on a *default* `open`: R2's
  file cache may or may not have the content.  Use `open/read`,
* if a case closes the **accepted** side of a connection first, that listener
  port lands in TIME_WAIT and cannot always be rebound by the next run.
  Close the client side first (or use a fresh port) — see cases 76/77,
* `port/awake` receives the **port** as its only argument, is called once per
  `wait`, and is *not* called on a timeout.  A handler that is a global
  function must be assigned *before* `wait` runs.

Important R2 quirks learned while building the suite:

* `try` does **not** catch "has no value" errors.  A case containing an
  undefined word drops the reference into its interactive error console and
  the runner times out.  Use only words defined by R2 (and define charsets
  such as `letters`/`digits` in the case; `alpha`/`digit` are unset globals
  in this build).
* Tuples hold at most 10 components (an 11-component literal or
  `make tuple!` block fails in R2) and preserve their length (3, 4, 5, ...).
* `case`/`switch` results: several values may precede a shared result block
  (`switch v [1 3 [odd] 2 [even]]`).
* `checksum/hash` requires its `size` refinement argument (an `integer!`).
* `parse` without `/all` skips whitespace before each rule.  `to`/`thru`
  leave/advance the position around the match.  `parse/all string delimiter`
  is the R2 splitter.  Parse `insert`/`change`/`remove` are not dialect
  commands in this build; use paren actions instead.
* R2 molds user functions as `func [spec][body]`, object fields in spec
  order, files as `%path` only when molded, and datatypes as `integer!` when
  molded but `integer` when formed.
* FFI specs use the datatype spelling: `make routine! [a [integer!] ...]`
  and `make struct! [a [integer!]]`.  `[integer]` (no bang) silently produces
  an unusable return/field, as in R2.  `routine!` values auto-call when
  evaluated in argument position, so read the value with `:r`
  (`type? :r` -> `routine!`, `mold :r` -> `routine`; `mold` of the *called*
  result is whatever the function returns).  `first`/`second`/`third` of a
  struct are field names, field values and the packed `binary!` bytes; struct
  fields are packed (an `integer!` is 4 bytes, `char!` 1, a `string!` field a
  4-byte pointer), and `free lib` releases the library.
* `draw` uses anti-aliasing by default.  Coordinates sit on pixel centres,
  so a horizontal `line 0x0 19x0` is a half-covered endpoint at x=0 and a
  full pixel at x=9.  `anti-alias off` restores hard edges; `line-cap`
  accepts `butt`/`square`/`round`.  `curve` with three points is a quadratic
  Bezier, with four a cubic; `spline` is a quadratic B-spline.
* `random n` is 1..n (not 0..n-1); `random pair` is 1..n per component and
  `random tuple` is 0..(n-1) per component.
* A script header (`REBOL [title: "..."]`) is applied only when the script is
  *run* (`rebol -s file` / the command line), not by `load`; `load` strips it.
* `compress` is zlib level 6 + a 4-byte little-endian original length;
  `decompress` accepts the same format.  Do not compare against
  `compressBound` output without the length suffix.
* `first`/`second`/`third` order a date as year/month/day and a time as
  hour/minute/seconds; tuple/pair components and binary bytes come back as
  integers (`first #{41}` is `65`, not `#"A"`).
* `draw` on a plain `image!` renders fills in the `fill-pen` colour and
  outlines in the `pen` colour (white by default); images carry
  *transparency* in the 4th pixel component (0 = opaque, 255 = transparent),
  so drawn coverage and loaded PNGs must be interpreted that way.

## Regenerating the reference oracle

The reference binary is expected at
`../reference-rebol-view-278-3-1.exe`.  On first run it shows the REBOL
installer, so seed the Wine profile once:

```bash
mkdir -p "/root/.wine32/drive_c/users/root/Application Data/rebol"
printf 'true' > "/root/.wine32/drive_c/users/root/Application Data/rebol/bypass-install"
```

Then `python3 tests/tools/run.py gen` (uses
`xvfb-run -a /usr/lib/wine/wine reference.exe -s Z:/tmp/.../case.r`).

## Coverage

The 64 cases cover: literals and arithmetic, strings, series positions and
editing, search/edit refinements (`find/tail`, `find/reverse`,
`reverse/part`, `uppercase/part`, `mold/only`, ...), sorting and set
operations, datatypes and conversions, logic and control flow, loops,
functions/closures/refinements, objects and inheritance, errors and
`disarm`, `parse` (basic, actions, advanced), dates/times/money, file I/O
(refinements such as `/lines` and `/binary`), codecs (base64, zlib, all
checksum variants), bitsets, `load`/`mold`, VID `layout` and font metrics,
image `draw` pixels, deterministic excerpts from the re-bol.com examples
(basics, series, loops, objects, functions, draw, strings), a
language-edge-case probes (`44-language-probe`: parse copy/opt/any,
select, take, join types, mod, rounding, make date!, objects;
`45-reflection-io`: body-of/words-of/third object, error objects,
read/write /part, size?/dir?/make-dir, to-local-file, sort/all, trig
units, make time!, money negation; `46-vid-parse`: VID pane
styles/offsets/sizes and layout options plus parse/series/string edge
cases), system identity/tuple/date-zone probes (`48-system-tuples-dates`),
image transparency and `draw` fill/stroke rules (`49-image-alpha`), and one
GUI case (`43-editor-gui`) that opens the built-in editor with
`editor %test.txt` and checks the resulting window titles/sizes.  The
editor case creates a dummy window first so `editor` returns instead of
blocking in its own event loop; it runs headlessly under Xvfb on both
platforms.

`checksum` coverage includes R2's default 24-bit PRZ CRC (initialised with
`len + first byte`), `checksum/tcp` (the Internet 16-bit checksum),
`checksum/method 'md5` / `'sha1` / `checksum/secure` (binary digests), and
`checksum/key` (HMAC).  The CRC algorithm was recovered from the REBOL core
source and verified against the oracle's 256-value single-byte table.

`47-checksum-hash` covers R2's internal string hash.  It was recovered by
disassembling the reference executable: `checksum/hash` runs Bob Jenkins'
lookup2 hash (`a = b = c = 0x9e3779b9`, `c += length`, 11-byte tail summed in
reverse byte order) over bytes folded through REBOL's `Upper_Case` table, then
returns `hash % max(size,1)` as an unsigned value.  The case also asserts the
`expect-arg` / `invalid-arg` error objects (including `arg3` being a block of
datatypes) and HMAC-MD5/SHA1 values.

`48-system-tuples-dates` pins the boot identity (`system/version`
`2.7.8.3.1`, `system/product`, `system/core`, `system/build`), multi-component
tuples (up to 10 components, length preserved, `pick`, `to-tuple`, `to-binary`,
component maths) and date time zones (`-8:00`, `+5:30`, `Z`, `date/zone`,
`date/date`, `date/time` set/get, absolute comparison, `make date!` block
order `[d m y]` / `[y m d]` with optional `time!`/zone).

`60-random-types` pins R2's `random` ranges: integer n → 1..n, pair →
1..n per component, tuple → 0..(n-1); the RNG sequence itself is not pinned.
`61-object-globals` pins free words inside functions of a copied object
(VID style/feel cloning) still resolving to the script's global context.
`64-file-change-dir` pins R2 file-path semantics: relative values resolve
against `system/script/path`, `read %dir/` lists a directory, and
`dir?`/`suffix?` see the same resolved path.  (It also caught a missing NUL
terminator in `to-file` construction.)

`62-dns` pins `read dns://` (local host name) and `read dns://localhost`
(127.0.0.1).  `63-parse-copy-new` pins `parse`'s `copy`/`set` creating
previously undefined words in the right binding context (string `copy`,
block `set`).

`59-compress-zlib` pins the byte-exact compressor: R2's `compress` is zlib
level 6 plus a little-endian length word, so repetitive inputs produce real
LZ77 length/distance codes (`789C4B4CC40F00C8300C2120000000` for 32 `a`s)
and round-trip through `decompress`.

`57-draw-aa` pins R2/AGG anti-aliasing: diagonal edge coverage ranges,
`anti-alias off`, round caps, `curve`/`spline` ink, and polygon fill.  Edge
values are checked as ranges because AGG's 256-subpixel quantisation can
differ from a float rasteriser by one step.  `58-first-series` pins
`first`/`second`/`third`/`last`/`pick` for tuples, pairs, times, dates (R2
orders dates as `[year month day]`), binaries (bytes are integers) and
images (pixels are tuples).

`84-mold-line-breaks` pins R2's formatted `mold`: a loaded multi-line block
keeps its line breaks (space + newline + 4 spaces per level, closing bracket
on its own line), `load "1 2 3"` molds with a trailing newline, parens behave
the same, markers survive `copy`/`reduce`/`compose`, a function body written
across lines molds that way, and single-line blocks (including runtime ones)
mold unchanged.

`85-mold-breaks-more` completes the MOLD model: the break is a flag on the
**value**, so a sub-series (`next`/`find`/`skip`/`at`) still emits the break
of its first element, `copy`/`reduce`/`compose` keep the per-value flags but
drop the trailing one, `load "[^/1 2]"` loses the flag (R2's shared integer
values 0 and 1) while `[^/2 2]` keeps it, `poke` clears a value's break,
`insert`/`append` carry the inserted block's breaks, `compose` splices a
block result (`compose/only` does not), and moulding the VID stylesheet's
`scroller` object (627 lines, inherited functions and blocks included) is
byte-identical to the reference.

`86-loop-binding` pins loop-variable scoping: `repeat`/`foreach`/`for`
values are visible to nested blocks (`rejoin [i " "]`, `prin rejoin [b/1]`)
inside a function, `forall`/`forskip` advance through a local series,
`remove-each` filters in place, `use` exposes its words to nested blocks, and
none of it leaks to a global of the same name.

`92-arg-type-checks` pins R2's call-time argument type checking: a spec's
`[types...]` block is enforced for positional and refinement arguments
(`f1: func [a [integer!]] [a]  f1 "x"` -> "f1 expected a argument of type:
integer"), `none` is rejected unless the type block allows it, typeset names
(`series!`, `number!`, `any-string!`) are honoured, and the datatype words in
a spec are normalised to datatype values (so HELP prints "(Type: integer)").

`93-change-default-range` pins `change` on strings: the default range is the
length of the new text (`change copy "Tom" "Phil"` -> "Phil",
`change copy "abcdef" [1 2 3]` -> "123def"), while blocks still replace one
element and `/part` overrides the range.

`91-path-paren-forms` pins paths whose components are parens or get-words,
including the set-path assignment forms (`b/(i): value`,
`m/(j)/(1): value`) and their molding.

`90-image-placement` pins how a face's image is placed when the face size
differs from the image: R2 blits it at the top-left at its natural size and
clips (no centring, no scaling) and only `FIT`/`ASPECT` scales it to the
face — with nearest-neighbour sampling — while a smaller face clips an
oversized image.

`89-gradient-effect` pins `EFFECT [gradient dir c1 c2]` in `to-image`: R2
moves each component from colour 1 toward colour 2 with
`c1 + trunc((c2-c1)*i/n)` (i over 0..n-1, n = width for `1x0`, height for
`0x1`, reversed for negative directions), e.g. an 8-pixel red->green ramp is
`FF0000 E01F00 C03F00 A05F00 807F00 609F00 40BF00 20DF00`.  The colour words
in the effect block are looked up (`blue`, `gold`), not read raw.

`88-eval-path-forms` pins the evaluator forms the VID engine needs:
`obj/func/ref: value` (calls the function with that refinement and the value
as its argument, one or two refinements), the plain `obj/field: value`
assignment, `obj/func/ref value`, `obj/block/n/field: value` and
`block/key: value` set-paths, and `make function!` copying its spec and body
(the moulded function does not change when the source block is appended to,
and an inherited function still resolves its facets in the instance).

`87-contrast-effect` pins `contrast n` for an 8-colour image at
0/5/10/20/40/60 and -5/-10/-20/-40/-60: each channel is stretched around that
channel's own image mean (`mean + trunc((v-mean)*num/den)`), so a
non-neutral image gains chroma when the per-channel means differ.

`83-what-dir-absolute` pins the script path: `what-dir` is absolute, a
directory, starts and ends with a separator, and `dirize` leaves it unchanged
(file create/read/delete relative to it also checked).  Cases must **not**
`change-dir`: the harness writes its result file relative to the script path,
so a directory change sends the results elsewhere (the corpus harness avoids
this by writing to an absolute path).

`82-text-metrics` pins `size-text` against the reference's own Arial
metrics (embedded table): single characters at several point sizes, short
strings, an empty string, multi-line text and the line heights from 8 to 48.
Long strings are deliberately not asserted (R2's inter-character spacing is
not recoverable from single-character measurements).

`81-port-spec-block` pins READ/WRITE with a **port spec** (block or object
carrying `scheme`/`target`; a spec block is evaluated key by key, so values
may be expressions): creating and reading a file through a spec, the
`/binary` and `/lines` refinements with a spec, `write/append` through a
spec, reusing a spec block for both write and read, and `form` of the spec
block.  Note: R2 rejects a spec *without* a scheme and a `path` in a read
spec, so the case avoids both; the clone accepts the scheme-less form
(lenient, documented).

`80-image-effects-filters` pins the pixel-transforming effects over two
5x5 sources (distinct pixels and a delta) plus a 4x1 colour ramp, all
fingerprinted with `checksum to-binary` of `to-image` of a layout face:
`flip` (all axes), `rotate 90/180/270` (including the reference's odd-size
180° centre-pixel quirk), `invert`, `grayscale`, `luma`, `multiply`, `key`,
`crop`, a chained `[flip rotate 90 invert]`, and `blur`/`sharpen` (3x3
convolutions, R2 kernels `{0,1,0,1,1,1,0,1,0}/5` and
`{0,-1,0,-1,8,-1,0,-1,0}/4`, truncated, edge-clamped).  Note: chaining two
convolutions in one effect block does **not** match the reference (its
second pass reads a different buffer), so the case keeps them separate.

`78-image-mold-binary` pins R2's image text form: `mold`/`form`/`to-string`
of an image give `make image! [WxH #{rgb} #{alpha}]`, one line per 10 pixels,
with the alpha block omitted when every pixel is opaque, and `to-binary`
returns the raw `B,G,R,A` pixel bytes (binary molding wraps at 32 bytes per
line).  `79-face-effects` pins the face image filters applied by `to-image`:
`flip` (default/`1x0`, `0x1`, `1x1`), `rotate 90/180/270`, `invert`,
`grayscale` (R2 uses 0.3/0.59/0.11), `key`, `crop`, and a chained
`[flip rotate 90 invert]` effect, all sampled by corner pixels.

`76-port-awake-accept` and `77-port-awake-read` pin the port event model:
the `awake` handler is called with the port itself before `wait` returns, one
event per `wait` call, `wait/all` + timeouts (handler not called on timeout),
and the data/EOF read events (`copy` → data, then `copy` → `none`).

`70-port-object-model`, `71-tcp-client-server`, `72-udp-port`,
`73-file-port`, `74-port-read-io` and `75-port-wait-errors` pin the generic
port system: `type?`/`port?`, the full `make port! [...]` mold and the
field-per-line form of a listener (with the dynamic `port-id`/`local-port`
cleared so the output is stable; the port serial in `state/misc` is
deterministic because the case creates the first port of the run), TCP
listen/accept/connect, field values on both ends (`local-port`,
`remote-port`, `remote-ip`), `copy` returning data and `none` at EOF, the
`wait`/`wait/all` results, `wait [port 0.05]` timeouts, `first` on a
non-listener raising, a failed connect raising, UDP datagrams, file
`open/new`/`open/read` with `length?`/`copy`/`status`, `read-io`/`write-io`
byte counts and appending, and the post-close `state/flags` (1024).

`56-ffi-library` pins the DLL FFI: `library!` identity and mold,
`load/library %kernel32.dll`, `make routine!` calling a real `MulDiv`, routine
reflection (`type? :r` -> `routine!`), and `make struct!` field get/set,
`third` bytes, initial values and `mold`.  The case is deterministic on both
platforms (POSIX resolves the Windows DLL names to a headless stub and
implements `MulDiv`/`lstrlenA`, so the same numbers as the Win32 oracle come
back).

`52-mixed-math` pins R2's arithmetic between numbers, times, dates, money and
tuples (both operand orders, integer vs decimal results, invalid combinations).
`53-files-dirs` covers directory `read`/`load`, sorting of file values, and
file housekeeping.  `54-compact-syntax` pins compact tokenization
(`print"hi"`, `a[1]`, `word{text}`).  `55-binary-append` covers binary
`append`/`insert` and `system/options/binary-base` molding (16/2/64).

`51-trim-auto` pins `trim/auto` (first non-blank line's indentation removed
from all lines, leading blank lines dropped, trailing whitespace kept).

`50-char-escapes-colors` pins R2's caret escapes in character and string
literals (`#"^A"`, `#"^/"`, `#"^["`, `#"^(1B)"`, `#"^(tab)"`, ...), the
molded form of control characters and strings, and the `rgb-to-hsv` /
`hsv-to-rgb` conversions (byte-exact against the oracle).

`49-image-alpha` pins R2's image transparency convention (the 4th component is
transparency: 0 = opaque, 255 = transparent, fully transparent pixels have
zeroed RGB) and the `draw` fill/stroke rules (fills use `fill-pen`, outlines
use `pen` which defaults to white).

`94-parse-split` pins PARSE's **split mode**: with `none` or a string as the
rules, PARSE returns a block of strings.  Delimiters are the rule's characters
plus R2's whitespace class (every control char up to space except NUL, DEL and
the Latin-1 no-break space) — a run of k whitespace-free delimiters yields k-1
empty fields, whitespace inside a run is absorbed, the field before a run is
emitted (empty at the start) and the field after a trailing run is not.
`/all` removes the whitespace delimiters.  Binary input produces strings
(`parse "a,,b" ","` -> `["a" "" "b"]`, `parse "a  b" " "` -> `["a" "b"]`,
`parse ",a,b," ","` -> `["" "a" "b"]`).  Wrong argument types raise
`script/expect-arg` with `rules [block! string! none!]`.

`95-load-binary-sniff` pins `load` of a **binary**: R2 sniffs image and WAV
data and otherwise returns the binary *unchanged* — no script-header or text
parsing, for every refinement.

`96-word-equality` pins word equality: `=`/`equal?`/`same?` treat
word/lit-word/set-word/get-word/refinement with the same name as equal, while
`strict-equal?` (`==`) does not.  Text series (string/file/url/email/tag/issue)
compare case-insensitively without `==`, binaries byte-wise.  `type?/word`
returns a WORD (moulded with the bang) while `type?` returns the datatype.

`97-form-object` pins `form` of an object: one `name: mold value` line per
field, newline terminated, no `make object!` wrapper (`form make object! []`
is `""`), while `mold` keeps the `make object! [...]` form.

`98-series-position-ops` pins position arithmetic: `at` is relative and
1-based (`at s 1` = s, `at s 2` = `next s`, `at tail s -2` = two back),
`copy/part` with a **negative** length copies that many elements *before* the
position, `copy` on an advanced series copies from the current position, and
`trim` (all refinements) modifies its series **in place** —
`trim "  x  "` shortens the same series.

`99-set-block-and-minmax` pins `set` with a block of words (element-wise for a
block value, the same value for every word otherwise, missing values padded
with `none` even without `/pad`) and `min`/`max` promoting to decimal when
either argument is decimal (`min 1 1.0` -> `1.0`).

`100-sort-compare-find-binary` pins `sort/compare`'s comparator direction
(TRUE = "x comes before y", so `func [x y] [x < y]` sorts ascending), block and
case-insensitive series comparison, and `find` on binaries with string,
binary and char patterns (plus `/tail`, `/last`).

`101-arg-type-errors` pins R2's structured argument errors:
`disarm try [index? none]` gives `expect-arg` with `arg1 'index?`,
`arg2 'series` and `arg3 [series! port!]` (the typeset block moulds with the
bangs); `head`/`read`/`write`/`exists?`/`delete`/`set-modes`/`get-modes`
reject wrong types, an unknown port scheme and a block that is not a port spec
raise `access/invalid-spec`, and `disarm` of a non-error raises `expect-arg`.

`102-png-alpha-map` pins R2's PNG alpha→transparency mapping
(`n=0 -> 255`, `n=1..127 -> 256-n`, `n=128..255 -> 255-n`, fully transparent
pixels have their colour zeroed).

`103-foreach-series-and-for` pins `foreach` over any string series (file!,
url!, string!) character by character and over a binary byte by byte, plus the
loop-variable scoping rules.

