# REBOL/View 2 clone — reverse-engineered from the R2 executable

REBOL 2 (including REBOL/View) was never open-sourced, so this project
clones it the only way possible: by reverse-engineering the shipped
Windows executable with [REA](https://github.com/morluto/rea).

## Deliverable

`dist-r2/` (and `dist-r2/rebol-view-2-clone.zip`) contains:

| Item | Description |
|---|---|
| `rebol-view.exe` | A clean-room REBOL 2 interpreter in C, cross-compiled to a Windows PE32 executable |
| `r2-source/` | The **complete REBOL/View 2.7.8 application source**, recovered from the reference executable |
| `clone-source/` | The C source of the interpreter clone |
| `tools/extract_boot.py` | The boot-image extraction tool (reproducible) |
| `tests/` | 66-case golden-output conformance suite (reference R2 oracle) |
| `examples/` | `hello.r`, `tour.r`, `gui.r`, `demo.r` (10-app demo) |
| `README.txt`, `REVERSE-ENGINEERING.md` | Usage and method |

## What was done

1. **Analysed the target with REA** — PE identity, imports (`imphash`),
   resources, managed classification. See `REVERSE-ENGINEERING.md` §2.
2. **Recovered the application source** — REBOL 2 embeds its entire boot
   image, mezzanine library, View/VID system and bundled modules inside
   the executable as 21 zlib streams. Inflating them yields 440 KB of
   original REBOL source, including **View and VID** and the **View
   Desktop**. Extraction is byte-for-byte reproducible.
3. **Built a REBOL 2 interpreter clone in C** — lexer/parser, evaluator
   with infix operators and refinements, value/series/context model, a
   native library, and a Win32 View/VID GUI. Cross-compiled with
   mingw-w64; verified under Wine.
4. **Packaged and documented** everything.

## Golden-output test suite

`tests/` contains 103 deterministic REBOL 2 cases whose expected output is
generated by running the **original REBOL/View 2.7.8.3.1 binary** under
Wine.  The clone passes **103/103 on Linux and 103/103 on Windows** (Wine).

```bash
python3 tests/tools/run.py test          # native Linux clone
python3 tests/tools/run.py test --wine   # Windows PE build under Wine
python3 tests/tools/run.py test --diff   # show diffs for failures
python3 tests/tools/run.py gen           # regenerate goldens from the oracle
```

A **GUI screenshot regression** covers the renderer: `python3
tools/gui_shots.py` renders the static layouts in `tests/gui/*.r` with the
Windows PE under Wine/Xvfb, crops the clone's own window and compares it with
the baselines in `tests/gui-baseline/` (per-pixel tolerance for font
antialiasing).  `--update` rewrites the baselines.

See `tests/README.md` for case layout, runner details and R2 quirks.
`python3 tools/examples_smoke.py [--wine]` runs every bundled example.

## Verified functionality

Run on Windows (verified under Wine):

```
rebol-view.exe examples\hello.r     # prints, arithmetic
rebol-view.exe examples\tour.r      # datatypes, series, control, functions, objects, codecs
rebol-view.exe examples\gui.r       # a real VID window built by the recovered
                                    # View Desktop style engine
rebol-view.exe                      # interactive >> console
```

## Honest status

The clone is now a **substantially functional REBOL/View 2 replacement**.
It embeds and runs the recovered boot image, the core mezzanines, the
Mezzanine Extensions, the Internet Protocols, Graphics, Draw System,
View/VID **and the full View Desktop module**, so the *real* VID engine
(120 styles) builds the GUI, and `view/new layout [...]` opens a real
Win32 window with working button actions.

Implemented: the core language, lexical binding/closures, position-based
series, ~230 natives with refinements, a much stronger `parse` (datatype
rules, set/copy, to/thru, sub-rules, /case, /all and paren actions, matching
R2's dialect), all `to-<type>` conversions,
real GIF/PNG/JPEG/BMP image decoding (via stb_image), a useful subset of
AGG `draw` (gradients, boxes, lines, circles, polygons, bitmap text, and
a push/pop transform stack with translate/scale/rotate/clip),
`find/with`/`select/part`/`sort/compare`, zlib-compatible
`compress`/`decompress`, base64/hex `enbase`/`debase`, all `checksum`
variants (default 24-bit PRZ CRC, `/tcp`, `/method 'md5/'sha1`,
`/secure`),
real
date/time/money values and `now` refinements, complete
`to-pair`/`to-tuple`/`to-integer`/`to-decimal` conversions, component
set-paths (`size/x:`), associative block paths (`blk/key`),
get-word path parts (`val/:axis`), object/function rebinding (`bind`,
per-instance style functions), correct REBOL truthiness (only `none`/`false`
are false) and `case`, pair/tuple/time/date `first`/`second`, and
`body-of`/`spec-of` reflection, functional `request/ok`, `request-text`,
`request-file` (OS dialog) and `alert`, `parse` with
`into`, `copy`/`set`, `to`/`thru`, `/case` and `/all`, HTTP/HTTPS (with
redirects), FTP, POP3, SMTP and IMAP, and the real VID style engine with a renderer that honours offsets, sizes, colours,
fonts, edges, decoded images (alpha-blended) and `fit`/`tile`/`colorize`/
`gradient` effects (including window gradient backdrops).

The suite drove a large round of fidelity fixes in this session: exact
`form`/`mold` for datatypes/files/times/dates/money/binary/bitsets/
functions/objects, `load` single-value and newline semantics, base64 and
zlib codecs, 4-component image pixels matching R2's `draw` coverage
behaviour, VID font metrics (`size-text` Arial tables), case-preserving
word interning, always-calling functions reached through paths, object
field order, `first`/`second`/`values-of` object semantics, `for` over
decimals/money/dates/chars, `with` as a facet dialect, and native
`clean-path`/`split-path`/`dirize`/`suffix?`/`apply`.  Later passes added
the exact default 24-bit PRZ `checksum` (plus `/tcp`, `/method 'md5`,
`'sha1`, `/secure`), `mold/only`, `find/reverse`, `reverse/part`,
`uppercase`/`lowercase /part`, `read`/`write` `/lines`/`/binary`, and
fixed path refinement flags leaking into nested calls (e.g.
`uppercase/part copy "abcdef" 3`).  A GUI regression case now exercises
`editor %test.txt` headlessly.  File/URL path extension
(`view-root/desktop/scripts/edit.r`), the default script title "Untitled"
and `system/script/path` were added so the recovered `editor` works.
A language-edge-case probe then fixed `series?` for file/URL/email/image,
`join` type preservation, `select` on strings (returns the next character),
`make date! [y m d]`, `parse` `opt`/`any` rule skipping, and zero-length
`parse copy` returning `none`.  A reflection/I-O probe then fixed
`body-of`/`words-of`/`third` on objects and functions, R2's nested
`mold` indentation, degree-based trig, `make time!`, `read`/`write
/part`, native `size?`/`dir?`/`make-dir`, `to-local-file`/`to-rebol-file`,
`sort/all`, dynamic set-paths (`o/:w:`), pair+integer arithmetic, money
negation, time fractions, and structured error metadata (cannot-use,
past-end).  A VID/parse probe then fixed `case` with non-block results
(used by the boot `replace`), `second`/`third`/`pick` on positioned
series (stock-image loading), `change/part` string replacement,
`replace/all`, and bold text metrics at 12pt.

`checksum/hash` is now exact: the reference build's routine was recovered by
disassembly.  It is Bob Jenkins' lookup2 hash (`a = b = c = 0x9e3779b9`,
`c += length`, reversed 11-byte tail) over bytes folded through REBOL's
`upper-case` table, reduced modulo the requested table size.  `checksum/key`
(HMAC-MD5/SHA-1) is also implemented.

`system/version` is the real `2.7.8.3.1` identity (so the recovered Graphics
module selects Arial, as on Win32), tuples keep up to ten components and their
length, and dates carry time zones (`date/zone`, `date/time`, `mold` suffix,
absolute comparison).  R2's image pixels store **transparency** (0 = opaque)
rather than alpha; the decoder, `poke`, `draw` fills/strokes and the Win32
renderer follow that convention, so `view layout [image drawn]` displays the
same picture as the reference.  VID buttons are owner-drawn with the face
colour/font/edge and windows get the `REBOL - <title>` caption.

`mold` **reproduces the source layout**: R2 keeps line breaks as block
element markers, so a line break becomes a space + newline + four spaces per
nesting level, a multi-line block closes on its own line and a nested block
keeps a leading break; the markers survive `copy`, `reduce`, `compose` and
function creation, and paths keep their word marks (`o/:w`).

`what-dir` (i.e. `system/script/path`) is the **absolute** directory of the
running script in R2's `file!` form (`%/Z/dir/` on Windows, mapped back to
`Z:/dir/` for file I/O), so paths built from `what-dir` are absolute exactly
as in the reference; the clone used to report `"./"`.

