================================================================================
 REBOL/View 2 clone  --  reverse-engineered from REBOL/View 2.7.8.3.1 (Win32)
================================================================================

WHAT THIS IS
------------
REBOL 2 (including REBOL/View) was never released as open source, so the only
way to clone it is to reverse-engineer the shipped Windows executable.  This
package contains:

  rebol-view.exe     a clean-room REBOL 2 interpreter written in C, cross
                     compiled for 32-bit and 64-bit Windows
  r2-source/         the complete REBOL/View 2.7.8 application source,
                     recovered from the reference executable's embedded
                     zlib-compressed boot image and modules
  clone-source/      the C source of the interpreter clone
  examples/          sample scripts

The reference executable analysed was:

  rebol-view-278-3-1.exe
  sha256 215e28f9660472b6271a9902573c9d190e4d7ccca33fcf8d6054941d52a3ab85
  https://www.rebol.com/downloads/v278/rebol-view-278-3-1.exe

See REVERSE-ENGINEERING.md for the full analysis and method.


QUICK START
-----------
  rebol-view.exe examples\hello.r        run a script
  rebol-view.exe examples\tour.r         language tour
  rebol-view.exe examples\gui.r          open a REBOL/View window
  rebol-view.exe examples\demo.r         the 10-app Paint/Game/Puzzle/... demo
  rebol-view.exe examples\ports.r        loopback TCP/UDP/file/console port demo
  rebol-view.exe                         interactive console (>> prompt)
  rebol-view.exe -v                      print the clone build id
                                           (expect demo19-2026-11-14)