`size-text` uses the reference's **own font metrics**: R2's Arial advance
width for every printable ASCII character at every point size 8–48 (and the
line heights) were measured from the original executable and embedded, so
`size-text`, text wrapping and caret geometry agree on Linux and under Wine
(long strings may differ by a pixel or two because R2's inter-character
spacing is not derivable from single-character probes).

Images are first-class values: `mold`/`form`/`to-string` produce the
reference's `make image! [WxH #{…rgb…} #{…alpha…}]` text (one line per 10
pixels, alpha block only when needed), `to-binary` exposes the raw
`B,G,R,A` bytes, and face **image effects** — `flip` (with axis pairs),
`rotate 90/180/270` (including the reference's odd-size 180° centre-pixel
quirk), `invert`, `grayscale` (R2's 0.3/0.59/0.11 weights), `key`,
`colorize`, `crop`, `luma`, `multiply` and the `blur`/`sharpen` 3×3
convolutions — are applied by one portable filter used by both the window
renderer and `to-image`, with pixel parity against the reference.

`read`/`write` also accept R2 **port specs** (blocks or objects with
`scheme`/`host`/`port-id`/`user`/`pass`/`target`/`path`): file specs read and
write files, network specs build the corresponding URL, and `tcp`/`udp`/
`console` specs go through the port layer.  Along the way a FORM fidelity bug
was fixed: R2's `form` of a set-word/get-word/lit-word/refinement is the bare
name (`form [a: :b 'c /d]` → `"a b c d"`), only `mold` keeps the marks.

The **generic port system is implemented** (`r2clone/port.c`): `open` of
`tcp://`, `udp://`, `file://` and `console://` specs (URL, file, block or
object form) returns a real `port!` with the reference's full field list
(`scheme host port-id user pass target path … awake`), its
`make port! [...]` MOLD / field-per-line FORM output, `state` object
(flags/misc/num/with/func/inBuffer/outBuffer) and GET-MODES/SET-MODES for the
socket options programs use (broadcast, keep-alive, no-delay, reuse-addr).
`insert`/`write` send (TCP writes flush immediately; UDP supports connected,
bound and broadcast sockets; `/lines` ports terminate each value with CRLF),
`copy`/`read` receive (buffered data, `none` at EOF, `copy/part`,
`/binary`, `/lines`, `/seek`/`/direct` file ports), `first` accepts a
connection from a listener, `wait`/`wait/all` return ready ports with
optional timeouts, `close` releases the socket/file (state flags → 1024),
`read-io`/`write-io` do binary port I/O and `length?` reports file-port
size.  R2's **port event model** works too: `port/awake` is called with the
port itself, one event per `wait`, `wait/all` returns a block of ready ports,
timeouts return `none` without firing handlers, and EOF is delivered as a
read event (`copy` → `none`).  `tools/ports_smoke.py` cross-tests the wire
protocol against the real reference in both directions (TCP, UDP and an
async server).  `examples/ports.r` is a self-contained loopback demo (TCP
listener/accept, UDP, file and console ports) whose output is identical on
the reference under Wine and on the clone.

The **re-bol.com example corpus runs**.  `tools/examples_corpus.py` fetches
<https://re-bol.com/examples.txt>, extracts its examples into runnable
snippets and `tools/examples_sections.py` replays them section-by-section
with headless stubs for the interactive/GUI functions (alert, request-*,
editor, view, ...), reporting any snippet that errors.  Of 325 extracted
examples, all but a handful run; the remaining ones need network access,
third-party scripts or data files, or are interactive TUIs.

**The 10-app demo (`examples/demo.r`) is largely working**: Paint (freehand
drawing, Save to a real PNG, Clear), Game (rate-driven board + arrow keys),
Puzzle (tile swapping), Calendar (`request-date`, month arrows) and Days all
run; Sounds opens and lists `C:\Windows\media`, and clicking a row loads
the WAV and plays it through the `sound://` port (`PlaySoundA` on Windows,
duration-based WAIT on other builds).  This round
added `sound://` (`open` → port!), the R2 WAV codec (`load` of a RIFF/WAVE
file returns the `sound` object with rate/channels/bits/volume/data),
nested-pane rendering and hit testing (text-list/list rows, selection
highlight and row actions; `request-list` and `request-dir` now work),
file/url/tag series operations (`first`/`last`/`length?`/`pick`/`find`/
`remove`/`copy` and file-key path append), Find-dialog field focus,
Enter-to-run field actions, correct `unview/only`/`unview/all` window
removal, HTTP redirects plus `load http://` (Video/tinyurl), a
passive-mode FTP client (`read`/`read/binary`/`read/lines`/`write`/`dir?`),
POP3/IMAP mailbox reads and SMTP `send` (Email), and `rate` timer events (`WM_TIMER` → `feel/engage` `time`), face-relative
mouse offsets (Paint drawing), canvas rendering for input faces with an
`effect` (including `effect [draw word]`), `to-image` of a face and
`save/png`, per-move `over` events, native-control repositioning after an
action, correct global binding inside cloned VID style/feel functions,
R2's `random` ranges (integer 1..n, pair 1..n per component, tuple 0..n-1),
`view/new` placement at the face offset + activation, custom-FEEL canvases
(Paint/Game are never native edit controls), R2 file-path resolution
(relative `system/script/path`, Windows `%/c/...` drives), and the
script-header window title (`REBOL - Demo`).  `rebol-view.exe -v` prints the build id
(`demo19-2026-11-14`).

**`compress` is byte-identical to the reference**: it is zlib level 6
(`Z_DEFAULT_COMPRESSION`, `78 9C` header) plus R2's trailing little-endian
original length.  The clone vendors zlib's deflate path (`Z_SOLO`, deflate
only) and matches the oracle on every input tested, including 70–80 KB
repetitive and random streams.  `decompress` is the existing full inflater.

**DRAW is anti-aliased** with an AGG-style coverage rasteriser (32 subpixel
rows, pixel-centre coordinates, butt/square/round caps) for `line`, `polygon`,
`triangle`, `circle`/`ellipse`, `curve`, `spline` and the `anti-alias`
command; edge coverage matches the reference to within one intensity step.
`curve` (quadratic/cubic Bezier), `spline` (quadratic B-spline, `closed`
and knot forms), `arc` (elliptical, clockwise, optional `closed`), dashed
`line-pattern` (foreground/background pen, pattern cleared by `none`) and
the `emboss` effect are real now.

**DLL FFI is implemented**: `load/library` (LoadLibraryA / dlopen),
`make routine!` (up to 16 integer-sized arguments and integer/char/logic/
string/struct returns, `__stdcall` on Win32) and `make struct!` (packed
integer!/char!/decimal!/string! fields, `s/field` get/set, `third s` bytes
and `mold`).  The Windows examples that call `user32.dll`, `kernel32.dll`,
`winmm.dll`, `avicap32.dll` and friends now run; on POSIX the well-known
Windows DLL names resolve to a headless stub so the corpus still replays.

That sweep drove another fidelity round: compact tokenization
(`print"hi"`, `a[1]`, `word{text}`, `if x<y[...]`), directory `read`/`load`
(`read %dir/` -> block of file! names, `%sub/` with a trailing slash, and
R2's `cannot-open` when a directory is named without one), case-insensitive
`sort` of files/URLs/binaries, R2's mixed-type arithmetic (`2 * 0:00:01`,
`0:00:01 + 2`, `2 + 1-Jan-2030`, `2 * $2.50`, `time / time` integer ratios,
`money / money` decimals), binary `append`/`insert` (R2's string-like rules),
and `mold` honouring `system/options/binary-base` (16 hex, 2 bits, 64 base64
with 64-character wrapping).

The **built-in editor now works**, repeatedly: `editor %file` opens the recovered
View Desktop editor window with its toolbar, resizes with the window, accepts
typing, saves with Ctrl-S (or the Save label), quits with Ctrl-Q, and its Find
dialog opens and cancels.  This needed a real R2 event model in the renderer
(`type`/`offset`/`key`/`face`/`window`/`shift`/`control`/`alt` event objects
dispatched to face `feel/detect` and `feel/engage`), window CLOSE/RESIZE
events, keycode (`Enter`/`escape`) dispatch, mouse over/away/down/up on canvas
faces, owner-drawn buttons/panels refresh and a focus bridge to Win32
`SetFocus`, child faces get `parent-face` (the help window's Close button
uses it), and destroying the last window no longer leaves a stale `WM_QUIT`
that made the next `editor`/`view` open a dead window.  Closing a window with
the system X now performs R2's default `unview/only` (removing its face from
the screen pane), so a closed Help window no longer reappears — and no longer
breaks the event loop — the next time the editor opens.  **F5 / Ctrl-E in the editor runs the script in REBOL**, exactly like the
reference: `do-file` saves the file and calls `launch/secure-cmd`, which now
starts a new interpreter process (`rebol-view.exe -s <file>`).  `launch`
(with `/reboot /uninstall /link /quit /secure-cmd /as-is /install`) and `run`
(open a file/URL with the system association) are implemented, and the
command line accepts R2's switches (`-s script`, `-q`, `--do code`, `-v`,
`-h`).

Text faces now render their full R2 layout: multiple lines, `para/origin`,
`para/margin`, tab stops, wrapping, `font/align`/`valign` and font shadows
(the editor's "Editor Shortcuts" help window displays correctly), `size-text`
measures the whole multi-line block, and `trim/auto` de-indents every line
(minus the first non-blank line's indentation) like the oracle.  Also fixed:
R2 caret escapes (`#"^A"`, `#"^/"`, `#"^["`,
`#"^(1B)"`, `#"^(tab)"`) and their molding in chars/strings, `caret-to-offset`/
`offset-to-caret`/`textinfo`/`rgb-to-hsv`/`hsv-to-rgb` natives, a crash when
`tail`/`head` received a non-series value, child-control window leaks on
repaint, and edit-control `EN_CHANGE` notifications incorrectly running field
actions.

Still incomplete: exact AGG gamma/quantisation and a few rarer draw
features, advanced requestor behaviour (live filters; the Find dialog now
pre-focuses its field), typed parse actions, and memory reclamation. The recovered `r2-source/` is the exact specification for
completing them.

See `REVERSE-ENGINEERING.md` for the full coverage matrix, method and
reproduction steps.