GUI SCREENSHOT REGRESSION
-------------------------
tools/gui_shots.py renders the static layouts in tests/gui/*.r with the
Windows PE under Wine/Xvfb and compares the clone's window against the
baselines in tests/gui-baseline/ (Pillow needed for the diff):

  python3 tools/gui_shots.py            compare with the baselines
  python3 tools/gui_shots.py --update   rewrite the baselines


GOLDEN-OUTPUT TEST SUITE
------------------------
The package includes tests/ -- 88 deterministic REBOL 2 cases whose
expected output was generated by running the ORIGINAL REBOL/View
2.7.8.3.1 executable under Wine.  The clone passes 88/88 on both Linux
and Windows.

  python3 tests/tools/run.py test          test the native Linux build
  python3 tests/tools/run.py test --wine   test the Windows build (Wine)
  python3 tests/tools/run.py test --diff   show diffs for failures
  python3 tests/tools/run.py gen           regenerate goldens (oracle)

See tests/README.md for the case layout, runner details and the R2
quirks discovered while building the suite.


WHAT WORKS
----------
  * The recovered R2 boot image is embedded in the executable and loaded
    at startup: the real REBOL 2 native specs and core mezzanine library
    (help, collect/keep, context, funct, array, ...), plus the recovered
    Mezzanine Extensions, Internet Protocols, Graphics, Draw System,
    View/VID and View Desktop modules.
  * **The real VID engine now runs.** `system/view/vid` is the recovered
    120-style style sheet, and `layout` builds real face objects with
    styles: title/text/body/heading, button/btn, field, area, check, radio,
    toggle, choice, slider, scroller, progress, panel, list, text-list,
    icon, image/box, and the rest of the View Desktop style sheet.
    Dialect words `across`, `below`, `return`, `space`, `pad`, `origin`,
    `indent`, `tab`, `tabs`, `at`, `guide`, `size`, `backcolor`,
    `backeffect`, `style`/`styles`, `do`, and `with` facets are handled by
    the original source.  Faces get correct offsets, sizes, fonts, edges,
    keyword/action functions (`face/action face value`), and init blocks.
  * The 10-app demo (examples\demo.r) runs: Paint freehand drawing and
    Save PNG, Game with rate timers and arrow keys, Puzzle tile swapping,
    Calendar/Days with request-date, and Sounds (list C:\Windows\media,
    click a WAV to play).  RATE timers, face-relative mouse
    offsets, effect-draw canvases, to-image/save-png and cloned-feel global
    binding are implemented.
  * Demo windows honor center-face offsets, activate themselves, and
    repaint swapped canvas controls (Paint/Game/Puzzle/Days work).
    Input faces with an effect OR a custom FEEL render as canvases, so
    Paint/Game never fall back to a native edit control.  Requestor popups
    return to their caller (Calendar/Days), ALERT no longer re-enters RATE
    timers (Game SCORE crash), and the Calendar arrows draw.
  * DNS (read dns:// and read dns://host) and parse copy/set into new words.
  * MOLD reproduces the source layout: line breaks are kept as block element
    markers (space + newline + indent, multi-line blocks close on their own
    line) and survive COPY/REDUCE/COMPOSE; paths keep word marks (o/:w).
  * WHAT-DIR is the absolute script directory (R2's %/Z/dir/ form, mapped
    for file I/O), so WHAT-DIR-based paths are absolute as in the reference.
  * SIZE-TEXT uses the reference's own Arial metrics (advance widths and
    line heights measured from the original at every size 8..48), so text
    wrapping and caret geometry match on Linux and Windows.
  * READ/WRITE accept PORT SPECS (block/object with scheme/target/host/...):
    file specs read and write files, network specs build the URL, tcp/udp
    specs use the port layer.  FORM of set-word/get-word/lit-word/refinement
    now matches R2 (bare name; MOLD keeps the marks).
  * IMAGE text form and filters: MOLD/FORM/TO-STRING produce R2's
    `make image! [WxH #{rgb} #{alpha}]` (10 pixels per line), TO-BINARY
    returns the raw B,G,R,A bytes, and face effects FLIP, ROTATE
    (90/180/270), INVERT, GRAYSCALE, KEY, COLORIZE, CROP, LUMA, MULTIPLY
    and the BLUR/SHARPEN 3x3 convolutions are applied by the same portable
    filter in windows and TO-IMAGE.
  * The generic PORT system (tcp://, udp://, file://, console://): OPEN
    returns a real port! with the reference's full field list, MOLD
    (`make port! [...]`) and FORM output and STATE object; INSERT/WRITE
    send (TCP, UDP incl. broadcast and /lines CRLF), COPY/READ receive
    (buffered data, NONE at EOF, /part, /binary, /lines, /direct and /seek
    file ports), FIRST accepts a connection, WAIT/WAIT-ALL return ready
    ports (with timeouts and PORT/TIMEOUT), CLOSE releases the socket,
    READ-IO/WRITE-IO do binary I/O, LENGTH? reports file size and
    GET-MODES/SET-MODES handle broadcast/keep-alive/no-delay/reuse-addr.
    examples/ports.r prints identical output on the reference.
  * Port events: 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, EOF is delivered as a read event.  The
    tools/ports_smoke.py harness cross-tests TCP/UDP/async servers against
    the original binary in both directions.
  * SOUND:// ports and the WAV codec: `load` of a RIFF/WAVE file returns the
    reference sound object (type/rate/channels/bits/volume/data),
    `open sound://` returns a port!, `insert` starts asynchronous playback
    (PlaySoundA on Windows), `wait` waits the sample duration, `close`
    stops.  Nested View panes (block/object/function, including TEXT-LIST
    rows) render, hit-test, highlight selected rows and dispatch actions.
  * Byte-exact COMPRESS: zlib level 6 plus R2's trailing length word,
    using the vendored zlib deflate path (deflate only, Z_SOLO/NO_GZIP).
  * Anti-aliased DRAW: an AGG-style coverage rasteriser for line, polygon,
    triangle, circle/ellipse, curve and spline (pixel-centre coordinates,
    butt/square/round caps, `anti-alias on|off`), matching the reference's
    edge coverage to within one intensity step.
  * DLL foreign-function interface: `load/library` (LoadLibrary/dlopen),
    `make routine!` (integer-sized arguments; integer/char/logic/string and
    struct returns; __stdcall on Win32) and `make struct!` (packed fields,
    `s/field` get/set, `third` bytes, `mold`), with `free` to release the
    library.  On POSIX the well-known Windows DLL names resolve to a
    headless stub so examples still replay.
  * REBOL lexical binding: words carry their context, function bodies are
    bound once, `/local` and refinement args work, and get-word spec args
    (`:value`) are supported.  Functions created inside an object/context
    inherit that object's binding (this is what makes the VID engine work).
  * **Position-based forall/forskip**, set-words evaluating full infix
    expressions, block destructuring `set [a b] block`, `bind block word`,
    datatype-aware `find`/`switch`, tuple/pair/image path access
    (`system/version/4`, `size/x`, `image/size`), and argv-wrapped
    function calls in paths (`obj/func arg`, `system/words/get-modes p m`).
  * Proper REBOL series positions: head tail next back skip at index?
    head? tail?, so append/insert/find/copy/length?/change/remove operate
    at the series position exactly as in R2 (including copy/part with a
    position, insert/change with block splicing).
  * Native refinements: find (/part /case /tail /last /match /any ...),
    copy (/part /deep), insert/change (/part /only /dup), sort
    (/skip /reverse /part), trim (/head /tail /lines /all /with),
    uppercase/lowercase (/part), union/intersect/difference/exclude on
    blocks and bitsets, maximum/minimum on pairs (component-wise).
  * Values and syntax: all common datatypes, blocks, parens, words/paths
    (case-insensitive), strings, binaries (including `64#{...}` base64
    literals), files, urls, tags, issues, tuples, pairs, times, dates,
    money, bitsets, images.
  * Evaluation: functions, refinements, infix operators, set/get/lit
    words, set-paths, objects and paths, lexical contexts,
    break/return/exit, catch/throw, closures.
  * Control: do if either unless while until loop repeat foreach forall
    forskip for forever reduce compose case switch attempt try comment
    quit halt use unset remove-each collect keep.
  * Series: first..tenth last length? pick poke head tail next back skip at
    append insert remove clear copy reverse find select sort unique union
    intersect difference exclude change extract.
  * Math, comparison, logic, type predicates, conversions (all `to-<type>`
    functions), codecs (enbase/debase/dehex), file and console I/O,
    mold/form/load/save.
  * `parse`: alternatives, some/any/opt, set/copy, to/thru, not/and/end,
    **into** (nested series), **insert/remove/change** actions, **/case**
    and **/all**, sub-rules, paren actions, literal word/char/string/number/
    bitset matching (case-insensitive by default), datatype rules
    (`pair!`, `integer!`, ...), standard charsets.
  * `image!` values with **real GIF/PNG/JPEG/BMP decoding** (via the
    public-domain stb_image decoder), so `load` of an image binary/file
    returns a usable image: `image/size`, `image/width`, `image/height`,
    `pick`/`poke`, `first`/`length?` and pixel access all work.
  * A useful subset of AGG `draw`: `pen`, `fill-pen`, `line-width`,
    `color`, `line`, `box`, `circle`/`ellipse`, `triangle`, `image`,
    `gradient`, `flood`, `reset`, **`text`** (an embedded 8x8 bitmap font,
    scalable via `font [size: N]`), **`polygon`**, **`clip`**, and a
    transform stack: **`translate`**, **`scale`**, **`rotate`**,
    **`push`**/**`pop`**.  This covers gradients, simple vector graphics,
    labels, arcs, dashed line patterns, emboss and transformed drawings;
    anti-aliasing is implemented (a few rarer commands are still absent).
  * Networking: read http:// and read https:// (TLS via WinHTTP on
    Windows; plain HTTP with redirects elsewhere), passive-mode FTP
    (read/read/binary/read/lines/write/dir?), POP3/IMAP mailbox reads and
    SMTP sending (SEND/ESMTP ports).  LOAD of an HTTP URL decodes images.
  * REBOL/View: view / view/new / unview / do-events / show / hide /
    get-face / set-face / layout / alert, rendering real VID faces on
    native Win32 controls (buttons, fields, checkboxes, static text).
    `view/new layout [...]` creates a real window; button/check actions
    are dispatched (function or block actions).

WHAT IS NOT YET FULLY IMPLEMENTED
---------------------------------
  * Some VID facets that need text metrics or advanced image effects may
    be approximate.
  * AGG rendering: image decoding is complete, `draw` supports the commands
    listed above (including bitmap text, arcs, dashed line patterns,
    transforms, clipping, anti-aliasing and emboss), and the Win32 renderer
    draws decoded images with alpha compositing, colours, text, fonts and
    edges.  Exact AGG gamma/quantisation still differs by about one step on
    anti-aliased edges.
  * Some typed parse forms (`copy/part`, typed set/copy) are incomplete;
    `into` parses a nested series only when it is fully consumed.
  * `find/with` (custom wildcards), `select/part`/`select/with`,
    `sort/compare` (function or record offset) and case-insensitive
    `sort` are implemented.  `copy/types` is not an R2 refinement.
  * **REBOL truth semantics**: only `none` and `false` are false; `0`,
    `0.0`, `""` and empty blocks are true (this is what makes VID `any
    [ratio = 1 0] ...` logic and many mezzanines correct).
  * `first`/`second`/`third`/`pick` work on pairs, tuples, times and
    dates; associative **block paths** (`blk/key`, `blk/key: value`) work
    for style sheets and other name/value blocks.
  * `set` accepts set-word/get-word/lit-word targets, so VID face
    assignment (`dp: fld`, `sld: scroller`) works.
  * **case** handles multi-token conditions (function calls) correctly, and
    **body-of / spec-of** work for functions and natives (`second`/`third`
    of a function yield its body/spec), which the reflection mezzanines use.
  * **Requestors:** `request/ok` and `request-text` render as themed VID
    popups (logo, message, field, buttons); `request-file` opens the native
    Windows file dialog (`local-request-file` via `GetOpenFileName`);
    `alert` uses a native message box.
  * **Conversions** are complete: `to-pair`/`to-tuple` from blocks,
    strings, integers and pairs; `to-integer`/`to-decimal` from time,
    money, pair and logic.
  * **Set-paths into components** work: `size/x:`, `pair/y:`, `tuple/2:`,
    `block/1:`, `str/1:`, `image/1:` and date facets. Get-word path
    components (`val/:axis`, `block/:i`) resolve too.
  * **Object/function semantics:** `bind` on blocks and objects rebinds
    words, `make object!` preserves explicit outer bindings while binding
    object fields, style functions are cloned and rebound per instance
    (sliders/scrollers/requestors work), and `exit` returns from the
    current function instead of unwinding the script.
  * **date!/time!/money!** are real values: correct mold, comparison,
    arithmetic (`date + 30`, `date - date`, `date + time`, money), path
    access (`d/year`, `d/month`, `d/day`, `d/date`, `d/time`,
    `d/weekday` (Monday=1), `d/yearday`, `d/zone`, `t/hour`, ...), ISO and
    `d-Mon-yyyy` literal parsing, `to-date`/`to-time`, and the full
    `now` refinement set (`now/date`, `now/time`, `now/year`, ...).
  * FTP, POP3, SMTP and IMAP are wired to the OS.  MIME/ODBC/registry/
    shell modules remain unwired.
  * The themed pickers `request-dir`/`request-list`/`request-date` build
    and run (nested list rows, navigation and selection work); `request-file`
    uses the OS dialog on Windows.  The Find dialog now pre-focuses its
    field, Enter runs field actions, and unview/only closes the right window;
    live filters are still untested.
  * Complex VID styles (slider, scroller, progress, list, text-list, area,
    choice, rotary) now construct correctly; custom `layout/styles/parent`
    and list supply functions are supported.
  * Memory is not reference-counted/released (long-running sessions leak);
    fine for scripts, not for servers.

The recovered source in r2-source/ is the specification for finishing
these items.


BUILDING
--------
  Native (Linux):
      cd clone-source && make

  Windows (cross-compile with mingw-w64):
      for f in value scan eval native view_win net boot_image modules main image draw; do
        i686-w64-mingw32-gcc -O2 -std=gnu99 -c $f.c -o $f.o
      done
      i686-w64-mingw32-gcc -O2 -s -o rebol-view.exe \
        value.o scan.o eval.o native.o view_win.o net.o boot_image.o modules.o \
        main.o image.o draw.o -lm -luser32 -lgdi32 -lwinhttp -lmsimg32 -lcomdlg32


LICENCE / PROVENANCE
--------------------
The interpreter clone is an original clean-room implementation.
The recovered REBOL source is the property of REBOL Technologies and is
included only to document and complete the interoperability effort.
`stb_image.h` is the public-domain / MIT-licensed single-header image
decoder by Sean Barrett (see the header for its licence).


GOLDEN SUITE FINDINGS (this session)
------------------------------------
The oracle suite drove a large fidelity pass: exact form/mold for all
datatypes (including functions and objects), load single-value/newline
semantics, base64/hex codecs, zlib-compatible compress/decompress,
all checksum variants (default PRZ CRC, /tcp, MD5/SHA1), 4-component image pixels and R2's coverage-style draw,
Arial size-text tables for VID, case-preserving word interning,
always-calling functions reached via paths, object field order and
first/words-of/values-of semantics, generic for over decimal/money/date/
char, round refinements, and native clean-path/split-path/dirize/suffix?/
apply.  The recovered View Desktop module now loads completely, so the
real 120-style VID sheet and its layout metrics are active.  Later
passes fixed `series?` types, `join`/`append`/`insert` type preservation,
`select` on strings, `make date!`, `parse opt/any` skipping and
zero-length `parse copy`, and added a headless `editor %test.txt` GUI
case.  A further reflection/I-O pass added object/function body/word
reflection, nested mold indentation, degree trig, make time!, read/write
/part, native size?/dir?/make-dir, to-local-file, sort/all, dynamic
set-paths, pair+integer math and structured error metadata.  A VID/parse
pass fixed `case` non-block results (boot `replace`), positioned-series
`second`/`third` (stock images), `change/part` strings, `replace/all`, and
bold 12pt text metrics.

Checksum support is complete: default 24-bit PRZ CRC, /tcp, /method
'md5 / 'sha1, and /secure.

Known gaps: AGG anti-aliasing and rarer draw commands/effects,
checksum/hash (internal R2 string hash, fallback only), advanced
live filters, and memory reclamation.
