feat: first release !
No files matched your search
@@ -0,0 +1,39 @@
|
|||||||
|
# ---> Go
|
||||||
|
# If you prefer the allow list template instead of the deny list, see community template:
|
||||||
|
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
|
||||||
|
#
|
||||||
|
# Binaries for programs and plugins
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
|
||||||
|
# Test binary, built with `go test -c`
|
||||||
|
*.test
|
||||||
|
|
||||||
|
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||||
|
*.out
|
||||||
|
|
||||||
|
# Dependency directories (remove the comment below to include it)
|
||||||
|
# vendor/
|
||||||
|
|
||||||
|
# Go workspace file
|
||||||
|
go.work
|
||||||
|
go.work.sum
|
||||||
|
|
||||||
|
# env file
|
||||||
|
.env
|
||||||
|
|
||||||
|
|
||||||
|
# Build output
|
||||||
|
build/bin/
|
||||||
|
|
||||||
|
# Frontend
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/*
|
||||||
|
!frontend/dist/.gitkeep
|
||||||
|
frontend/wailsjs/
|
||||||
|
|
||||||
|
# Screenshot tool
|
||||||
|
tools/screenshots/node_modules/
|
||||||
@@ -0,0 +1,408 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
Everything you need to start working on **Plotzilla**, a Linux screenwriting app (an Arc Studio Pro /
|
||||||
|
Final Draft alternative) that produces scripts in the Hollywood standard format. Read this file
|
||||||
|
first; `README.md` is the user-facing documentation.
|
||||||
|
|
||||||
|
## 1. At a glance
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Backend | Go ≥ 1.23, [Wails v2](https://wails.io) (GTK 3 + WebKitGTK 4.1) |
|
||||||
|
| Frontend | TypeScript 7, [ProseMirror](https://prosemirror.net), Vite 8, plain CSS, no UI framework |
|
||||||
|
| Target | Any Linux desktop (GNOME, Plasma, Xfce…; Wayland and X11), GNOME look (Arch dev machine) |
|
||||||
|
| Native format | Fountain (`.fountain`); also FDX import/export and PDF export |
|
||||||
|
| License | GPL-3.0 (`LICENSE`); new dependencies must be GPL-3.0 compatible |
|
||||||
|
| Language | **Everything user-facing is English**: UI, messages, dialogs, README, docs, comments, commit messages |
|
||||||
|
|
||||||
|
## 2. Commands
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make # npm install + vite build + go build → build/bin/plotzilla
|
||||||
|
make test # go test ./internal/...
|
||||||
|
make screenshots # regenerate the README images (needs Firefox and pdftoppm)
|
||||||
|
make dev # wails dev (live reload; needs `go install github.com/wailsapp/wails/v2/cmd/wails@latest`)
|
||||||
|
./build/bin/plotzilla path/to/script.fountain
|
||||||
|
|
||||||
|
cd frontend && npm run build # tsc --noEmit (type check) + vite build → frontend/dist
|
||||||
|
go vet -tags desktop,production,webkit2_41 ./...
|
||||||
|
gofmt -l . # must print nothing
|
||||||
|
```
|
||||||
|
|
||||||
|
- The Go build **requires the tag `webkit2_41`** (the machine only ships WebKitGTK 4.1). Plain
|
||||||
|
`go build .` fails; always go through `make` or pass `-tags desktop,production,webkit2_41`.
|
||||||
|
- `main.go` embeds `frontend/dist` (`//go:embed all:frontend/dist`). The frontend must be built
|
||||||
|
before the Go binary. `frontend/public/.gitkeep` keeps `dist/` non-empty on a fresh clone.
|
||||||
|
- System deps (Arch): `go nodejs npm webkit2gtk-4.1 gtk3`. Optional font: `ttf-courier-prime`.
|
||||||
|
Optional Hunspell dictionaries for spell checking: `hunspell-en_us`, `hunspell-fr`…
|
||||||
|
|
||||||
|
Definition of done for any change: `make` succeeds, `make test` passes, `gofmt -l .` is empty,
|
||||||
|
`npm run build` has no type errors, `npm audit` reports no vulnerabilities, README updated if
|
||||||
|
behaviour or shortcuts changed.
|
||||||
|
|
||||||
|
## 3. Repository map
|
||||||
|
|
||||||
|
```
|
||||||
|
main.go Wails bootstrap: frameless translucent window, LANGUAGE=en, CLI file argument
|
||||||
|
app.go App struct bound to JS: file I/O, dialogs, pagination, autosave recovery
|
||||||
|
desktop_linux.go cgo: desktop light/dark preference for GTK dialogs, window button layout, compositing
|
||||||
|
internal/screenplay the model: Document{TitlePage, Elements, Settings}, Element{Type, Runs, SceneNumber,
|
||||||
|
Dual, Level, Locked}, Run{Text, b/i/u, Note, Rev}, revision set names
|
||||||
|
internal/fountain Fountain parser (parse.go) and writer (write.go), incl. Plotzilla's boneyard data
|
||||||
|
internal/fdx Final Draft XML reader/writer
|
||||||
|
internal/layout line wrapping + pagination (paper sizes, locked pages); the single source of truth
|
||||||
|
for page geometry
|
||||||
|
internal/pdf hand-written PDF 1.4 writer, standard Courier fonts, zero dependencies
|
||||||
|
internal/spell Hunspell .aff/.dic reader, checker (compounds too), suggestions, word scan
|
||||||
|
frontend/index.html app shell: header bar, navigator, paper, HUD, <dialog>s
|
||||||
|
frontend/src/main.ts app controller: state, save/autosave, pagination loop, navigator, menus, shortcuts, window frame
|
||||||
|
frontend/src/schema.ts ProseMirror schema + conversion PM doc ⇄ ScriptDocument JSON
|
||||||
|
frontend/src/commands.ts screenplay keymap (Enter/Tab/Ctrl+1…9), retype, dual dialogue, auto-format
|
||||||
|
frontend/src/revisions.ts revision marking and locked-page anchors (plugins), lock/unlock/clear
|
||||||
|
frontend/src/autocomplete.ts suggestion popup (characters, locations, times, extensions, shots, transitions)
|
||||||
|
frontend/src/decorations.ts live page-break widgets + empty-element placeholder
|
||||||
|
frontend/src/search.ts find & replace: query, match highlights, next/previous, replace (all)
|
||||||
|
frontend/src/spellcheck.ts misspelling underlines (from Go), word under the cursor left alone
|
||||||
|
frontend/src/menu.ts popup menus with keyboard navigation (spelling corrections, languages)
|
||||||
|
frontend/src/backend.ts typed wrappers for window.go.main.App and the Wails runtime
|
||||||
|
frontend/src/icons.ts inline Lucide-style SVG icons
|
||||||
|
frontend/src/style.css the whole UI theme (dark, blue) and the on-screen page geometry
|
||||||
|
screenshots/ README images (2880×1800 UI captures + pdf-output.png)
|
||||||
|
tools/screenshots/ `make screenshots`: sample script, mock server (main.go), Firefox capture (capture.mjs)
|
||||||
|
VERSION current version (1.0)
|
||||||
|
CHANGELOG.md Keep a Changelog; sections Added, Changed, Fixed only
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Architecture
|
||||||
|
|
||||||
|
### Data flow
|
||||||
|
|
||||||
|
```
|
||||||
|
ProseMirror doc ──toScript()──▶ ScriptDocument JSON ──Wails──▶ screenplay.Document (Go)
|
||||||
|
▲ │
|
||||||
|
└────────fromScript()◀──── OpenResult ◀── fountain/fdx ◀──────┘
|
||||||
|
├─▶ layout.Paginate ─▶ breaks → editor widgets
|
||||||
|
└─▶ layout.Paginate ─▶ pdf.Render
|
||||||
|
```
|
||||||
|
|
||||||
|
- The **Go model is canonical**. The frontend never parses or writes files itself; it sends the
|
||||||
|
whole `ScriptDocument` to Go (`Save`, `Paginate`, `ExportPDF`, …). Documents are small enough
|
||||||
|
for this to be cheap; pagination is debounced (300 ms).
|
||||||
|
- **Pagination lives only in Go** (`internal/layout`). The editor shows page breaks computed by
|
||||||
|
that same code, so the screen and the PDF always agree. Never reimplement wrapping or page
|
||||||
|
rules in TypeScript.
|
||||||
|
|
||||||
|
### The JSON contract (`backend.ts` ⇄ `internal/screenplay`)
|
||||||
|
|
||||||
|
`ScriptDocument = { titlePage, elements, settings? }`
|
||||||
|
`Element = { type, runs: [{text, b?, i?, u?, n?, rev?}] | null, sceneNumber?, dual?, level?, newPage?, locked? }`
|
||||||
|
`Settings = { paper?: '' | 'a4', revisions?: [{name, color, date}], revising?, locked? }`
|
||||||
|
|
||||||
|
- `runs` may be `null` from Go; always read it as `el.runs ?? []`. Every settings field may be
|
||||||
|
missing (Go omits zero values).
|
||||||
|
- `n: true` marks a note run (Fountain `[[…]]`): part of `Text()` and of every offset, never
|
||||||
|
printed (`Element.PrintedText()`, `printedText()` in the frontend). `rev: n` is the revision
|
||||||
|
set the text belongs to (`settings.revisions[n-1]`).
|
||||||
|
- `newPage: true` forces a page break before the element (Fountain `===`, FDX
|
||||||
|
`StartsNewPage`). On a dialogue part or a dual dialogue it breaks before the whole block;
|
||||||
|
on an element that prints nothing it moves to the next printed one. `Ctrl+Enter`
|
||||||
|
(`pageBreak` in commands.ts) sets it on the block's first element, never on a part.
|
||||||
|
- `level` is a section's depth (from 1). `locked: [{offset, page}]` lists the locked pages that
|
||||||
|
start in the element (rune offsets, like `Break`); in the editor they live in the element's
|
||||||
|
`locked` attribute as UTF-16 offsets (`runeOffset`/`utf16Offset` in schema.ts convert).
|
||||||
|
- A `"\n"` inside a run is a hard line break (ProseMirror `hard_break` node).
|
||||||
|
- `dual: true` on a **character** element means "this dialogue block sits to the right of the
|
||||||
|
previous one". In the editor this is a nested `dual > column column > element+` structure.
|
||||||
|
- `Break.label` / `ScenePage.label` is the printed page number (`12`, `12A`, `12-13`); `page` is
|
||||||
|
the physical page index. Show the label, compare with `page`.
|
||||||
|
- Element **indexes** used by `Break` and `ScenePage` count elements in flat document order,
|
||||||
|
including empty ones and elements inside dual dialogues. Use `flatElements(doc)` in the
|
||||||
|
frontend whenever you map an index to a position; never use `doc.child(i)`.
|
||||||
|
- `Break.offset` is a **rune** (code point) offset. JS strings are UTF-16: convert with
|
||||||
|
`utf16Offset()` (decorations.ts). `Misspelling` (`element`, `offset`, `length`) follows the
|
||||||
|
same rules.
|
||||||
|
- Any change to these structs must be made in both `internal/screenplay/screenplay.go` and
|
||||||
|
`frontend/src/backend.ts`, in the same change.
|
||||||
|
|
||||||
|
### Element types
|
||||||
|
|
||||||
|
`scene, action, character, parenthetical, dialogue, transition, shot, intertitle, centered,
|
||||||
|
section, synopsis` (Ctrl+1…9 for the first nine, in that order; the order of `ELEMENT_TYPES` in
|
||||||
|
schema.ts defines the shortcuts). Sections and synopses are outline elements: not printed
|
||||||
|
(`ElementType.Printed()` / `isPrinted()`), typed with `# ` / `= ` (auto-format).
|
||||||
|
|
||||||
|
**Checklist to add or change an element type** (the compiler catches the `Record<ElementType,…>`
|
||||||
|
maps, but not the rest):
|
||||||
|
|
||||||
|
1. `internal/screenplay`: constant, `Uppercase()` / `InDialogue()` / `Printed()` if relevant.
|
||||||
|
2. `internal/layout`: `specs` (left inch, width chars, blank lines before), `x()` alignment,
|
||||||
|
keep-with-next / splittable rules.
|
||||||
|
3. `internal/fountain`: parse rule and writer rule (Fountain has few types; document any lossy
|
||||||
|
mapping in README "Formats").
|
||||||
|
4. `internal/fdx`: `typeNames` and the reader switch.
|
||||||
|
5. Tests in `fountain_test.go`, `fdx_test.go`, `layout_test.go`.
|
||||||
|
6. `frontend/src/backend.ts` union, `schema.ts` `ELEMENT_TYPES` + `LABELS`.
|
||||||
|
7. `commands.ts`: `NEXT_ON_ENTER`, `RETYPE_ON_EMPTY_ENTER`, `TAB`, `SHIFT_TAB`, auto-detection.
|
||||||
|
8. `autocomplete.ts` if it has suggestions; `style.css` `.el-<type>` + `--t-<type>` color.
|
||||||
|
9. README shortcut table and format table; tooltip in `index.html` if the Ctrl+N range changes.
|
||||||
|
|
||||||
|
### Screenplay format rules (do not break)
|
||||||
|
|
||||||
|
US Letter, Courier 12 pt = 10 chars/inch, 6 lines/inch, 54 body lines per page, 1" top/bottom,
|
||||||
|
1.5" left margin. Indents (inches from page edge / width in chars): scene & action 1.5/60,
|
||||||
|
character 3.7/38, parenthetical 3.1/25 with 1-char hanging indent, dialogue 2.5/35, transition
|
||||||
|
right-aligned at 7.5", dual columns at 1.5" and 4.5". Pagination: scene headings and inserts are
|
||||||
|
kept with the next two lines; action and dialogue split only at sentence ends with ≥ 2 lines on
|
||||||
|
each side; never end a page on a parenthetical; split dialogue gets `(MORE)` / `NAME (CONT'D)`;
|
||||||
|
dual dialogue is never split; title page and page 1 are unnumbered; sections, synopses, notes
|
||||||
|
and lines holding only a note are not printed.
|
||||||
|
A4 (`layout.PaperGeometry`) keeps every margin and width: the page is 8.27" wide and holds 58
|
||||||
|
lines; right scene numbers move from 7.75" to 7.6". Revision asterisks go at 8.1" (A4: 7.95"), a
|
||||||
|
revised page's header (`Pink Revision - 09/28/26`) at 1.5" on the page-number line; a page is
|
||||||
|
starred only for its latest revision.
|
||||||
|
Locked pages (`settings.locked` + `Element.Locked`): each locked page starts where its anchor
|
||||||
|
is; overflow makes A pages (`12` → `12A` → `12B`), a page left empty is merged into the previous
|
||||||
|
one (`12-13`), an anchor inside a dialogue block cuts it with `(MORE)` / `(CONT'D)`, an anchor
|
||||||
|
inside a dual dialogue starts the page above the whole block.
|
||||||
|
The editor CSS reproduces the same geometry with `in` and `ch` units (1ch = 0.1in), the page
|
||||||
|
width through `--page-width` (`.paper[data-paper='a4']`): **if you change a spec in `layout.go`,
|
||||||
|
change `style.css` too** (and vice versa).
|
||||||
|
|
||||||
|
### Frontend state and saving
|
||||||
|
|
||||||
|
- `app` in `main.ts` holds `path`, `dirty`, `revision`, `saving`, `draftSaved`, `titlePage`,
|
||||||
|
`settings`, `layout`, preferences. The ProseMirror doc is the source of truth for the script
|
||||||
|
body; the title page lives in `app.titlePage` and the production settings (paper, revision
|
||||||
|
sets, marking, locking) in `app.settings`. Settings are not editor transactions: after
|
||||||
|
changing one, call `settingsChanged()` (marks the script changed, repaginates).
|
||||||
|
- Revisions (`revisions.ts`): `revisionPlugin` marks, in an appended transaction, the ranges
|
||||||
|
each change inserted (a deletion marks its neighbour); it skips undo/redo
|
||||||
|
(`isHistoryTransaction`) so undo removes text and mark together. `lockPlugin` maps every
|
||||||
|
locked-page anchor through each change and rewrites the `locked` attributes; lock, unlock and
|
||||||
|
clearing marks are built by `lockPages`, `unlockPages`, `clearRevisionMarks`. Their own
|
||||||
|
transactions carry the `INTERNAL` meta so the plugins never react to each other. Locking and
|
||||||
|
unlocking are not undoable (`addToHistory: false`), like the setting they go with.
|
||||||
|
- The `revision` mark is not inclusive (typing next to revised text is not revised unless
|
||||||
|
marking is on); the `note` mark is, like bold. Hard breaks carry note/revision marks only.
|
||||||
|
- **The frontend owns the dirty flag** and pushes it to Go with `SetDirty`. Go's `Save` must not
|
||||||
|
reset it: an autosave can finish after newer edits (`revision` guards this).
|
||||||
|
- Every change goes through `markChanged()` (revision++, dirty, schedule autosave).
|
||||||
|
- Autosave (1.2 s idle): writes the real file when there is a path, otherwise
|
||||||
|
`~/.local/share/plotzilla/recovery.fountain` (offered back at launch, removed on explicit discard
|
||||||
|
or first save).
|
||||||
|
- Spelling is checked in Go (`SpellCheck`, 500 ms after the last change, stale results
|
||||||
|
dropped like pagination); the frontend only draws underlines and menus. Dictionaries are the
|
||||||
|
system's Hunspell files, loaded lazily per language; the personal dictionary is
|
||||||
|
`~/.local/share/plotzilla/dictionary.txt`. Compound words are tried only when the word
|
||||||
|
itself is unknown (`Dictionary.accepts`): parts need COMPOUNDFLAG or the BEGIN/MIDDLE/LAST
|
||||||
|
flag of their position; the first part may take a prefix, the last a suffix, any other affix
|
||||||
|
needs COMPOUNDPERMITFLAG in its continuation classes. Suggestions do not build compounds.
|
||||||
|
- Find & replace is frontend-only (`search.ts`): matches are computed on `blockText`, where one
|
||||||
|
character is one document position. Replacements go through `replaceText()` (commands.ts),
|
||||||
|
which keeps the marks, and each one is its own undo step (`closeHistory`).
|
||||||
|
- Closing: `OnBeforeClose` in Go returns "prevent" while dirty and emits `confirm-close`; the
|
||||||
|
frontend asks with its own dialog and calls `runtime.Quit()` after `SetDirty(false)`.
|
||||||
|
|
||||||
|
### Window and desktop integration
|
||||||
|
|
||||||
|
- The window is **frameless and translucent**; the top bar is a GNOME-style header bar on every
|
||||||
|
desktop (`--wails-draggable: drag`, every interactive child `no-drag`, double-click toggles
|
||||||
|
maximise). `body` draws the 12 px rounded corners; `body.maximized` removes them, and so does
|
||||||
|
`body.opaque` (no compositor, hence no alpha channel: rounded corners would show black
|
||||||
|
wedges); `body.backdrop` dims the bar when unfocused.
|
||||||
|
- **Nothing may depend on GNOME being the desktop.** Read desktop settings through GTK or the
|
||||||
|
XDG portal, never with `gsettings`/`org.gnome.*` alone (they hold GNOME's defaults, not the
|
||||||
|
user's choice, on other desktops). `WindowFrame()` returns GTK's `gtk-decoration-layout`
|
||||||
|
(each desktop feeds it: GNOME/Plasma settings, XSettings on Xfce/MATE/Cinnamon,
|
||||||
|
`settings.ini`) and whether the window is really translucent; the frontend lays out the
|
||||||
|
buttons from it and ignores entries it does not draw (`menu`, `appmenu`, `icon`, `spacer`).
|
||||||
|
The light/dark preference for native dialogs comes from the portal's
|
||||||
|
`org.freedesktop.appearance color-scheme`, with GNOME's `color-scheme` as the fallback when
|
||||||
|
no portal answers; "no preference" leaves GTK's configured theme alone.
|
||||||
|
- **Never use Wails `runtime.MessageDialog` for questions**: on Linux it ignores custom buttons
|
||||||
|
and shows GTK stock Yes/No/OK translated into the system language. Use `messageBox()` in
|
||||||
|
`main.ts` (supports `destructive`).
|
||||||
|
- `main.go` sets `LANGUAGE=en` so GTK's own strings (file chooser) are English.
|
||||||
|
- `desktop_linux.go` must only touch GTK through `g_idle_add` (main loop); Wails callbacks run
|
||||||
|
on other goroutines. `query_window_frame` shows how to get an answer back synchronously
|
||||||
|
(refcounted request + `GCond` with a timeout); never call it from the main thread.
|
||||||
|
|
||||||
|
## 5. Testing
|
||||||
|
|
||||||
|
- Go: unit tests live next to each package (`make test`). Add a test for every parser,
|
||||||
|
writer or pagination change; round-trip tests (`Parse(Write(doc)) == doc`) protect formats.
|
||||||
|
- PDF visual check: `PLOTZILLA_PDF=/tmp/x.pdf go test ./internal/pdf`, then
|
||||||
|
`pdftoppm -png -r 60 /tmp/x.pdf /tmp/page` and look at the image, or
|
||||||
|
`pdftotext -layout /tmp/x.pdf -` to check columns.
|
||||||
|
- UI without the Go side: serve `frontend/dist` over HTTP with a small script defining
|
||||||
|
`window.go.main.App` (async stubs returning sample data) and `window.runtime`, injected before
|
||||||
|
the module script; screenshot with
|
||||||
|
`firefox --headless -no-remote -profile <tmpdir> --window-size=1440,900 --screenshot out.png URL`.
|
||||||
|
Disable animations in that page (`*{animation:none!important;transition:none!important}`)
|
||||||
|
or the capture happens mid-fade. Firefox is not WebKitGTK: confirm anything engine-specific
|
||||||
|
(zoom, drag, dialogs, fonts) in the real app with `make dev`.
|
||||||
|
- Screenshots (`screenshots/`): regenerate them with `make screenshots` whenever the UI changes
|
||||||
|
visibly, and keep the README references in sync (a new image: add its steps to
|
||||||
|
`tools/screenshots/capture.mjs`). The run is deterministic: unchanged UI gives identical
|
||||||
|
pixels. How it works:
|
||||||
|
- `tools/screenshots/main.go` serves `frontend/dist` with a `window.go.main.App` proxy posting
|
||||||
|
each call to `/api/<Method>`, answered by the real `fountain`, `layout` and `screenplay`
|
||||||
|
packages, so pagination, locked pages and revision sets are **real**. The sample script is
|
||||||
|
`tools/screenshots/the-last-reel.fountain`; `?v=typos` and `?v=outline` serve variants (the
|
||||||
|
misspellings `projecter`, `thraeds`, `wacth` for `spelling.png`, whose suggestions are fixed,
|
||||||
|
so no dictionary is needed; sections, synopses and a note for `outline.png` and
|
||||||
|
`revisions.png`). `Save` writes nothing; revision sets have fixed dates.
|
||||||
|
- `capture.mjs` drives Firefox through `puppeteer-core` (WebDriver BiDi) at 1440×900, device
|
||||||
|
scale 2, with animations, transitions and the caret disabled and `<html spellcheck="false">`
|
||||||
|
(WebKitGTK does not spell-check; Firefox does). It moves the pointer off the header before
|
||||||
|
each capture (tooltips).
|
||||||
|
- BiDi cannot omit the background, so `main.go` masks the 12 px window corners (radius 24 px
|
||||||
|
at scale 2), and renders `pdf-output.png`: the PDF export of the sample with scene numbers,
|
||||||
|
`pdftoppm -r 110`, pages side by side on the `--bg` color.
|
||||||
|
- `FIREFOX=/path/to/firefox` picks another browser binary; `SCREENSHOTS_FLAGS="-out dir"`
|
||||||
|
writes the images elsewhere (to compare before replacing).
|
||||||
|
- Behaviour that only exists in the real window (drag, resize, GTK dialogs, close flow,
|
||||||
|
autosave timing) must be checked by running `./build/bin/plotzilla`; say so when you could not.
|
||||||
|
|
||||||
|
## 6. Go best practices (this repo)
|
||||||
|
|
||||||
|
- `gofmt` everything; `go vet` clean with the build tags. Standard library first: the PDF writer
|
||||||
|
and all formats have **no third-party dependency**, keep it that way unless there is a strong reason.
|
||||||
|
- Business logic lives in `internal/…` packages that know nothing about Wails; `app.go` is a thin
|
||||||
|
adapter (dialogs, file system, JSON-friendly return types). Keep packages free of GUI imports
|
||||||
|
so they stay testable with plain `go test`.
|
||||||
|
- Bound methods: exported methods on `App` become JS APIs. Return `(T, error)` and let the
|
||||||
|
frontend handle the error; return `nil`/`""` (not an error) when the user cancels a dialog.
|
||||||
|
- Wrap errors with context (`fmt.Errorf("reading FDX: %w", err)`), lower-case, no trailing
|
||||||
|
punctuation. Never `panic` on user input; malformed files degrade to best effort.
|
||||||
|
- Write files atomically (`writeAtomic`: temp file in the same directory + rename).
|
||||||
|
- Text is Unicode: iterate with runes, use `screenplay.UpperRunes` when offsets must survive
|
||||||
|
upper-casing (`strings.ToUpper("ß")` changes length). Offsets exchanged with the UI are runes.
|
||||||
|
- Prefer small pure functions and value types; avoid package-level mutable state (the specs
|
||||||
|
tables are read-only). Use `min`/`max` builtins, `strings.Builder`, `bytes.Buffer`.
|
||||||
|
- Comments explain *why* (format rules, GTK quirks), not what; doc comments on exported identifiers
|
||||||
|
start with the name.
|
||||||
|
- cgo is confined to `desktop_linux.go` behind `//go:build linux`.
|
||||||
|
|
||||||
|
## 7. TypeScript best practices (this repo)
|
||||||
|
|
||||||
|
- `strict` mode, `noUnusedLocals`; `npm run build` must type-check cleanly. No `any`: use
|
||||||
|
`unknown` and narrow, or a precise type. Use `import type` for type-only imports.
|
||||||
|
- No framework: DOM APIs, small modules, one responsibility per file. Query elements once and keep
|
||||||
|
references; build DOM with `createElement`/`textContent`. Use `innerHTML` only for static
|
||||||
|
trusted markup (icons); **never** for script text, file names or error messages.
|
||||||
|
- ProseMirror rules:
|
||||||
|
- All document changes go through transactions (`view.dispatch(tr)`); never mutate DOM inside
|
||||||
|
the editor. Build one transaction per user action so undo is a single step; set
|
||||||
|
`addToHistory: false` for non-content metadata (page-break decorations).
|
||||||
|
- Commands follow the `(state, dispatch) => boolean` contract: return `false` when not
|
||||||
|
applicable, do nothing if `dispatch` is undefined.
|
||||||
|
- When positions change inside a transaction, map them with `tr.mapping.map()` instead of
|
||||||
|
recomputing from the old document.
|
||||||
|
- Positions are UTF-16 offsets; convert Go rune offsets explicitly.
|
||||||
|
- Plugin order matters: autocomplete before the screenplay keymap, keymaps before `baseKeymap`.
|
||||||
|
- Async calls to Go can resolve after the document changed: compare against a captured doc or
|
||||||
|
`revision` before applying results (see `paginate()` and `autosave()`).
|
||||||
|
- Handle every promise: `await` inside `try/catch`, or `.catch(reportError | console.error)`.
|
||||||
|
- `localStorage` only for per-user preferences (zoom, panel, autosave, export options), always
|
||||||
|
through the `load`/`store` helpers (they swallow storage errors).
|
||||||
|
- Keyboard shortcuts: global ones in the `shortcuts` map (capture phase, skipped while a dialog is
|
||||||
|
open); editing ones in `screenplayKeys()`. Update the README table and tooltips together.
|
||||||
|
|
||||||
|
## 8. CSS best practices (this repo)
|
||||||
|
|
||||||
|
- One stylesheet, organised in commented sections (topbar, menu, main, hud, paper, page break,
|
||||||
|
autocomplete, dialogs). Plain CSS, no preprocessor.
|
||||||
|
- **Design tokens only**: colors, radii, easing and fonts come from the custom properties in
|
||||||
|
`:root` (`--bg`, `--surface`, `--text`, `--accent`, `--t-<element>`…). Do not hard-code a new
|
||||||
|
color in a rule; add a token. The theme is intentionally always dark, blue-dominant.
|
||||||
|
- Screen geometry of the page uses physical units (`in`, `pt`, `ch`) that mirror
|
||||||
|
`internal/layout`; UI chrome uses `px`. Do not mix them.
|
||||||
|
- Class names are short, kebab-case, component-scoped (`.nav-head`, `.win-button`); state is a
|
||||||
|
class on `body` (`.focus-mode`, `.no-navigator`, `.maximized`, `.backdrop`) or a `data-*`
|
||||||
|
attribute (`[data-state='saved']`), never inline styles except computed positions.
|
||||||
|
- Animate only `opacity` and `transform`/`translate` with `var(--ease)`; keep durations
|
||||||
|
≤ 350 ms; every hover state has a matching transition. Respect focus visibility
|
||||||
|
(`:focus-visible` outlines on buttons).
|
||||||
|
- Custom properties inherit, which the page-break widget relies on (`--indent` per element type)
|
||||||
|
and so does window dragging (`--wails-draggable`). Remember both when nesting new elements in
|
||||||
|
`.topbar` or `.el`.
|
||||||
|
- Target WebKitGTK: `-webkit-` scrollbar pseudo-elements plus standard `scrollbar-*` properties;
|
||||||
|
`zoom` is used for editor zoom; `backdrop-filter` is fine. Avoid features WebKit lacks.
|
||||||
|
|
||||||
|
## 9. Gotchas already paid for
|
||||||
|
|
||||||
|
- `go:embed` fails if `frontend/dist` is missing → run `make`, not `go build`.
|
||||||
|
- GTK stock buttons follow the system locale (`fr_FR` here) → in-app dialogs + `LANGUAGE=en`.
|
||||||
|
- GTK 3 ignores the desktop's dark preference → `desktop_linux.go` (portal, then GNOME fallback).
|
||||||
|
- GTK reports GNOME's `appmenu` button as `menu`; both are ignored by the header bar.
|
||||||
|
- `gsettings` exists on every desktop that has GTK 3, but outside GNOME it returns GNOME's
|
||||||
|
defaults: it is not a way to read the user's desktop settings.
|
||||||
|
- Fountain cannot express insert/shot or intertitle types: shots round-trip only when they start
|
||||||
|
with a known prefix (`INSERT`, `CLOSE ON`, `POV`…); all-caps centred text is read as an
|
||||||
|
intertitle. Documented in README; keep the parse and write rules symmetric.
|
||||||
|
- Fountain has no revisions, locks or paper size: they are boneyard comments, which other apps
|
||||||
|
ignore. Inline markers travel with the text (`/*rev 2*/…/*/rev*/`, `/*page 12*/`), settings are
|
||||||
|
one `/* Plotzilla {json} */` block at the end (`*/` inside JSON is written `*\/`). The parser
|
||||||
|
first replaces notes and markers by tokens (U+E000 payload U+E001, no line break) so a note
|
||||||
|
spanning lines keeps its paragraph; line rules test `bare(line)` (tokens removed) and `inline`
|
||||||
|
turns tokens back into runs and locks. Writers must put Fountain's force prefixes (`.`, `@`,
|
||||||
|
`!`, `>`) **before** any marker. A script without these features must write byte-identical
|
||||||
|
output to before (`TestPlainScriptUnchanged`).
|
||||||
|
- The Fountain writer skips empty elements: their locked pages and forced page break are carried
|
||||||
|
to the next element written (layout does the same for elements that print nothing).
|
||||||
|
- Final Draft has no sections or synopses: the FDX writer stores them as `ScriptNote`s whose
|
||||||
|
text starts with `#` / `=`, attached (Range `0,0`) to the next paragraph, or to an empty
|
||||||
|
trailing Action paragraph at the end; the reader turns such notes back into elements. An
|
||||||
|
ordinary note starting with `#`, `=` or `\` is written with a leading `\`, removed on
|
||||||
|
reading. Revised text is `<Text RevisionID="n">`, the sets a `<Revisions>` block named
|
||||||
|
`Blue Revision - date`. The exact Final Draft schema for these (ScriptNote placement,
|
||||||
|
Revisions attributes) was written from memory, not checked against Final Draft itself.
|
||||||
|
- COMPOUNDRULE parts are bare dictionary words (no affixes), as in Hunspell; the first
|
||||||
|
COMPOUNDRULE line is the rule count.
|
||||||
|
- A literal BOM or other invisible character in Go source breaks `go vet`; write `""`.
|
||||||
|
- `npm` blocks install scripts (esbuild postinstall); the build still works with the bundled
|
||||||
|
binary.
|
||||||
|
- Vite empties `dist/` on each build; placeholders belong in `frontend/public/`.
|
||||||
|
- Floating layers over the script (menus, suggestions, HUD) use the opaque `--popover` token:
|
||||||
|
translucent backgrounds let the script text bleed through.
|
||||||
|
- A `position: fixed` popup anchored to the text must follow scrolling (see `reposition` in
|
||||||
|
autocomplete.ts).
|
||||||
|
- Hidden-but-hoverable UI (focus mode) must stay in place with `opacity: 0`; moving it off-screen
|
||||||
|
with a transform also moves its hover area.
|
||||||
|
- The dev shell is zsh: unquoted variables are not word-split and an unmatched glob is an error.
|
||||||
|
- `pkill -f <pattern>` also matches the shell running it when the pattern is in its command
|
||||||
|
line (it kills your own command, exit code 144); use `pkill -x <name>`.
|
||||||
|
- Firefox gives a synthetic `ClipboardEvent` an empty `clipboardData`: test paste with
|
||||||
|
`navigator.clipboard.writeText` + a real `Ctrl+V`.
|
||||||
|
|
||||||
|
## 10. Git and commits
|
||||||
|
|
||||||
|
- Commits are **atomic**: one logical change per commit, with the code, its tests and its
|
||||||
|
documentation together. Every commit must build (`make`) and pass `make test`, so any commit
|
||||||
|
can be checked out or reverted on its own. Do not mix a fix with a feature or a reformat.
|
||||||
|
- Messages are in **English** and follow this convention:
|
||||||
|
|
||||||
|
| Prefix | Use for |
|
||||||
|
|---|---|
|
||||||
|
| `feat:` | a new feature or a user-visible improvement |
|
||||||
|
| `fix:` | a bug fix |
|
||||||
|
| `chore:` | changelog and maintenance (dependency updates, build and project configuration) |
|
||||||
|
| `ci:` | anything that touches CI |
|
||||||
|
| `test:` | changes to tests only |
|
||||||
|
| `docs:` | README, AGENTS.md and other documentation |
|
||||||
|
|
||||||
|
- Summary line: `<prefix> <what the commit does>`, imperative mood, lower case, no final period,
|
||||||
|
72 characters at most (`feat: add dual dialogue`, `fix: keep autocomplete popup under the
|
||||||
|
caret when scrolling`). Leave a blank line, then explain *why* in the body when it is not
|
||||||
|
obvious.
|
||||||
|
- A feature commit includes its tests; use `test:` only for commits that change tests alone.
|
||||||
|
Screenshot updates go with `docs:`.
|
||||||
|
- Never commit build output (`build/bin`, `frontend/dist` except `.gitkeep`,
|
||||||
|
`frontend/node_modules`, `frontend/wailsjs`); `.gitignore` covers them.
|
||||||
|
|
||||||
|
## 11. Roadmap (not implemented)
|
||||||
|
|
||||||
|
Character/location reports, recent files, locked pages and paper size in FDX.
|
||||||
|
Keep new features consistent with the rules above: Go owns formats and layout, the frontend
|
||||||
|
owns interaction.
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to Plotzilla are documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). The current
|
||||||
|
version is in the `VERSION` file.
|
||||||
|
|
||||||
|
## [1.0] - 2026-09-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Screenplay editor on a page drawn at the real printed size, with scene heading, action,
|
||||||
|
character, parenthetical, dialogue, transition, insert/shot, intertitle and centered elements
|
||||||
|
(`Ctrl+1` to `Ctrl+9`).
|
||||||
|
- Final Draft-style typing: `Enter` creates the next logical element, `Tab` cycles the type,
|
||||||
|
scene headings, inserts, parentheticals and transitions are recognized as you type.
|
||||||
|
- Dual dialogue (`Ctrl+D`), bold, italic and underline.
|
||||||
|
- Autocomplete for character names, extensions, locations, times of day, inserts and
|
||||||
|
transitions.
|
||||||
|
- Live page breaks computed by the PDF layout engine, with `(MORE)` / `(CONT'D)` and the usual
|
||||||
|
pagination rules.
|
||||||
|
- Scene navigator with scene numbers and pages; focus mode; zoom.
|
||||||
|
- Find and replace, with match case and whole words.
|
||||||
|
- Spell checking with the system's Hunspell dictionaries, including compound words (with
|
||||||
|
`COMPOUNDRULE` patterns), a personal dictionary and screenplay-aware rules (character names,
|
||||||
|
sluglines, abbreviations).
|
||||||
|
- Title page editor.
|
||||||
|
- Fountain as the native format; Final Draft (`.fdx`) import and export; PDF export in US Letter
|
||||||
|
or A4, with optional title page and scene numbers.
|
||||||
|
- Fountain sections, synopses and notes, shown in the editor and in the navigator outline,
|
||||||
|
never printed.
|
||||||
|
- Colored revisions (Blue, Pink, Yellow…) with revision headers and asterisks in the PDF.
|
||||||
|
- Locked pages, with A pages (`12A`) and merged pages (`12-13`).
|
||||||
|
- Forced page breaks (`Ctrl+Enter`), read and written as Fountain's `===` and Final Draft's
|
||||||
|
`StartsNewPage`.
|
||||||
|
- Sections, synopses, notes and revisions in Final Draft files.
|
||||||
|
- Autosave, with recovery of untitled scripts, and a confirmation before discarding changes.
|
||||||
|
- Frameless window with an in-app header bar, English interface whatever the system language.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The window no longer depends on GNOME: window buttons follow the desktop's GTK button layout,
|
||||||
|
and the light/dark preference is read from the XDG desktop portal (GNOME setting as fallback).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- File choosers no longer switch to light mode on KDE Plasma and other non-GNOME desktops.
|
||||||
|
- Window corners stay square instead of showing black wedges when no compositor is running.
|
||||||
@@ -1,18 +1,232 @@
|
|||||||
MIT License
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
Copyright (c) 2026 Kharec
|
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||||
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
|
||||||
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
|
||||||
following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
Preamble
|
||||||
portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
||||||
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
|
||||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
“This License” refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||||
|
|
||||||
|
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||||
|
|
||||||
|
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||||
|
|
||||||
|
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||||
|
|
||||||
|
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||||
|
|
||||||
|
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||||
|
|
||||||
|
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||||
|
|
||||||
|
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||||
|
|
||||||
|
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||||
|
|
||||||
|
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
plotzilla
|
||||||
|
Copyright (C) 2026 Kharec
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
plotzilla Copyright (C) 2026 Kharec
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# webkit2_41: Arch and recent distros only ship WebKitGTK 4.1.
|
||||||
|
TAGS := desktop,production,webkit2_41
|
||||||
|
|
||||||
|
.PHONY: build frontend dev test screenshots clean
|
||||||
|
|
||||||
|
build: frontend
|
||||||
|
go build -tags $(TAGS) -ldflags "-s -w" -o build/bin/plotzilla .
|
||||||
|
|
||||||
|
frontend:
|
||||||
|
cd frontend && npm install && npm run build
|
||||||
|
|
||||||
|
# Live reload (requires the Wails CLI: go install github.com/wailsapp/wails/v2/cmd/wails@latest)
|
||||||
|
dev:
|
||||||
|
wails dev -tags webkit2_41
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test ./internal/...
|
||||||
|
|
||||||
|
# README images (screenshots/), from the sample script in tools/screenshots.
|
||||||
|
# Needs Firefox, and pdftoppm (poppler) for pdf-output.png.
|
||||||
|
screenshots: frontend
|
||||||
|
cd tools/screenshots && npm install --no-fund
|
||||||
|
go run ./tools/screenshots $(SCREENSHOTS_FLAGS)
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -rf build/bin frontend/dist/assets frontend/dist/index.html
|
||||||
@@ -1,3 +1,492 @@
|
|||||||
# plotzilla
|
# Plotzilla
|
||||||
|
|
||||||
Unleash your scripts on the world.
|
Unleash your plot on the world.
|
||||||
|
|
||||||
|
A screenwriting app for Linux that formats scripts to the Hollywood standard as you type.
|
||||||
|
It saves plain-text Fountain files, imports and exports Final Draft, and prints
|
||||||
|
industry-standard PDFs.
|
||||||
|
|
||||||
|
Plotzilla is built with Go and [Wails](https://wails.io) (GTK 3 and WebKitGTK), with a
|
||||||
|
[ProseMirror](https://prosemirror.net) editor. It has a GNOME look but is not tied to
|
||||||
|
GNOME: it runs on any Linux desktop (KDE Plasma, Xfce, Cinnamon, MATE…), on Wayland or X11, and
|
||||||
|
follows the desktop's window button layout and light/dark preference.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [Installation](#installation)
|
||||||
|
- [The editor](#the-editor)
|
||||||
|
- [Screenplay elements](#screenplay-elements)
|
||||||
|
- [Typing a script](#typing-a-script)
|
||||||
|
- [Outline and notes](#outline-and-notes)
|
||||||
|
- [Autocomplete](#autocomplete)
|
||||||
|
- [Find and replace](#find-and-replace)
|
||||||
|
- [Spelling](#spelling)
|
||||||
|
- [Pages and scenes](#pages-and-scenes)
|
||||||
|
- [Revisions and locked pages](#revisions-and-locked-pages)
|
||||||
|
- [Title page](#title-page)
|
||||||
|
- [Saving and files](#saving-and-files)
|
||||||
|
- [Exporting](#exporting)
|
||||||
|
- [Keyboard shortcuts](#keyboard-shortcuts)
|
||||||
|
- [Desktop integration](#desktop-integration)
|
||||||
|
- [Development](#development)
|
||||||
|
- [Not supported yet](#not-supported-yet)
|
||||||
|
- [License](#license)
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Requirements (Arch Linux package names): `go` 1.23 or later, `nodejs` 20.19 or later, `npm`,
|
||||||
|
`webkit2gtk-4.1`, `gtk3`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make # builds build/bin/plotzilla
|
||||||
|
./build/bin/plotzilla my-film.fountain # the file argument is optional
|
||||||
|
```
|
||||||
|
|
||||||
|
Install the Courier Prime font (`ttf-courier-prime` on the AUR) so the text on screen matches
|
||||||
|
the PDF exactly. Without it, Plotzilla uses Courier New, Nimbus Mono or Liberation Mono.
|
||||||
|
|
||||||
|
Spell checking uses the system's Hunspell dictionaries: install one per language you write in,
|
||||||
|
for example `hunspell-en_us`, `hunspell-en_gb` or `hunspell-fr`.
|
||||||
|
|
||||||
|
## The editor
|
||||||
|
|
||||||
|
The script is shown as a sheet of paper, at the real size and with the real margins of the
|
||||||
|
printed page. The window has four areas:
|
||||||
|
|
||||||
|
- **Header bar** (top): file name and save status, file buttons, the element type menu,
|
||||||
|
formatting and note buttons, find, spelling and revisions buttons, title page and export
|
||||||
|
buttons, and the scene navigator and focus mode toggles. Drag it to move the window;
|
||||||
|
double-click it to maximize.
|
||||||
|
- **Scene navigator** (left): every scene with its number, heading and page, grouped under the
|
||||||
|
script's sections, with their synopses. The current scene is highlighted. Click an entry to
|
||||||
|
jump to it. The autosave switch is at the bottom.
|
||||||
|
- **Page** (center): the script, with scene numbers in the left margin and live page breaks.
|
||||||
|
- **Status bar** (bottom, floating): the current element type, what `Enter` and `Tab` will do
|
||||||
|
next, the current page out of the total, the word count and, while revising or once pages are
|
||||||
|
locked, the current revision and `Pages Locked`.
|
||||||
|
|
||||||
|
The bold, italic, underline, note and dual dialogue buttons light up when the cursor is inside
|
||||||
|
such text; the revisions button lights up while revisions are marked or pages are locked. The save status shows `Edited`, `Saving…`, `Saved · auto` (or `Saved` when autosave is
|
||||||
|
off) and, for a script that has never been saved, `Draft backed up`.
|
||||||
|
|
||||||
|
**Focus mode** (`Ctrl+Shift+F`) hides the navigator, the header bar and the status bar so only
|
||||||
|
the page remains. Move the pointer to the top or bottom edge to bring the bars back.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Zoom** goes from 60% to 200% (`Ctrl+=`, `Ctrl+-`, `Ctrl+0`). Zoom, the navigator's visibility,
|
||||||
|
autosave, spelling and the export options are remembered between sessions.
|
||||||
|
|
||||||
|
## Screenplay elements
|
||||||
|
|
||||||
|
| Element | Shortcut | Format |
|
||||||
|
|---|---|---|
|
||||||
|
| Scene heading (slugline) | `Ctrl+1` | Capitals, 1.5" from the left edge, numbered |
|
||||||
|
| Action | `Ctrl+2` | 1.5" from the left edge, full width |
|
||||||
|
| Character | `Ctrl+3` | Capitals, 3.7" from the left edge |
|
||||||
|
| Parenthetical | `Ctrl+4` | 3.1" from the left edge, in parentheses, hanging indent |
|
||||||
|
| Dialogue | `Ctrl+5` | 2.5" from the left edge, 35 characters wide |
|
||||||
|
| Transition | `Ctrl+6` | Capitals, right-aligned |
|
||||||
|
| Insert / shot | `Ctrl+7` | Capitals, like a scene heading but not numbered and not a scene |
|
||||||
|
| Intertitle | `Ctrl+8` | Capitals, centered (title cards such as `PARIS, 1942`) |
|
||||||
|
| Centered | `Ctrl+9` | Centered text (for example `THE END`) |
|
||||||
|
| Section | type `# ` | Outline heading (`#`, `##`, `###`…), not printed |
|
||||||
|
| Synopsis | type `= ` | Summary of a scene or section, not printed |
|
||||||
|
|
||||||
|
The element type menu in the header bar lists them all with their shortcuts. Use the arrow
|
||||||
|
keys and `Enter` to pick one from the keyboard. Sections and synopses are described in
|
||||||
|
[Outline and notes](#outline-and-notes).
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**Dual dialogue** puts two speeches side by side, for characters talking at the same time.
|
||||||
|
Press `Ctrl+D` (or the columns button) in a dialogue:
|
||||||
|
|
||||||
|
- If the next or previous dialogue block is adjacent, the two are placed side by side.
|
||||||
|
- Otherwise an empty right column opens with a new character cue.
|
||||||
|
- Inside a dual dialogue, `Ctrl+D` splits it back into two blocks.
|
||||||
|
|
||||||
|
In the editor, the columns are drawn side by side, marked by a thin line in the margin.
|
||||||
|
`Enter` at the end of the left column moves to the right column, and at the end of the right
|
||||||
|
column it leaves the block.
|
||||||
|
|
||||||
|
**Text formatting**: bold, italic and underline (`Ctrl+B`, `Ctrl+I`, `Ctrl+U`) are kept in
|
||||||
|
Fountain, Final Draft and PDF files. Notes (`Ctrl+Shift+N`) are described in
|
||||||
|
[Outline and notes](#outline-and-notes).
|
||||||
|
|
||||||
|
## Typing a script
|
||||||
|
|
||||||
|
Plotzilla follows the Final Draft conventions, so a script can be written without touching the
|
||||||
|
mouse.
|
||||||
|
|
||||||
|
`Enter` at the end of an element creates the element that usually follows it:
|
||||||
|
|
||||||
|
| After | `Enter` creates |
|
||||||
|
|---|---|
|
||||||
|
| Scene heading | Action |
|
||||||
|
| Action | Action |
|
||||||
|
| Character | Dialogue |
|
||||||
|
| Parenthetical | Dialogue |
|
||||||
|
| Dialogue | Action |
|
||||||
|
| Transition | Scene heading |
|
||||||
|
| Insert, intertitle, centered | Action |
|
||||||
|
| Section | Scene heading |
|
||||||
|
| Synopsis | Action |
|
||||||
|
|
||||||
|
`Enter` on an **empty** element changes its type instead: an empty action becomes a scene
|
||||||
|
heading, an empty character or dialogue becomes an action, and an empty parenthetical becomes
|
||||||
|
dialogue. `Enter` in the middle of an element splits it in two.
|
||||||
|
|
||||||
|
`Tab` changes the type of the current element: Action → Character → Transition → Scene heading
|
||||||
|
→ Action, and Dialogue ⇄ Parenthetical. `Shift+Tab` goes the other way.
|
||||||
|
|
||||||
|
`Shift+Enter` adds a line break inside the same element.
|
||||||
|
|
||||||
|
Some elements are recognized as you type:
|
||||||
|
|
||||||
|
- `INT. `, `EXT. `, `EST. `, `INT./EXT. ` or `I/E ` at the start of an action makes it a scene
|
||||||
|
heading.
|
||||||
|
- `INSERT ` at the start of an action makes it an insert.
|
||||||
|
- `# ` at the start of an empty action or scene heading makes it a section (`## ` a
|
||||||
|
subsection, down to `###### `), and `= ` makes it a synopsis.
|
||||||
|
- `(` at the start of an empty dialogue opens a parenthetical, with the closing parenthesis
|
||||||
|
already in place.
|
||||||
|
- An all-caps action ending in `TO:` becomes a transition when you press `Enter`.
|
||||||
|
|
||||||
|
Changing an element to a parenthetical adds the parentheses; changing it back removes them.
|
||||||
|
Inside a parenthetical, `Enter` just before the closing parenthesis moves on to the dialogue.
|
||||||
|
|
||||||
|
Pasted plain text is read as Fountain, so a script copied from another app or a text file keeps
|
||||||
|
its scene headings, characters and dialogue.
|
||||||
|
|
||||||
|
Undo and redo: `Ctrl+Z`, `Ctrl+Shift+Z` or `Ctrl+Y`.
|
||||||
|
|
||||||
|
## Outline and notes
|
||||||
|
|
||||||
|
Plotzilla keeps the outline tools of Fountain. None of them is printed; they are saved in
|
||||||
|
Fountain files, and as script notes in Final Draft files (see [Saving and files](#saving-and-files)).
|
||||||
|
|
||||||
|
- **Sections** (`# Act One`, `## The Rialto`) structure the script into acts, sequences or
|
||||||
|
any grouping you like. Type `# ` (or `## `, `### `…) at the start of an empty line, or pick
|
||||||
|
**Section** in the element type menu. The level shows as `#` marks in the left margin.
|
||||||
|
- **Synopses** (`= The young woman smuggles the can into the cinema.`) sum up a section or a
|
||||||
|
scene. Type `= ` at the start of an empty line, or pick **Synopsis** in the menu.
|
||||||
|
- **Notes** (`[[Warmer light here?]]`) are remarks inside the text. Press `Ctrl+Shift+N` (or
|
||||||
|
the note button) to start or end a note, like bold; select text and press it to turn the
|
||||||
|
selection into a note. Notes are shown highlighted in yellow.
|
||||||
|
|
||||||
|
The scene navigator shows the sections as headings above their scenes and each synopsis under
|
||||||
|
the entry it follows, so the navigator reads as an outline. Sections, synopses and notes do not
|
||||||
|
count in the word count, and a line that only holds a note takes no room on the printed page.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Autocomplete
|
||||||
|
|
||||||
|
Suggestions appear under the cursor while you type. Use `↑` and `↓` to browse, `Enter` or
|
||||||
|
`Tab` to accept, and `Esc` to dismiss.
|
||||||
|
|
||||||
|
- **Character**: names already used in the script, most frequent first. After an opening
|
||||||
|
parenthesis: `V.O.`, `O.S.`, `O.C.`, `CONT'D`.
|
||||||
|
- **Scene heading**: `INT.`, `EXT.`, `INT./EXT.`, `EST.`; then the locations already used; then,
|
||||||
|
after ` - `, the time of day (`DAY`, `NIGHT`, `CONTINUOUS`, `LATER`, `MOMENTS LATER`,
|
||||||
|
`MORNING`, `EVENING`, `DUSK`, `DAWN`, `SAME`) and any other time used in the script.
|
||||||
|
- **Insert**: `INSERT -`, `CLOSE ON`, `ANGLE ON`, `POV -`, `WIDE ON`, `EXTREME CLOSE UP ON`,
|
||||||
|
`BACK TO SCENE`.
|
||||||
|
- **Transition**: `CUT TO:`, `FADE OUT.`, `FADE TO:`, `DISSOLVE TO:`, `SMASH CUT TO:`,
|
||||||
|
`MATCH CUT TO:`, `JUMP CUT TO:`, `FADE TO BLACK.`
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Find and replace
|
||||||
|
|
||||||
|
`Ctrl+F` (or the magnifier button) opens the find bar at the top right of the page. Text
|
||||||
|
selected in the script is searched right away. Every match is highlighted and the counter shows
|
||||||
|
which one is selected (`3 of 12`).
|
||||||
|
|
||||||
|
- `Enter` and `Shift+Enter` in the find field go to the next and previous match; `F3` and
|
||||||
|
`Shift+F3` (or `Ctrl+G` and `Ctrl+Shift+G`) do the same from anywhere. The search wraps around
|
||||||
|
the script.
|
||||||
|
- The two buttons next to the field match the case exactly and match whole words only.
|
||||||
|
- `Ctrl+H` (or the arrow at the left of the bar) shows the replace field. `Enter` there, or
|
||||||
|
**Replace**, replaces the selected match and moves to the next one. **All**
|
||||||
|
(`Ctrl+Alt+Enter`) replaces every match at once.
|
||||||
|
- Replaced text keeps its bold, italic and underline. Each replacement, and a whole
|
||||||
|
**Replace all**, is undone in one step with `Ctrl+Z`.
|
||||||
|
- `Esc` closes the bar and returns to the script.
|
||||||
|
|
||||||
|
The search covers the script, not the title page.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Spelling
|
||||||
|
|
||||||
|
Misspelled words get a wavy red underline, half a second after you stop typing. The word you
|
||||||
|
are typing is left alone until the cursor leaves it. Right-click an underlined word for:
|
||||||
|
|
||||||
|
- corrections, most likely first, in the word's case (`TEH` gives `THE`);
|
||||||
|
- **Add to Dictionary**: the word is accepted from now on, in every language. The personal
|
||||||
|
dictionary is the plain text file `~/.local/share/plotzilla/dictionary.txt`;
|
||||||
|
- **Ignore All**: the word is accepted until Plotzilla is closed.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The spelling button in the header bar lists the installed dictionaries. The first time,
|
||||||
|
Plotzilla picks the one matching the system language. `F7` turns spell checking on and off.
|
||||||
|
|
||||||
|
Screenplays are full of names, so:
|
||||||
|
|
||||||
|
- Character cues are not checked, and the names they introduce are accepted everywhere,
|
||||||
|
possessive included (`ELODIE's`).
|
||||||
|
- `INT.`, `EXT.`, `EST.` and `I/E` at the start of a scene heading, and common abbreviations
|
||||||
|
such as `CONT'D`, `V.O.`, `O.S.` and `POV`, are accepted.
|
||||||
|
- Words with digits (`3rd`, `R2D2`) and single letters are not checked.
|
||||||
|
|
||||||
|
Plotzilla reads Hunspell dictionaries itself (in `$DICPATH`, `~/.local/share/hunspell`,
|
||||||
|
`/usr/share/hunspell` and `/usr/share/myspell`). It understands prefixes, suffixes, elisions
|
||||||
|
(`l'homme`), capitalization and compound words: a German, Dutch or Scandinavian compound
|
||||||
|
missing from the dictionary (`Haustürschlüssel`) is accepted when the dictionary allows its
|
||||||
|
parts to be joined, including the compound patterns some dictionaries describe with Hunspell's
|
||||||
|
`COMPOUNDRULE`.
|
||||||
|
|
||||||
|
## Pages and scenes
|
||||||
|
|
||||||
|
Page breaks are computed by the same engine as the PDF export and drawn live in the editor, with
|
||||||
|
the page number, so the screen always matches the printed script.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Pagination follows the usual conventions:
|
||||||
|
|
||||||
|
- A page holds 54 lines of Courier 12 pt (58 on A4), so one page is about one minute of
|
||||||
|
screen time.
|
||||||
|
- A scene heading or an insert never ends a page.
|
||||||
|
- Action and dialogue only break at the end of a sentence, with at least two lines on each side.
|
||||||
|
- A page never ends on a parenthetical.
|
||||||
|
- Dialogue that continues onto the next page gets `(MORE)` at the bottom and `NAME (CONT'D)` at
|
||||||
|
the top of the next page.
|
||||||
|
- A dual dialogue is never split across pages.
|
||||||
|
- The title page and page 1 are not numbered.
|
||||||
|
- Sections, synopses and notes are not printed.
|
||||||
|
|
||||||
|
**Forced page breaks**: `Ctrl+Enter` starts a new page at the cursor (Fountain's `===`). In the
|
||||||
|
middle of an element it splits it, at the end it opens the next element on a new page, and at
|
||||||
|
the start of an element it puts that element on a new page, or takes it back if it already was.
|
||||||
|
In a dialogue block or a dual dialogue, the whole block moves to the next page: dialogue is
|
||||||
|
never split by hand. A forced break is labelled `PAGE BREAK` in the editor, next to the page
|
||||||
|
number.
|
||||||
|
|
||||||
|
Scenes are numbered automatically. Scene numbers written in a Fountain file (`#12A#`) or a Final
|
||||||
|
Draft file are kept.
|
||||||
|
|
||||||
|
## Revisions and locked pages
|
||||||
|
|
||||||
|
Once a script is in production, changes are issued as colored revision pages. The revisions
|
||||||
|
button in the header bar opens the revision menu:
|
||||||
|
|
||||||
|
- **Start Revisions** creates the first revision set, **Blue**, dated today, and starts marking
|
||||||
|
changes. **New Revision Set** starts the next color, in the industry order: Blue, Pink,
|
||||||
|
Yellow, Green, Goldenrod, Buff, Salmon, Cherry, then Double White, Double Blue and so on.
|
||||||
|
- **Mark Revisions** turns marking on or off. While it is on, everything you type, paste or
|
||||||
|
replace is marked with the current set, and a deletion marks the character next to it so the
|
||||||
|
line still shows as changed. Undo removes a change and its mark together.
|
||||||
|
- Revised text is tinted with the color of its set, and the status bar shows the set being
|
||||||
|
marked. The menu lists every set with its date.
|
||||||
|
- **Clear Revision Marks…** turns all revised text back into original text (it can be undone);
|
||||||
|
the sets are kept.
|
||||||
|
- **Lock Pages** fixes every page where it starts now. Material added to a page then flows onto
|
||||||
|
A pages (`12A`, `12B`) instead of pushing the following pages, and a page whose material has
|
||||||
|
all been removed is merged with the page before it (`12-13`). Each locked page starts on the
|
||||||
|
same text however the text around it is edited. Choose **Lock Pages** again to unlock: the
|
||||||
|
script is paginated normally, and locking again numbers the pages afresh.
|
||||||
|
|
||||||
|
In the PDF, a revised page gets a header naming its revision and date (`Pink Revision -
|
||||||
|
09/28/26`), and each line changed in that revision an asterisk in the right margin. A page
|
||||||
|
keeps the color of the latest revision that changed it; its older changes are no longer starred.
|
||||||
|
The export dialog can leave revision marks out.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Title page
|
||||||
|
|
||||||
|
`Ctrl+Shift+T` (or the title page button) opens the title page: title, credit ("Written by"),
|
||||||
|
authors, source ("Based on…"), contact, draft date and notes. On the PDF, the title block is
|
||||||
|
centered in the upper half, the contact is at the bottom left and the draft date and notes are
|
||||||
|
at the bottom right.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Saving and files
|
||||||
|
|
||||||
|
**Fountain** (`.fountain`) is the native format. It is plain text, readable in any editor, easy
|
||||||
|
to track with git, and supported by Highland, Fade In, WriterDuet and Arc Studio. Plotzilla also
|
||||||
|
opens `.spmd` and `.txt` files as Fountain.
|
||||||
|
|
||||||
|
**Final Draft** (`.fdx`) files can be opened and saved. Styles, scene numbers, dual dialogue and
|
||||||
|
forced page breaks are kept. Final Draft stores the title page as free text, so on import
|
||||||
|
Plotzilla fills the title page fields from how each line is aligned. In Final Draft files:
|
||||||
|
|
||||||
|
- notes are script notes at their place in the text;
|
||||||
|
- sections and synopses, which Final Draft does not have, are script notes starting with `#` or
|
||||||
|
`=` at the start of the paragraph that follows them, and are read back as sections and
|
||||||
|
synopses;
|
||||||
|
- revised text keeps its revision set, and the sets are named like `Pink Revision - 09/28/26`
|
||||||
|
(a set named by Final Draft, such as `Goldenrod Rev.`, keeps its color);
|
||||||
|
- locked pages and the paper size are not written: save as Fountain to keep them.
|
||||||
|
|
||||||
|
Fountain has no insert or intertitle elements, so Plotzilla writes them the usual way:
|
||||||
|
|
||||||
|
- An insert is written as an all-caps line. It is read back as an insert when it starts like
|
||||||
|
one (`INSERT`, `CLOSE ON`, `ANGLE ON`, `POV`, `WIDE ON`, `BACK TO SCENE`…). Otherwise it
|
||||||
|
comes back as an all-caps action line, which prints the same way.
|
||||||
|
- An intertitle is written as centered text (`> PARIS, 1942 <`). Any all-caps centered text is
|
||||||
|
read back as an intertitle.
|
||||||
|
|
||||||
|
In Final Draft, inserts map to the Shot element and intertitles to centered action.
|
||||||
|
|
||||||
|
Sections (`#`), synopses (`=`) and notes (`[[…]]`) are read and written as Fountain defines
|
||||||
|
them. What Fountain has no syntax for is stored in boneyard comments, which other Fountain apps
|
||||||
|
ignore:
|
||||||
|
|
||||||
|
- revised text is wrapped in `/*rev 2*/…/*/rev*/`, where the number is the revision set;
|
||||||
|
- a locked page starts at `/*page 12*/`;
|
||||||
|
- the paper size, the revision sets and whether revisions are marked and pages locked are kept
|
||||||
|
in one `/* Plotzilla {…} */` line at the end of the file.
|
||||||
|
|
||||||
|
A forced page break is written `===` on its own line. A script that uses none of these features
|
||||||
|
is written exactly as before. Other boneyard comments in a Fountain file are ignored when it is
|
||||||
|
opened, so they are lost when Plotzilla saves it.
|
||||||
|
|
||||||
|
**Autosave** is on by default; turn it off with the switch at the bottom of the scene navigator.
|
||||||
|
When it is on, Plotzilla saves the script to its file 1.2 seconds after your last keystroke. A
|
||||||
|
script that has no file yet is backed up to `~/.local/share/plotzilla/recovery.fountain`, and on
|
||||||
|
the next launch Plotzilla offers to restore it.
|
||||||
|
|
||||||
|
Before closing the window, creating a new script or opening another one with unsaved changes,
|
||||||
|
Plotzilla asks whether to discard them.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
A script can be opened from the command line: `plotzilla path/to/script.fountain`.
|
||||||
|
|
||||||
|
## Exporting
|
||||||
|
|
||||||
|
**PDF** (`Ctrl+P`): US Letter or A4, Courier 12 pt, 10 characters per inch, 6 lines per inch.
|
||||||
|
The export dialog can include the title page, print scene numbers in both margins (for a
|
||||||
|
shooting script) and, when the script has revisions, print the revision headers and asterisks.
|
||||||
|
The PDF uses the standard Courier fonts built into every PDF reader, and its properties carry
|
||||||
|
the title and author.
|
||||||
|
|
||||||
|
The **paper** size is chosen in the export dialog and saved with the script, because it changes
|
||||||
|
the pagination: the editor shows the A4 page and its page breaks as soon as it is chosen. A4
|
||||||
|
keeps the same margins and text widths as US Letter; the longer page holds 58 lines instead of
|
||||||
|
54.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
| Element | Position | Width |
|
||||||
|
|---|---|---|
|
||||||
|
| Scene heading, action | 1.5" from the left edge | 60 characters |
|
||||||
|
| Character | 3.7" | 38 characters |
|
||||||
|
| Parenthetical | 3.1", hanging indent | 25 characters |
|
||||||
|
| Dialogue | 2.5" | 35 characters |
|
||||||
|
| Transition | right-aligned at 7.5" | |
|
||||||
|
| Insert / shot | 1.5", capitals, not numbered | 60 characters |
|
||||||
|
| Intertitle | centered, capitals | 60 characters |
|
||||||
|
| Dual dialogue | columns at 1.5" and 4.5" | 27 and 28 characters |
|
||||||
|
|
||||||
|
The title page and first pages of a sample script, as exported:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The standard Courier fonts cover Western European characters (accents, curly quotes, dashes).
|
||||||
|
Other characters, such as Greek, Cyrillic or Asian scripts, are printed as `?`.
|
||||||
|
|
||||||
|
**Final Draft** (`Ctrl+Shift+E`): writes an `.fdx` file that opens in Final Draft and other apps
|
||||||
|
that read FDX.
|
||||||
|
|
||||||
|
## Keyboard shortcuts
|
||||||
|
|
||||||
|
| Keys | Action |
|
||||||
|
|---|---|
|
||||||
|
| `Enter` | Next logical element (see [Typing a script](#typing-a-script)) |
|
||||||
|
| `Shift+Enter` | Line break inside the element |
|
||||||
|
| `Ctrl+Enter` | Forced page break |
|
||||||
|
| `Tab` / `Shift+Tab` | Change the element type |
|
||||||
|
| `Ctrl+1` … `Ctrl+9` | Scene heading, action, character, parenthetical, dialogue, transition, insert, intertitle, centered |
|
||||||
|
| `Ctrl+D` | Dual dialogue on or off |
|
||||||
|
| `Ctrl+B` / `Ctrl+I` / `Ctrl+U` | Bold, italic, underline |
|
||||||
|
| `Ctrl+Shift+N` | Note on or off |
|
||||||
|
| `# ` / `= ` at the start of an empty line | Section, synopsis |
|
||||||
|
| `Ctrl+Z` / `Ctrl+Shift+Z` or `Ctrl+Y` | Undo, redo |
|
||||||
|
| `Ctrl+N` / `Ctrl+O` | New script, open |
|
||||||
|
| `Ctrl+S` / `Ctrl+Shift+S` | Save, save as |
|
||||||
|
| `Ctrl+P` / `Ctrl+Shift+E` | Export PDF, export to Final Draft |
|
||||||
|
| `Ctrl+Shift+T` | Title page |
|
||||||
|
| `Ctrl+\` | Show or hide the scene navigator |
|
||||||
|
| `Ctrl+Shift+F` | Focus mode |
|
||||||
|
| `Ctrl+=` / `Ctrl+-` / `Ctrl+0` | Zoom in, zoom out, reset |
|
||||||
|
| `↑` / `↓`, `Enter` or `Tab`, `Esc` | Browse, accept or dismiss suggestions |
|
||||||
|
| `Ctrl+F` / `Ctrl+H` | Find, find and replace |
|
||||||
|
| `F3` / `Shift+F3`, or `Ctrl+G` / `Ctrl+Shift+G` | Next, previous match |
|
||||||
|
| `Enter` / `Shift+Enter` in the find field | Next, previous match |
|
||||||
|
| `Enter` / `Ctrl+Alt+Enter` in the replace field | Replace, replace all |
|
||||||
|
| `F7` | Spell checking on or off |
|
||||||
|
|
||||||
|
## Desktop integration
|
||||||
|
|
||||||
|
- The header bar replaces the system title bar: drag it to move the window and double-click it
|
||||||
|
to maximize. The window buttons follow the desktop's button layout, like other GTK
|
||||||
|
applications: which buttons appear (only close with GNOME's default layout) and on which side.
|
||||||
|
- The window has rounded corners, which become square when maximized, or when no compositor
|
||||||
|
makes the window transparent (some X11 window managers). The header bar dims when the window
|
||||||
|
loses focus.
|
||||||
|
- The interface is always dark. File choosers follow the desktop's light or dark preference
|
||||||
|
(read from the XDG desktop portal, or from GNOME's setting when no portal is running) and
|
||||||
|
switch when it changes; without an explicit preference they keep the desktop's GTK theme.
|
||||||
|
- All text is in English, including the buttons of the system file chooser, whatever the system
|
||||||
|
language.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make test # Go tests
|
||||||
|
make screenshots # regenerate the images of this README (needs Firefox and pdftoppm)
|
||||||
|
make dev # live reload, requires the Wails CLI:
|
||||||
|
# go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
Always build with `make`, or pass `-tags desktop,production,webkit2_41` to `go build`. The Go
|
||||||
|
binary embeds `frontend/dist`, so the frontend has to be built first.
|
||||||
|
|
||||||
|
```
|
||||||
|
main.go, app.go Wails application and the methods the frontend calls
|
||||||
|
desktop_linux.go desktop integration: light/dark preference, window button layout
|
||||||
|
internal/screenplay document model
|
||||||
|
internal/fountain Fountain reader and writer
|
||||||
|
internal/fdx Final Draft reader and writer
|
||||||
|
internal/layout line wrapping and pagination, shared by the editor and the PDF
|
||||||
|
internal/pdf PDF generator with no dependencies
|
||||||
|
internal/spell Hunspell dictionary reader and spell checker
|
||||||
|
frontend/src editor: schema, commands, autocomplete, page breaks, find, spelling,
|
||||||
|
revisions and locked pages, interface
|
||||||
|
screenshots/ images used in this README
|
||||||
|
tools/screenshots the tool behind `make screenshots`
|
||||||
|
```
|
||||||
|
|
||||||
|
Contributor guidelines (architecture, conventions, testing, and Go, TypeScript and CSS
|
||||||
|
practices) are in [AGENTS.md](AGENTS.md).
|
||||||
|
|
||||||
|
## Not supported yet
|
||||||
|
|
||||||
|
Locked pages and the paper size in Final Draft files; characters outside Western European
|
||||||
|
scripts in the PDF.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Plotzilla is free software, released under the GNU General Public License v3.0. See
|
||||||
|
[LICENSE](LICENSE).
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/wailsapp/wails/v2/pkg/runtime"
|
||||||
|
|
||||||
|
"plotzilla/internal/fdx"
|
||||||
|
"plotzilla/internal/fountain"
|
||||||
|
"plotzilla/internal/layout"
|
||||||
|
"plotzilla/internal/pdf"
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
"plotzilla/internal/spell"
|
||||||
|
)
|
||||||
|
|
||||||
|
// App is bound to the frontend: every exported method is callable from JS.
|
||||||
|
type App struct {
|
||||||
|
ctx context.Context
|
||||||
|
dirty bool
|
||||||
|
initialPath string
|
||||||
|
|
||||||
|
// Wails runs each call on its own goroutine: spelling calls share one
|
||||||
|
// loaded dictionary.
|
||||||
|
spellMu sync.Mutex
|
||||||
|
checker *spell.Checker
|
||||||
|
checkerLang string
|
||||||
|
}
|
||||||
|
|
||||||
|
type OpenResult struct {
|
||||||
|
Path string `json:"path"`
|
||||||
|
Document *screenplay.Document `json:"document"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LayoutInfo struct {
|
||||||
|
Pages int `json:"pages"`
|
||||||
|
Breaks []layout.Break `json:"breaks"`
|
||||||
|
Scenes []layout.ScenePage `json:"scenes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SpellInfo struct {
|
||||||
|
Languages []string `json:"languages"`
|
||||||
|
Default string `json:"default"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ExportOptions struct {
|
||||||
|
SceneNumbers bool `json:"sceneNumbers"`
|
||||||
|
TitlePage bool `json:"titlePage"`
|
||||||
|
// Revisions prints revision headers and asterisks.
|
||||||
|
Revisions bool `json:"revisions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var scriptFilters = []runtime.FileFilter{
|
||||||
|
{DisplayName: "Screenplays (*.fountain, *.fdx)", Pattern: "*.fountain;*.fdx;*.spmd;*.txt"},
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewApp() *App { return &App{} }
|
||||||
|
|
||||||
|
func (a *App) startup(ctx context.Context) {
|
||||||
|
a.ctx = ctx
|
||||||
|
followSystemColorScheme()
|
||||||
|
}
|
||||||
|
|
||||||
|
// beforeClose keeps the window open while there are unsaved changes and
|
||||||
|
// lets the frontend ask; it quits again once the user has decided.
|
||||||
|
func (a *App) beforeClose(ctx context.Context) bool {
|
||||||
|
if !a.dirty {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
runtime.EventsEmit(a.ctx, "confirm-close")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) NewDocument() *screenplay.Document { return screenplay.New() }
|
||||||
|
|
||||||
|
// InitialFile returns the script passed on the command line, if any.
|
||||||
|
func (a *App) InitialFile() (*OpenResult, error) {
|
||||||
|
if a.initialPath == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
path := a.initialPath
|
||||||
|
a.initialPath = ""
|
||||||
|
return a.load(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) Open() (*OpenResult, error) {
|
||||||
|
path, err := runtime.OpenFileDialog(a.ctx, runtime.OpenDialogOptions{Title: "Open Screenplay", Filters: scriptFilters})
|
||||||
|
if err != nil || path == "" {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return a.load(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) load(path string) (*OpenResult, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var doc *screenplay.Document
|
||||||
|
if strings.EqualFold(filepath.Ext(path), ".fdx") {
|
||||||
|
if doc, err = fdx.Read(bytes.NewReader(data)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
doc = fountain.Parse(string(data))
|
||||||
|
}
|
||||||
|
return &OpenResult{Path: path, Document: doc}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save writes the document to path, asking for one when empty. It returns
|
||||||
|
// the path written, or "" if the user cancelled.
|
||||||
|
func (a *App) Save(doc screenplay.Document, path string) (string, error) {
|
||||||
|
if path == "" {
|
||||||
|
return a.SaveAs(doc, "")
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if strings.EqualFold(filepath.Ext(path), ".fdx") {
|
||||||
|
if err := fdx.Write(&buf, &doc); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
buf.WriteString(fountain.Write(&doc))
|
||||||
|
}
|
||||||
|
// The dirty flag is owned by the frontend (SetDirty): an autosave may
|
||||||
|
// finish after newer edits were made.
|
||||||
|
if err := writeAtomic(path, buf.Bytes()); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) SaveAs(doc screenplay.Document, current string) (string, error) {
|
||||||
|
path, err := a.saveDialog("Save Screenplay", current, ".fountain", scriptFilters)
|
||||||
|
if err != nil || path == "" {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return a.Save(doc, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ExportPDF(doc screenplay.Document, opts ExportOptions, current string) (string, error) {
|
||||||
|
path, err := a.saveDialog("Export PDF", current, ".pdf",
|
||||||
|
[]runtime.FileFilter{{DisplayName: "PDF (*.pdf)", Pattern: "*.pdf"}})
|
||||||
|
if err != nil || path == "" {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var pages []layout.Page
|
||||||
|
if opts.TitlePage && !doc.TitlePage.IsEmpty() {
|
||||||
|
pages = append(pages, layout.TitlePage(doc.TitlePage, doc.Settings.Paper))
|
||||||
|
}
|
||||||
|
pages = append(pages, layout.Paginate(&doc, layout.Options{SceneNumbers: opts.SceneNumbers}).Pages...)
|
||||||
|
pdfOpts := pdf.Options{Title: doc.TitlePage.Title, Author: doc.TitlePage.Author, Paper: doc.Settings.Paper}
|
||||||
|
if opts.Revisions {
|
||||||
|
pdfOpts.Revisions = doc.Settings.Revisions
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err = pdf.Render(&buf, pages, pdfOpts)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, writeAtomic(path, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ExportFDX(doc screenplay.Document, current string) (string, error) {
|
||||||
|
path, err := a.saveDialog("Export to Final Draft", current, ".fdx",
|
||||||
|
[]runtime.FileFilter{{DisplayName: "Final Draft (*.fdx)", Pattern: "*.fdx"}})
|
||||||
|
if err != nil || path == "" {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := fdx.Write(&buf, &doc); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, writeAtomic(path, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paginate returns where pages break so the editor can draw them live.
|
||||||
|
func (a *App) Paginate(doc screenplay.Document) LayoutInfo {
|
||||||
|
res := layout.Paginate(&doc, layout.Options{})
|
||||||
|
return LayoutInfo{Pages: len(res.Pages), Breaks: res.Breaks, Scenes: res.Scenes}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseFountain converts pasted plain text into elements.
|
||||||
|
func (a *App) ParseFountain(text string) []screenplay.Element {
|
||||||
|
return fountain.ParseText(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevisionSet returns revision set n (from 1), dated today.
|
||||||
|
func (a *App) RevisionSet(n int) screenplay.Revision {
|
||||||
|
r := screenplay.RevisionSet(n)
|
||||||
|
r.Date = time.Now().Format("01/02/06")
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) SetDirty(dirty bool) { a.dirty = dirty }
|
||||||
|
|
||||||
|
// dataDir is the XDG data directory (~/.local/share).
|
||||||
|
func dataDir() string {
|
||||||
|
if dir := os.Getenv("XDG_DATA_HOME"); dir != "" {
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
home, _ := os.UserHomeDir()
|
||||||
|
return filepath.Join(home, ".local", "share")
|
||||||
|
}
|
||||||
|
|
||||||
|
// recoveryPath is where untitled scripts are autosaved.
|
||||||
|
func recoveryPath() string { return filepath.Join(dataDir(), "plotzilla", "recovery.fountain") }
|
||||||
|
|
||||||
|
// personalDictionaryPath holds the words added with "Add to Dictionary",
|
||||||
|
// one per line, shared by every language.
|
||||||
|
func personalDictionaryPath() string { return filepath.Join(dataDir(), "plotzilla", "dictionary.txt") }
|
||||||
|
|
||||||
|
// SaveRecovery autosaves a script that has no file yet.
|
||||||
|
func (a *App) SaveRecovery(doc screenplay.Document) error {
|
||||||
|
path := recoveryPath()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writeAtomic(path, []byte(fountain.Write(&doc)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) ClearRecovery() { _ = os.Remove(recoveryPath()) }
|
||||||
|
|
||||||
|
// Recovery returns the autosaved untitled script left by a previous
|
||||||
|
// session, or nil.
|
||||||
|
func (a *App) Recovery() (*OpenResult, error) {
|
||||||
|
path := recoveryPath()
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
res, err := a.load(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
res.Path = ""
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dictionaryDirs lists where Hunspell dictionaries are installed, in the
|
||||||
|
// order Hunspell itself searches them.
|
||||||
|
func dictionaryDirs() []string {
|
||||||
|
var dirs []string
|
||||||
|
if p := os.Getenv("DICPATH"); p != "" {
|
||||||
|
dirs = append(dirs, filepath.SplitList(p)...)
|
||||||
|
}
|
||||||
|
return append(dirs,
|
||||||
|
filepath.Join(dataDir(), "hunspell"),
|
||||||
|
"/usr/local/share/hunspell",
|
||||||
|
"/usr/share/hunspell",
|
||||||
|
"/usr/share/myspell",
|
||||||
|
"/usr/share/myspell/dicts",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SpellLanguages lists the installed dictionaries and the one matching
|
||||||
|
// the system locale.
|
||||||
|
func (a *App) SpellLanguages() SpellInfo {
|
||||||
|
codes := []string{}
|
||||||
|
for _, l := range spell.Available(dictionaryDirs()) {
|
||||||
|
codes = append(codes, l.Code)
|
||||||
|
}
|
||||||
|
locale := os.Getenv("LC_ALL")
|
||||||
|
if locale == "" {
|
||||||
|
locale = os.Getenv("LANG")
|
||||||
|
}
|
||||||
|
return SpellInfo{Languages: codes, Default: spell.Preferred(codes, locale)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// spellChecker returns the checker for lang, loading its dictionary the
|
||||||
|
// first time it is asked for.
|
||||||
|
func (a *App) spellChecker(lang string) (*spell.Checker, error) {
|
||||||
|
a.spellMu.Lock()
|
||||||
|
defer a.spellMu.Unlock()
|
||||||
|
if a.checker != nil && a.checkerLang == lang {
|
||||||
|
return a.checker, nil
|
||||||
|
}
|
||||||
|
langs := spell.Available(dictionaryDirs())
|
||||||
|
i := slices.IndexFunc(langs, func(l spell.Language) bool { return l.Code == lang })
|
||||||
|
if i < 0 {
|
||||||
|
return nil, fmt.Errorf("no %s dictionary installed", lang)
|
||||||
|
}
|
||||||
|
l := langs[i]
|
||||||
|
dict, err := spell.Load(l.Aff, l.Dic)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("loading the %s dictionary: %w", lang, err)
|
||||||
|
}
|
||||||
|
var personal []string
|
||||||
|
if data, err := os.ReadFile(personalDictionaryPath()); err == nil {
|
||||||
|
personal = strings.Fields(string(data))
|
||||||
|
}
|
||||||
|
a.checker, a.checkerLang = spell.NewChecker(dict, personal), lang
|
||||||
|
return a.checker, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SpellCheck returns the misspelled words of the script.
|
||||||
|
func (a *App) SpellCheck(doc screenplay.Document, lang string) ([]spell.Misspelling, error) {
|
||||||
|
c, err := a.spellChecker(lang)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c.Misspellings(&doc), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) SpellSuggest(word, lang string) ([]string, error) {
|
||||||
|
c, err := a.spellChecker(lang)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c.Suggest(word), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddToDictionary accepts word in every language from now on.
|
||||||
|
func (a *App) AddToDictionary(word string) error {
|
||||||
|
word = strings.TrimSpace(word)
|
||||||
|
if word == "" || strings.ContainsAny(word, " \t\n") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
a.spellMu.Lock()
|
||||||
|
defer a.spellMu.Unlock()
|
||||||
|
path := personalDictionaryPath()
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return fmt.Errorf("reading the personal dictionary: %w", err)
|
||||||
|
}
|
||||||
|
words := strings.Fields(string(data))
|
||||||
|
if !slices.Contains(words, word) {
|
||||||
|
words = append(words, word)
|
||||||
|
slices.Sort(words)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := writeAtomic(path, []byte(strings.Join(words, "\n")+"\n")); err != nil {
|
||||||
|
return fmt.Errorf("saving the personal dictionary: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if a.checker != nil {
|
||||||
|
a.checker.Add(word)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WindowFrame describes how the in-app header bar should draw the window.
|
||||||
|
type WindowFrame struct {
|
||||||
|
// Buttons is the desktop's title bar button layout in GTK's
|
||||||
|
// gtk-decoration-layout format, e.g. "appmenu:minimize,maximize,close".
|
||||||
|
Buttons string `json:"buttons"`
|
||||||
|
// Rounded is false when no compositor gives the window transparency.
|
||||||
|
Rounded bool `json:"rounded"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WindowFrame returns the title bar button layout that GTK windows use on
|
||||||
|
// this desktop (GNOME, Plasma, Xfce…) so the in-app header bar can place its
|
||||||
|
// window buttons like every other window, and whether rounded corners can
|
||||||
|
// be drawn.
|
||||||
|
func (a *App) WindowFrame() WindowFrame { return systemWindowFrame() }
|
||||||
|
|
||||||
|
func (a *App) saveDialog(title, current, ext string, filters []runtime.FileFilter) (string, error) {
|
||||||
|
dir, name := "", "untitled"+ext
|
||||||
|
if current != "" {
|
||||||
|
dir = filepath.Dir(current)
|
||||||
|
name = strings.TrimSuffix(filepath.Base(current), filepath.Ext(current)) + ext
|
||||||
|
}
|
||||||
|
path, err := runtime.SaveFileDialog(a.ctx, runtime.SaveDialogOptions{
|
||||||
|
Title: title, DefaultDirectory: dir, DefaultFilename: name, Filters: filters,
|
||||||
|
})
|
||||||
|
if err != nil || path == "" {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
// The GTK dialog does not append the extension on its own.
|
||||||
|
if filepath.Ext(path) == "" {
|
||||||
|
path += ext
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAtomic(path string, data []byte) error {
|
||||||
|
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, werr := tmp.Write(data)
|
||||||
|
cerr := tmp.Close()
|
||||||
|
if err := errors.Join(werr, cerr); err != nil {
|
||||||
|
os.Remove(tmp.Name())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
|
||||||
|
os.Remove(tmp.Name())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp.Name(), path)
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
/*
|
||||||
|
#cgo pkg-config: gtk+-3.0 gio-2.0
|
||||||
|
#include <gtk/gtk.h>
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- colour scheme
|
||||||
|
|
||||||
|
// GTK 3 does not follow the desktop's light/dark preference on its own (only
|
||||||
|
// libadwaita apps do). Apply it to the native parts of the window — file
|
||||||
|
// choosers and message dialogs — and keep following it when it changes.
|
||||||
|
//
|
||||||
|
// The preference comes from the XDG settings portal, which GNOME, KDE Plasma
|
||||||
|
// and other desktops implement; GNOME's own setting is the fallback when no
|
||||||
|
// portal answers. Without an explicit preference, GTK keeps what the desktop
|
||||||
|
// configured for it (settings.ini, XSettings).
|
||||||
|
|
||||||
|
enum { SCHEME_DEFAULT, SCHEME_DARK, SCHEME_LIGHT };
|
||||||
|
|
||||||
|
static gboolean configured_dark;
|
||||||
|
static gboolean have_configured_dark;
|
||||||
|
|
||||||
|
static void apply_scheme(int scheme) {
|
||||||
|
GtkSettings *settings = gtk_settings_get_default();
|
||||||
|
if (settings == NULL) return;
|
||||||
|
if (!have_configured_dark) {
|
||||||
|
g_object_get(settings, "gtk-application-prefer-dark-theme", &configured_dark, NULL);
|
||||||
|
have_configured_dark = TRUE;
|
||||||
|
}
|
||||||
|
gboolean dark = scheme == SCHEME_DARK ? TRUE : scheme == SCHEME_LIGHT ? FALSE : configured_dark;
|
||||||
|
g_object_set(settings, "gtk-application-prefer-dark-theme", dark, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
// GNOME fallback: org.gnome.desktop.interface color-scheme.
|
||||||
|
|
||||||
|
static void apply_gnome_scheme(GSettings *settings) {
|
||||||
|
gchar *scheme = g_settings_get_string(settings, "color-scheme");
|
||||||
|
apply_scheme(g_strcmp0(scheme, "prefer-dark") == 0 ? SCHEME_DARK
|
||||||
|
: g_strcmp0(scheme, "prefer-light") == 0 ? SCHEME_LIGHT
|
||||||
|
: SCHEME_DEFAULT);
|
||||||
|
g_free(scheme);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_gnome_scheme_changed(GSettings *settings, gchar *key, gpointer data) {
|
||||||
|
apply_gnome_scheme(settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void follow_gnome_scheme(void) {
|
||||||
|
GSettingsSchemaSource *source = g_settings_schema_source_get_default();
|
||||||
|
if (source == NULL) return;
|
||||||
|
GSettingsSchema *schema = g_settings_schema_source_lookup(source, "org.gnome.desktop.interface", TRUE);
|
||||||
|
if (schema == NULL) return;
|
||||||
|
gboolean has_key = g_settings_schema_has_key(schema, "color-scheme");
|
||||||
|
g_settings_schema_unref(schema);
|
||||||
|
if (!has_key) return;
|
||||||
|
|
||||||
|
// Never freed: it must outlive the window to keep delivering changes.
|
||||||
|
GSettings *settings = g_settings_new("org.gnome.desktop.interface");
|
||||||
|
apply_gnome_scheme(settings);
|
||||||
|
g_signal_connect(settings, "changed::color-scheme", G_CALLBACK(on_gnome_scheme_changed), NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
// XDG portal: org.freedesktop.appearance color-scheme, 0 = no preference,
|
||||||
|
// 1 = prefer dark, 2 = prefer light.
|
||||||
|
|
||||||
|
#define PORTAL_NAME "org.freedesktop.portal.Desktop"
|
||||||
|
#define PORTAL_PATH "/org/freedesktop/portal/desktop"
|
||||||
|
#define PORTAL_SETTINGS "org.freedesktop.portal.Settings"
|
||||||
|
#define APPEARANCE "org.freedesktop.appearance"
|
||||||
|
|
||||||
|
static int scheme_from_portal(GVariant *value) {
|
||||||
|
// Settings.Read wraps the value in one variant too many; unwrap them all.
|
||||||
|
g_variant_ref(value);
|
||||||
|
while (g_variant_is_of_type(value, G_VARIANT_TYPE_VARIANT)) {
|
||||||
|
GVariant *inner = g_variant_get_variant(value);
|
||||||
|
g_variant_unref(value);
|
||||||
|
value = inner;
|
||||||
|
}
|
||||||
|
guint32 scheme = g_variant_is_of_type(value, G_VARIANT_TYPE_UINT32) ? g_variant_get_uint32(value) : 0;
|
||||||
|
g_variant_unref(value);
|
||||||
|
return scheme == 1 ? SCHEME_DARK : scheme == 2 ? SCHEME_LIGHT : SCHEME_DEFAULT;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_portal_setting_changed(GDBusConnection *bus, const gchar *sender, const gchar *path,
|
||||||
|
const gchar *iface, const gchar *signal, GVariant *params, gpointer data) {
|
||||||
|
const gchar *ns, *key;
|
||||||
|
GVariant *value;
|
||||||
|
g_variant_get(params, "(&s&sv)", &ns, &key, &value);
|
||||||
|
if (g_strcmp0(ns, APPEARANCE) == 0 && g_strcmp0(key, "color-scheme") == 0) apply_scheme(scheme_from_portal(value));
|
||||||
|
g_variant_unref(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_portal_read(GObject *source, GAsyncResult *res, gpointer data) {
|
||||||
|
GDBusConnection *bus = G_DBUS_CONNECTION(source);
|
||||||
|
GVariant *reply = g_dbus_connection_call_finish(bus, res, NULL);
|
||||||
|
if (reply == NULL) {
|
||||||
|
// No portal, or one without the setting.
|
||||||
|
g_object_unref(bus);
|
||||||
|
follow_gnome_scheme();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
GVariant *value;
|
||||||
|
g_variant_get(reply, "(v)", &value);
|
||||||
|
apply_scheme(scheme_from_portal(value));
|
||||||
|
g_variant_unref(value);
|
||||||
|
g_variant_unref(reply);
|
||||||
|
// The connection and the subscription live as long as the process.
|
||||||
|
g_dbus_connection_signal_subscribe(bus, PORTAL_NAME, PORTAL_SETTINGS, "SettingChanged", PORTAL_PATH, APPEARANCE,
|
||||||
|
G_DBUS_SIGNAL_FLAGS_NONE, on_portal_setting_changed, NULL, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void on_session_bus(GObject *source, GAsyncResult *res, gpointer data) {
|
||||||
|
GDBusConnection *bus = g_bus_get_finish(res, NULL);
|
||||||
|
if (bus == NULL) {
|
||||||
|
follow_gnome_scheme();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
g_dbus_connection_call(bus, PORTAL_NAME, PORTAL_PATH, PORTAL_SETTINGS, "Read",
|
||||||
|
g_variant_new("(ss)", APPEARANCE, "color-scheme"), G_VARIANT_TYPE("(v)"),
|
||||||
|
G_DBUS_CALL_FLAGS_NONE, 5000, NULL, on_portal_read, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
static gboolean follow_color_scheme(gpointer data) {
|
||||||
|
g_bus_get(G_BUS_TYPE_SESSION, NULL, on_session_bus, NULL);
|
||||||
|
return G_SOURCE_REMOVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Safe to call from any thread: the work runs on the GTK main loop.
|
||||||
|
static void schedule_follow_color_scheme(void) {
|
||||||
|
g_idle_add(follow_color_scheme, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- window frame
|
||||||
|
|
||||||
|
// What the in-app header bar needs to look like the desktop's other windows:
|
||||||
|
// GTK's decoration layout, which every desktop feeds to GTK in its own way
|
||||||
|
// (GNOME and Plasma settings, XSettings on Xfce, MATE, Cinnamon, settings.ini
|
||||||
|
// elsewhere), and whether the window really is translucent. Without a
|
||||||
|
// compositor the window has no alpha channel and rounded corners would show
|
||||||
|
// black wedges.
|
||||||
|
//
|
||||||
|
// GTK may only be touched on its main loop, while the caller is a Wails
|
||||||
|
// goroutine: the request is answered from an idle callback. It is reference
|
||||||
|
// counted so that a caller giving up on a stalled loop cannot free it under
|
||||||
|
// the callback.
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
GMutex lock;
|
||||||
|
GCond answered;
|
||||||
|
gboolean done;
|
||||||
|
gchar *layout;
|
||||||
|
gboolean translucent;
|
||||||
|
gint refs;
|
||||||
|
} FrameRequest;
|
||||||
|
|
||||||
|
static void frame_request_unref(FrameRequest *req) {
|
||||||
|
if (!g_atomic_int_dec_and_test(&req->refs)) return;
|
||||||
|
g_mutex_clear(&req->lock);
|
||||||
|
g_cond_clear(&req->answered);
|
||||||
|
g_free(req->layout);
|
||||||
|
g_free(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
static gboolean window_is_translucent(void) {
|
||||||
|
GdkScreen *screen = gdk_screen_get_default();
|
||||||
|
if (screen == NULL || !gdk_screen_is_composited(screen)) return FALSE;
|
||||||
|
GdkVisual *rgba = gdk_screen_get_rgba_visual(screen);
|
||||||
|
gboolean translucent = FALSE;
|
||||||
|
GList *windows = gtk_window_list_toplevels();
|
||||||
|
for (GList *w = windows; w != NULL; w = w->next) {
|
||||||
|
if (rgba != NULL && gtk_widget_get_visual(GTK_WIDGET(w->data)) == rgba) translucent = TRUE;
|
||||||
|
}
|
||||||
|
g_list_free(windows);
|
||||||
|
return translucent;
|
||||||
|
}
|
||||||
|
|
||||||
|
static gboolean answer_frame_request(gpointer data) {
|
||||||
|
FrameRequest *req = data;
|
||||||
|
gchar *layout = NULL;
|
||||||
|
GtkSettings *settings = gtk_settings_get_default();
|
||||||
|
if (settings != NULL) g_object_get(settings, "gtk-decoration-layout", &layout, NULL);
|
||||||
|
gboolean translucent = window_is_translucent();
|
||||||
|
|
||||||
|
g_mutex_lock(&req->lock);
|
||||||
|
req->layout = layout;
|
||||||
|
req->translucent = translucent;
|
||||||
|
req->done = TRUE;
|
||||||
|
g_cond_signal(&req->answered);
|
||||||
|
g_mutex_unlock(&req->lock);
|
||||||
|
frame_request_unref(req);
|
||||||
|
return G_SOURCE_REMOVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns FALSE when the main loop did not answer in time. *layout is
|
||||||
|
// g_malloc'ed (possibly NULL) and must be freed with g_free.
|
||||||
|
static gboolean query_window_frame(gchar **layout, gboolean *translucent) {
|
||||||
|
FrameRequest *req = g_new0(FrameRequest, 1);
|
||||||
|
g_mutex_init(&req->lock);
|
||||||
|
g_cond_init(&req->answered);
|
||||||
|
req->refs = 2;
|
||||||
|
g_idle_add(answer_frame_request, req);
|
||||||
|
|
||||||
|
gint64 deadline = g_get_monotonic_time() + 2 * G_TIME_SPAN_SECOND;
|
||||||
|
g_mutex_lock(&req->lock);
|
||||||
|
while (!req->done) {
|
||||||
|
if (!g_cond_wait_until(&req->answered, &req->lock, deadline)) break;
|
||||||
|
}
|
||||||
|
gboolean done = req->done;
|
||||||
|
*layout = done ? g_strdup(req->layout) : NULL;
|
||||||
|
*translucent = done && req->translucent;
|
||||||
|
g_mutex_unlock(&req->lock);
|
||||||
|
frame_request_unref(req);
|
||||||
|
return done;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
import "C"
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
func followSystemColorScheme() {
|
||||||
|
C.schedule_follow_color_scheme()
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultButtonLayout is used when GTK cannot be asked: GNOME's default.
|
||||||
|
const defaultButtonLayout = "appmenu:close"
|
||||||
|
|
||||||
|
// systemWindowFrame reads GTK's title bar button layout and whether the
|
||||||
|
// window is composited. It must not be called from the GTK main thread.
|
||||||
|
func systemWindowFrame() WindowFrame {
|
||||||
|
var layout *C.gchar
|
||||||
|
var translucent C.gboolean
|
||||||
|
if C.query_window_frame(&layout, &translucent) == C.FALSE {
|
||||||
|
return WindowFrame{Buttons: defaultButtonLayout, Rounded: true}
|
||||||
|
}
|
||||||
|
defer C.g_free(C.gpointer(unsafe.Pointer(layout)))
|
||||||
|
buttons := defaultButtonLayout
|
||||||
|
if layout != nil {
|
||||||
|
if s := strings.TrimSpace(C.GoString((*C.char)(unsafe.Pointer(layout)))); s != "" {
|
||||||
|
buttons = s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return WindowFrame{Buttons: buttons, Rounded: translucent != C.FALSE}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Plotzilla</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="topbar" id="topbar">
|
||||||
|
<div class="win-controls" id="win-left"></div>
|
||||||
|
<div class="brand"><span class="logo" data-icon="logo"></span>Plotzilla</div>
|
||||||
|
<div class="doc">
|
||||||
|
<span id="doc-name" class="doc-name">Untitled</span>
|
||||||
|
<span id="save-state" class="save-state"></span>
|
||||||
|
</div>
|
||||||
|
<div class="spacer"></div>
|
||||||
|
|
||||||
|
<nav class="tools">
|
||||||
|
<div class="group">
|
||||||
|
<button data-action="new" data-icon="new" data-tip="New · Ctrl+N"></button>
|
||||||
|
<button data-action="open" data-icon="open" data-tip="Open · Ctrl+O"></button>
|
||||||
|
<button data-action="save" data-icon="save" data-tip="Save · Ctrl+S"></button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button id="type-button" class="type-button" data-tip="Element type · Ctrl+1…9">
|
||||||
|
<span class="type-dot"></span><span id="type-label">Action</span><span class="chev" data-icon="chevron"></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button data-action="bold" data-icon="bold" data-tip="Bold · Ctrl+B"></button>
|
||||||
|
<button data-action="italic" data-icon="italic" data-tip="Italic · Ctrl+I"></button>
|
||||||
|
<button data-action="underline" data-icon="underline" data-tip="Underline · Ctrl+U"></button>
|
||||||
|
<button data-action="note" data-icon="note" data-tip="Note · Ctrl+Shift+N"></button>
|
||||||
|
<button data-action="dual" data-icon="dual" data-tip="Dual dialogue · Ctrl+D"></button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button data-action="find" data-icon="search" data-tip="Find and replace · Ctrl+F"></button>
|
||||||
|
<button data-action="spelling" data-icon="spell" data-tip="Spelling · F7"></button>
|
||||||
|
<button data-action="revisions" data-icon="revisions" data-tip="Revisions and locked pages"></button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button data-action="title" data-icon="title" data-tip="Title page · Ctrl+Shift+T"></button>
|
||||||
|
<button data-action="pdf" data-icon="pdf" data-tip="Export PDF · Ctrl+P"></button>
|
||||||
|
<button data-action="fdx" data-icon="fdx" data-tip="Export to Final Draft · Ctrl+Shift+E"></button>
|
||||||
|
</div>
|
||||||
|
<div class="group">
|
||||||
|
<button data-action="navigator" data-icon="navigator" data-tip="Scenes · Ctrl+\"></button>
|
||||||
|
<button data-action="focus" data-icon="focus" data-tip="Focus mode · Ctrl+Shift+F"></button>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div class="win-controls" id="win-right"></div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<ul id="type-menu" class="menu" hidden></ul>
|
||||||
|
|
||||||
|
<div class="main">
|
||||||
|
<aside class="navigator">
|
||||||
|
<div class="nav-head">
|
||||||
|
<h2>Scenes</h2>
|
||||||
|
<span id="scene-count" class="count"></span>
|
||||||
|
</div>
|
||||||
|
<p id="scene-empty" class="empty">Type <kbd>INT.</kbd> or <kbd>EXT.</kbd> to start your first scene.</p>
|
||||||
|
<ol id="scene-list"></ol>
|
||||||
|
<div class="nav-foot">
|
||||||
|
<label class="switch">
|
||||||
|
<input type="checkbox" id="autosave-toggle" />
|
||||||
|
<span class="track"><span class="thumb"></span></span>
|
||||||
|
Autosave
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div class="workspace">
|
||||||
|
<div class="scroller" id="scroller">
|
||||||
|
<div class="paper" id="paper">
|
||||||
|
<div id="editor"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="search" id="search" data-mode="find" hidden>
|
||||||
|
<button class="search-toggle" data-search="toggle" data-icon="expand" data-tip="Replace · Ctrl+H"></button>
|
||||||
|
<div class="search-fields">
|
||||||
|
<div class="search-row">
|
||||||
|
<input id="search-input" placeholder="Find" autocomplete="off" spellcheck="false" />
|
||||||
|
<span id="search-count" class="search-count"></span>
|
||||||
|
<button data-search="case" data-icon="matchCase" data-tip="Match case"></button>
|
||||||
|
<button data-search="word" data-icon="wholeWord" data-tip="Whole words"></button>
|
||||||
|
<span class="sep"></span>
|
||||||
|
<button data-search="previous" data-icon="up" data-tip="Previous · Shift+Enter"></button>
|
||||||
|
<button data-search="next" data-icon="down" data-tip="Next · Enter"></button>
|
||||||
|
<button data-search="close" data-icon="close" data-tip="Close · Esc"></button>
|
||||||
|
</div>
|
||||||
|
<div class="search-row replace-row">
|
||||||
|
<input id="replace-input" placeholder="Replace with" autocomplete="off" spellcheck="false" />
|
||||||
|
<button class="text-button" data-search="replace" data-tip="Replace · Enter">Replace</button>
|
||||||
|
<button class="text-button" data-search="replaceAll" data-tip="Replace all · Ctrl+Alt+Enter">All</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="hud">
|
||||||
|
<span id="st-type" class="hud-type"></span>
|
||||||
|
<span id="st-hint" class="hud-hint"></span>
|
||||||
|
<span class="sep"></span>
|
||||||
|
<span id="st-pages"></span>
|
||||||
|
<span class="sep"></span>
|
||||||
|
<span id="st-words"></span>
|
||||||
|
<span id="st-rev-sep" class="sep" hidden></span>
|
||||||
|
<span id="st-rev" class="hud-rev" hidden></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<dialog id="title-dialog">
|
||||||
|
<form method="dialog">
|
||||||
|
<h2>Title Page</h2>
|
||||||
|
<label>Title <input name="title" autocomplete="off" /></label>
|
||||||
|
<div class="row">
|
||||||
|
<label>Credit <input name="credit" placeholder="Written by" autocomplete="off" /></label>
|
||||||
|
<label>Author(s) <input name="author" autocomplete="off" /></label>
|
||||||
|
</div>
|
||||||
|
<label>Source <input name="source" placeholder="Based on the novel by…" autocomplete="off" /></label>
|
||||||
|
<div class="row">
|
||||||
|
<label>Contact <textarea name="contact" rows="4"></textarea></label>
|
||||||
|
<label>Draft date <textarea name="draftDate" rows="2"></textarea>
|
||||||
|
<span class="sub">Notes</span><textarea name="notes" rows="1"></textarea>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<menu>
|
||||||
|
<button value="cancel" formnovalidate>Cancel</button>
|
||||||
|
<button value="ok" class="primary">Done</button>
|
||||||
|
</menu>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="export-dialog">
|
||||||
|
<form method="dialog">
|
||||||
|
<h2>Export PDF</h2>
|
||||||
|
<p class="muted"><span id="export-paper">US Letter</span> · Courier 12 pt · standard margins</p>
|
||||||
|
<label class="check"><input type="checkbox" name="titlePage" checked /> Include title page</label>
|
||||||
|
<label class="check"><input type="checkbox" name="sceneNumbers" /> Scene numbers (shooting script)</label>
|
||||||
|
<label class="check"><input type="checkbox" name="revisions" checked /> Revision marks and page headers</label>
|
||||||
|
<label class="inline">Paper
|
||||||
|
<select name="paper">
|
||||||
|
<option value="">US Letter</option>
|
||||||
|
<option value="a4">A4</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<menu>
|
||||||
|
<button value="cancel" formnovalidate>Cancel</button>
|
||||||
|
<button value="ok" class="primary">Export…</button>
|
||||||
|
</menu>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="message-dialog" class="message">
|
||||||
|
<form method="dialog">
|
||||||
|
<h2 id="message-title"></h2>
|
||||||
|
<p id="message-text"></p>
|
||||||
|
<menu>
|
||||||
|
<button value="cancel" id="message-cancel" formnovalidate></button>
|
||||||
|
<button value="ok" id="message-ok" class="primary"></button>
|
||||||
|
</menu>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"name": "plotzilla-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc --noEmit && vite build"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"prosemirror-commands": "^1.6.2",
|
||||||
|
"prosemirror-history": "^1.4.1",
|
||||||
|
"prosemirror-keymap": "^1.2.2",
|
||||||
|
"prosemirror-model": "^1.24.1",
|
||||||
|
"prosemirror-state": "^1.4.3",
|
||||||
|
"prosemirror-transform": "^1.10.2",
|
||||||
|
"prosemirror-view": "^1.37.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "^7.0.2",
|
||||||
|
"vite": "^8.3.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
// Inline suggestions for character cues, scene headings and transitions,
|
||||||
|
// drawn from what the script already contains.
|
||||||
|
import { EditorState, Plugin } from 'prosemirror-state'
|
||||||
|
import { EditorView } from 'prosemirror-view'
|
||||||
|
import { blockText, elementType, flatElements, printedText } from './schema'
|
||||||
|
|
||||||
|
const SCENE_PREFIXES = ['INT. ', 'EXT. ', 'INT./EXT. ', 'EST. ']
|
||||||
|
const TIMES = ['DAY', 'NIGHT', 'CONTINUOUS', 'LATER', 'MOMENTS LATER', 'MORNING', 'EVENING', 'DUSK', 'DAWN', 'SAME']
|
||||||
|
const EXTENSIONS = ["V.O.", 'O.S.', 'O.C.', "CONT'D"]
|
||||||
|
const TRANSITIONS = ['CUT TO:', 'FADE OUT.', 'FADE TO:', 'DISSOLVE TO:', 'SMASH CUT TO:', 'MATCH CUT TO:', 'JUMP CUT TO:', 'FADE TO BLACK.']
|
||||||
|
const SHOTS = ['INSERT - ', 'CLOSE ON ', 'ANGLE ON ', 'POV - ', 'WIDE ON ', 'EXTREME CLOSE UP ON ', 'BACK TO SCENE']
|
||||||
|
const PREFIX_RE = /^(INT\.\/EXT\.|INT\/EXT|I\/E\.?|INT\.|EXT\.|EST\.)\s*/
|
||||||
|
|
||||||
|
interface Suggestions {
|
||||||
|
items: string[]
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
key: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function byFrequency(values: string[], exclude: string): string[] {
|
||||||
|
const counts = new Map<string, number>()
|
||||||
|
for (const v of values) if (v && v !== exclude) counts.set(v, (counts.get(v) ?? 0) + 1)
|
||||||
|
return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([v]) => v)
|
||||||
|
}
|
||||||
|
|
||||||
|
function collect(state: EditorState, skip: number): { names: string[]; locations: string[]; times: string[] } {
|
||||||
|
const names: string[] = []
|
||||||
|
const locations: string[] = []
|
||||||
|
const times: string[] = []
|
||||||
|
flatElements(state.doc).forEach(({ node, pos }) => {
|
||||||
|
if (pos === skip) return
|
||||||
|
const text = printedText(node).toUpperCase().trim()
|
||||||
|
const type = elementType(node)
|
||||||
|
if (type === 'character') {
|
||||||
|
names.push(text.replace(/\^$/, '').replace(/\(.*$/, '').trim())
|
||||||
|
} else if (type === 'scene') {
|
||||||
|
const rest = text.replace(PREFIX_RE, '')
|
||||||
|
const dash = rest.lastIndexOf(' - ')
|
||||||
|
locations.push((dash >= 0 ? rest.slice(0, dash) : rest).trim())
|
||||||
|
if (dash >= 0) times.push(rest.slice(dash + 3).trim())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return { names, locations, times }
|
||||||
|
}
|
||||||
|
|
||||||
|
function compute(state: EditorState): Suggestions | null {
|
||||||
|
const { $from, empty } = state.selection
|
||||||
|
const node = $from.parent
|
||||||
|
if (!empty || $from.parentOffset !== node.content.size) return null
|
||||||
|
const type = elementType(node)
|
||||||
|
const raw = blockText(node)
|
||||||
|
const text = raw.toUpperCase()
|
||||||
|
const start = $from.start()
|
||||||
|
const skip = $from.before()
|
||||||
|
const make = (items: string[], offset: number): Suggestions | null =>
|
||||||
|
items.length ? { items: items.slice(0, 8), from: start + offset, to: start + raw.length, key: `${skip}:${raw}` } : null
|
||||||
|
|
||||||
|
if (type === 'character' && text.trim()) {
|
||||||
|
const paren = text.lastIndexOf('(')
|
||||||
|
if (paren >= 0 && !text.includes(')', paren)) {
|
||||||
|
const typed = text.slice(paren + 1)
|
||||||
|
return make(
|
||||||
|
EXTENSIONS.filter((e) => e.startsWith(typed) && e !== typed).map((e) => e + ')'),
|
||||||
|
paren + 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const names = byFrequency(collect(state, skip).names, '')
|
||||||
|
return make(names.filter((n) => n.startsWith(text) && n !== text), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === 'scene' && text.trim()) {
|
||||||
|
const prefix = text.match(PREFIX_RE)
|
||||||
|
if (!prefix) {
|
||||||
|
return make(SCENE_PREFIXES.filter((p) => p.startsWith(text) && p !== text), 0)
|
||||||
|
}
|
||||||
|
const rest = text.slice(prefix[0].length)
|
||||||
|
const dash = rest.lastIndexOf(' - ')
|
||||||
|
const { locations, times } = collect(state, skip)
|
||||||
|
if (dash < 0) {
|
||||||
|
if (!rest) return null
|
||||||
|
const locs = byFrequency(locations, '').filter((l) => l.startsWith(rest) && l !== rest)
|
||||||
|
return make(locs.map((l) => l + ' - '), prefix[0].length)
|
||||||
|
}
|
||||||
|
const typed = rest.slice(dash + 3)
|
||||||
|
const all = [...new Set([...TIMES, ...byFrequency(times, '')])]
|
||||||
|
return make(all.filter((t) => t.startsWith(typed) && t !== typed), prefix[0].length + dash + 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === 'shot' && text.trim()) {
|
||||||
|
return make(SHOTS.filter((s) => s.startsWith(text) && s !== text), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === 'transition' && text.trim()) {
|
||||||
|
return make(TRANSITIONS.filter((t) => t.startsWith(text) && t !== text), 0)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function autocompletePlugin(): Plugin {
|
||||||
|
const popup = document.createElement('ul')
|
||||||
|
popup.className = 'autocomplete'
|
||||||
|
popup.hidden = true
|
||||||
|
let current: Suggestions | null = null
|
||||||
|
let index = 0
|
||||||
|
let dismissed = ''
|
||||||
|
|
||||||
|
const render = (view: EditorView) => {
|
||||||
|
if (!current || !view.hasFocus()) {
|
||||||
|
popup.hidden = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
popup.replaceChildren(
|
||||||
|
...current.items.map((item, i) => {
|
||||||
|
const li = document.createElement('li')
|
||||||
|
li.textContent = item
|
||||||
|
li.classList.toggle('active', i === index)
|
||||||
|
li.addEventListener('mousedown', (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
index = i
|
||||||
|
accept(view)
|
||||||
|
})
|
||||||
|
return li
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
const coords = view.coordsAtPos(current.from)
|
||||||
|
popup.style.left = `${coords.left}px`
|
||||||
|
popup.style.top = `${coords.bottom + 4}px`
|
||||||
|
popup.hidden = false
|
||||||
|
}
|
||||||
|
|
||||||
|
const accept = (view: EditorView) => {
|
||||||
|
if (!current) return
|
||||||
|
const { from, to, items } = current
|
||||||
|
view.dispatch(view.state.tr.insertText(items[index], from, to).scrollIntoView())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The popup is position: fixed, so it must follow the script when it scrolls.
|
||||||
|
let currentView: EditorView | null = null
|
||||||
|
const reposition = () => {
|
||||||
|
if (currentView && !popup.hidden) render(currentView)
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Plugin({
|
||||||
|
view(view) {
|
||||||
|
currentView = view
|
||||||
|
document.body.appendChild(popup)
|
||||||
|
document.addEventListener('scroll', reposition, true)
|
||||||
|
return {
|
||||||
|
update(view) {
|
||||||
|
const next = compute(view.state)
|
||||||
|
if (next && next.key === dismissed) current = null
|
||||||
|
else {
|
||||||
|
if (!current || !next || next.key !== current.key) index = 0
|
||||||
|
current = next
|
||||||
|
}
|
||||||
|
render(view)
|
||||||
|
},
|
||||||
|
destroy() {
|
||||||
|
document.removeEventListener('scroll', reposition, true)
|
||||||
|
currentView = null
|
||||||
|
popup.remove()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
handleKeyDown(view, event) {
|
||||||
|
if (!current || popup.hidden) return false
|
||||||
|
switch (event.key) {
|
||||||
|
case 'ArrowDown':
|
||||||
|
index = (index + 1) % current.items.length
|
||||||
|
render(view)
|
||||||
|
return true
|
||||||
|
case 'ArrowUp':
|
||||||
|
index = (index - 1 + current.items.length) % current.items.length
|
||||||
|
render(view)
|
||||||
|
return true
|
||||||
|
case 'Enter':
|
||||||
|
case 'Tab':
|
||||||
|
if (event.shiftKey) return false
|
||||||
|
accept(view)
|
||||||
|
return true
|
||||||
|
case 'Escape':
|
||||||
|
dismissed = current.key
|
||||||
|
current = null
|
||||||
|
render(view)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
handleDOMEvents: {
|
||||||
|
blur() {
|
||||||
|
popup.hidden = true
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
// Typed access to the Go methods bound by Wails (window.go.main.App) and to
|
||||||
|
// the Wails runtime.
|
||||||
|
|
||||||
|
export type ElementType =
|
||||||
|
| 'scene'
|
||||||
|
| 'action'
|
||||||
|
| 'character'
|
||||||
|
| 'parenthetical'
|
||||||
|
| 'dialogue'
|
||||||
|
| 'transition'
|
||||||
|
| 'shot'
|
||||||
|
| 'intertitle'
|
||||||
|
| 'centered'
|
||||||
|
| 'section'
|
||||||
|
| 'synopsis'
|
||||||
|
|
||||||
|
export interface Run {
|
||||||
|
text: string
|
||||||
|
b?: boolean
|
||||||
|
i?: boolean
|
||||||
|
u?: boolean
|
||||||
|
/** A writer's note: shown in the editor, never printed. */
|
||||||
|
n?: boolean
|
||||||
|
/** Revision set (from 1) in which the text was added or changed. */
|
||||||
|
rev?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A locked page starting at a rune offset of the element's text. */
|
||||||
|
export interface PageLock {
|
||||||
|
offset: number
|
||||||
|
page: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Element {
|
||||||
|
type: ElementType
|
||||||
|
runs: Run[] | null
|
||||||
|
sceneNumber?: string
|
||||||
|
dual?: boolean
|
||||||
|
/** Depth of a section, from 1. */
|
||||||
|
level?: number
|
||||||
|
/** Forced page break before the element (Fountain "==="). */
|
||||||
|
newPage?: boolean
|
||||||
|
locked?: PageLock[] | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TitlePage {
|
||||||
|
title: string
|
||||||
|
credit: string
|
||||||
|
author: string
|
||||||
|
source: string
|
||||||
|
draftDate: string
|
||||||
|
contact: string
|
||||||
|
notes: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Revision {
|
||||||
|
name: string // "Blue", "Double Pink"
|
||||||
|
color: string // "blue", "pink"…
|
||||||
|
date: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Production settings (screenplay.Settings); every field may be missing. */
|
||||||
|
export interface Settings {
|
||||||
|
paper?: '' | 'a4'
|
||||||
|
revisions?: Revision[] | null
|
||||||
|
revising?: boolean
|
||||||
|
locked?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScriptDocument {
|
||||||
|
titlePage: TitlePage
|
||||||
|
elements: Element[]
|
||||||
|
settings?: Settings
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenResult {
|
||||||
|
path: string
|
||||||
|
document: ScriptDocument
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PageBreak {
|
||||||
|
element: number
|
||||||
|
offset: number
|
||||||
|
page: number
|
||||||
|
/** The printed page number: "12", "12A", "12-13". */
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ScenePage {
|
||||||
|
element: number
|
||||||
|
number: string
|
||||||
|
page: number
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LayoutInfo {
|
||||||
|
pages: number
|
||||||
|
breaks: PageBreak[] | null
|
||||||
|
scenes: ScenePage[] | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A misspelled word: element index as in PageBreak, rune offset and length. */
|
||||||
|
export interface Misspelling {
|
||||||
|
element: number
|
||||||
|
offset: number
|
||||||
|
length: number
|
||||||
|
word: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SpellInfo {
|
||||||
|
languages: string[] | null
|
||||||
|
default: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How to draw the window frame (see WindowFrame in app.go). */
|
||||||
|
export interface WindowFrame {
|
||||||
|
/** GTK decoration layout, e.g. "appmenu:minimize,maximize,close". */
|
||||||
|
buttons: string
|
||||||
|
/** False without a compositor: the window cannot have rounded corners. */
|
||||||
|
rounded: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExportOptions {
|
||||||
|
sceneNumbers: boolean
|
||||||
|
titlePage: boolean
|
||||||
|
revisions: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface GoApp {
|
||||||
|
NewDocument(): Promise<ScriptDocument>
|
||||||
|
InitialFile(): Promise<OpenResult | null>
|
||||||
|
Open(): Promise<OpenResult | null>
|
||||||
|
Save(doc: ScriptDocument, path: string): Promise<string>
|
||||||
|
SaveAs(doc: ScriptDocument, current: string): Promise<string>
|
||||||
|
ExportPDF(doc: ScriptDocument, opts: ExportOptions, current: string): Promise<string>
|
||||||
|
ExportFDX(doc: ScriptDocument, current: string): Promise<string>
|
||||||
|
Paginate(doc: ScriptDocument): Promise<LayoutInfo>
|
||||||
|
ParseFountain(text: string): Promise<Element[] | null>
|
||||||
|
SetDirty(dirty: boolean): Promise<void>
|
||||||
|
SaveRecovery(doc: ScriptDocument): Promise<void>
|
||||||
|
ClearRecovery(): Promise<void>
|
||||||
|
Recovery(): Promise<OpenResult | null>
|
||||||
|
WindowFrame(): Promise<WindowFrame>
|
||||||
|
RevisionSet(n: number): Promise<Revision>
|
||||||
|
SpellLanguages(): Promise<SpellInfo>
|
||||||
|
SpellCheck(doc: ScriptDocument, lang: string): Promise<Misspelling[] | null>
|
||||||
|
SpellSuggest(word: string, lang: string): Promise<string[] | null>
|
||||||
|
AddToDictionary(word: string): Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface WailsRuntime {
|
||||||
|
WindowSetTitle(title: string): void
|
||||||
|
WindowMinimise(): void
|
||||||
|
WindowToggleMaximise(): void
|
||||||
|
WindowIsMaximised(): Promise<boolean>
|
||||||
|
EventsOn(event: string, callback: (...data: unknown[]) => void): () => void
|
||||||
|
Quit(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
go: { main: { App: GoApp } }
|
||||||
|
runtime: WailsRuntime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = new Proxy({} as GoApp, {
|
||||||
|
get: (_, name: string) => (...args: unknown[]) =>
|
||||||
|
(window.go.main.App as unknown as Record<string, (...a: unknown[]) => unknown>)[name](...args),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const runtime = new Proxy({} as WailsRuntime, {
|
||||||
|
get: (_, name: string) => (...args: unknown[]) =>
|
||||||
|
(window.runtime as unknown as Record<string, (...a: unknown[]) => unknown>)[name](...args),
|
||||||
|
})
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
// Screenplay editing behaviour, modelled on Final Draft / Arc Studio:
|
||||||
|
// Enter moves to the element that naturally follows, Tab cycles the current
|
||||||
|
// element's type, and typing is auto-detected where it is unambiguous.
|
||||||
|
import { Command, EditorState, Plugin, TextSelection, Transaction } from 'prosemirror-state'
|
||||||
|
import { Node as PMNode } from 'prosemirror-model'
|
||||||
|
import { toggleMark } from 'prosemirror-commands'
|
||||||
|
import { undo, redo } from 'prosemirror-history'
|
||||||
|
import type { ElementType } from './backend'
|
||||||
|
import { ELEMENT_TYPES, blockText, dualNode, elementType, schema } from './schema'
|
||||||
|
|
||||||
|
/** Element created by Enter at the end of a non-empty element. */
|
||||||
|
export const NEXT_ON_ENTER: Record<ElementType, ElementType> = {
|
||||||
|
scene: 'action',
|
||||||
|
action: 'action',
|
||||||
|
character: 'dialogue',
|
||||||
|
parenthetical: 'dialogue',
|
||||||
|
dialogue: 'action',
|
||||||
|
transition: 'scene',
|
||||||
|
shot: 'action',
|
||||||
|
intertitle: 'action',
|
||||||
|
centered: 'action',
|
||||||
|
section: 'scene',
|
||||||
|
synopsis: 'action',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enter on an empty element changes its type instead of adding a line. */
|
||||||
|
const RETYPE_ON_EMPTY_ENTER: Record<ElementType, ElementType> = {
|
||||||
|
scene: 'action',
|
||||||
|
action: 'scene',
|
||||||
|
character: 'action',
|
||||||
|
parenthetical: 'dialogue',
|
||||||
|
dialogue: 'action',
|
||||||
|
transition: 'action',
|
||||||
|
shot: 'action',
|
||||||
|
intertitle: 'action',
|
||||||
|
centered: 'action',
|
||||||
|
section: 'action',
|
||||||
|
synopsis: 'action',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TAB: Record<ElementType, ElementType> = {
|
||||||
|
action: 'character',
|
||||||
|
character: 'transition',
|
||||||
|
transition: 'scene',
|
||||||
|
scene: 'action',
|
||||||
|
dialogue: 'parenthetical',
|
||||||
|
parenthetical: 'dialogue',
|
||||||
|
shot: 'action',
|
||||||
|
intertitle: 'action',
|
||||||
|
centered: 'action',
|
||||||
|
section: 'action',
|
||||||
|
synopsis: 'action',
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHIFT_TAB: Record<ElementType, ElementType> = {
|
||||||
|
action: 'scene',
|
||||||
|
scene: 'transition',
|
||||||
|
transition: 'character',
|
||||||
|
character: 'action',
|
||||||
|
dialogue: 'character',
|
||||||
|
parenthetical: 'dialogue',
|
||||||
|
shot: 'action',
|
||||||
|
intertitle: 'action',
|
||||||
|
centered: 'action',
|
||||||
|
section: 'action',
|
||||||
|
synopsis: 'action',
|
||||||
|
}
|
||||||
|
|
||||||
|
const SCENE_PREFIX = /^(int|ext|est|int\.?\/ext|i\/e)\.?\s$/i
|
||||||
|
const SHOT_PREFIX = /^insert(\s-|:)?\s$/i
|
||||||
|
// Fountain's outline markers, typed at the start of an empty line.
|
||||||
|
const SECTION_PREFIX = /^(#{1,6}) $/
|
||||||
|
const SYNOPSIS_PREFIX = /^= $/
|
||||||
|
const TRANSITION = /^[^a-z]+ TO:$/
|
||||||
|
|
||||||
|
function isBlank(node: PMNode): boolean {
|
||||||
|
const text = blockText(node)
|
||||||
|
return text.trim() === '' || (elementType(node) === 'parenthetical' && text.trim() === '()')
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Changes the type of the element at pos, adding or removing the
|
||||||
|
* parentheses that a parenthetical carries.
|
||||||
|
*/
|
||||||
|
export function retype(tr: Transaction, pos: number, type: ElementType): Transaction {
|
||||||
|
const node = tr.doc.nodeAt(pos)!
|
||||||
|
const old = elementType(node)
|
||||||
|
if (old === type) return tr
|
||||||
|
tr.setNodeMarkup(pos, undefined, { ...node.attrs, type })
|
||||||
|
const text = blockText(node)
|
||||||
|
const start = pos + 1
|
||||||
|
const end = start + node.content.size
|
||||||
|
if (type === 'parenthetical') {
|
||||||
|
if (!text.startsWith('(')) {
|
||||||
|
tr.insertText(')', end)
|
||||||
|
tr.insertText('(', start)
|
||||||
|
const size = tr.doc.nodeAt(pos)!.content.size
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, start + size - 1))
|
||||||
|
}
|
||||||
|
} else if (old === 'parenthetical') {
|
||||||
|
if (text.endsWith(')')) tr.delete(end - 1, end)
|
||||||
|
if (text.startsWith('(')) tr.delete(start, start + 1)
|
||||||
|
}
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the text between from and to (inside one element), keeping the
|
||||||
|
* bold, italic and underline of the text it replaces.
|
||||||
|
*/
|
||||||
|
export function replaceText(tr: Transaction, from: number, to: number, text: string): Transaction {
|
||||||
|
if (!text) return tr.delete(from, to)
|
||||||
|
const marks = tr.doc.nodeAt(from)?.marks ?? []
|
||||||
|
return tr.replaceWith(from, to, schema.text(text, marks))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setType(type: ElementType): Command {
|
||||||
|
return (state, dispatch) => {
|
||||||
|
const { $from, $to } = state.selection
|
||||||
|
if (dispatch) {
|
||||||
|
const tr = state.tr
|
||||||
|
if ($from.sameParent($to)) {
|
||||||
|
retype(tr, $from.before(), type)
|
||||||
|
} else {
|
||||||
|
state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
|
||||||
|
if (node.type === schema.nodes.element) {
|
||||||
|
tr.setNodeMarkup(pos, undefined, { ...node.attrs, type })
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cycle(map: Record<ElementType, ElementType>): Command {
|
||||||
|
return (state, dispatch) => {
|
||||||
|
const type = elementType(state.selection.$from.parent)
|
||||||
|
return setType(map[type])(state, dispatch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enter: Command = (state, dispatch) => {
|
||||||
|
const tr = state.tr
|
||||||
|
if (!state.selection.empty) tr.deleteSelection()
|
||||||
|
const $pos = tr.selection.$from
|
||||||
|
const node = $pos.parent
|
||||||
|
const pos = $pos.before()
|
||||||
|
let type = elementType(node)
|
||||||
|
|
||||||
|
// Inside a dual dialogue, finishing a column moves on: the left column
|
||||||
|
// hands over to the right one, the right column exits below the block.
|
||||||
|
const colDepth = $pos.depth - 1
|
||||||
|
if ($pos.node(colDepth).type === schema.nodes.column) {
|
||||||
|
const text = blockText(node)
|
||||||
|
const atEnd =
|
||||||
|
$pos.parentOffset === node.content.size ||
|
||||||
|
(type === 'parenthetical' && text.endsWith(')') && $pos.parentOffset === node.content.size - 1)
|
||||||
|
const blank = isBlank(node)
|
||||||
|
if (blank || (atEnd && type === 'dialogue')) {
|
||||||
|
if (dispatch) {
|
||||||
|
const dual = $pos.node(colDepth - 1)
|
||||||
|
const dualPos = $pos.before(colDepth - 1)
|
||||||
|
const isRight = $pos.index(colDepth - 1) === 1
|
||||||
|
const rightStart = dualPos + 1 + dual.child(0).nodeSize + 1 // first element of the right column
|
||||||
|
const dualEnd = dualPos + dual.nodeSize
|
||||||
|
if (blank && $pos.node(colDepth).childCount > 1) tr.delete(pos, pos + node.nodeSize)
|
||||||
|
if (isRight) {
|
||||||
|
const at = tr.mapping.map(dualEnd)
|
||||||
|
tr.insert(at, schema.nodes.element.create({ type: 'action' }))
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, at + 1))
|
||||||
|
} else {
|
||||||
|
const at = tr.mapping.map(rightStart)
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, at + 1 + tr.doc.nodeAt(at)!.content.size))
|
||||||
|
}
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isBlank(node)) {
|
||||||
|
if (dispatch) {
|
||||||
|
if (type === 'parenthetical') tr.delete(pos + 1, pos + 1 + node.content.size)
|
||||||
|
dispatch(retype(tr, pos, RETYPE_ON_EMPTY_ENTER[type]).scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = blockText(node)
|
||||||
|
if (type === 'action' && TRANSITION.test(text)) {
|
||||||
|
tr.setNodeMarkup(pos, undefined, { ...node.attrs, type: 'transition' })
|
||||||
|
type = 'transition'
|
||||||
|
}
|
||||||
|
// Inside a parenthetical, the closing ")" counts as the end.
|
||||||
|
const atEnd =
|
||||||
|
$pos.parentOffset === node.content.size ||
|
||||||
|
(type === 'parenthetical' && text.endsWith(')') && $pos.parentOffset === node.content.size - 1)
|
||||||
|
|
||||||
|
if (dispatch) {
|
||||||
|
if (atEnd) {
|
||||||
|
const after = pos + node.nodeSize
|
||||||
|
tr.insert(after, schema.nodes.element.create({ type: NEXT_ON_ENTER[type] }))
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, after + 1))
|
||||||
|
} else {
|
||||||
|
// The second half never inherits a forced page break.
|
||||||
|
tr.split($pos.pos, 1, [{ type: schema.nodes.element, attrs: { type, sceneNumber: '', level: node.attrs.level } }])
|
||||||
|
}
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const inDialogue = (t: ElementType | null) => t === 'parenthetical' || t === 'dialogue'
|
||||||
|
|
||||||
|
/** Top-level child range [start, end) of the dialogue block containing index. */
|
||||||
|
function dialogueBlockAt(doc: PMNode, index: number): [number, number] | null {
|
||||||
|
const t = (i: number) => {
|
||||||
|
const n = doc.child(i)
|
||||||
|
return n.type === schema.nodes.element ? elementType(n) : null
|
||||||
|
}
|
||||||
|
let start = index
|
||||||
|
while (start > 0 && inDialogue(t(start))) start--
|
||||||
|
if (t(start) !== 'character') return null
|
||||||
|
let end = start + 1
|
||||||
|
while (end < doc.childCount && inDialogue(t(end))) end++
|
||||||
|
return [start, end]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ctrl+D: puts the dialogue under the cursor side by side with the next (or
|
||||||
|
* previous) one. Without a neighbour, opens an empty right column. Inside a
|
||||||
|
* dual dialogue, splits it back into two blocks.
|
||||||
|
*/
|
||||||
|
export const toggleDual: Command = (state, dispatch) => {
|
||||||
|
const { $from } = state.selection
|
||||||
|
const doc = state.doc
|
||||||
|
for (let d = $from.depth; d > 0; d--) {
|
||||||
|
const dual = $from.node(d)
|
||||||
|
if (dual.type !== schema.nodes.dual) continue
|
||||||
|
if (dispatch) {
|
||||||
|
const pos = $from.before(d)
|
||||||
|
const inRight = $from.index(d) === 1
|
||||||
|
const tr = state.tr.replaceWith(pos, pos + dual.nodeSize, dual.child(0).content.append(dual.child(1).content))
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, $from.pos - (inRight ? 4 : 2)))
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if ($from.depth !== 1) return false
|
||||||
|
const cur = dialogueBlockAt(doc, $from.index(0))
|
||||||
|
if (!cur) return false
|
||||||
|
let left = cur
|
||||||
|
let right: [number, number] | null = null
|
||||||
|
const next = cur[1] < doc.childCount ? dialogueBlockAt(doc, cur[1]) : null
|
||||||
|
const prev = cur[0] > 0 ? dialogueBlockAt(doc, cur[0] - 1) : null
|
||||||
|
if (next && next[0] === cur[1]) right = next
|
||||||
|
else if (prev && prev[1] === cur[0]) [left, right] = [prev, cur]
|
||||||
|
|
||||||
|
if (dispatch) {
|
||||||
|
const posOf = (i: number) => {
|
||||||
|
let p = 0
|
||||||
|
for (let k = 0; k < i; k++) p += doc.child(k).nodeSize
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
const nodes = ([a, b]: [number, number]) => Array.from({ length: b - a }, (_, k) => doc.child(a + k))
|
||||||
|
const from = posOf(left[0])
|
||||||
|
const mid = posOf(left[1])
|
||||||
|
const to = posOf((right ?? left)[1])
|
||||||
|
const rightNodes = right ? nodes(right) : [schema.nodes.element.create({ type: 'character' })]
|
||||||
|
const tr = state.tr.replaceWith(from, to, dualNode(nodes(left), rightNodes))
|
||||||
|
// dual + column open before the left content; +2 more for the right column.
|
||||||
|
const sel = !right ? mid + 5 : $from.pos + ($from.pos >= mid ? 4 : 2)
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, sel))
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ctrl+Enter: forces a page break at the cursor, like "===" in Fountain. At
|
||||||
|
* the start of an element (or on an empty one) it toggles the break before
|
||||||
|
* it; elsewhere it splits the element, or opens the next one, on a new page.
|
||||||
|
* In a dialogue block, or a dual dialogue, it toggles the break before the
|
||||||
|
* whole block: dialogue is never split by hand.
|
||||||
|
*/
|
||||||
|
export const pageBreak: Command = (state, dispatch) => {
|
||||||
|
const { $from } = state.selection
|
||||||
|
if ($from.parent.type !== schema.nodes.element) return false
|
||||||
|
const doc = state.doc
|
||||||
|
let pos = $from.before()
|
||||||
|
let splittable = $from.depth === 1
|
||||||
|
if ($from.depth > 1) {
|
||||||
|
pos = $from.before(1) + 2 // first element of the left column
|
||||||
|
splittable = false
|
||||||
|
} else if (inDialogue(elementType($from.parent))) {
|
||||||
|
const block = dialogueBlockAt(doc, $from.index(0))
|
||||||
|
if (block) {
|
||||||
|
pos = 0
|
||||||
|
for (let k = 0; k < block[0]; k++) pos += doc.child(k).nodeSize
|
||||||
|
splittable = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const node = doc.nodeAt(pos)!
|
||||||
|
if (dispatch) {
|
||||||
|
const tr = state.tr
|
||||||
|
if (!state.selection.empty) tr.deleteSelection()
|
||||||
|
const $pos = tr.selection.$from
|
||||||
|
const type = elementType(node)
|
||||||
|
if (splittable && $pos.parentOffset > 0 && !isBlank(node)) {
|
||||||
|
if ($pos.parentOffset === $pos.parent.content.size) {
|
||||||
|
const after = pos + $pos.parent.nodeSize
|
||||||
|
tr.insert(after, schema.nodes.element.create({ type: NEXT_ON_ENTER[type], newPage: true }))
|
||||||
|
tr.setSelection(TextSelection.create(tr.doc, after + 1))
|
||||||
|
} else {
|
||||||
|
const attrs = { type, sceneNumber: '', level: node.attrs.level, newPage: true }
|
||||||
|
tr.split($pos.pos, 1, [{ type: schema.nodes.element, attrs }])
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tr.setNodeMarkup(pos, undefined, { ...node.attrs, newPage: !node.attrs.newPage })
|
||||||
|
}
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const hardBreak: Command =(state, dispatch) => {
|
||||||
|
if (dispatch) dispatch(state.tr.replaceSelectionWith(schema.nodes.hard_break.create()).scrollIntoView())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
export function screenplayKeys(): Record<string, Command> {
|
||||||
|
const keys: Record<string, Command> = {
|
||||||
|
Enter: enter,
|
||||||
|
'Shift-Enter': hardBreak,
|
||||||
|
'Mod-Enter': pageBreak,
|
||||||
|
Tab: cycle(TAB),
|
||||||
|
'Shift-Tab': cycle(SHIFT_TAB),
|
||||||
|
'Mod-b': toggleMark(schema.marks.bold),
|
||||||
|
'Mod-i': toggleMark(schema.marks.italic),
|
||||||
|
'Mod-u': toggleMark(schema.marks.underline),
|
||||||
|
'Mod-Shift-n': toggleMark(schema.marks.note),
|
||||||
|
'Mod-z': undo,
|
||||||
|
'Mod-Shift-z': redo,
|
||||||
|
'Mod-y': redo,
|
||||||
|
'Mod-d': toggleDual,
|
||||||
|
}
|
||||||
|
ELEMENT_TYPES.slice(0, 9).forEach((type, i) => {
|
||||||
|
keys[`Mod-${i + 1}`] = setType(type)
|
||||||
|
})
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Auto-detection while typing: "INT. " in an action becomes a scene heading,
|
||||||
|
* "INSERT " an insert, "# " (or "## "…) a section and "= " a synopsis, and "("
|
||||||
|
* at the start of an empty dialogue opens a parenthetical.
|
||||||
|
*/
|
||||||
|
export function autoFormatPlugin(): Plugin {
|
||||||
|
return new Plugin({
|
||||||
|
props: {
|
||||||
|
handleTextInput(view, from, to, text) {
|
||||||
|
const { $from } = view.state.selection
|
||||||
|
const node = $from.parent
|
||||||
|
if (text === '(' && elementType(node) === 'dialogue' && node.content.size === 0 && from === to) {
|
||||||
|
view.dispatch(retype(view.state.tr, $from.before(), 'parenthetical').scrollIntoView())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
},
|
||||||
|
},
|
||||||
|
appendTransaction(trs, _old, state: EditorState) {
|
||||||
|
if (!trs.some((t) => t.docChanged)) return null
|
||||||
|
const { $from } = state.selection
|
||||||
|
const node = $from.parent
|
||||||
|
if (node.type !== schema.nodes.element) return null
|
||||||
|
const current = elementType(node)
|
||||||
|
const text = blockText(node)
|
||||||
|
if (current === 'action' || current === 'scene') {
|
||||||
|
const section = SECTION_PREFIX.exec(text)
|
||||||
|
if (section || SYNOPSIS_PREFIX.test(text)) {
|
||||||
|
const pos = $from.before()
|
||||||
|
const attrs = { ...node.attrs, type: section ? 'section' : 'synopsis', level: section?.[1].length ?? 1 }
|
||||||
|
return state.tr.setNodeMarkup(pos, undefined, attrs).delete(pos + 1, pos + 1 + node.content.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (current !== 'action') return null
|
||||||
|
const type = SCENE_PREFIX.test(text) ? 'scene' : SHOT_PREFIX.test(text) ? 'shot' : null
|
||||||
|
if (!type) return null
|
||||||
|
return state.tr.setNodeMarkup($from.before(), undefined, { ...node.attrs, type })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// View decorations: live page breaks computed by the Go layout engine, and a
|
||||||
|
// placeholder naming the type of the empty element under the cursor.
|
||||||
|
import { Plugin, PluginKey } from 'prosemirror-state'
|
||||||
|
import { Decoration, DecorationSet } from 'prosemirror-view'
|
||||||
|
import { Node as PMNode } from 'prosemirror-model'
|
||||||
|
import type { PageBreak } from './backend'
|
||||||
|
import { LABELS, blockText, elementType, flatElements, schema, utf16Offset } from './schema'
|
||||||
|
|
||||||
|
export { utf16Offset }
|
||||||
|
|
||||||
|
export const pagesKey = new PluginKey<DecorationSet>('pages')
|
||||||
|
|
||||||
|
function pageWidget(page: string, inline: boolean, type: string, forced = false): HTMLElement {
|
||||||
|
const el = document.createElement(inline ? 'span' : 'div')
|
||||||
|
el.className = `page-break${inline ? ` inline in-${type}` : ''}${forced ? ' forced' : ''}`
|
||||||
|
el.contentEditable = 'false'
|
||||||
|
if (forced) {
|
||||||
|
const tag = document.createElement('span')
|
||||||
|
tag.className = 'page-forced'
|
||||||
|
tag.textContent = 'Page break'
|
||||||
|
el.appendChild(tag)
|
||||||
|
}
|
||||||
|
const num = document.createElement('span')
|
||||||
|
num.className = 'page-number'
|
||||||
|
num.textContent = `${page}.`
|
||||||
|
el.appendChild(num)
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPageDecorations(doc: PMNode, breaks: PageBreak[]): DecorationSet {
|
||||||
|
const flat = flatElements(doc)
|
||||||
|
const decos: Decoration[] = []
|
||||||
|
for (const br of breaks) {
|
||||||
|
const entry = flat[br.element]
|
||||||
|
if (!entry) continue
|
||||||
|
const { node, pos, dualPos } = entry
|
||||||
|
const type = elementType(node)
|
||||||
|
const label = br.label || String(br.page)
|
||||||
|
// A forced break (Ctrl+Enter) says so; the dual dialogue's is on its first element.
|
||||||
|
const forced = br.offset === 0 && !!(dualPos !== null ? doc.nodeAt(dualPos + 2)?.attrs.newPage : node.attrs.newPage)
|
||||||
|
const key = `pb${br.page}${forced ? 'f' : ''}`
|
||||||
|
if (dualPos !== null) {
|
||||||
|
// A dual dialogue is never split: the page starts above the whole block.
|
||||||
|
decos.push(Decoration.widget(dualPos, () => pageWidget(label, false, type, forced), { side: -1, key }))
|
||||||
|
} else if (br.offset === 0) {
|
||||||
|
decos.push(Decoration.widget(pos, () => pageWidget(label, false, type, forced), { side: -1, key }))
|
||||||
|
} else {
|
||||||
|
const at = pos + 1 + utf16Offset(blockText(node), br.offset)
|
||||||
|
decos.push(
|
||||||
|
Decoration.widget(at, () => pageWidget(label, true, type), {
|
||||||
|
side: -1,
|
||||||
|
key: `pb${br.page}-${type}`,
|
||||||
|
ignoreSelection: true,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return DecorationSet.create(doc, decos)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pagesPlugin(): Plugin<DecorationSet> {
|
||||||
|
return new Plugin<DecorationSet>({
|
||||||
|
key: pagesKey,
|
||||||
|
state: {
|
||||||
|
init: () => DecorationSet.empty,
|
||||||
|
apply(tr, set) {
|
||||||
|
const fresh = tr.getMeta(pagesKey) as DecorationSet | undefined
|
||||||
|
return fresh ?? set.map(tr.mapping, tr.doc)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
decorations: (state) => pagesKey.getState(state),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function placeholderPlugin(): Plugin {
|
||||||
|
return new Plugin({
|
||||||
|
props: {
|
||||||
|
decorations(state) {
|
||||||
|
const { $from } = state.selection
|
||||||
|
const node = $from.parent
|
||||||
|
if (node.type !== schema.nodes.element || node.content.size > 0) return null
|
||||||
|
const pos = $from.before()
|
||||||
|
return DecorationSet.create(state.doc, [
|
||||||
|
Decoration.node(pos, pos + node.nodeSize, {
|
||||||
|
class: 'is-empty',
|
||||||
|
'data-placeholder': LABELS[elementType(node)],
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Stroke icons in the Lucide style (24×24 grid, ISC licence).
|
||||||
|
const paths: Record<string, string> = {
|
||||||
|
logo: '<path d="M4 11v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8H4Z"/><path d="m4 11-.88-2.87a2 2 0 0 1 1.33-2.5l11.48-3.5a2 2 0 0 1 2.5 1.32l.87 2.87L4 11.01Z"/><path d="m6.6 4.99 3.38 4.2"/><path d="m11.86 3.38 3.38 4.2"/>',
|
||||||
|
new: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M12 18v-6"/><path d="M9 15h6"/>',
|
||||||
|
open: '<path d="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"/>',
|
||||||
|
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8"/><path d="M7 3v5h8"/>',
|
||||||
|
bold: '<path d="M6 12h9a4 4 0 0 1 0 8H6z"/><path d="M6 4h8a4 4 0 0 1 0 8H6z"/>',
|
||||||
|
italic: '<path d="M19 4h-9"/><path d="M14 20H5"/><path d="M15 4 9 20"/>',
|
||||||
|
underline: '<path d="M6 4v6a6 6 0 0 0 12 0V4"/><path d="M4 20h16"/>',
|
||||||
|
dual: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16"/><path d="M6 9h3M6 13h3M15 9h3M15 13h3"/>',
|
||||||
|
title: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>',
|
||||||
|
pdf: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>',
|
||||||
|
fdx: '<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><path d="m16 6-4-4-4 4"/><path d="M12 2v13"/>',
|
||||||
|
navigator: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/>',
|
||||||
|
focus: '<path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/>',
|
||||||
|
search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
|
||||||
|
replace: '<path d="M14 4a2 2 0 0 1 2-2"/><path d="M16 10a2 2 0 0 1-2-2"/><path d="M20 2a2 2 0 0 1 2 2"/><path d="M22 8a2 2 0 0 1-2 2"/><path d="m3 7 3 3 3-3"/><path d="M6 10V5a3 3 0 0 1 3-3h1"/><rect x="2" y="14" width="8" height="8" rx="2"/>',
|
||||||
|
matchCase: '<path d="m3 15 4-8 4 8"/><path d="M4 13h6"/><circle cx="18" cy="12" r="3"/><path d="M21 9v6"/>',
|
||||||
|
wholeWord: '<circle cx="7" cy="12" r="3"/><path d="M10 9v6"/><circle cx="17" cy="12" r="3"/><path d="M14 7v8"/><path d="M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1"/>',
|
||||||
|
up: '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
|
||||||
|
down: '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
|
||||||
|
expand: '<path d="m9 18 6-6-6-6"/>',
|
||||||
|
note: '<path d="M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z"/><path d="M15 3v6h6"/><path d="M7 13h6"/><path d="M7 17h4"/>',
|
||||||
|
revisions: '<path d="M12 20h9"/><path d="M16.38 3.62a1 1 0 0 1 3 3L7.37 18.64a2 2 0 0 1-.86.5l-2.87.84a.5.5 0 0 1-.62-.62l.84-2.87a2 2 0 0 1 .5-.86z"/><path d="m15 5 3 3"/>',
|
||||||
|
spell: '<path d="m6 16 6-12 6 12"/><path d="M8 12h8"/><path d="m16 20 2 2 4-4"/>',
|
||||||
|
check: '<path d="M20 6 9 17l-5-5"/>',
|
||||||
|
chevron: '<path d="m6 9 6 6 6-6"/>',
|
||||||
|
close: '<path d="M17 7 7 17"/><path d="m7 7 10 10"/>',
|
||||||
|
minimize: '<path d="M7 16h10"/>',
|
||||||
|
maximize: '<rect x="6.5" y="6.5" width="11" height="11" rx="1.5"/>',
|
||||||
|
restore: '<rect x="5.5" y="9" width="9.5" height="9.5" rx="1.5"/><path d="M9 9V7a1.5 1.5 0 0 1 1.5-1.5H17A1.5 1.5 0 0 1 18.5 7v6.5A1.5 1.5 0 0 1 17 15h-2"/>',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function icon(name: string): string {
|
||||||
|
return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths[name] ?? ''}</svg>`
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
// Popup menus opened at a point (context menu) or under a button, with
|
||||||
|
// keyboard navigation. Only one is open at a time.
|
||||||
|
import { icon } from './icons'
|
||||||
|
|
||||||
|
export interface MenuItem {
|
||||||
|
label?: string
|
||||||
|
action?: () => void
|
||||||
|
checked?: boolean // a check mark column is drawn when any item sets it
|
||||||
|
disabled?: boolean
|
||||||
|
hint?: string // right-aligned, like a shortcut
|
||||||
|
strong?: boolean
|
||||||
|
separator?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const menu = document.createElement('ul')
|
||||||
|
menu.className = 'menu popup'
|
||||||
|
menu.hidden = true
|
||||||
|
document.body.appendChild(menu)
|
||||||
|
|
||||||
|
let entries: { li: HTMLLIElement; item: MenuItem }[] = []
|
||||||
|
let index = -1
|
||||||
|
let anchor: Element | null = null
|
||||||
|
let onClose: (() => void) | null = null
|
||||||
|
|
||||||
|
export function menuOpen(): boolean {
|
||||||
|
return !menu.hidden
|
||||||
|
}
|
||||||
|
|
||||||
|
export function closeMenu() {
|
||||||
|
if (menu.hidden) return
|
||||||
|
menu.hidden = true
|
||||||
|
anchor = null
|
||||||
|
const done = onClose
|
||||||
|
onClose = null
|
||||||
|
done?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
function highlight(i: number) {
|
||||||
|
index = i
|
||||||
|
entries.forEach((e, k) => e.li.classList.toggle('active', k === i))
|
||||||
|
}
|
||||||
|
|
||||||
|
function choose(item: MenuItem) {
|
||||||
|
closeMenu()
|
||||||
|
item.action?.()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a menu with its top-left corner at (x, y), kept inside the window.
|
||||||
|
* A click on `from` (the button that opened it) is left to that button,
|
||||||
|
* so it can close the menu again.
|
||||||
|
*/
|
||||||
|
export function openMenu(items: MenuItem[], x: number, y: number, opts: { from?: Element; onClose?: () => void } = {}) {
|
||||||
|
closeMenu()
|
||||||
|
const checks = items.some((i) => i.checked !== undefined)
|
||||||
|
entries = []
|
||||||
|
menu.replaceChildren(
|
||||||
|
...items.map((item) => {
|
||||||
|
const li = document.createElement('li')
|
||||||
|
if (item.separator) {
|
||||||
|
li.className = 'sep'
|
||||||
|
return li
|
||||||
|
}
|
||||||
|
li.classList.toggle('disabled', !!item.disabled)
|
||||||
|
li.classList.toggle('strong', !!item.strong)
|
||||||
|
if (checks) {
|
||||||
|
const mark = document.createElement('span')
|
||||||
|
mark.className = 'check'
|
||||||
|
if (item.checked) mark.innerHTML = icon('check')
|
||||||
|
li.appendChild(mark)
|
||||||
|
}
|
||||||
|
li.append(item.label ?? '')
|
||||||
|
if (item.hint) {
|
||||||
|
const kbd = document.createElement('kbd')
|
||||||
|
kbd.textContent = item.hint
|
||||||
|
li.appendChild(kbd)
|
||||||
|
}
|
||||||
|
if (!item.disabled) {
|
||||||
|
const k = entries.length
|
||||||
|
entries.push({ li, item })
|
||||||
|
li.addEventListener('mousedown', (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
choose(item)
|
||||||
|
})
|
||||||
|
li.addEventListener('mousemove', () => highlight(k))
|
||||||
|
}
|
||||||
|
return li
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
anchor = opts.from ?? null
|
||||||
|
onClose = opts.onClose ?? null
|
||||||
|
index = -1
|
||||||
|
menu.hidden = false
|
||||||
|
const rect = menu.getBoundingClientRect()
|
||||||
|
menu.style.left = `${Math.max(8, Math.min(x, innerWidth - rect.width - 8))}px`
|
||||||
|
menu.style.top = `${y + rect.height > innerHeight - 8 ? Math.max(8, y - rect.height) : y}px`
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('mousedown', (e) => {
|
||||||
|
const target = e.target as Node
|
||||||
|
if (!menu.hidden && !menu.contains(target) && !anchor?.contains(target)) closeMenu()
|
||||||
|
})
|
||||||
|
|
||||||
|
window.addEventListener('blur', closeMenu)
|
||||||
|
document.addEventListener('scroll', closeMenu, true)
|
||||||
|
|
||||||
|
window.addEventListener(
|
||||||
|
'keydown',
|
||||||
|
(e) => {
|
||||||
|
if (menu.hidden) return
|
||||||
|
const n = entries.length
|
||||||
|
const keys: Record<string, () => void> = {
|
||||||
|
ArrowDown: () => n && highlight((index + 1) % n),
|
||||||
|
ArrowUp: () => n && highlight((index - 1 + n) % n),
|
||||||
|
Enter: () => (index >= 0 ? choose(entries[index].item) : closeMenu()),
|
||||||
|
Escape: closeMenu,
|
||||||
|
}
|
||||||
|
if (!keys[e.key]) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
keys[e.key]()
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
)
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// Production revisions: new text is marked with the current revision set
|
||||||
|
// while revisions are on, and locked pages keep their starting point as the
|
||||||
|
// text around them is edited. Pagination itself stays in Go.
|
||||||
|
import { EditorState, Plugin, Transaction } from 'prosemirror-state'
|
||||||
|
import { Mapping } from 'prosemirror-transform'
|
||||||
|
import { Node as PMNode } from 'prosemirror-model'
|
||||||
|
import { isHistoryTransaction } from 'prosemirror-history'
|
||||||
|
import type { PageBreak } from './backend'
|
||||||
|
import { blockText, flatElements, schema, utf16Offset, type LockAttr } from './schema'
|
||||||
|
|
||||||
|
/** Transactions made by these plugins, or that set locked pages themselves. */
|
||||||
|
const INTERNAL = 'plotzilla-revisions'
|
||||||
|
|
||||||
|
export interface CurrentRevision {
|
||||||
|
level: number
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every range a transaction inserted or replaced, in its final document. */
|
||||||
|
function changedRanges(trs: readonly Transaction[]): [number, number][] {
|
||||||
|
let ranges: [number, number][] = []
|
||||||
|
for (const tr of trs) {
|
||||||
|
ranges = ranges.map(([a, b]) => [tr.mapping.map(a, -1), tr.mapping.map(b, 1)])
|
||||||
|
if (!tr.docChanged || tr.getMeta(INTERNAL) || isHistoryTransaction(tr)) continue
|
||||||
|
tr.steps.forEach((step, i) => {
|
||||||
|
const rest = tr.mapping.slice(i + 1)
|
||||||
|
step.getMap().forEach((_oldStart, _oldEnd, start, end) => {
|
||||||
|
ranges.push([rest.map(start, -1), rest.map(end, 1)])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return ranges
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks what is typed, pasted or replaced with the current revision set.
|
||||||
|
* A deletion marks the character next to it, so the line still gets its
|
||||||
|
* asterisk. Undo and redo are left alone.
|
||||||
|
*/
|
||||||
|
export function revisionPlugin(current: () => CurrentRevision | null): Plugin {
|
||||||
|
return new Plugin({
|
||||||
|
appendTransaction(trs, _old, state) {
|
||||||
|
const rev = current()
|
||||||
|
if (!rev || !trs.some((t) => t.docChanged)) return null
|
||||||
|
const mark = schema.marks.revision.create(rev)
|
||||||
|
const tr = state.tr
|
||||||
|
const size = state.doc.content.size
|
||||||
|
for (const [from, to] of changedRanges(trs)) {
|
||||||
|
if (to > from) {
|
||||||
|
tr.addMark(from, to, mark)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
const $pos = state.doc.resolve(Math.min(from, size))
|
||||||
|
if ($pos.parent.type !== schema.nodes.element) continue
|
||||||
|
if ($pos.parentOffset > 0) tr.addMark(from - 1, from, mark)
|
||||||
|
else if ($pos.parent.content.size > 0) tr.addMark(from, from + 1, mark)
|
||||||
|
}
|
||||||
|
return tr.docChanged ? tr.setMeta(INTERNAL, true) : null
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Anchor {
|
||||||
|
pos: number
|
||||||
|
page: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function anchors(doc: PMNode): Anchor[] {
|
||||||
|
const out: Anchor[] = []
|
||||||
|
for (const { node, pos } of flatElements(doc)) {
|
||||||
|
for (const l of (node.attrs.locked as LockAttr[] | null) ?? []) out.push({ pos: pos + 1 + l.offset, page: l.page })
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sets the locked pages of every element; returns tr for chaining. */
|
||||||
|
function setLocks(tr: Transaction, perElement: Map<number, LockAttr[]>): Transaction {
|
||||||
|
for (const { node, pos } of flatElements(tr.doc)) {
|
||||||
|
const want = perElement.get(pos) ?? null
|
||||||
|
const have = node.attrs.locked as LockAttr[] | null
|
||||||
|
if (JSON.stringify(have) !== JSON.stringify(want)) tr.setNodeMarkup(pos, undefined, { ...node.attrs, locked: want })
|
||||||
|
}
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps each locked page where it started: its anchor follows the edits
|
||||||
|
* around it, into the next element when its own is deleted.
|
||||||
|
*/
|
||||||
|
export function lockPlugin(locked: () => boolean): Plugin {
|
||||||
|
return new Plugin({
|
||||||
|
appendTransaction(trs, oldState, state) {
|
||||||
|
if (!locked() || !trs.some((t) => t.docChanged) || trs.some((t) => t.getMeta(INTERNAL))) return null
|
||||||
|
const old = anchors(oldState.doc)
|
||||||
|
if (!old.length) return null
|
||||||
|
const mapping = new Mapping()
|
||||||
|
for (const tr of trs) mapping.appendMapping(tr.mapping)
|
||||||
|
const moved = old.map((a) => ({ pos: mapping.map(a.pos, -1), page: a.page })).sort((a, b) => a.pos - b.pos)
|
||||||
|
|
||||||
|
const flat = flatElements(state.doc)
|
||||||
|
const perElement = new Map<number, LockAttr[]>()
|
||||||
|
let e = 0
|
||||||
|
for (const a of moved) {
|
||||||
|
// The element holding the anchor, or the next one when it fell
|
||||||
|
// between elements.
|
||||||
|
while (e < flat.length - 1 && a.pos > flat[e].pos + 1 + flat[e].node.content.size) e++
|
||||||
|
const { node, pos } = flat[e]
|
||||||
|
const offset = Math.min(Math.max(a.pos - pos - 1, 0), node.content.size)
|
||||||
|
perElement.set(pos, [...(perElement.get(pos) ?? []), { offset, page: a.page }])
|
||||||
|
}
|
||||||
|
const tr = setLocks(state.tr, perElement)
|
||||||
|
return tr.docChanged ? tr.setMeta(INTERNAL, true) : null
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Locks the pages where they break now. Not undoable, like the setting. */
|
||||||
|
export function lockPages(state: EditorState, breaks: PageBreak[]): Transaction {
|
||||||
|
const flat = flatElements(state.doc)
|
||||||
|
const perElement = new Map<number, LockAttr[]>()
|
||||||
|
for (const br of breaks) {
|
||||||
|
const entry = flat[br.element]
|
||||||
|
if (!entry) continue
|
||||||
|
const offset = utf16Offset(blockText(entry.node), br.offset)
|
||||||
|
perElement.set(entry.pos, [...(perElement.get(entry.pos) ?? []), { offset, page: br.label || String(br.page) }])
|
||||||
|
}
|
||||||
|
return setLocks(state.tr, perElement).setMeta(INTERNAL, true).setMeta('addToHistory', false)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unlockPages(state: EditorState): Transaction {
|
||||||
|
return setLocks(state.tr, new Map()).setMeta(INTERNAL, true).setMeta('addToHistory', false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes every revision mark; one undo step. */
|
||||||
|
export function clearRevisionMarks(state: EditorState): Transaction {
|
||||||
|
return state.tr.removeMark(0, state.doc.content.size, schema.marks.revision).setMeta(INTERNAL, true)
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
import { Schema, Node as PMNode, Fragment, Mark } from 'prosemirror-model'
|
||||||
|
import type { Element, ElementType, PageLock, Revision, Run, ScriptDocument, Settings, TitlePage } from './backend'
|
||||||
|
|
||||||
|
/** The first nine have the shortcuts Ctrl+1…9, in this order. */
|
||||||
|
export const ELEMENT_TYPES: ElementType[] = [
|
||||||
|
'scene',
|
||||||
|
'action',
|
||||||
|
'character',
|
||||||
|
'parenthetical',
|
||||||
|
'dialogue',
|
||||||
|
'transition',
|
||||||
|
'shot',
|
||||||
|
'intertitle',
|
||||||
|
'centered',
|
||||||
|
'section',
|
||||||
|
'synopsis',
|
||||||
|
]
|
||||||
|
|
||||||
|
/** Outline elements: part of the script file, never printed. */
|
||||||
|
export const isPrinted = (t: ElementType) => t !== 'section' && t !== 'synopsis'
|
||||||
|
|
||||||
|
export const LABELS: Record<ElementType, string> = {
|
||||||
|
scene: 'Scene Heading',
|
||||||
|
action: 'Action',
|
||||||
|
character: 'Character',
|
||||||
|
parenthetical: 'Parenthetical',
|
||||||
|
dialogue: 'Dialogue',
|
||||||
|
transition: 'Transition',
|
||||||
|
shot: 'Insert / Shot',
|
||||||
|
intertitle: 'Intertitle',
|
||||||
|
centered: 'Centered',
|
||||||
|
section: 'Section',
|
||||||
|
synopsis: 'Synopsis',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A locked page in the editor: its offset is in UTF-16 units (positions). */
|
||||||
|
export interface LockAttr {
|
||||||
|
offset: number
|
||||||
|
page: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// One node type for every screenplay element: switching type is then a
|
||||||
|
// simple attribute change, which keeps Tab/Enter cycling cheap. A dual
|
||||||
|
// dialogue is a "dual" node holding two columns of elements.
|
||||||
|
export const schema = new Schema({
|
||||||
|
nodes: {
|
||||||
|
doc: { content: '(element | dual)+' },
|
||||||
|
element: {
|
||||||
|
content: 'inline*',
|
||||||
|
marks: '_',
|
||||||
|
defining: true,
|
||||||
|
// locked: LockAttr[] | null, the locked pages starting in the element.
|
||||||
|
attrs: {
|
||||||
|
type: { default: 'action' },
|
||||||
|
sceneNumber: { default: '' },
|
||||||
|
level: { default: 1 },
|
||||||
|
newPage: { default: false },
|
||||||
|
locked: { default: null },
|
||||||
|
},
|
||||||
|
parseDOM: [
|
||||||
|
{
|
||||||
|
tag: 'p',
|
||||||
|
// Locked pages are not copied: a page starts in one place only.
|
||||||
|
getAttrs: (dom) => {
|
||||||
|
const el = dom as HTMLElement
|
||||||
|
const type = el.dataset.type as ElementType | undefined
|
||||||
|
return {
|
||||||
|
type: type && ELEMENT_TYPES.includes(type) ? type : 'action',
|
||||||
|
sceneNumber: el.dataset.sceneNumber ?? '',
|
||||||
|
level: Math.max(1, Number(el.dataset.level) || 1),
|
||||||
|
newPage: el.dataset.newPage === 'true',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
toDOM: (node) => [
|
||||||
|
'p',
|
||||||
|
{
|
||||||
|
class: `el el-${node.attrs.type}`,
|
||||||
|
'data-type': node.attrs.type,
|
||||||
|
...(node.attrs.sceneNumber ? { 'data-scene-number': node.attrs.sceneNumber } : {}),
|
||||||
|
...(node.attrs.type === 'section' ? { 'data-level': String(node.attrs.level) } : {}),
|
||||||
|
...(node.attrs.newPage ? { 'data-new-page': 'true' } : {}),
|
||||||
|
},
|
||||||
|
0,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
dual: {
|
||||||
|
content: 'column column',
|
||||||
|
isolating: true,
|
||||||
|
parseDOM: [{ tag: 'div.dual' }],
|
||||||
|
toDOM: () => ['div', { class: 'dual' }, 0],
|
||||||
|
},
|
||||||
|
column: {
|
||||||
|
content: 'element+',
|
||||||
|
isolating: true,
|
||||||
|
parseDOM: [{ tag: 'div.dual-col' }],
|
||||||
|
toDOM: () => ['div', { class: 'dual-col' }, 0],
|
||||||
|
},
|
||||||
|
text: { group: 'inline' },
|
||||||
|
hard_break: {
|
||||||
|
inline: true,
|
||||||
|
group: 'inline',
|
||||||
|
selectable: false,
|
||||||
|
leafText: () => '\n',
|
||||||
|
parseDOM: [{ tag: 'br' }],
|
||||||
|
toDOM: () => ['br'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
marks: {
|
||||||
|
bold: { parseDOM: [{ tag: 'strong' }, { tag: 'b' }], toDOM: () => ['strong', 0] },
|
||||||
|
italic: { parseDOM: [{ tag: 'em' }, { tag: 'i' }], toDOM: () => ['em', 0] },
|
||||||
|
underline: { parseDOM: [{ tag: 'u' }], toDOM: () => ['u', 0] },
|
||||||
|
note: { parseDOM: [{ tag: 'span.note' }], toDOM: () => ['span', { class: 'note' }, 0] },
|
||||||
|
// Text of revision set `level`. Not inclusive: typing next to revised
|
||||||
|
// text is only marked while revisions are being marked.
|
||||||
|
revision: {
|
||||||
|
attrs: { level: { default: 1 }, color: { default: 'blue' } },
|
||||||
|
inclusive: false,
|
||||||
|
parseDOM: [
|
||||||
|
{
|
||||||
|
tag: 'span.rev',
|
||||||
|
getAttrs: (dom) => {
|
||||||
|
const el = dom as HTMLElement
|
||||||
|
return { level: Math.max(1, Number(el.dataset.level) || 1), color: el.dataset.color ?? 'blue' }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
toDOM: (mark) => ['span', { class: 'rev', 'data-level': String(mark.attrs.level), 'data-color': mark.attrs.color }, 0],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export function elementType(node: PMNode): ElementType {
|
||||||
|
return node.attrs.type as ElementType
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plain text of an element, with hard breaks as "\n" (matches the Go side). */
|
||||||
|
export function blockText(node: PMNode): string {
|
||||||
|
return node.textBetween(0, node.content.size, '\n', '\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The printed text of an element: without its notes. */
|
||||||
|
export function printedText(node: PMNode): string {
|
||||||
|
let text = ''
|
||||||
|
node.forEach((child) => {
|
||||||
|
if (!schema.marks.note.isInSet(child.marks)) text += child.isText ? child.text! : '\n'
|
||||||
|
})
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Converts a rune offset (Go) into a UTF-16 offset (JS) within text. */
|
||||||
|
export function utf16Offset(text: string, runes: number): number {
|
||||||
|
let i = 0
|
||||||
|
for (const ch of text) {
|
||||||
|
if (runes-- <= 0) break
|
||||||
|
i += ch.length
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Converts a UTF-16 offset within text into a rune offset (Go). */
|
||||||
|
export function runeOffset(text: string, utf16: number): number {
|
||||||
|
return [...text.slice(0, utf16)].length
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FlatElement {
|
||||||
|
node: PMNode
|
||||||
|
pos: number
|
||||||
|
/** Position of the enclosing dual node, for elements of a dual dialogue. */
|
||||||
|
dualPos: number | null
|
||||||
|
/** Set on the first element of the right column. */
|
||||||
|
dual: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Elements in document order, the same indexing as the Go side uses. */
|
||||||
|
export function flatElements(doc: PMNode): FlatElement[] {
|
||||||
|
const out: FlatElement[] = []
|
||||||
|
doc.forEach((node, offset) => {
|
||||||
|
if (node.type !== schema.nodes.dual) {
|
||||||
|
out.push({ node, pos: offset, dualPos: null, dual: false })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
node.forEach((col, colOffset, colIndex) => {
|
||||||
|
col.forEach((el, elOffset, elIndex) => {
|
||||||
|
const pos = offset + 1 + colOffset + 1 + elOffset
|
||||||
|
out.push({ node: el, pos, dualPos: offset, dual: colIndex === 1 && elIndex === 0 })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
const sameStyle = (a: Run, b: Run) =>
|
||||||
|
!!a.b === !!b.b && !!a.i === !!b.i && !!a.u === !!b.u && !!a.n === !!b.n && (a.rev ?? 0) === (b.rev ?? 0)
|
||||||
|
|
||||||
|
function runsOf(node: PMNode): Run[] {
|
||||||
|
const runs: Run[] = []
|
||||||
|
node.forEach((child) => {
|
||||||
|
const run: Run = { text: child.isText ? child.text! : '\n' }
|
||||||
|
for (const m of child.marks) {
|
||||||
|
if (m.type === schema.marks.bold) run.b = true
|
||||||
|
if (m.type === schema.marks.italic) run.i = true
|
||||||
|
if (m.type === schema.marks.underline) run.u = true
|
||||||
|
if (m.type === schema.marks.note) run.n = true
|
||||||
|
if (m.type === schema.marks.revision) run.rev = m.attrs.level
|
||||||
|
}
|
||||||
|
const last = runs[runs.length - 1]
|
||||||
|
if (last && sameStyle(last, run)) {
|
||||||
|
last.text += run.text
|
||||||
|
} else {
|
||||||
|
runs.push(run)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toElement(node: PMNode): Element {
|
||||||
|
const el: Element = { type: elementType(node), runs: runsOf(node) }
|
||||||
|
if (node.attrs.sceneNumber) el.sceneNumber = node.attrs.sceneNumber
|
||||||
|
if (el.type === 'section') el.level = node.attrs.level
|
||||||
|
if (node.attrs.newPage) el.newPage = true
|
||||||
|
const locked = node.attrs.locked as LockAttr[] | null
|
||||||
|
if (locked?.length) {
|
||||||
|
const text = blockText(node)
|
||||||
|
el.locked = locked.map((l): PageLock => ({ offset: runeOffset(text, l.offset), page: l.page }))
|
||||||
|
}
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toScript(doc: PMNode, titlePage: TitlePage, settings: Settings): ScriptDocument {
|
||||||
|
const elements = flatElements(doc).map(({ node, dual }) => {
|
||||||
|
const el = toElement(node)
|
||||||
|
if (dual) el.dual = true
|
||||||
|
return el
|
||||||
|
})
|
||||||
|
return { titlePage, elements, settings }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** revisions names the colour of revised text (Run.rev). */
|
||||||
|
export function fromElement(el: Element, revisions: Revision[] = []): PMNode {
|
||||||
|
const inline: PMNode[] = []
|
||||||
|
let text = ''
|
||||||
|
for (const run of el.runs ?? []) {
|
||||||
|
const marks: Mark[] = []
|
||||||
|
if (run.b) marks.push(schema.marks.bold.create())
|
||||||
|
if (run.i) marks.push(schema.marks.italic.create())
|
||||||
|
if (run.u) marks.push(schema.marks.underline.create())
|
||||||
|
if (run.n) marks.push(schema.marks.note.create())
|
||||||
|
if (run.rev) marks.push(schema.marks.revision.create({ level: run.rev, color: revisions[run.rev - 1]?.color ?? 'blue' }))
|
||||||
|
// A line break keeps the note or revision it belongs to, not emphasis.
|
||||||
|
const breakMarks = marks.filter((m) => m.type === schema.marks.note || m.type === schema.marks.revision)
|
||||||
|
run.text.split('\n').forEach((part, i) => {
|
||||||
|
if (i > 0) inline.push(schema.nodes.hard_break.create(null, null, breakMarks))
|
||||||
|
if (part) inline.push(schema.text(part, marks))
|
||||||
|
})
|
||||||
|
text += run.text
|
||||||
|
}
|
||||||
|
const type = ELEMENT_TYPES.includes(el.type) ? el.type : 'action'
|
||||||
|
const locked = el.locked?.length
|
||||||
|
? el.locked.map((l): LockAttr => ({ offset: utf16Offset(text, l.offset), page: l.page }))
|
||||||
|
: null
|
||||||
|
return schema.nodes.element.create(
|
||||||
|
{ type, sceneNumber: el.sceneNumber ?? '', level: Math.max(1, el.level ?? 1), newPage: !!el.newPage, locked },
|
||||||
|
inline,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dualNode(left: PMNode[], right: PMNode[]): PMNode {
|
||||||
|
return schema.nodes.dual.create(null, [
|
||||||
|
schema.nodes.column.create(null, left),
|
||||||
|
schema.nodes.column.create(null, right),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
const inDialogue = (t: ElementType) => t === 'parenthetical' || t === 'dialogue'
|
||||||
|
|
||||||
|
export function fromScript(script: ScriptDocument): PMNode {
|
||||||
|
const els = script.elements ?? []
|
||||||
|
const revisions = script.settings?.revisions ?? []
|
||||||
|
const node = (el: Element) => fromElement(el, revisions)
|
||||||
|
const blocks: PMNode[] = []
|
||||||
|
let blockStart = -1 // index in blocks of the last top-level dialogue block
|
||||||
|
for (let i = 0; i < els.length; i++) {
|
||||||
|
const el = els[i]
|
||||||
|
if (el.type === 'character' && el.dual && blockStart >= 0) {
|
||||||
|
const right = [node(el)]
|
||||||
|
while (i + 1 < els.length && inDialogue(els[i + 1].type)) right.push(node(els[++i]))
|
||||||
|
blocks.push(dualNode(blocks.splice(blockStart), right))
|
||||||
|
blockStart = -1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if (el.type === 'character') blockStart = blocks.length
|
||||||
|
else if (!inDialogue(el.type)) blockStart = -1
|
||||||
|
blocks.push(node(el))
|
||||||
|
}
|
||||||
|
if (blocks.length === 0) blocks.push(schema.nodes.element.create({ type: 'scene' }))
|
||||||
|
return schema.nodes.doc.create(null, Fragment.fromArray(blocks))
|
||||||
|
}
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
// Find and replace in the script body. The plugin keeps the query and its
|
||||||
|
// matches and highlights them; the commands move between matches by
|
||||||
|
// selecting them and replace through ordinary transactions, so undo works.
|
||||||
|
import { Command, EditorState, Plugin, PluginKey, TextSelection } from 'prosemirror-state'
|
||||||
|
import { Decoration, DecorationSet } from 'prosemirror-view'
|
||||||
|
import { Node as PMNode } from 'prosemirror-model'
|
||||||
|
import { closeHistory } from 'prosemirror-history'
|
||||||
|
import { blockText, flatElements } from './schema'
|
||||||
|
import { replaceText } from './commands'
|
||||||
|
|
||||||
|
export interface SearchQuery {
|
||||||
|
text: string
|
||||||
|
caseSensitive: boolean
|
||||||
|
wholeWord: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Match {
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SearchState {
|
||||||
|
query: SearchQuery
|
||||||
|
matches: Match[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const searchKey = new PluginKey<SearchState>('search')
|
||||||
|
|
||||||
|
const EMPTY: SearchQuery = { text: '', caseSensitive: false, wholeWord: false }
|
||||||
|
|
||||||
|
function pattern(query: SearchQuery): RegExp {
|
||||||
|
const escaped = query.text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||||
|
const source = query.wholeWord ? `(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])` : escaped
|
||||||
|
return new RegExp(source, query.caseSensitive ? 'gu' : 'giu')
|
||||||
|
}
|
||||||
|
|
||||||
|
function findMatches(doc: PMNode, query: SearchQuery): Match[] {
|
||||||
|
if (!query.text) return []
|
||||||
|
const re = pattern(query)
|
||||||
|
const matches: Match[] = []
|
||||||
|
for (const { node, pos } of flatElements(doc)) {
|
||||||
|
// blockText has one character per position (hard breaks included), so
|
||||||
|
// string indexes map directly onto document positions.
|
||||||
|
const text = blockText(node)
|
||||||
|
for (const m of text.matchAll(re)) {
|
||||||
|
matches.push({ from: pos + 1 + m.index, to: pos + 1 + m.index + m[0].length })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches
|
||||||
|
}
|
||||||
|
|
||||||
|
export function searchPlugin(): Plugin<SearchState> {
|
||||||
|
return new Plugin<SearchState>({
|
||||||
|
key: searchKey,
|
||||||
|
state: {
|
||||||
|
init: () => ({ query: EMPTY, matches: [] }),
|
||||||
|
apply(tr, prev, _old, state) {
|
||||||
|
const query = (tr.getMeta(searchKey) as SearchQuery | undefined) ?? prev.query
|
||||||
|
if (query === prev.query && !tr.docChanged) return prev
|
||||||
|
return { query, matches: findMatches(state.doc, query) }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
decorations(state) {
|
||||||
|
const { matches } = searchKey.getState(state)!
|
||||||
|
if (!matches.length) return null
|
||||||
|
const { from, to } = state.selection
|
||||||
|
return DecorationSet.create(
|
||||||
|
state.doc,
|
||||||
|
matches.map((m) =>
|
||||||
|
Decoration.inline(m.from, m.to, { class: m.from === from && m.to === to ? 'search-match active' : 'search-match' }),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function searchMatches(state: EditorState): Match[] {
|
||||||
|
return searchKey.getState(state)?.matches ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Index of the match that is currently selected, or -1. */
|
||||||
|
export function activeMatch(state: EditorState): number {
|
||||||
|
const { from, to } = state.selection
|
||||||
|
return searchMatches(state).findIndex((m) => m.from === from && m.to === to)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSearch(query: SearchQuery): Command {
|
||||||
|
return (state, dispatch) => {
|
||||||
|
if (dispatch) dispatch(state.tr.setMeta(searchKey, query).setMeta('addToHistory', false))
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Selects the next match after the selection (dir 1) or the previous one
|
||||||
|
* (dir -1), wrapping around the script. With `here`, a match starting at
|
||||||
|
* the cursor counts as the next one (incremental search while typing).
|
||||||
|
*/
|
||||||
|
export function selectMatch(dir: 1 | -1, here = false): Command {
|
||||||
|
return (state, dispatch) => {
|
||||||
|
const matches = searchMatches(state)
|
||||||
|
if (!matches.length) return false
|
||||||
|
const { from, to } = state.selection
|
||||||
|
const m =
|
||||||
|
dir > 0
|
||||||
|
? (matches.find((m) => m.from >= (here ? from : to)) ?? matches[0])
|
||||||
|
: (matches.findLast((m) => m.to <= from) ?? matches[matches.length - 1])
|
||||||
|
if (dispatch) dispatch(state.tr.setSelection(TextSelection.create(state.doc, m.from, m.to)).scrollIntoView())
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces the selected match, then selects the next one. */
|
||||||
|
export function replaceMatch(text: string): Command {
|
||||||
|
return (state, dispatch) => {
|
||||||
|
const i = activeMatch(state)
|
||||||
|
if (i < 0) return selectMatch(1)(state, dispatch)
|
||||||
|
if (dispatch) {
|
||||||
|
const m = searchMatches(state)[i]
|
||||||
|
// Its own undo step, even right after typing or another replacement.
|
||||||
|
const tr = replaceText(closeHistory(state.tr), m.from, m.to, text)
|
||||||
|
const after = tr.mapping.map(m.to)
|
||||||
|
const next = findMatches(tr.doc, searchKey.getState(state)!.query).find((n) => n.from >= after)
|
||||||
|
if (next) tr.setSelection(TextSelection.create(tr.doc, next.from, next.to))
|
||||||
|
dispatch(tr.scrollIntoView())
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Replaces every match in one step, so a single undo restores them all. */
|
||||||
|
export function replaceAll(text: string): Command {
|
||||||
|
return (state, dispatch) => {
|
||||||
|
const matches = searchMatches(state)
|
||||||
|
if (!matches.length) return false
|
||||||
|
if (dispatch) {
|
||||||
|
const tr = closeHistory(state.tr)
|
||||||
|
for (const m of [...matches].reverse()) replaceText(tr, m.from, m.to, text)
|
||||||
|
dispatch(tr)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// Spelling: wavy underlines under the words the Go checker reports. The
|
||||||
|
// word being typed is left alone until the cursor leaves it.
|
||||||
|
import { EditorState, Plugin, PluginKey, Transaction } from 'prosemirror-state'
|
||||||
|
import { Decoration, DecorationSet } from 'prosemirror-view'
|
||||||
|
import { Node as PMNode } from 'prosemirror-model'
|
||||||
|
import type { Misspelling } from './backend'
|
||||||
|
import { blockText, flatElements } from './schema'
|
||||||
|
import { utf16Offset } from './decorations'
|
||||||
|
|
||||||
|
interface SpellState {
|
||||||
|
set: DecorationSet
|
||||||
|
typing: boolean // the last change was an edit, not a cursor move
|
||||||
|
}
|
||||||
|
|
||||||
|
interface WordSpec {
|
||||||
|
word: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const spellKey = new PluginKey<SpellState>('spell')
|
||||||
|
|
||||||
|
export function buildSpellDecorations(doc: PMNode, found: Misspelling[], ignored: Set<string>): DecorationSet {
|
||||||
|
const flat = flatElements(doc)
|
||||||
|
const decos: Decoration[] = []
|
||||||
|
for (const m of found) {
|
||||||
|
const entry = flat[m.element]
|
||||||
|
if (!entry || ignored.has(m.word.toLowerCase())) continue
|
||||||
|
const text = blockText(entry.node)
|
||||||
|
const start = entry.pos + 1
|
||||||
|
const spec: WordSpec = { word: m.word }
|
||||||
|
decos.push(
|
||||||
|
Decoration.inline(
|
||||||
|
start + utf16Offset(text, m.offset),
|
||||||
|
start + utf16Offset(text, m.offset + m.length),
|
||||||
|
{ class: 'misspelled' },
|
||||||
|
spec,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return DecorationSet.create(doc, decos)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Maps the underlines through a change, dropping those it touched. */
|
||||||
|
function mapThrough(set: DecorationSet, tr: Transaction): DecorationSet {
|
||||||
|
let mapped = set.map(tr.mapping, tr.doc)
|
||||||
|
tr.mapping.maps.forEach((map, i) => {
|
||||||
|
const rest = tr.mapping.slice(i + 1)
|
||||||
|
map.forEach((_oldStart, _oldEnd, start, end) => {
|
||||||
|
const touched = mapped.find(rest.map(start, -1), rest.map(end, 1))
|
||||||
|
if (touched.length) mapped = mapped.remove(touched)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return mapped
|
||||||
|
}
|
||||||
|
|
||||||
|
export function spellPlugin(): Plugin<SpellState> {
|
||||||
|
return new Plugin<SpellState>({
|
||||||
|
key: spellKey,
|
||||||
|
state: {
|
||||||
|
init: () => ({ set: DecorationSet.empty, typing: false }),
|
||||||
|
apply(tr, prev) {
|
||||||
|
const fresh = tr.getMeta(spellKey) as DecorationSet | undefined
|
||||||
|
const typing = tr.docChanged ? true : tr.selectionSet ? false : prev.typing
|
||||||
|
if (fresh) return { set: fresh, typing }
|
||||||
|
if (tr.docChanged) return { set: mapThrough(prev.set, tr), typing }
|
||||||
|
return typing === prev.typing ? prev : { set: prev.set, typing }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
props: {
|
||||||
|
decorations(state) {
|
||||||
|
const { set, typing } = spellKey.getState(state)!
|
||||||
|
if (!typing) return set
|
||||||
|
const head = state.selection.head
|
||||||
|
const here = set.find(head, head)
|
||||||
|
return here.length ? set.remove(here) : set
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MisspelledWord {
|
||||||
|
from: number
|
||||||
|
to: number
|
||||||
|
word: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The underlined word at pos, if any. */
|
||||||
|
export function misspellingAt(state: EditorState, pos: number): MisspelledWord | null {
|
||||||
|
const d = spellKey.getState(state)?.set.find(pos, pos).find((d) => d.from <= pos && pos <= d.to)
|
||||||
|
return d ? { from: d.from, to: d.to, word: (d.spec as WordSpec).word } : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The current underlines without those of word (added or ignored). */
|
||||||
|
export function withoutWord(state: EditorState, word: string): DecorationSet {
|
||||||
|
const set = spellKey.getState(state)!.set
|
||||||
|
const lower = word.toLowerCase()
|
||||||
|
return set.remove(set.find(undefined, undefined, (spec: WordSpec) => spec.word.toLowerCase() === lower))
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"isolatedModules": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
build: { outDir: 'dist', emptyOutDir: true, target: 'es2020' },
|
||||||
|
})
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
module plotzilla
|
||||||
|
|
||||||
|
go 1.23
|
||||||
|
|
||||||
|
require github.com/wailsapp/wails/v2 v2.10.2
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/bep/debounce v1.2.1 // indirect
|
||||||
|
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||||
|
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||||
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/gorilla/websocket v1.5.3 // indirect
|
||||||
|
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
|
||||||
|
github.com/labstack/echo/v4 v4.13.3 // indirect
|
||||||
|
github.com/labstack/gommon v0.4.2 // indirect
|
||||||
|
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
|
||||||
|
github.com/leaanthony/gosod v1.0.4 // indirect
|
||||||
|
github.com/leaanthony/slicer v1.6.0 // indirect
|
||||||
|
github.com/leaanthony/u v1.1.1 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||||
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
|
github.com/samber/lo v1.49.1 // indirect
|
||||||
|
github.com/tkrajina/go-reflector v0.5.8 // indirect
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
|
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||||
|
github.com/wailsapp/go-webview2 v1.0.19 // indirect
|
||||||
|
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||||
|
golang.org/x/crypto v0.33.0 // indirect
|
||||||
|
golang.org/x/net v0.35.0 // indirect
|
||||||
|
golang.org/x/sys v0.30.0 // indirect
|
||||||
|
golang.org/x/text v0.22.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||||
|
github.com/bep/debounce v1.2.1/go.mod h1:H8yggRPQKLUhUoqrJC1bO2xNya7vanpDl7xR3ISbCJ0=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||||
|
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||||
|
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||||
|
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
|
||||||
|
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||||
|
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
|
||||||
|
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
||||||
|
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||||
|
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||||
|
github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc=
|
||||||
|
github.com/leaanthony/debme v1.2.1/go.mod h1:3V+sCm5tYAgQymvSOfYQ5Xx2JCr+OXiD9Jkw3otUjiA=
|
||||||
|
github.com/leaanthony/go-ansi-parser v1.6.1 h1:xd8bzARK3dErqkPFtoF9F3/HgN8UQk0ed1YDKpEz01A=
|
||||||
|
github.com/leaanthony/go-ansi-parser v1.6.1/go.mod h1:+vva/2y4alzVmmIEpk9QDhA7vLC5zKDTRwfZGOp3IWU=
|
||||||
|
github.com/leaanthony/gosod v1.0.4 h1:YLAbVyd591MRffDgxUOU1NwLhT9T1/YiwjKZpkNFeaI=
|
||||||
|
github.com/leaanthony/gosod v1.0.4/go.mod h1:GKuIL0zzPj3O1SdWQOdgURSuhkF+Urizzxh26t9f1cw=
|
||||||
|
github.com/leaanthony/slicer v1.6.0 h1:1RFP5uiPJvT93TAHi+ipd3NACobkW53yUiBqZheE/Js=
|
||||||
|
github.com/leaanthony/slicer v1.6.0/go.mod h1:o/Iz29g7LN0GqH3aMjWAe90381nyZlDNquK+mtH2Fj8=
|
||||||
|
github.com/leaanthony/u v1.1.1 h1:TUFjwDGlNX+WuwVEzDqQwC2lOv0P4uhTQw7CMFdiK7M=
|
||||||
|
github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQcaRfI=
|
||||||
|
github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||||
|
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
|
||||||
|
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
|
||||||
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
|
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||||
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
|
github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew=
|
||||||
|
github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o=
|
||||||
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||||
|
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
|
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||||
|
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||||
|
github.com/wailsapp/go-webview2 v1.0.19 h1:7U3QcDj1PrBPaxJNCui2k1SkWml+Q5kvFUFyTImA6NU=
|
||||||
|
github.com/wailsapp/go-webview2 v1.0.19/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
|
||||||
|
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
|
||||||
|
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
|
||||||
|
github.com/wailsapp/wails/v2 v2.10.2 h1:29U+c5PI4K4hbx8yFbFvwpCuvqK9VgNv8WGobIlKlXk=
|
||||||
|
github.com/wailsapp/wails/v2 v2.10.2/go.mod h1:XuN4IUOPpzBrHUkEd7sCU5ln4T/p1wQedfxP7fKik+4=
|
||||||
|
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||||
|
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||||
|
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
|
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||||
|
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||||
|
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||||
|
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||||
|
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,555 @@
|
|||||||
|
// Package fdx reads and writes Final Draft XML (.fdx) files.
|
||||||
|
//
|
||||||
|
// Final Draft has no Fountain sections or synopses: they are written as
|
||||||
|
// script notes whose text starts with "#" or "=", attached to the start of
|
||||||
|
// the next paragraph, and read back as such. Notes inside the text are
|
||||||
|
// script notes at their position; revised text carries the RevisionID of
|
||||||
|
// its revision set; a forced page break is StartsNewPage.
|
||||||
|
package fdx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/xml"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
type file struct {
|
||||||
|
XMLName xml.Name `xml:"FinalDraft"`
|
||||||
|
DocumentType string `xml:"DocumentType,attr"`
|
||||||
|
Template string `xml:"Template,attr"`
|
||||||
|
Version string `xml:"Version,attr"`
|
||||||
|
Content content `xml:"Content"`
|
||||||
|
TitlePage *titlePage `xml:"TitlePage,omitempty"`
|
||||||
|
Revisions *revisions `xml:"Revisions,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type revisions struct {
|
||||||
|
ActiveSet int `xml:"ActiveSet,attr"`
|
||||||
|
RevisionMode string `xml:"RevisionMode,attr"`
|
||||||
|
Items []revision `xml:"Revision"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type revision struct {
|
||||||
|
ID int `xml:"ID,attr"`
|
||||||
|
Name string `xml:"Name,attr"`
|
||||||
|
Color string `xml:"Color,attr,omitempty"`
|
||||||
|
PageColor string `xml:"PageColor,attr,omitempty"`
|
||||||
|
Mark string `xml:"Mark,attr,omitempty"`
|
||||||
|
FullRevision string `xml:"FullRevision,attr,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type scriptNote struct {
|
||||||
|
ID int `xml:"ID,attr"`
|
||||||
|
Range string `xml:"Range,attr"` // "start,length" in the paragraph's text
|
||||||
|
Paragraphs []paragraph `xml:"Paragraph"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type content struct {
|
||||||
|
Paragraphs []paragraph `xml:"Paragraph"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type titlePage struct {
|
||||||
|
Content content `xml:"Content"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type paragraph struct {
|
||||||
|
Type string `xml:"Type,attr,omitempty"`
|
||||||
|
Number string `xml:"Number,attr,omitempty"`
|
||||||
|
Alignment string `xml:"Alignment,attr,omitempty"`
|
||||||
|
StartsNewPage string `xml:"StartsNewPage,attr,omitempty"`
|
||||||
|
ScriptNotes []scriptNote `xml:"ScriptNote"`
|
||||||
|
Texts []text `xml:"Text"`
|
||||||
|
DualDialogue *content `xml:"DualDialogue,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type text struct {
|
||||||
|
Style string `xml:"Style,attr,omitempty"`
|
||||||
|
RevisionID int `xml:"RevisionID,attr,omitempty"`
|
||||||
|
Value string `xml:",chardata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// revisionColors are Final Draft's 48-bit page colours for each revision
|
||||||
|
// colour, in the order they are searched for in a revision set's name.
|
||||||
|
var revisionColors = []struct{ name, hex string }{
|
||||||
|
{"goldenrod", "#DADAA5A52020"},
|
||||||
|
{"white", "#FFFFFFFFFFFF"},
|
||||||
|
{"blue", "#ADADD8D8E6E6"},
|
||||||
|
{"pink", "#FFFFC0C0CBCB"},
|
||||||
|
{"yellow", "#FFFFFFFF9999"},
|
||||||
|
{"green", "#9999FFFF9999"},
|
||||||
|
{"buff", "#F0F0DCDC8282"},
|
||||||
|
{"salmon", "#FAFA80807272"},
|
||||||
|
{"cherry", "#DEDE31316363"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// revisionName is how Plotzilla names a set in Final Draft: "Blue
|
||||||
|
// Revision - 09/28/26".
|
||||||
|
var revisionName = regexp.MustCompile(`^(.*?) Revision(?: - (.+))?$`)
|
||||||
|
|
||||||
|
var typeNames = map[screenplay.ElementType]string{
|
||||||
|
screenplay.Scene: "Scene Heading",
|
||||||
|
screenplay.Action: "Action",
|
||||||
|
screenplay.Character: "Character",
|
||||||
|
screenplay.Parenthetical: "Parenthetical",
|
||||||
|
screenplay.Dialogue: "Dialogue",
|
||||||
|
screenplay.Transition: "Transition",
|
||||||
|
screenplay.Centered: "Action",
|
||||||
|
screenplay.Shot: "Shot",
|
||||||
|
screenplay.Intertitle: "Action",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read parses an FDX document.
|
||||||
|
func Read(r io.Reader) (*screenplay.Document, error) {
|
||||||
|
var f file
|
||||||
|
dec := xml.NewDecoder(r)
|
||||||
|
dec.CharsetReader = func(_ string, in io.Reader) (io.Reader, error) { return in, nil }
|
||||||
|
if err := dec.Decode(&f); err != nil {
|
||||||
|
return nil, fmt.Errorf("reading FDX: %w", err)
|
||||||
|
}
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
rd := &reader{levels: map[int]int{}}
|
||||||
|
if f.Revisions != nil {
|
||||||
|
for i, rv := range f.Revisions.Items {
|
||||||
|
rd.levels[rv.ID] = i + 1
|
||||||
|
doc.Settings.Revisions = append(doc.Settings.Revisions, readRevision(rv, i+1))
|
||||||
|
}
|
||||||
|
doc.Settings.Revising = f.Revisions.RevisionMode == "Yes" && len(f.Revisions.Items) > 0
|
||||||
|
}
|
||||||
|
for _, p := range f.Content.Paragraphs {
|
||||||
|
rd.paragraph(p)
|
||||||
|
}
|
||||||
|
doc.Elements = rd.out
|
||||||
|
if len(doc.Elements) == 0 {
|
||||||
|
doc.Elements = []screenplay.Element{screenplay.NewElement(screenplay.Scene, "")}
|
||||||
|
}
|
||||||
|
if f.TitlePage != nil {
|
||||||
|
doc.TitlePage = readTitlePage(f.TitlePage.Content.Paragraphs)
|
||||||
|
}
|
||||||
|
return doc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readRevision(rv revision, level int) screenplay.Revision {
|
||||||
|
def := screenplay.RevisionSet(level)
|
||||||
|
r := screenplay.Revision{Name: strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(rv.Name), "Rev."))}
|
||||||
|
if m := revisionName.FindStringSubmatch(rv.Name); m != nil {
|
||||||
|
r.Name, r.Date = m[1], m[2]
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(r.Name)
|
||||||
|
for _, c := range revisionColors {
|
||||||
|
if strings.Contains(lower, c.name) {
|
||||||
|
r.Color = c.name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.Color == "" {
|
||||||
|
r.Color = def.Color
|
||||||
|
}
|
||||||
|
if r.Name == "" {
|
||||||
|
r.Name = def.Name
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
type reader struct {
|
||||||
|
out []screenplay.Element
|
||||||
|
levels map[int]int // Final Draft RevisionID → revision set
|
||||||
|
newPage bool // a page break on a paragraph that was left out
|
||||||
|
}
|
||||||
|
|
||||||
|
type inlineNote struct {
|
||||||
|
offset int
|
||||||
|
text string
|
||||||
|
}
|
||||||
|
|
||||||
|
// notes adds the sections and synopses stored in a paragraph's script
|
||||||
|
// notes and returns its other notes.
|
||||||
|
func (rd *reader) notes(sns []scriptNote) []inlineNote {
|
||||||
|
var inline []inlineNote
|
||||||
|
for _, sn := range sns {
|
||||||
|
var lines []string
|
||||||
|
for _, p := range sn.Paragraphs {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, t := range p.Texts {
|
||||||
|
b.WriteString(t.Value)
|
||||||
|
}
|
||||||
|
lines = append(lines, b.String())
|
||||||
|
}
|
||||||
|
body := strings.Join(lines, "\n")
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(body, "#"):
|
||||||
|
rest := strings.TrimLeft(body, "#")
|
||||||
|
rd.out = append(rd.out, screenplay.Element{Type: screenplay.Section, Level: len(body) - len(rest),
|
||||||
|
Runs: []screenplay.Run{{Text: strings.TrimSpace(rest)}}})
|
||||||
|
case strings.HasPrefix(body, "="):
|
||||||
|
rd.out = append(rd.out, screenplay.Element{Type: screenplay.Synopsis,
|
||||||
|
Runs: []screenplay.Run{{Text: strings.TrimSpace(strings.TrimPrefix(body, "="))}}})
|
||||||
|
default:
|
||||||
|
start, _, _ := strings.Cut(sn.Range, ",")
|
||||||
|
offset, _ := strconv.Atoi(strings.TrimSpace(start))
|
||||||
|
inline = append(inline, inlineNote{offset: max(offset, 0), text: strings.TrimPrefix(body, `\`)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return inline
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rd *reader) paragraph(p paragraph) {
|
||||||
|
notes := rd.notes(p.ScriptNotes)
|
||||||
|
newPage := p.StartsNewPage == "Yes" || rd.newPage
|
||||||
|
rd.newPage = false
|
||||||
|
if p.DualDialogue != nil {
|
||||||
|
start := len(rd.out)
|
||||||
|
cues := 0
|
||||||
|
for _, inner := range p.DualDialogue.Paragraphs {
|
||||||
|
n := len(rd.out)
|
||||||
|
rd.paragraph(inner)
|
||||||
|
if inner.Type == "Character" && len(rd.out) > n {
|
||||||
|
if cues++; cues == 2 {
|
||||||
|
rd.out[len(rd.out)-1].Dual = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if newPage && len(rd.out) > start {
|
||||||
|
rd.out[start].NewPage = true
|
||||||
|
} else {
|
||||||
|
rd.newPage = newPage
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
el := screenplay.Element{SceneNumber: p.Number, NewPage: newPage}
|
||||||
|
switch p.Type {
|
||||||
|
case "Scene Heading":
|
||||||
|
el.Type = screenplay.Scene
|
||||||
|
case "Character":
|
||||||
|
el.Type = screenplay.Character
|
||||||
|
case "Parenthetical":
|
||||||
|
el.Type = screenplay.Parenthetical
|
||||||
|
case "Dialogue":
|
||||||
|
el.Type = screenplay.Dialogue
|
||||||
|
case "Transition":
|
||||||
|
el.Type = screenplay.Transition
|
||||||
|
case "Shot":
|
||||||
|
el.Type = screenplay.Shot
|
||||||
|
default:
|
||||||
|
el.Type = screenplay.Action
|
||||||
|
if p.Alignment == "Center" {
|
||||||
|
el.Type = screenplay.Centered
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if el.Type != screenplay.Scene {
|
||||||
|
el.SceneNumber = ""
|
||||||
|
}
|
||||||
|
for _, t := range p.Texts {
|
||||||
|
el.Runs = append(el.Runs, screenplay.Run{
|
||||||
|
Text: t.Value,
|
||||||
|
Bold: strings.Contains(t.Style, "Bold"),
|
||||||
|
Italic: strings.Contains(t.Style, "Italic"),
|
||||||
|
Underline: strings.Contains(t.Style, "Underline"),
|
||||||
|
Rev: rd.levels[t.RevisionID],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
el.Runs = insertNotes(screenplay.NormalizeRuns(el.Runs), notes)
|
||||||
|
if el.IsEmpty() {
|
||||||
|
rd.newPage = newPage
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Final Draft has no intertitle: they are centred, all-caps action.
|
||||||
|
if el.Type == screenplay.Centered && isAllCaps(el.PrintedText()) {
|
||||||
|
el.Type = screenplay.Intertitle
|
||||||
|
}
|
||||||
|
rd.out = append(rd.out, el)
|
||||||
|
}
|
||||||
|
|
||||||
|
// insertNotes puts note runs at their rune offsets in the text.
|
||||||
|
func insertNotes(runs []screenplay.Run, notes []inlineNote) []screenplay.Run {
|
||||||
|
if len(notes) == 0 {
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
slices.SortStableFunc(notes, func(a, b inlineNote) int { return a.offset - b.offset })
|
||||||
|
var out []screenplay.Run
|
||||||
|
pos, next := 0, 0
|
||||||
|
for _, r := range runs {
|
||||||
|
rs := []rune(r.Text)
|
||||||
|
start := 0
|
||||||
|
for ; next < len(notes) && notes[next].offset-pos < len(rs); next++ {
|
||||||
|
if at := notes[next].offset - pos; at > start {
|
||||||
|
part := r
|
||||||
|
part.Text = string(rs[start:at])
|
||||||
|
out = append(out, part)
|
||||||
|
start = at
|
||||||
|
}
|
||||||
|
out = append(out, screenplay.Run{Text: notes[next].text, Note: true})
|
||||||
|
}
|
||||||
|
if start < len(rs) {
|
||||||
|
r.Text = string(rs[start:])
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
pos += len(rs)
|
||||||
|
}
|
||||||
|
for ; next < len(notes); next++ {
|
||||||
|
out = append(out, screenplay.Run{Text: notes[next].text, Note: true})
|
||||||
|
}
|
||||||
|
return screenplay.NormalizeRuns(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// readTitlePage maps Final Draft's free-form title page onto our fields:
|
||||||
|
// the first centred line is the title, a line containing "by" is the credit
|
||||||
|
// and the following one the author; left-aligned text goes to contact.
|
||||||
|
func readTitlePage(ps []paragraph) screenplay.TitlePage {
|
||||||
|
var tp screenplay.TitlePage
|
||||||
|
var centered, left, right []string
|
||||||
|
for _, p := range ps {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, t := range p.Texts {
|
||||||
|
b.WriteString(t.Value)
|
||||||
|
}
|
||||||
|
s := strings.TrimSpace(b.String())
|
||||||
|
if s == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch p.Alignment {
|
||||||
|
case "Center":
|
||||||
|
centered = append(centered, s)
|
||||||
|
case "Right":
|
||||||
|
right = append(right, s)
|
||||||
|
default:
|
||||||
|
left = append(left, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loop:
|
||||||
|
for i, s := range centered {
|
||||||
|
switch {
|
||||||
|
case tp.Title == "":
|
||||||
|
tp.Title = s
|
||||||
|
case tp.Credit == "" && strings.Contains(strings.ToLower(s), "by"):
|
||||||
|
tp.Credit = s
|
||||||
|
case tp.Credit != "" && tp.Author == "":
|
||||||
|
tp.Author = s
|
||||||
|
default:
|
||||||
|
tp.Source = strings.TrimSpace(strings.Join(centered[i:], "\n"))
|
||||||
|
break loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tp.Contact = strings.Join(left, "\n")
|
||||||
|
tp.DraftDate = strings.Join(right, "\n")
|
||||||
|
return tp
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write serialises a Document to FDX. Locked pages and the paper size are
|
||||||
|
// not written.
|
||||||
|
func Write(w io.Writer, doc *screenplay.Document) error {
|
||||||
|
wr := &writer{}
|
||||||
|
wr.f = file{DocumentType: "Script", Template: "No", Version: "5"}
|
||||||
|
els := doc.Elements
|
||||||
|
for i := 0; i < len(els); {
|
||||||
|
el := els[i]
|
||||||
|
if !el.Type.Printed() {
|
||||||
|
if !el.IsEmpty() {
|
||||||
|
wr.pending = append(wr.pending, wr.note(outlineText(el), 0))
|
||||||
|
}
|
||||||
|
wr.newPage = wr.newPage || el.NewPage
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if el.Type == screenplay.Character {
|
||||||
|
j := blockEnd(els, i)
|
||||||
|
if j < len(els) && els[j].Type == screenplay.Character && els[j].Dual {
|
||||||
|
k := blockEnd(els, j)
|
||||||
|
dual := &content{}
|
||||||
|
for _, inner := range els[i:k] {
|
||||||
|
if !inner.IsEmpty() {
|
||||||
|
dual.Paragraphs = append(dual.Paragraphs, wr.paragraph(inner))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wr.add(paragraph{DualDialogue: dual}, el.NewPage)
|
||||||
|
i = k
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if el.IsEmpty() {
|
||||||
|
wr.newPage = wr.newPage || el.NewPage
|
||||||
|
} else {
|
||||||
|
wr.add(wr.paragraph(el), el.NewPage)
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if len(wr.pending) > 0 {
|
||||||
|
// Outline at the very end: an empty paragraph carries it.
|
||||||
|
wr.f.Content.Paragraphs = append(wr.f.Content.Paragraphs, paragraph{Type: "Action", ScriptNotes: wr.pending})
|
||||||
|
}
|
||||||
|
if !doc.TitlePage.IsEmpty() {
|
||||||
|
wr.f.TitlePage = &titlePage{Content: content{Paragraphs: writeTitlePage(doc.TitlePage)}}
|
||||||
|
}
|
||||||
|
if sets := doc.Settings.Revisions; len(sets) > 0 {
|
||||||
|
rs := &revisions{ActiveSet: len(sets), RevisionMode: "No"}
|
||||||
|
if doc.Settings.Revising {
|
||||||
|
rs.RevisionMode = "Yes"
|
||||||
|
}
|
||||||
|
for i, set := range sets {
|
||||||
|
name := set.Name + " Revision"
|
||||||
|
if set.Date != "" {
|
||||||
|
name += " - " + set.Date
|
||||||
|
}
|
||||||
|
hex := ""
|
||||||
|
for _, c := range revisionColors {
|
||||||
|
if c.name == set.Color {
|
||||||
|
hex = c.hex
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rs.Items = append(rs.Items, revision{ID: i + 1, Name: name, Color: hex, PageColor: hex, Mark: "*", FullRevision: "No"})
|
||||||
|
}
|
||||||
|
wr.f.Revisions = rs
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
buf.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="no" ?>` + "\n")
|
||||||
|
enc := xml.NewEncoder(&buf)
|
||||||
|
enc.Indent("", " ")
|
||||||
|
if err := enc.Encode(wr.f); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
buf.WriteString("\n")
|
||||||
|
_, err := w.Write(buf.Bytes())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
type writer struct {
|
||||||
|
f file
|
||||||
|
notes int // script notes written so far, for their IDs
|
||||||
|
pending []scriptNote // sections and synopses waiting for the next paragraph
|
||||||
|
newPage bool // page break of an element that was left out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wr *writer) note(body string, offset int) scriptNote {
|
||||||
|
wr.notes++
|
||||||
|
sn := scriptNote{ID: wr.notes, Range: strconv.Itoa(offset) + ",0"}
|
||||||
|
for _, line := range strings.Split(body, "\n") {
|
||||||
|
sn.Paragraphs = append(sn.Paragraphs, paragraph{Texts: []text{{Value: line}}})
|
||||||
|
}
|
||||||
|
return sn
|
||||||
|
}
|
||||||
|
|
||||||
|
// add appends a top-level paragraph with the outline and page break that
|
||||||
|
// precede it.
|
||||||
|
func (wr *writer) add(p paragraph, newPage bool) {
|
||||||
|
if newPage || wr.newPage {
|
||||||
|
p.StartsNewPage = "Yes"
|
||||||
|
}
|
||||||
|
p.ScriptNotes = append(wr.pending, p.ScriptNotes...)
|
||||||
|
wr.pending, wr.newPage = nil, false
|
||||||
|
wr.f.Content.Paragraphs = append(wr.f.Content.Paragraphs, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func outlineText(el screenplay.Element) string {
|
||||||
|
text := strings.ReplaceAll(el.Text(), "\n", " ")
|
||||||
|
if el.Type == screenplay.Section {
|
||||||
|
return strings.Repeat("#", max(el.Level, 1)) + " " + text
|
||||||
|
}
|
||||||
|
return "= " + text
|
||||||
|
}
|
||||||
|
|
||||||
|
// blockEnd returns the index just past the dialogue block starting at the
|
||||||
|
// character cue i.
|
||||||
|
func blockEnd(els []screenplay.Element, i int) int {
|
||||||
|
j := i + 1
|
||||||
|
for j < len(els) && els[j].Type.InDialogue() {
|
||||||
|
j++
|
||||||
|
}
|
||||||
|
return j
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wr *writer) paragraph(el screenplay.Element) paragraph {
|
||||||
|
p := paragraph{Type: typeNames[el.Type]}
|
||||||
|
if p.Type == "" {
|
||||||
|
p.Type = "Action"
|
||||||
|
}
|
||||||
|
if el.Type == screenplay.Centered || el.Type == screenplay.Intertitle {
|
||||||
|
p.Alignment = "Center"
|
||||||
|
}
|
||||||
|
if el.Type == screenplay.Scene {
|
||||||
|
p.Number = el.SceneNumber
|
||||||
|
}
|
||||||
|
var runs []screenplay.Run
|
||||||
|
offset := 0 // runes of printed text so far
|
||||||
|
for _, r := range el.Runs {
|
||||||
|
if r.Note {
|
||||||
|
body := r.Text
|
||||||
|
// A note starting like an outline element would be read as one.
|
||||||
|
if strings.HasPrefix(body, "#") || strings.HasPrefix(body, "=") || strings.HasPrefix(body, `\`) {
|
||||||
|
body = `\` + body
|
||||||
|
}
|
||||||
|
p.ScriptNotes = append(p.ScriptNotes, wr.note(body, offset))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
offset += len([]rune(r.Text))
|
||||||
|
runs = append(runs, r)
|
||||||
|
}
|
||||||
|
for _, r := range screenplay.NormalizeRuns(runs) {
|
||||||
|
t := r.Text
|
||||||
|
if el.Type.Uppercase() {
|
||||||
|
t = screenplay.UpperRunes(t)
|
||||||
|
}
|
||||||
|
p.Texts = append(p.Texts, text{Style: style(r), RevisionID: r.Rev, Value: t})
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeTitlePage(tp screenplay.TitlePage) []paragraph {
|
||||||
|
var ps []paragraph
|
||||||
|
add := func(align, s string) {
|
||||||
|
for _, line := range strings.Split(s, "\n") {
|
||||||
|
ps = append(ps, paragraph{Type: "Action", Alignment: align, Texts: []text{{Value: line}}})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blank := func(n int) {
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
add("Center", "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blank(16)
|
||||||
|
add("Center", tp.Title)
|
||||||
|
blank(2)
|
||||||
|
add("Center", tp.Credit)
|
||||||
|
blank(1)
|
||||||
|
add("Center", tp.Author)
|
||||||
|
if tp.Source != "" {
|
||||||
|
blank(2)
|
||||||
|
add("Center", tp.Source)
|
||||||
|
}
|
||||||
|
blank(16)
|
||||||
|
if tp.Contact != "" {
|
||||||
|
add("Left", tp.Contact)
|
||||||
|
}
|
||||||
|
if tp.DraftDate != "" {
|
||||||
|
add("Right", tp.DraftDate)
|
||||||
|
}
|
||||||
|
if tp.Notes != "" {
|
||||||
|
add("Right", tp.Notes)
|
||||||
|
}
|
||||||
|
return ps
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAllCaps(s string) bool {
|
||||||
|
return strings.ContainsFunc(s, unicode.IsLetter) && !strings.ContainsFunc(s, unicode.IsLower)
|
||||||
|
}
|
||||||
|
|
||||||
|
func style(r screenplay.Run) string {
|
||||||
|
var parts []string
|
||||||
|
if r.Bold {
|
||||||
|
parts = append(parts, "Bold")
|
||||||
|
}
|
||||||
|
if r.Italic {
|
||||||
|
parts = append(parts, "Italic")
|
||||||
|
}
|
||||||
|
if r.Underline {
|
||||||
|
parts = append(parts, "Underline")
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "+")
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package fdx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRoundTrip(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{
|
||||||
|
TitlePage: screenplay.TitlePage{Title: "Le Dernier Rouleau", Credit: "Written by", Author: "Jane Doe"},
|
||||||
|
Elements: []screenplay.Element{
|
||||||
|
{Type: screenplay.Scene, Runs: []screenplay.Run{{Text: "INT. CABINE - NUIT"}}, SceneNumber: "1"},
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{{Text: "Elle "}, {Text: "entre", Bold: true, Underline: true}, {Text: "."}}},
|
||||||
|
{Type: screenplay.Character, Runs: []screenplay.Run{{Text: "ÉLODIE"}}},
|
||||||
|
{Type: screenplay.Parenthetical, Runs: []screenplay.Run{{Text: "(bas)"}}},
|
||||||
|
{Type: screenplay.Dialogue, Runs: []screenplay.Run{{Text: "Ça finit ici."}}},
|
||||||
|
{Type: screenplay.Character, Runs: []screenplay.Run{{Text: "BOB"}}, Dual: true},
|
||||||
|
{Type: screenplay.Dialogue, Runs: []screenplay.Run{{Text: "Non."}}},
|
||||||
|
{Type: screenplay.Shot, Runs: []screenplay.Run{{Text: "INSERT - LA LETTRE"}}},
|
||||||
|
{Type: screenplay.Centered, Runs: []screenplay.Run{{Text: "Fin"}}},
|
||||||
|
{Type: screenplay.Intertitle, Runs: []screenplay.Run{{Text: "PARIS, 1942"}}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := Write(&buf, doc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := Read(&buf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Elements, doc.Elements) {
|
||||||
|
t.Errorf("elements:\n got %+v\nwant %+v", got.Elements, doc.Elements)
|
||||||
|
}
|
||||||
|
if got.TitlePage.Title != doc.TitlePage.Title || got.TitlePage.Author != doc.TitlePage.Author {
|
||||||
|
t.Errorf("title page: %+v", got.TitlePage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOutlineNotesRevisions(t *testing.T) {
|
||||||
|
bob := screenplay.Element{Type: screenplay.Character, Runs: []screenplay.Run{{Text: "BOB"}}, Dual: true}
|
||||||
|
doc := &screenplay.Document{
|
||||||
|
Settings: screenplay.Settings{
|
||||||
|
Revisions: []screenplay.Revision{{Name: "Blue", Color: "blue", Date: "09/14/26"}, {Name: "Pink", Color: "pink", Date: "09/28/26"}},
|
||||||
|
Revising: true,
|
||||||
|
},
|
||||||
|
Elements: []screenplay.Element{
|
||||||
|
{Type: screenplay.Section, Level: 2, Runs: []screenplay.Run{{Text: "Act One"}}},
|
||||||
|
{Type: screenplay.Synopsis, Runs: []screenplay.Run{{Text: "It starts."}}},
|
||||||
|
{Type: screenplay.Scene, Runs: []screenplay.Run{{Text: "INT. BOOTH - NIGHT"}}, NewPage: true},
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{
|
||||||
|
{Text: "He "}, {Text: "waits", Rev: 2, Bold: true}, {Text: ".", Rev: 1},
|
||||||
|
{Text: "# not a section", Note: true}, {Text: " Then", Rev: 1}, {Text: "fix", Note: true},
|
||||||
|
}},
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{{Text: "only a note", Note: true}}},
|
||||||
|
{Type: screenplay.Character, Runs: []screenplay.Run{{Text: "ALICE"}}, NewPage: true},
|
||||||
|
{Type: screenplay.Dialogue, Runs: []screenplay.Run{{Text: "Hi."}}},
|
||||||
|
bob,
|
||||||
|
{Type: screenplay.Dialogue, Runs: []screenplay.Run{{Text: "Hey."}}},
|
||||||
|
{Type: screenplay.Section, Level: 1, Runs: []screenplay.Run{{Text: "The End"}}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := Write(&buf, doc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
for _, want := range []string{`StartsNewPage="Yes"`, `RevisionID="2"`, `Name="Pink Revision - 09/28/26"`, `RevisionMode="Yes"`, `\# not a section`} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("missing %s in:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
got, err := Read(&buf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Settings, doc.Settings) {
|
||||||
|
t.Errorf("settings: %+v", got.Settings)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got.Elements, doc.Elements) {
|
||||||
|
for i := range got.Elements {
|
||||||
|
if i >= len(doc.Elements) || !reflect.DeepEqual(got.Elements[i], doc.Elements[i]) {
|
||||||
|
t.Errorf("element %d: %+v", i, got.Elements[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("round trip:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFinalDraftRevisionNames(t *testing.T) {
|
||||||
|
// A set named by Final Draft keeps its colour; an unknown name falls
|
||||||
|
// back to the colour of its position.
|
||||||
|
if r := readRevision(revision{Name: "Goldenrod Rev."}, 5); r.Name != "Goldenrod" || r.Color != "goldenrod" {
|
||||||
|
t.Errorf("got %+v", r)
|
||||||
|
}
|
||||||
|
if r := readRevision(revision{Name: "Second draft"}, 2); r.Name != "Second draft" || r.Color != "pink" {
|
||||||
|
t.Errorf("got %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package fountain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
const sample = `Title: The Last Reel
|
||||||
|
Credit: Written by
|
||||||
|
Author: Jane Doe
|
||||||
|
Draft date: 1 Sept 2026
|
||||||
|
|
||||||
|
INT. PROJECTION BOOTH - NIGHT #1#
|
||||||
|
|
||||||
|
Dust hangs in the **beam** of the projector.
|
||||||
|
|
||||||
|
INSERT - THE TICKET STUB
|
||||||
|
|
||||||
|
> Paris, 1942 <
|
||||||
|
|
||||||
|
MARGOT (V.O.)
|
||||||
|
(quietly)
|
||||||
|
It always ends *here*.
|
||||||
|
Right here.
|
||||||
|
|
||||||
|
CUT TO:
|
||||||
|
|
||||||
|
.FLASHBACK
|
||||||
|
|
||||||
|
@McCLANE
|
||||||
|
Yippee.
|
||||||
|
|
||||||
|
HANS ^
|
||||||
|
Nein.
|
||||||
|
|
||||||
|
!SHOUTING IS ACTION
|
||||||
|
and continues.
|
||||||
|
|
||||||
|
> THE END <
|
||||||
|
`
|
||||||
|
|
||||||
|
func types(doc *screenplay.Document) []screenplay.ElementType {
|
||||||
|
var out []screenplay.ElementType
|
||||||
|
for _, e := range doc.Elements {
|
||||||
|
out = append(out, e.Type)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParse(t *testing.T) {
|
||||||
|
doc := Parse(sample)
|
||||||
|
if doc.TitlePage.Title != "The Last Reel" || doc.TitlePage.Author != "Jane Doe" {
|
||||||
|
t.Fatalf("title page: %+v", doc.TitlePage)
|
||||||
|
}
|
||||||
|
want := []screenplay.ElementType{
|
||||||
|
screenplay.Scene, screenplay.Action, screenplay.Shot, screenplay.Centered,
|
||||||
|
screenplay.Character, screenplay.Parenthetical, screenplay.Dialogue,
|
||||||
|
screenplay.Transition, screenplay.Scene,
|
||||||
|
screenplay.Character, screenplay.Dialogue,
|
||||||
|
screenplay.Character, screenplay.Dialogue,
|
||||||
|
screenplay.Action, screenplay.Intertitle,
|
||||||
|
}
|
||||||
|
if got := types(doc); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("types:\n got %v\nwant %v", got, want)
|
||||||
|
}
|
||||||
|
if doc.Elements[0].SceneNumber != "1" || doc.Elements[0].Text() != "INT. PROJECTION BOOTH - NIGHT" {
|
||||||
|
t.Errorf("scene: %+v", doc.Elements[0])
|
||||||
|
}
|
||||||
|
if r := doc.Elements[1].Runs; len(r) != 3 || !r[1].Bold || r[1].Text != "beam" {
|
||||||
|
t.Errorf("bold runs: %+v", r)
|
||||||
|
}
|
||||||
|
if got := doc.Elements[2].Text(); got != "INSERT - THE TICKET STUB" {
|
||||||
|
t.Errorf("shot: %q", got)
|
||||||
|
}
|
||||||
|
if got := doc.Elements[6].Text(); got != "It always ends here.\nRight here." {
|
||||||
|
t.Errorf("dialogue: %q", got)
|
||||||
|
}
|
||||||
|
if got := doc.Elements[9].Text(); got != "McCLANE" {
|
||||||
|
t.Errorf("forced character: %q", got)
|
||||||
|
}
|
||||||
|
if hans := doc.Elements[11]; hans.Text() != "HANS" || !hans.Dual || doc.Elements[9].Dual {
|
||||||
|
t.Errorf("dual cue: %+v", hans)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInlineLiteralAsterisk(t *testing.T) {
|
||||||
|
runs := parseInline("2 * 3 = 6")
|
||||||
|
if len(runs) != 1 || runs[0].Text != "2 * 3 = 6" || runs[0].Italic {
|
||||||
|
t.Errorf("got %+v", runs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoundTrip(t *testing.T) {
|
||||||
|
first := Parse(sample)
|
||||||
|
second := Parse(Write(first))
|
||||||
|
if !reflect.DeepEqual(first, second) {
|
||||||
|
t.Fatalf("round trip changed the document:\n%s", Write(first))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const outline = `# Act One
|
||||||
|
|
||||||
|
## The Booth
|
||||||
|
|
||||||
|
= Margot finds the reel.
|
||||||
|
|
||||||
|
INT. PROJECTION BOOTH - NIGHT
|
||||||
|
|
||||||
|
Dust hangs in the beam. [[Too dark? Try dawn.]]
|
||||||
|
|
||||||
|
[[Cut the cat
|
||||||
|
|
||||||
|
or keep it for the ending.]]
|
||||||
|
|
||||||
|
MARGOT [[she whispers]]
|
||||||
|
(quietly)
|
||||||
|
It always ends here.
|
||||||
|
`
|
||||||
|
|
||||||
|
func TestOutlineAndNotes(t *testing.T) {
|
||||||
|
doc := Parse(outline)
|
||||||
|
want := []screenplay.ElementType{
|
||||||
|
screenplay.Section, screenplay.Section, screenplay.Synopsis, screenplay.Scene,
|
||||||
|
screenplay.Action, screenplay.Action, screenplay.Character, screenplay.Parenthetical, screenplay.Dialogue,
|
||||||
|
}
|
||||||
|
if got := types(doc); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Fatalf("types:\n got %v\nwant %v", got, want)
|
||||||
|
}
|
||||||
|
els := doc.Elements
|
||||||
|
if els[0].Level != 1 || els[0].Text() != "Act One" || els[1].Level != 2 || els[1].Text() != "The Booth" {
|
||||||
|
t.Errorf("sections: %+v %+v", els[0], els[1])
|
||||||
|
}
|
||||||
|
if els[2].Text() != "Margot finds the reel." {
|
||||||
|
t.Errorf("synopsis: %q", els[2].Text())
|
||||||
|
}
|
||||||
|
if r := els[4].Runs; len(r) != 2 || r[1].Text != "Too dark? Try dawn." || !r[1].Note || r[0].Note {
|
||||||
|
t.Errorf("inline note: %+v", r)
|
||||||
|
}
|
||||||
|
if r := els[5].Runs; len(r) != 1 || !r[0].Note || r[0].Text != "Cut the cat\n\nor keep it for the ending." {
|
||||||
|
t.Errorf("note paragraph: %+v", r)
|
||||||
|
}
|
||||||
|
if els[6].PrintedText() != "MARGOT " || !els[6].Runs[1].Note {
|
||||||
|
t.Errorf("note after a cue: %+v", els[6].Runs)
|
||||||
|
}
|
||||||
|
if second := Parse(Write(doc)); !reflect.DeepEqual(doc, second) {
|
||||||
|
t.Fatalf("round trip changed the document:\n%s", Write(doc))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionsAndLocks(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{
|
||||||
|
TitlePage: screenplay.TitlePage{Title: "Reel"},
|
||||||
|
Settings: screenplay.Settings{
|
||||||
|
Paper: screenplay.A4,
|
||||||
|
Revisions: []screenplay.Revision{{Name: "Blue", Color: "blue", Date: "09/28/26"}, {Name: "Pink", Color: "pink", Date: "*/"}},
|
||||||
|
Revising: true,
|
||||||
|
Locked: true,
|
||||||
|
},
|
||||||
|
Elements: []screenplay.Element{
|
||||||
|
{Type: screenplay.Scene, Runs: []screenplay.Run{{Text: "INT. BOOTH - NIGHT"}}, Locked: []screenplay.PageLock{{Offset: 0, Page: "2"}}},
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{
|
||||||
|
{Text: "Dust hangs in the "}, {Text: "golden", Rev: 2, Bold: true}, {Text: " beam.", Rev: 1},
|
||||||
|
{Text: " She waits.", Rev: 1, Note: true}, {Text: " Then leaves."},
|
||||||
|
}, Locked: []screenplay.PageLock{{Offset: 25, Page: "3"}, {Offset: 25, Page: "4"}}},
|
||||||
|
{Type: screenplay.Character, Runs: []screenplay.Run{{Text: "MARGOT"}}},
|
||||||
|
{Type: screenplay.Parenthetical, Runs: []screenplay.Run{{Text: "(quietly)", Rev: 1}}, Locked: []screenplay.PageLock{{Offset: 0, Page: "4A"}}},
|
||||||
|
{Type: screenplay.Dialogue, Runs: []screenplay.Run{{Text: "Here."}}},
|
||||||
|
{Type: screenplay.Shot, Runs: []screenplay.Run{{Text: "INSERT - ", Rev: 1}, {Text: "THE TICKET"}}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
out := Write(doc)
|
||||||
|
if !strings.Contains(out, "/*page 2*/INT. BOOTH") || !strings.Contains(out, "/*rev 2*/**golden**/*/rev*//*rev 1*/ /*page 3*//*page 4*/beam.") {
|
||||||
|
t.Errorf("markers:\n%s", out)
|
||||||
|
}
|
||||||
|
if got := Parse(out); !reflect.DeepEqual(doc, got) {
|
||||||
|
for i := range got.Elements {
|
||||||
|
if !reflect.DeepEqual(got.Elements[i], doc.Elements[i]) {
|
||||||
|
t.Errorf("element %d:\n got %#v\nwant %#v", i, got.Elements[i], doc.Elements[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("round trip changed the document:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlainScriptUnchanged(t *testing.T) {
|
||||||
|
// No Plotzilla data in a script that uses none of it.
|
||||||
|
if out := Write(Parse(sample)); strings.Contains(out, "/*") || strings.Contains(out, "[[") {
|
||||||
|
t.Errorf("unexpected markers:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPastedText(t *testing.T) {
|
||||||
|
els := ParseText("# Act Two\r\n\r\nJOHN\r\nHi. [[louder]]\r\n")
|
||||||
|
if len(els) != 3 || els[0].Type != screenplay.Section || els[2].PrintedText() != "Hi. " {
|
||||||
|
t.Errorf("got %+v", els)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvalidNoteStaysText(t *testing.T) {
|
||||||
|
// An empty line ends a note: without the two spaces this is not one.
|
||||||
|
doc := Parse("Wait [[for it\n\nnow]] here.\n")
|
||||||
|
if len(doc.Elements) != 2 || doc.Elements[0].Text() != "Wait [[for it" || doc.Elements[0].Runs[0].Note {
|
||||||
|
t.Errorf("got %+v", doc.Elements)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForcedPageBreak(t *testing.T) {
|
||||||
|
doc := Parse("INT. HOUSE - DAY\n\nHe waits.\n\n===\n\nEXT. ROAD - NIGHT\n\nJOHN\nHi.\n\n===\nLater.\n")
|
||||||
|
want := []bool{false, false, true, false, false, true}
|
||||||
|
for i, el := range doc.Elements {
|
||||||
|
if el.NewPage != want[i] {
|
||||||
|
t.Errorf("element %d %q: NewPage = %v", i, el.Text(), el.NewPage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := Write(doc)
|
||||||
|
if !strings.Contains(out, "He waits.\n\n===\n\nEXT. ROAD") {
|
||||||
|
t.Errorf("page break not written:\n%s", out)
|
||||||
|
}
|
||||||
|
if second := Parse(out); !reflect.DeepEqual(doc, second) {
|
||||||
|
t.Fatalf("round trip changed the document:\n%s", out)
|
||||||
|
}
|
||||||
|
// The page break of an empty element moves to the next one written.
|
||||||
|
doc.Elements[1] = screenplay.Element{Type: screenplay.Action, NewPage: true}
|
||||||
|
if again := Parse(Write(doc)); !again.Elements[1].NewPage || again.Elements[1].Type != screenplay.Scene {
|
||||||
|
t.Errorf("carried page break: %+v", again.Elements)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,418 @@
|
|||||||
|
// Package fountain reads and writes the Fountain plain-text screenplay
|
||||||
|
// format (https://fountain.io/syntax).
|
||||||
|
package fountain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
sceneRe = regexp.MustCompile(`(?i)^(INT|EXT|EST|INT\.?/EXT|I/E)[. ]`)
|
||||||
|
sceneNumberRe = regexp.MustCompile(`\s*#([\w.\-]+)#\s*$`)
|
||||||
|
transitionRe = regexp.MustCompile(`^[^a-z]*TO:$`)
|
||||||
|
titleKeyRe = regexp.MustCompile(`^([A-Za-z][A-Za-z ]*):\s*(.*)$`)
|
||||||
|
boneyardRe = regexp.MustCompile(`(?s)/\*.*?\*/`)
|
||||||
|
pageBreakRe = regexp.MustCompile(`^={3,}$`)
|
||||||
|
// Plotzilla's own data lives in boneyard comments, which other Fountain
|
||||||
|
// apps ignore: the document settings in one block at the end, and
|
||||||
|
// revision and locked-page markers inline, where they travel with the
|
||||||
|
// text they mark.
|
||||||
|
settingsRe = regexp.MustCompile(`(?s)/\*\s*Plotzilla (\{.*?\})\s*\*/`)
|
||||||
|
markerRe = regexp.MustCompile(`/\*(rev \d+|/rev|page [^*\s]+)\*/`)
|
||||||
|
noteRe = regexp.MustCompile(`(?s)\[\[.*?\]\]`)
|
||||||
|
tokenRe = regexp.MustCompile("\uE000[^\uE001]*\uE001")
|
||||||
|
// Fountain has no shot element: shots are all-caps action lines.
|
||||||
|
shotRe = regexp.MustCompile(`^(INSERT|CLOSE ON|CLOSE UP|EXTREME CLOSE|ECU|CU|ANGLE ON|NEW ANGLE|REVERSE ANGLE|POV|WIDE ON|WIDE SHOT|OVERHEAD|BACK TO SCENE|TRACKING|AERIAL)\b`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Parse converts Fountain source into a Document. Boneyard that is not
|
||||||
|
// Plotzilla's own data is dropped.
|
||||||
|
func Parse(src string) *screenplay.Document {
|
||||||
|
src = strings.TrimPrefix(src, "\ufeff")
|
||||||
|
src = strings.ReplaceAll(src, "\r\n", "\n")
|
||||||
|
src = strings.ReplaceAll(src, "\r", "\n")
|
||||||
|
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
if m := settingsRe.FindAllStringSubmatchIndex(src, -1); len(m) > 0 {
|
||||||
|
last := m[len(m)-1]
|
||||||
|
doc.Settings = parseSettings(src[last[2]:last[3]])
|
||||||
|
src = src[:last[0]] + src[last[1]:]
|
||||||
|
}
|
||||||
|
p := tokenize(src)
|
||||||
|
lines := strings.Split(p.src, "\n")
|
||||||
|
start := parseTitlePage(lines, &doc.TitlePage)
|
||||||
|
doc.Elements = p.elements(lines[start:])
|
||||||
|
if len(doc.Elements) == 0 {
|
||||||
|
doc.Elements = []screenplay.Element{screenplay.NewElement(screenplay.Scene, "")}
|
||||||
|
}
|
||||||
|
return doc
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseSettings(data string) screenplay.Settings {
|
||||||
|
var s screenplay.Settings
|
||||||
|
if json.Unmarshal([]byte(data), &s) != nil {
|
||||||
|
return screenplay.Settings{}
|
||||||
|
}
|
||||||
|
if s.Paper != screenplay.A4 {
|
||||||
|
s.Paper = screenplay.Letter
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseText parses body text (no title page), such as pasted plain text.
|
||||||
|
func ParseText(text string) []screenplay.Element {
|
||||||
|
text = strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\r", "\n")
|
||||||
|
p := tokenize(text)
|
||||||
|
return p.elements(strings.Split(p.src, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseElements parses body lines (no title page).
|
||||||
|
func ParseElements(lines []string) []screenplay.Element {
|
||||||
|
return ParseText(strings.Join(lines, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// parser holds the source once notes and markers have been replaced by
|
||||||
|
// tokens: U+E000, a payload, U+E001. Tokens contain no line break, so a
|
||||||
|
// note spanning lines no longer splits its paragraph, and line rules look
|
||||||
|
// at the text without them (bare).
|
||||||
|
type parser struct {
|
||||||
|
src string
|
||||||
|
notes []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func token(payload string) string { return "\uE000" + payload + "\uE001" }
|
||||||
|
|
||||||
|
// bare removes the tokens: what line classification looks at.
|
||||||
|
func bare(s string) string { return strings.TrimSpace(tokenRe.ReplaceAllString(s, "")) }
|
||||||
|
|
||||||
|
func tokenize(src string) *parser {
|
||||||
|
src = markerRe.ReplaceAllStringFunc(src, func(m string) string {
|
||||||
|
body := m[2 : len(m)-2]
|
||||||
|
switch {
|
||||||
|
case body == "/rev":
|
||||||
|
return token("r")
|
||||||
|
case strings.HasPrefix(body, "rev "):
|
||||||
|
return token("r" + body[4:])
|
||||||
|
}
|
||||||
|
return token("p" + strings.TrimPrefix(body, "page "))
|
||||||
|
})
|
||||||
|
src = boneyardRe.ReplaceAllString(src, "")
|
||||||
|
p := &parser{}
|
||||||
|
src = noteRe.ReplaceAllStringFunc(src, func(m string) string {
|
||||||
|
note, ok := noteText(m[2 : len(m)-2])
|
||||||
|
if !ok {
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
p.notes = append(p.notes, note)
|
||||||
|
return token("n" + strconv.Itoa(len(p.notes)-1))
|
||||||
|
})
|
||||||
|
p.src = src
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// noteText validates a note's content: it may span lines, but an empty
|
||||||
|
// line inside it must hold two spaces, as in dialogue.
|
||||||
|
func noteText(s string) (string, bool) {
|
||||||
|
lines := strings.Split(s, "\n")
|
||||||
|
for i := 1; i < len(lines)-1; i++ {
|
||||||
|
if strings.TrimSpace(lines[i]) == "" {
|
||||||
|
if len(lines[i]) < 2 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
lines[i] = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n"), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *parser) elements(lines []string) []screenplay.Element {
|
||||||
|
var out []screenplay.Element
|
||||||
|
add := func(t screenplay.ElementType, text string) {
|
||||||
|
runs, locks := p.inline(text)
|
||||||
|
out = append(out, screenplay.Element{Type: t, Runs: runs, Locked: locks})
|
||||||
|
}
|
||||||
|
blank := func(i int) bool { return i < 0 || i >= len(lines) || strings.TrimSpace(lines[i]) == "" }
|
||||||
|
|
||||||
|
prevBlank := true
|
||||||
|
newPage := false // a "===" line: the next element starts a page
|
||||||
|
for i := 0; i < len(lines); i++ {
|
||||||
|
trimmed := strings.TrimSpace(lines[i])
|
||||||
|
if trimmed == "" {
|
||||||
|
prevBlank = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
nextBlank := blank(i + 1)
|
||||||
|
b := bare(trimmed)
|
||||||
|
if pageBreakRe.MatchString(b) {
|
||||||
|
newPage = true
|
||||||
|
prevBlank = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
first := len(out)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(b, "#"):
|
||||||
|
text := strings.TrimLeft(trimmed, "#")
|
||||||
|
add(screenplay.Section, strings.TrimSpace(text))
|
||||||
|
out[len(out)-1].Level = max(len(b)-len(strings.TrimLeft(b, "#")), 1)
|
||||||
|
|
||||||
|
case strings.HasPrefix(b, "="):
|
||||||
|
add(screenplay.Synopsis, strings.TrimSpace(strings.TrimPrefix(trimmed, "=")))
|
||||||
|
|
||||||
|
case strings.HasPrefix(b, ">") && strings.HasSuffix(b, "<") && len(b) > 1:
|
||||||
|
// Fountain only knows centred text; an all-caps one is read as
|
||||||
|
// an intertitle (title card), which is how Plotzilla writes them.
|
||||||
|
text := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(trimmed, ">"), "<"))
|
||||||
|
if isCharacterCue(bare(text)) {
|
||||||
|
add(screenplay.Intertitle, text)
|
||||||
|
} else {
|
||||||
|
add(screenplay.Centered, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
case prevBlank && nextBlank && shotRe.MatchString(b) && isCharacterCue(b):
|
||||||
|
add(screenplay.Shot, trimmed)
|
||||||
|
|
||||||
|
case strings.HasPrefix(b, ">"):
|
||||||
|
add(screenplay.Transition, strings.TrimSpace(strings.TrimPrefix(trimmed, ">")))
|
||||||
|
|
||||||
|
case strings.HasPrefix(b, ".") && !strings.HasPrefix(b, ".."):
|
||||||
|
p.addScene(&out, strings.TrimPrefix(trimmed, "."))
|
||||||
|
|
||||||
|
case prevBlank && sceneRe.MatchString(b):
|
||||||
|
p.addScene(&out, trimmed)
|
||||||
|
|
||||||
|
case prevBlank && nextBlank && transitionRe.MatchString(b):
|
||||||
|
add(screenplay.Transition, trimmed)
|
||||||
|
|
||||||
|
case prevBlank && !nextBlank && !strings.HasPrefix(b, "!") &&
|
||||||
|
(strings.HasPrefix(b, "@") || isCharacterCue(b)):
|
||||||
|
cue := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(trimmed, "@"), "^"))
|
||||||
|
add(screenplay.Character, cue)
|
||||||
|
out[len(out)-1].Dual = strings.HasSuffix(b, "^")
|
||||||
|
i = p.dialogue(lines, i+1, &out)
|
||||||
|
|
||||||
|
default:
|
||||||
|
// Action: consecutive non-blank lines form one paragraph.
|
||||||
|
para := []string{strings.TrimPrefix(strings.TrimPrefix(trimmed, "!"), "~")}
|
||||||
|
for !blank(i + 1) {
|
||||||
|
i++
|
||||||
|
para = append(para, strings.TrimSpace(strings.TrimPrefix(lines[i], "~")))
|
||||||
|
}
|
||||||
|
add(screenplay.Action, strings.Join(para, "\n"))
|
||||||
|
}
|
||||||
|
if newPage && len(out) > first {
|
||||||
|
out[first].NewPage = true
|
||||||
|
newPage = false
|
||||||
|
}
|
||||||
|
prevBlank = false
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *parser) addScene(out *[]screenplay.Element, text string) {
|
||||||
|
el := screenplay.Element{Type: screenplay.Scene}
|
||||||
|
if m := sceneNumberRe.FindStringSubmatch(text); m != nil {
|
||||||
|
el.SceneNumber = m[1]
|
||||||
|
text = text[:len(text)-len(m[0])]
|
||||||
|
}
|
||||||
|
el.Runs, el.Locked = p.inline(strings.TrimSpace(text))
|
||||||
|
*out = append(*out, el)
|
||||||
|
}
|
||||||
|
|
||||||
|
// dialogue consumes the lines of a dialogue block starting at i and
|
||||||
|
// returns the index of the last consumed line.
|
||||||
|
func (p *parser) dialogue(lines []string, i int, out *[]screenplay.Element) int {
|
||||||
|
var cur []string
|
||||||
|
add := func(t screenplay.ElementType, text string) {
|
||||||
|
runs, locks := p.inline(text)
|
||||||
|
*out = append(*out, screenplay.Element{Type: t, Runs: runs, Locked: locks})
|
||||||
|
}
|
||||||
|
flush := func() {
|
||||||
|
if len(cur) > 0 {
|
||||||
|
add(screenplay.Dialogue, strings.Join(cur, "\n"))
|
||||||
|
cur = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ; i < len(lines); i++ {
|
||||||
|
line := lines[i]
|
||||||
|
trimmed := strings.TrimSpace(line)
|
||||||
|
if trimmed == "" {
|
||||||
|
// Two spaces keep an intentional empty line inside dialogue.
|
||||||
|
if len(line) >= 2 && len(cur) > 0 {
|
||||||
|
cur = append(cur, "")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if b := bare(trimmed); strings.HasPrefix(b, "(") && strings.HasSuffix(b, ")") {
|
||||||
|
flush()
|
||||||
|
add(screenplay.Parenthetical, trimmed)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cur = append(cur, trimmed)
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return i - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func isCharacterCue(s string) bool {
|
||||||
|
name := strings.TrimSuffix(s, "^")
|
||||||
|
if j := strings.Index(name, "("); j >= 0 {
|
||||||
|
name = name[:j]
|
||||||
|
}
|
||||||
|
hasLetter := false
|
||||||
|
for _, r := range name {
|
||||||
|
if unicode.IsLetter(r) {
|
||||||
|
hasLetter = true
|
||||||
|
if unicode.IsLower(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasLetter
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTitlePage reads "Key: value" pairs at the top of the file and returns
|
||||||
|
// the index of the first body line.
|
||||||
|
func parseTitlePage(lines []string, tp *screenplay.TitlePage) int {
|
||||||
|
if len(lines) == 0 || !titleKeyRe.MatchString(lines[0]) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var key string
|
||||||
|
values := map[string][]string{}
|
||||||
|
i := 0
|
||||||
|
for ; i < len(lines); i++ {
|
||||||
|
line := lines[i]
|
||||||
|
if strings.TrimSpace(line) == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if m := titleKeyRe.FindStringSubmatch(line); m != nil && !startsIndented(line) {
|
||||||
|
key = strings.ToLower(strings.TrimSpace(m[1]))
|
||||||
|
if v := strings.TrimSpace(m[2]); v != "" {
|
||||||
|
values[key] = append(values[key], v)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if key != "" {
|
||||||
|
values[key] = append(values[key], strings.TrimSpace(line))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get := func(keys ...string) string {
|
||||||
|
var parts []string
|
||||||
|
for _, k := range keys {
|
||||||
|
for _, v := range values[k] {
|
||||||
|
parts = append(parts, plain(v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "\n")
|
||||||
|
}
|
||||||
|
tp.Title = get("title")
|
||||||
|
tp.Credit = get("credit")
|
||||||
|
tp.Author = get("author", "authors")
|
||||||
|
tp.Source = get("source")
|
||||||
|
tp.DraftDate = get("draft date", "date")
|
||||||
|
tp.Contact = get("contact")
|
||||||
|
tp.Notes = get("notes", "copyright")
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
func startsIndented(line string) bool {
|
||||||
|
return strings.HasPrefix(line, "\t") || strings.HasPrefix(line, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// plain drops emphasis, notes and markers from a title page value.
|
||||||
|
func plain(s string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range parseInline(s) {
|
||||||
|
b.WriteString(r.Text)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseInline parses emphasis; notes are dropped.
|
||||||
|
func parseInline(s string) []screenplay.Run {
|
||||||
|
runs, _ := (&parser{}).inline(s)
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
|
||||||
|
// inline turns Fountain emphasis (**bold**, *italic*, _underline_, with
|
||||||
|
// backslash escapes) into runs, and tokens into notes, revision levels and
|
||||||
|
// page locks. A marker only opens a span when a matching marker follows on
|
||||||
|
// the same line, so stray asterisks stay literal.
|
||||||
|
func (p *parser) inline(s string) ([]screenplay.Run, []screenplay.PageLock) {
|
||||||
|
var runs []screenplay.Run
|
||||||
|
var locks []screenplay.PageLock
|
||||||
|
var cur screenplay.Run
|
||||||
|
var buf strings.Builder
|
||||||
|
offset := 0 // runes of element text so far
|
||||||
|
flush := func() {
|
||||||
|
if buf.Len() > 0 {
|
||||||
|
cur.Text = buf.String()
|
||||||
|
runs = append(runs, cur)
|
||||||
|
buf.Reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rs := []rune(s)
|
||||||
|
closes := func(from int, marker string) bool {
|
||||||
|
rest := string(rs[from:])
|
||||||
|
if nl := strings.IndexByte(rest, '\n'); nl >= 0 {
|
||||||
|
rest = rest[:nl]
|
||||||
|
}
|
||||||
|
return strings.Contains(rest, marker)
|
||||||
|
}
|
||||||
|
for i := 0; i < len(rs); i++ {
|
||||||
|
c := rs[i]
|
||||||
|
switch {
|
||||||
|
case c == '\uE000':
|
||||||
|
end := i + 1
|
||||||
|
for end < len(rs) && rs[end] != '\uE001' {
|
||||||
|
end++
|
||||||
|
}
|
||||||
|
payload := string(rs[i+1 : min(end, len(rs))])
|
||||||
|
i = end
|
||||||
|
if payload == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
arg := payload[1:]
|
||||||
|
switch payload[0] {
|
||||||
|
case 'n':
|
||||||
|
if n, err := strconv.Atoi(arg); err == nil && n < len(p.notes) {
|
||||||
|
flush()
|
||||||
|
runs = append(runs, screenplay.Run{Text: p.notes[n], Note: true, Rev: cur.Rev})
|
||||||
|
offset += len([]rune(p.notes[n]))
|
||||||
|
}
|
||||||
|
case 'r':
|
||||||
|
flush()
|
||||||
|
cur.Rev, _ = strconv.Atoi(arg)
|
||||||
|
case 'p':
|
||||||
|
locks = append(locks, screenplay.PageLock{Offset: offset, Page: arg})
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
case c == '\\' && i+1 < len(rs) && strings.ContainsRune(`*_\`, rs[i+1]):
|
||||||
|
buf.WriteRune(rs[i+1])
|
||||||
|
offset++
|
||||||
|
i++
|
||||||
|
case c == '*' && i+1 < len(rs) && rs[i+1] == '*' && (cur.Bold || closes(i+2, "**")):
|
||||||
|
flush()
|
||||||
|
cur.Bold = !cur.Bold
|
||||||
|
i++
|
||||||
|
case c == '*' && (cur.Italic || closes(i+1, "*")):
|
||||||
|
flush()
|
||||||
|
cur.Italic = !cur.Italic
|
||||||
|
case c == '_' && (cur.Underline || closes(i+1, "_")):
|
||||||
|
flush()
|
||||||
|
cur.Underline = !cur.Underline
|
||||||
|
default:
|
||||||
|
buf.WriteRune(c)
|
||||||
|
offset++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return screenplay.NormalizeRuns(runs), locks
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
package fountain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Write serialises a Document to Fountain. Elements that Fountain would
|
||||||
|
// otherwise misread are written with the explicit "force" prefixes.
|
||||||
|
func Write(doc *screenplay.Document) string {
|
||||||
|
var b strings.Builder
|
||||||
|
writeTitlePage(&b, doc.TitlePage)
|
||||||
|
|
||||||
|
var prev screenplay.ElementType
|
||||||
|
var carried []screenplay.PageLock // locks of skipped empty elements
|
||||||
|
carriedPage := false // and their forced page break
|
||||||
|
first := true
|
||||||
|
for _, el := range doc.Elements {
|
||||||
|
if el.IsEmpty() {
|
||||||
|
for _, l := range el.Locked {
|
||||||
|
carried = append(carried, screenplay.PageLock{Page: l.Page})
|
||||||
|
}
|
||||||
|
carriedPage = carriedPage || el.NewPage
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
locks := append(carried, el.Locked...)
|
||||||
|
newPage := carriedPage || el.NewPage
|
||||||
|
carried, carriedPage = nil, false
|
||||||
|
inBlock := el.Type.InDialogue() && (prev == screenplay.Character || prev.InDialogue())
|
||||||
|
if !first && !inBlock {
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
// "===" cannot sit inside a dialogue block: layout breaks before the
|
||||||
|
// block anyway.
|
||||||
|
if newPage && !inBlock {
|
||||||
|
b.WriteString("===\n\n")
|
||||||
|
}
|
||||||
|
first = false
|
||||||
|
prev = el.Type
|
||||||
|
|
||||||
|
if el.Type == screenplay.Intertitle || el.Type == screenplay.Shot {
|
||||||
|
el = upper(el)
|
||||||
|
}
|
||||||
|
// Notes keep their line breaks where Fountain keeps the element's.
|
||||||
|
keepLines := el.Type == screenplay.Action || el.Type == screenplay.Dialogue
|
||||||
|
text := markup(el, locks, keepLines)
|
||||||
|
plainText := el.PrintedText()
|
||||||
|
switch el.Type {
|
||||||
|
// Case is kept as typed ("McCLANE"); layout upper-cases when printing.
|
||||||
|
case screenplay.Scene:
|
||||||
|
if !sceneRe.MatchString(plainText) {
|
||||||
|
text = "." + text
|
||||||
|
}
|
||||||
|
if el.SceneNumber != "" {
|
||||||
|
text += " #" + el.SceneNumber + "#"
|
||||||
|
}
|
||||||
|
case screenplay.Character:
|
||||||
|
if sceneRe.MatchString(plainText) || !isCharacterCue(plainText) {
|
||||||
|
text = "@" + text
|
||||||
|
}
|
||||||
|
if el.Dual {
|
||||||
|
text += " ^"
|
||||||
|
}
|
||||||
|
case screenplay.Parenthetical:
|
||||||
|
text = strings.ReplaceAll(text, "\n", " ")
|
||||||
|
if !strings.HasPrefix(plainText, "(") {
|
||||||
|
text = "(" + text
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(plainText, ")") {
|
||||||
|
text += ")"
|
||||||
|
}
|
||||||
|
case screenplay.Dialogue:
|
||||||
|
text = strings.ReplaceAll(text, "\n\n", "\n \n")
|
||||||
|
case screenplay.Transition:
|
||||||
|
if !transitionRe.MatchString(plainText) {
|
||||||
|
text = "> " + text
|
||||||
|
}
|
||||||
|
case screenplay.Centered, screenplay.Intertitle:
|
||||||
|
text = "> " + strings.ReplaceAll(text, "\n", " <\n> ") + " <"
|
||||||
|
case screenplay.Shot:
|
||||||
|
// Written as an all-caps line; read back as a shot when it
|
||||||
|
// starts like one (INSERT, CLOSE ON, POV, ...).
|
||||||
|
text = strings.ReplaceAll(text, "\n", " ")
|
||||||
|
if check := strings.ReplaceAll(plainText, "\n", " "); needsForcedAction(check) && !shotRe.MatchString(check) {
|
||||||
|
text = "!" + text
|
||||||
|
}
|
||||||
|
case screenplay.Section:
|
||||||
|
text = strings.Repeat("#", max(el.Level, 1)) + " " + strings.ReplaceAll(text, "\n", " ")
|
||||||
|
case screenplay.Synopsis:
|
||||||
|
text = "= " + strings.ReplaceAll(text, "\n", " ")
|
||||||
|
default:
|
||||||
|
if needsForcedAction(plainText) {
|
||||||
|
text = "!" + text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteString(text)
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
writeSettings(&b, doc.Settings)
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeSettings stores the production settings in a boneyard block that
|
||||||
|
// other Fountain apps ignore.
|
||||||
|
func writeSettings(b *strings.Builder, s screenplay.Settings) {
|
||||||
|
if s.IsZero() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(s)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// "*/" can only occur inside a JSON string, where "\/" means "/".
|
||||||
|
b.WriteString("\n/* Plotzilla " + strings.ReplaceAll(string(data), "*/", `*\/`) + " */\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// upper capitalises the text of an element that is always written in
|
||||||
|
// capitals, leaving its notes alone.
|
||||||
|
func upper(el screenplay.Element) screenplay.Element {
|
||||||
|
runs := make([]screenplay.Run, len(el.Runs))
|
||||||
|
for i, r := range el.Runs {
|
||||||
|
if !r.Note {
|
||||||
|
r.Text = screenplay.UpperRunes(r.Text)
|
||||||
|
}
|
||||||
|
runs[i] = r
|
||||||
|
}
|
||||||
|
el.Runs = runs
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
func needsForcedAction(s string) bool {
|
||||||
|
first := s
|
||||||
|
if i := strings.IndexByte(s, '\n'); i >= 0 {
|
||||||
|
first = s[:i]
|
||||||
|
}
|
||||||
|
first = strings.TrimSpace(first)
|
||||||
|
if first == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.ContainsRune(".>@#=~!", rune(first[0])) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if sceneRe.MatchString(first) || transitionRe.MatchString(first) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// An all-caps first line followed by more lines would read as a character.
|
||||||
|
return strings.Contains(s, "\n") && isCharacterCue(first)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeTitlePage(b *strings.Builder, tp screenplay.TitlePage) {
|
||||||
|
if tp.IsEmpty() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
field := func(key, value string) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lines := strings.Split(value, "\n")
|
||||||
|
if len(lines) == 1 {
|
||||||
|
b.WriteString(key + ": " + value + "\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.WriteString(key + ":\n")
|
||||||
|
for _, l := range lines {
|
||||||
|
b.WriteString(" " + strings.TrimSpace(l) + "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
field("Title", tp.Title)
|
||||||
|
field("Credit", tp.Credit)
|
||||||
|
field("Author", tp.Author)
|
||||||
|
field("Source", tp.Source)
|
||||||
|
field("Draft date", tp.DraftDate)
|
||||||
|
field("Contact", tp.Contact)
|
||||||
|
field("Notes", tp.Notes)
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// markup renders runs with Fountain emphasis markers, notes ("[[…]]"),
|
||||||
|
// revision markers ("/*rev 2*/…/*/rev*/") and locked page starts
|
||||||
|
// ("/*page 12*/"). Emphasis cannot span lines in Fountain, so markers are
|
||||||
|
// closed and reopened around "\n".
|
||||||
|
func markup(el screenplay.Element, locks []screenplay.PageLock, keepNoteLines bool) string {
|
||||||
|
var b strings.Builder
|
||||||
|
pos, next, rev := 0, 0, 0
|
||||||
|
emitLocks := func() {
|
||||||
|
for ; next < len(locks) && locks[next].Offset <= pos; next++ {
|
||||||
|
b.WriteString("/*page " + locks[next].Page + "*/")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range splitRuns(el.Runs, locks) {
|
||||||
|
emitLocks()
|
||||||
|
if r.Rev != rev {
|
||||||
|
if rev > 0 {
|
||||||
|
b.WriteString("/*/rev*/")
|
||||||
|
}
|
||||||
|
if r.Rev > 0 {
|
||||||
|
b.WriteString("/*rev " + strconv.Itoa(r.Rev) + "*/")
|
||||||
|
}
|
||||||
|
rev = r.Rev
|
||||||
|
}
|
||||||
|
pos += len([]rune(r.Text))
|
||||||
|
if r.Note {
|
||||||
|
b.WriteString("[[" + noteMarkup(r.Text, keepNoteLines) + "]]")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
open, close := "", ""
|
||||||
|
if r.Underline {
|
||||||
|
open += "_"
|
||||||
|
}
|
||||||
|
if r.Bold {
|
||||||
|
open += "**"
|
||||||
|
}
|
||||||
|
if r.Italic {
|
||||||
|
open += "*"
|
||||||
|
}
|
||||||
|
for i := len(open) - 1; i >= 0; i-- {
|
||||||
|
close += string(open[i])
|
||||||
|
}
|
||||||
|
for i, line := range strings.Split(r.Text, "\n") {
|
||||||
|
if i > 0 {
|
||||||
|
b.WriteString("\n")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(line) == "" || open == "" {
|
||||||
|
b.WriteString(escape(line))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Keep surrounding spaces outside the markers.
|
||||||
|
lead := len(line) - len(strings.TrimLeftFunc(line, unicode.IsSpace))
|
||||||
|
trail := len(strings.TrimRightFunc(line, unicode.IsSpace))
|
||||||
|
b.WriteString(line[:lead] + open + escape(line[lead:trail]) + close + line[trail:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rev > 0 {
|
||||||
|
b.WriteString("/*/rev*/")
|
||||||
|
}
|
||||||
|
emitLocks()
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitRuns cuts runs where a page lock falls, so that its marker can be
|
||||||
|
// written between two runs.
|
||||||
|
func splitRuns(runs []screenplay.Run, locks []screenplay.PageLock) []screenplay.Run {
|
||||||
|
if len(locks) == 0 {
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
var out []screenplay.Run
|
||||||
|
pos := 0
|
||||||
|
for _, r := range runs {
|
||||||
|
rs := []rune(r.Text)
|
||||||
|
start := 0
|
||||||
|
for _, l := range locks {
|
||||||
|
if at := l.Offset - pos; at > start && at < len(rs) {
|
||||||
|
part := r
|
||||||
|
part.Text = string(rs[start:at])
|
||||||
|
out = append(out, part)
|
||||||
|
start = at
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.Text = string(rs[start:])
|
||||||
|
out = append(out, r)
|
||||||
|
pos += len(rs)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func noteMarkup(s string, keepLines bool) string {
|
||||||
|
s = strings.ReplaceAll(strings.ReplaceAll(s, "[[", "[ ["), "]]", "] ]")
|
||||||
|
if !keepLines {
|
||||||
|
return strings.ReplaceAll(s, "\n", " ")
|
||||||
|
}
|
||||||
|
// An empty line inside a note holds two spaces, as in dialogue.
|
||||||
|
lines := strings.Split(s, "\n")
|
||||||
|
for i := 1; i < len(lines)-1; i++ {
|
||||||
|
if strings.TrimSpace(lines[i]) == "" {
|
||||||
|
lines[i] = " "
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func escape(s string) string {
|
||||||
|
s = strings.ReplaceAll(s, `\`, `\\`)
|
||||||
|
s = strings.ReplaceAll(s, "*", `\*`)
|
||||||
|
return strings.ReplaceAll(s, "_", `\_`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,908 @@
|
|||||||
|
// Package layout turns a Document into printed pages following the
|
||||||
|
// Hollywood screenplay standard: US Letter (or A4), Courier 12pt (10
|
||||||
|
// characters per inch, 6 lines per inch), 1.5" left margin, ~55 lines per
|
||||||
|
// page so that one page reads as roughly one minute of screen time.
|
||||||
|
//
|
||||||
|
// It applies the usual pagination rules: a scene heading is never the last
|
||||||
|
// thing on a page, action and dialogue only break at the end of a sentence
|
||||||
|
// with at least two lines on each side, a page never ends on a
|
||||||
|
// parenthetical, and split dialogue gets "(MORE)" / "NAME (CONT'D)".
|
||||||
|
// Sections, synopses and notes are not printed. An element marked NewPage
|
||||||
|
// (Fountain "===") starts a page.
|
||||||
|
//
|
||||||
|
// Once pages are locked, every locked page starts where it did when it was
|
||||||
|
// locked: material added to a page flows onto A pages (12A, 12B), and a
|
||||||
|
// page whose material was all removed is merged with the previous one
|
||||||
|
// (12-13).
|
||||||
|
package layout
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
TopMargin = 1.0 // inches
|
||||||
|
CharWidth = 0.1 // Courier 12pt
|
||||||
|
LineHeight = 1.0 / 6
|
||||||
|
RightEdge = 7.5
|
||||||
|
)
|
||||||
|
|
||||||
|
// Geometry is what changes with the paper size. The text keeps the same
|
||||||
|
// margins and widths on A4; the page is longer, so it holds more lines.
|
||||||
|
type Geometry struct {
|
||||||
|
Width, Height float64 // inches
|
||||||
|
Lines int // body lines per page, between 1" margins
|
||||||
|
// SceneNumber is where the right-hand scene number starts, and
|
||||||
|
// RevisionMark where the revision asterisk goes.
|
||||||
|
SceneNumber float64
|
||||||
|
RevisionMark float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// PaperGeometry returns the geometry of a paper size.
|
||||||
|
func PaperGeometry(paper screenplay.Paper) Geometry {
|
||||||
|
if paper == screenplay.A4 {
|
||||||
|
return Geometry{Width: 8.27, Height: 11.69, Lines: 58, SceneNumber: 7.6, RevisionMark: 7.95}
|
||||||
|
}
|
||||||
|
return Geometry{Width: 8.5, Height: 11, Lines: 54, SceneNumber: 7.75, RevisionMark: 8.1}
|
||||||
|
}
|
||||||
|
|
||||||
|
type spec struct {
|
||||||
|
left float64 // inches from the left edge of the page
|
||||||
|
width int // characters per line
|
||||||
|
before int // blank lines before the element
|
||||||
|
}
|
||||||
|
|
||||||
|
var specs = map[screenplay.ElementType]spec{
|
||||||
|
screenplay.Scene: {1.5, 60, 2},
|
||||||
|
screenplay.Action: {1.5, 60, 1},
|
||||||
|
screenplay.Character: {3.7, 38, 1},
|
||||||
|
screenplay.Parenthetical: {3.1, 25, 0},
|
||||||
|
screenplay.Dialogue: {2.5, 35, 0},
|
||||||
|
screenplay.Transition: {1.5, 60, 1},
|
||||||
|
screenplay.Centered: {1.5, 60, 1},
|
||||||
|
screenplay.Shot: {1.5, 60, 1},
|
||||||
|
screenplay.Intertitle: {1.5, 60, 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
type Segment struct {
|
||||||
|
Text string
|
||||||
|
Bold bool
|
||||||
|
Italic bool
|
||||||
|
Underline bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Line struct {
|
||||||
|
Row int // 0-based line within the page body
|
||||||
|
X float64 // inches from the left edge of the page
|
||||||
|
Segments []Segment
|
||||||
|
SceneNumber string // printed in both margins when set
|
||||||
|
Rev int // latest revision set of the text on the line
|
||||||
|
}
|
||||||
|
|
||||||
|
type Page struct {
|
||||||
|
Number int // 1, 2, 3… in print order (0 for a title page)
|
||||||
|
Label string // the printed page number: "12", "12A", "12-13"
|
||||||
|
Lines []Line
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rev is the latest revision set of the text on the page: the page is
|
||||||
|
// issued on that colour.
|
||||||
|
func (p Page) Rev() int {
|
||||||
|
rev := 0
|
||||||
|
for _, l := range p.Lines {
|
||||||
|
rev = max(rev, l.Rev)
|
||||||
|
}
|
||||||
|
return rev
|
||||||
|
}
|
||||||
|
|
||||||
|
// Break marks where a page starts in the source: the element index and the
|
||||||
|
// rune offset inside that element's text.
|
||||||
|
type Break struct {
|
||||||
|
Element int `json:"element"`
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScenePage struct {
|
||||||
|
Element int `json:"element"`
|
||||||
|
Number string `json:"number"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Pages []Page
|
||||||
|
Breaks []Break
|
||||||
|
Scenes []ScenePage
|
||||||
|
}
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
SceneNumbers bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// dualSpecs place the two columns of a dual dialogue side by side:
|
||||||
|
// left column from 1.5", right column from 4.5".
|
||||||
|
var dualSpecs = [2]map[screenplay.ElementType]spec{
|
||||||
|
{
|
||||||
|
screenplay.Character: {2.5, 20, 1},
|
||||||
|
screenplay.Parenthetical: {1.8, 22, 0},
|
||||||
|
screenplay.Dialogue: {1.5, 27, 0},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
screenplay.Character: {5.5, 20, 1},
|
||||||
|
screenplay.Parenthetical: {4.8, 22, 0},
|
||||||
|
screenplay.Dialogue: {4.5, 28, 0},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
type style uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
sBold style = 1 << iota
|
||||||
|
sItalic
|
||||||
|
sUnderline
|
||||||
|
)
|
||||||
|
|
||||||
|
type item struct {
|
||||||
|
elem int
|
||||||
|
typ screenplay.ElementType
|
||||||
|
runes []rune
|
||||||
|
styles []style
|
||||||
|
revs []int // revision set of each rune
|
||||||
|
src []int // offset of each rune in the element's text
|
||||||
|
ranges [][2]int
|
||||||
|
before int
|
||||||
|
sceneNumber string
|
||||||
|
dual bool
|
||||||
|
sp spec
|
||||||
|
pages []string // locked pages starting with this item
|
||||||
|
newPage bool // forced page break before the item
|
||||||
|
}
|
||||||
|
|
||||||
|
// newItem prepares the printed text of an element: notes are removed, and
|
||||||
|
// so are the lines that held nothing but a note.
|
||||||
|
func newItem(idx int, el screenplay.Element) *item {
|
||||||
|
it := &item{elem: idx, typ: el.Type, dual: el.Dual, newPage: el.NewPage}
|
||||||
|
type char struct {
|
||||||
|
r rune
|
||||||
|
st style
|
||||||
|
rev int
|
||||||
|
note bool
|
||||||
|
}
|
||||||
|
var all []char
|
||||||
|
for _, r := range el.Runs {
|
||||||
|
var st style
|
||||||
|
if r.Bold {
|
||||||
|
st |= sBold
|
||||||
|
}
|
||||||
|
if r.Italic {
|
||||||
|
st |= sItalic
|
||||||
|
}
|
||||||
|
if r.Underline {
|
||||||
|
st |= sUnderline
|
||||||
|
}
|
||||||
|
for _, c := range r.Text {
|
||||||
|
all = append(all, char{c, st, r.Rev, r.Note})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
started := false
|
||||||
|
for start, i := 0, 0; i <= len(all); i++ {
|
||||||
|
if i < len(all) && all[i].r != '\n' {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
line := all[start:i]
|
||||||
|
note, text := false, false
|
||||||
|
for _, c := range line {
|
||||||
|
note = note || c.note
|
||||||
|
text = text || (!c.note && !unicode.IsSpace(c.r))
|
||||||
|
}
|
||||||
|
if !note || text {
|
||||||
|
if started {
|
||||||
|
it.add('\n', 0, 0, start-1)
|
||||||
|
}
|
||||||
|
started = true
|
||||||
|
for k, c := range line {
|
||||||
|
if !c.note {
|
||||||
|
it.add(c.r, c.st, c.rev, start+k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
start = i + 1
|
||||||
|
}
|
||||||
|
it.relayout(specs[el.Type])
|
||||||
|
return it
|
||||||
|
}
|
||||||
|
|
||||||
|
func (it *item) add(c rune, st style, rev, src int) {
|
||||||
|
if c == '\t' {
|
||||||
|
c = ' '
|
||||||
|
}
|
||||||
|
if it.typ.Uppercase() {
|
||||||
|
c = unicode.ToUpper(c)
|
||||||
|
}
|
||||||
|
it.runes = append(it.runes, c)
|
||||||
|
it.styles = append(it.styles, st)
|
||||||
|
it.revs = append(it.revs, rev)
|
||||||
|
it.src = append(it.src, src)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (it *item) blank() bool { return strings.TrimSpace(string(it.runes)) == "" }
|
||||||
|
|
||||||
|
// offset converts a printed rune index into an offset in the element text.
|
||||||
|
func (it *item) offset(i int) int {
|
||||||
|
switch {
|
||||||
|
case i < len(it.src):
|
||||||
|
return it.src[i]
|
||||||
|
case len(it.src) > 0:
|
||||||
|
return it.src[len(it.src)-1] + 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// index is the first printed rune at or after an element text offset.
|
||||||
|
func (it *item) index(offset int) int {
|
||||||
|
i := 0
|
||||||
|
for i < len(it.src) && it.src[i] < offset {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
// cut splits the item before printed rune k, for a locked page starting
|
||||||
|
// there. Spaces and line breaks around the cut go.
|
||||||
|
func (it *item) cut(k int) (*item, *item) {
|
||||||
|
tail := *it
|
||||||
|
head := *it
|
||||||
|
end := k
|
||||||
|
for end > 0 && unicode.IsSpace(it.runes[end-1]) {
|
||||||
|
end--
|
||||||
|
}
|
||||||
|
for k < len(it.runes) && unicode.IsSpace(it.runes[k]) {
|
||||||
|
k++
|
||||||
|
}
|
||||||
|
head.runes, head.styles, head.revs, head.src = it.runes[:end], it.styles[:end], it.revs[:end], it.src[:end]
|
||||||
|
tail.runes, tail.styles, tail.revs, tail.src = it.runes[k:], it.styles[k:], it.revs[k:], it.src[k:]
|
||||||
|
tail.pages = nil
|
||||||
|
tail.newPage = false
|
||||||
|
head.relayout(it.sp)
|
||||||
|
tail.relayout(it.sp)
|
||||||
|
return &head, &tail
|
||||||
|
}
|
||||||
|
|
||||||
|
// splittable reports whether a locked page may start inside the element.
|
||||||
|
func (it *item) splittable() bool {
|
||||||
|
switch it.typ {
|
||||||
|
case screenplay.Action, screenplay.Centered, screenplay.Dialogue, screenplay.Parenthetical:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (it *item) relayout(sp spec) {
|
||||||
|
it.sp = sp
|
||||||
|
it.before = sp.before
|
||||||
|
cont := sp.width
|
||||||
|
if it.typ == screenplay.Parenthetical {
|
||||||
|
cont-- // hanging indent under the opening parenthesis
|
||||||
|
}
|
||||||
|
it.ranges = Wrap(it.runes, sp.width, cont)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (it *item) x(li int) float64 {
|
||||||
|
sp := it.sp
|
||||||
|
n := float64(it.ranges[li][1] - it.ranges[li][0])
|
||||||
|
switch it.typ {
|
||||||
|
case screenplay.Transition:
|
||||||
|
return RightEdge - n*CharWidth
|
||||||
|
case screenplay.Centered, screenplay.Intertitle:
|
||||||
|
return sp.left + (float64(sp.width)-n)*CharWidth/2
|
||||||
|
case screenplay.Parenthetical:
|
||||||
|
if li > 0 {
|
||||||
|
return sp.left + CharWidth
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sp.left
|
||||||
|
}
|
||||||
|
|
||||||
|
func (it *item) rev(li int) int {
|
||||||
|
rev := 0
|
||||||
|
for _, r := range it.revs[it.ranges[li][0]:it.ranges[li][1]] {
|
||||||
|
rev = max(rev, r)
|
||||||
|
}
|
||||||
|
return rev
|
||||||
|
}
|
||||||
|
|
||||||
|
func (it *item) segments(li int) []Segment {
|
||||||
|
var segs []Segment
|
||||||
|
var cur style
|
||||||
|
rg := it.ranges[li]
|
||||||
|
for i := rg[0]; i < rg[1]; i++ {
|
||||||
|
st := it.styles[i]
|
||||||
|
if len(segs) == 0 || st != cur {
|
||||||
|
segs = append(segs, Segment{Bold: st&sBold != 0, Italic: st&sItalic != 0, Underline: st&sUnderline != 0})
|
||||||
|
cur = st
|
||||||
|
}
|
||||||
|
segs[len(segs)-1].Text += string(it.runes[i])
|
||||||
|
}
|
||||||
|
return segs
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap splits text into lines of at most width characters (contWidth for the
|
||||||
|
// following lines), breaking on spaces and on "\n". It returns rune ranges.
|
||||||
|
func Wrap(r []rune, width, contWidth int) [][2]int {
|
||||||
|
width, contWidth = max(width, 1), max(contWidth, 1)
|
||||||
|
n := len(r)
|
||||||
|
var out [][2]int
|
||||||
|
start := 0
|
||||||
|
for {
|
||||||
|
w := width
|
||||||
|
if len(out) > 0 {
|
||||||
|
w = contWidth
|
||||||
|
}
|
||||||
|
end, lastSpace := start, -1
|
||||||
|
for end < n && r[end] != '\n' && end-start < w {
|
||||||
|
if r[end] == ' ' {
|
||||||
|
lastSpace = end
|
||||||
|
}
|
||||||
|
end++
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case end >= n:
|
||||||
|
return append(out, trimRange(r, start, n))
|
||||||
|
case r[end] == '\n':
|
||||||
|
out = append(out, trimRange(r, start, end))
|
||||||
|
start = end + 1
|
||||||
|
case r[end] == ' ':
|
||||||
|
out = append(out, trimRange(r, start, end))
|
||||||
|
if start = skipSpaces(r, end); start >= n {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
case lastSpace > start:
|
||||||
|
out = append(out, trimRange(r, start, lastSpace))
|
||||||
|
start = skipSpaces(r, lastSpace)
|
||||||
|
default: // a single word longer than the line
|
||||||
|
out = append(out, [2]int{start, end})
|
||||||
|
start = end
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func trimRange(r []rune, s, e int) [2]int {
|
||||||
|
for e > s && r[e-1] == ' ' {
|
||||||
|
e--
|
||||||
|
}
|
||||||
|
return [2]int{s, e}
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipSpaces(r []rune, i int) int {
|
||||||
|
for i < len(r) && r[i] == ' ' {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
type unit struct {
|
||||||
|
head *item // the element, or the character cue of a dialogue block
|
||||||
|
parts []*item // parentheticals and dialogue following a cue
|
||||||
|
block bool
|
||||||
|
right *unit // second column of a dual dialogue
|
||||||
|
// A dialogue block cut by a locked page: the first part ends with
|
||||||
|
// (MORE), the next one starts with NAME (CONT'D).
|
||||||
|
more, contd bool
|
||||||
|
pages []string // locked pages starting with this unit
|
||||||
|
newPage bool // forced page break before the unit
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *unit) items() []*item {
|
||||||
|
return append([]*item{u.head}, u.parts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *unit) height() int {
|
||||||
|
n := 0
|
||||||
|
for _, it := range u.items() {
|
||||||
|
n += len(it.ranges)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// minLines is how much of the unit must fit under a scene heading.
|
||||||
|
func (u *unit) minLines() int {
|
||||||
|
if !u.block {
|
||||||
|
return min(2, len(u.head.ranges))
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for _, p := range u.parts {
|
||||||
|
n += len(p.ranges)
|
||||||
|
}
|
||||||
|
return len(u.head.ranges) + min(2, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paginate lays the document out on pages.
|
||||||
|
func Paginate(doc *screenplay.Document, opt Options) *Result {
|
||||||
|
locked := doc.Settings.Locked
|
||||||
|
var items []*item
|
||||||
|
var carried []string // locked pages of elements that print nothing
|
||||||
|
carriedPage := false // and their forced page break
|
||||||
|
scene := 0
|
||||||
|
for i, el := range doc.Elements {
|
||||||
|
var locks []screenplay.PageLock
|
||||||
|
if locked {
|
||||||
|
for _, l := range carried {
|
||||||
|
locks = append(locks, screenplay.PageLock{Page: l})
|
||||||
|
}
|
||||||
|
locks = append(locks, el.Locked...)
|
||||||
|
}
|
||||||
|
var it *item
|
||||||
|
if !el.IsEmpty() && el.Type.Printed() {
|
||||||
|
it = newItem(i, el)
|
||||||
|
}
|
||||||
|
if it == nil || it.blank() {
|
||||||
|
carried = nil // now in locks
|
||||||
|
for _, l := range locks {
|
||||||
|
carried = append(carried, l.Page)
|
||||||
|
}
|
||||||
|
carriedPage = carriedPage || el.NewPage
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
carried = nil
|
||||||
|
it.newPage = it.newPage || carriedPage
|
||||||
|
carriedPage = false
|
||||||
|
if el.Type == screenplay.Scene {
|
||||||
|
scene++
|
||||||
|
it.sceneNumber = el.SceneNumber
|
||||||
|
if it.sceneNumber == "" {
|
||||||
|
it.sceneNumber = strconv.Itoa(scene)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
items = append(items, lockItem(it, locks, &carried)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
var units []unit
|
||||||
|
for i := 0; i < len(items); i++ {
|
||||||
|
it := items[i]
|
||||||
|
if it.typ == screenplay.Character {
|
||||||
|
u := unit{head: it, block: true, pages: it.pages, newPage: it.newPage}
|
||||||
|
for i+1 < len(items) && items[i+1].typ.InDialogue() {
|
||||||
|
i++
|
||||||
|
part := items[i]
|
||||||
|
if len(part.pages) > 0 && !it.dual && !nextIsDual(items, i) {
|
||||||
|
u.more = true
|
||||||
|
units = append(units, u)
|
||||||
|
u = unit{head: it, block: true, contd: true, pages: part.pages}
|
||||||
|
} else {
|
||||||
|
u.pages = append(u.pages, part.pages...)
|
||||||
|
}
|
||||||
|
// A page cannot be forced inside a dialogue block: it breaks
|
||||||
|
// before the block.
|
||||||
|
u.newPage = u.newPage || part.newPage
|
||||||
|
u.parts = append(u.parts, part)
|
||||||
|
}
|
||||||
|
if prev := len(units) - 1; it.dual && prev >= 0 && units[prev].block && units[prev].right == nil {
|
||||||
|
for side, col := range []*unit{&units[prev], &u} {
|
||||||
|
for _, ci := range col.items() {
|
||||||
|
ci.relayout(dualSpecs[side][ci.typ])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A dual dialogue is never split: its locked pages start above it.
|
||||||
|
units[prev].pages = append(units[prev].pages, u.pages...)
|
||||||
|
units[prev].newPage = units[prev].newPage || u.newPage
|
||||||
|
units[prev].right = &u
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
units = append(units, u)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if it.typ.InDialogue() {
|
||||||
|
it.before = 1 // dialogue without a cue: keep it off the previous element
|
||||||
|
}
|
||||||
|
units = append(units, unit{head: it, pages: it.pages, newPage: it.newPage})
|
||||||
|
}
|
||||||
|
|
||||||
|
p := &paginator{res: &Result{}, opt: opt, geo: PaperGeometry(doc.Settings.Paper), locked: locked}
|
||||||
|
p.newPage()
|
||||||
|
for i, u := range units {
|
||||||
|
var next *unit
|
||||||
|
if i+1 < len(units) {
|
||||||
|
next = &units[i+1]
|
||||||
|
if (locked && len(next.pages) > 0) || next.newPage {
|
||||||
|
next = nil // the next unit starts its own page anyway
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if locked {
|
||||||
|
p.startLocked(u.pages)
|
||||||
|
}
|
||||||
|
if u.newPage && len(p.page.Lines) > 0 {
|
||||||
|
p.newPage()
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case u.right != nil:
|
||||||
|
p.placeDual(u)
|
||||||
|
case u.block:
|
||||||
|
p.placeBlock(u)
|
||||||
|
default:
|
||||||
|
p.placeItem(u.head, next)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if locked {
|
||||||
|
// Locked pages whose material is all gone, at the end.
|
||||||
|
p.startLocked(carried)
|
||||||
|
if len(p.res.Pages) > 1 && len(p.page.Lines) == 0 {
|
||||||
|
p.dropEmptyPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A page merged with an emptied one after it was renamed ("6-7").
|
||||||
|
for i, b := range p.res.Breaks {
|
||||||
|
p.res.Breaks[i].Label = p.res.Pages[b.Page-1].Label
|
||||||
|
}
|
||||||
|
for i, s := range p.res.Scenes {
|
||||||
|
p.res.Scenes[i].Label = p.res.Pages[s.Page-1].Label
|
||||||
|
}
|
||||||
|
return p.res
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextIsDual reports whether the block holding items[i] is the left column
|
||||||
|
// of a dual dialogue.
|
||||||
|
func nextIsDual(items []*item, i int) bool {
|
||||||
|
for j := i + 1; j < len(items); j++ {
|
||||||
|
if !items[j].typ.InDialogue() {
|
||||||
|
return items[j].typ == screenplay.Character && items[j].dual
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// lockItem attaches the locked pages that start in an item, cutting it
|
||||||
|
// where a page starts inside it. A page starting at its very end starts
|
||||||
|
// with the next item.
|
||||||
|
func lockItem(it *item, locks []screenplay.PageLock, carried *[]string) []*item {
|
||||||
|
out := []*item{it}
|
||||||
|
cur := it
|
||||||
|
base := 0 // printed runes of it before cur
|
||||||
|
for _, l := range locks {
|
||||||
|
k := it.index(l.Offset) - base
|
||||||
|
switch {
|
||||||
|
case k >= len(cur.runes) || strings.TrimSpace(string(cur.runes[k:])) == "":
|
||||||
|
*carried = append(*carried, l.Page)
|
||||||
|
case k <= 0 || !cur.splittable() || strings.TrimSpace(string(cur.runes[:k])) == "":
|
||||||
|
cur.pages = append(cur.pages, l.Page)
|
||||||
|
default:
|
||||||
|
head, tail := cur.cut(k)
|
||||||
|
base += len(cur.runes) - len(tail.runes)
|
||||||
|
tail.pages = []string{l.Page}
|
||||||
|
out[len(out)-1] = head
|
||||||
|
out = append(out, tail)
|
||||||
|
cur = tail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
type paginator struct {
|
||||||
|
res *Result
|
||||||
|
page *Page
|
||||||
|
row int
|
||||||
|
pending bool // the next emitted source line starts a new page
|
||||||
|
opt Options
|
||||||
|
geo Geometry
|
||||||
|
locked bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// newPage starts the next page. Once pages are locked, a page that does
|
||||||
|
// not start a locked page is an A page of the previous one.
|
||||||
|
func (p *paginator) newPage() {
|
||||||
|
label := strconv.Itoa(len(p.res.Pages) + 1)
|
||||||
|
if p.locked && p.page != nil {
|
||||||
|
label = nextLabel(p.page.Label)
|
||||||
|
}
|
||||||
|
p.addPage(label)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) addPage(label string) {
|
||||||
|
p.res.Pages = append(p.res.Pages, Page{Number: len(p.res.Pages) + 1, Label: label})
|
||||||
|
p.page = &p.res.Pages[len(p.res.Pages)-1]
|
||||||
|
p.row = 0
|
||||||
|
p.pending = len(p.res.Pages) > 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// startLocked starts the locked pages that begin with the next unit. A
|
||||||
|
// page left empty in between lost all its material: it is merged into the
|
||||||
|
// page before it ("12-13").
|
||||||
|
func (p *paginator) startLocked(labels []string) {
|
||||||
|
for _, l := range labels {
|
||||||
|
switch {
|
||||||
|
case len(p.page.Lines) > 0:
|
||||||
|
p.addPage(l)
|
||||||
|
case len(p.res.Pages) > 1:
|
||||||
|
p.dropEmptyPage()
|
||||||
|
p.addPage(l)
|
||||||
|
default: // nothing before the first locked page
|
||||||
|
p.page.Label = firstLabel(p.page.Label) + "-" + l
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) dropEmptyPage() {
|
||||||
|
n := len(p.res.Pages)
|
||||||
|
empty := p.res.Pages[n-1].Label
|
||||||
|
p.res.Pages = p.res.Pages[:n-1]
|
||||||
|
p.page = &p.res.Pages[n-2]
|
||||||
|
p.page.Label = firstLabel(p.page.Label) + "-" + lastLabel(empty)
|
||||||
|
p.row = p.geo.Lines
|
||||||
|
}
|
||||||
|
|
||||||
|
func firstLabel(l string) string { return strings.Split(l, "-")[0] }
|
||||||
|
|
||||||
|
func lastLabel(l string) string {
|
||||||
|
parts := strings.Split(l, "-")
|
||||||
|
return parts[len(parts)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextLabel names the page added after a locked page: 12 → 12A → 12B.
|
||||||
|
func nextLabel(label string) string {
|
||||||
|
l := lastLabel(label)
|
||||||
|
if n := len(l); n > 0 && l[n-1] >= 'A' && l[n-1] < 'Z' && strings.ContainsAny(l, "0123456789") {
|
||||||
|
return l[:n-1] + string(l[n-1]+1)
|
||||||
|
}
|
||||||
|
return l + "A"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) emit(it *item, li int) {
|
||||||
|
if p.pending {
|
||||||
|
p.res.Breaks = append(p.res.Breaks, Break{Element: it.elem, Offset: it.offset(it.ranges[li][0]), Page: p.page.Number, Label: p.page.Label})
|
||||||
|
p.pending = false
|
||||||
|
}
|
||||||
|
line := Line{Row: p.row, X: it.x(li), Segments: it.segments(li), Rev: it.rev(li)}
|
||||||
|
if it.typ == screenplay.Scene && li == 0 {
|
||||||
|
p.res.Scenes = append(p.res.Scenes, ScenePage{Element: it.elem, Number: it.sceneNumber, Page: p.page.Number, Label: p.page.Label})
|
||||||
|
if p.opt.SceneNumbers {
|
||||||
|
line.SceneNumber = it.sceneNumber
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.page.Lines = append(p.page.Lines, line)
|
||||||
|
p.row++
|
||||||
|
}
|
||||||
|
|
||||||
|
// emitText adds a line that does not come from the source ((MORE), CONT'D).
|
||||||
|
func (p *paginator) emitText(x float64, s string) {
|
||||||
|
p.page.Lines = append(p.page.Lines, Line{Row: p.row, X: x, Segments: []Segment{{Text: s}}})
|
||||||
|
p.row++
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) spaceBefore(it *item) int {
|
||||||
|
if p.row == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return it.before
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) placeItem(it *item, next *unit) {
|
||||||
|
n := len(it.ranges)
|
||||||
|
// Scene headings and inserts never end a page: keep them with what follows.
|
||||||
|
if (it.typ == screenplay.Scene || it.typ == screenplay.Shot) && p.row > 0 && next != nil {
|
||||||
|
need := it.before + n + next.head.before + next.minLines()
|
||||||
|
if p.row+need > p.geo.Lines {
|
||||||
|
p.newPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
splittable := it.typ == screenplay.Action || it.typ == screenplay.Centered
|
||||||
|
start := 0
|
||||||
|
for {
|
||||||
|
before := p.spaceBefore(it)
|
||||||
|
if p.row+before+n-start <= p.geo.Lines {
|
||||||
|
p.row += before
|
||||||
|
for li := start; li < n; li++ {
|
||||||
|
p.emit(it, li)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
avail := p.geo.Lines - p.row - before
|
||||||
|
k := 0
|
||||||
|
if splittable {
|
||||||
|
k = sentenceSplit(it, start, avail)
|
||||||
|
}
|
||||||
|
if k == 0 && p.row == 0 {
|
||||||
|
k = avail // longer than a page with no clean break
|
||||||
|
}
|
||||||
|
if k > 0 {
|
||||||
|
p.row += before
|
||||||
|
for li := start; li < start+k; li++ {
|
||||||
|
p.emit(it, li)
|
||||||
|
}
|
||||||
|
start += k
|
||||||
|
}
|
||||||
|
p.newPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type dline struct {
|
||||||
|
it *item
|
||||||
|
li int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) placeBlock(u unit) {
|
||||||
|
var flat []dline
|
||||||
|
for _, part := range u.parts {
|
||||||
|
for li := range part.ranges {
|
||||||
|
flat = append(flat, dline{part, li})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cue := u.head
|
||||||
|
contd := u.contd
|
||||||
|
more := 0
|
||||||
|
if u.more {
|
||||||
|
more = 1
|
||||||
|
}
|
||||||
|
pos := 0
|
||||||
|
for {
|
||||||
|
before := p.spaceBefore(cue)
|
||||||
|
head := len(cue.ranges)
|
||||||
|
if contd {
|
||||||
|
head = 1
|
||||||
|
}
|
||||||
|
rem := len(flat) - pos
|
||||||
|
if p.row+before+head+rem+more <= p.geo.Lines {
|
||||||
|
p.row += before
|
||||||
|
p.emitCue(cue, contd)
|
||||||
|
for _, d := range flat[pos:] {
|
||||||
|
p.emit(d.it, d.li)
|
||||||
|
}
|
||||||
|
if u.more {
|
||||||
|
p.emitText(specs[screenplay.Character].left, "(MORE)")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
avail := p.geo.Lines - p.row - before - head - 1 // one line for (MORE)
|
||||||
|
k := dialogueSplit(flat, pos, avail)
|
||||||
|
if k == 0 && p.row == 0 {
|
||||||
|
k = min(max(avail, 1), rem-1)
|
||||||
|
}
|
||||||
|
if k > 0 {
|
||||||
|
p.row += before
|
||||||
|
p.emitCue(cue, contd)
|
||||||
|
for _, d := range flat[pos : pos+k] {
|
||||||
|
p.emit(d.it, d.li)
|
||||||
|
}
|
||||||
|
p.emitText(specs[screenplay.Character].left, "(MORE)")
|
||||||
|
pos += k
|
||||||
|
contd = true
|
||||||
|
}
|
||||||
|
p.newPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// placeDual lays both columns side by side. A dual dialogue is never split.
|
||||||
|
func (p *paginator) placeDual(u unit) {
|
||||||
|
h := max(u.height(), u.right.height())
|
||||||
|
before := p.spaceBefore(u.head)
|
||||||
|
if p.row > 0 && p.row+before+h > p.geo.Lines {
|
||||||
|
p.newPage()
|
||||||
|
before = 0
|
||||||
|
}
|
||||||
|
p.row += before
|
||||||
|
base := p.row
|
||||||
|
for _, col := range []*unit{&u, u.right} {
|
||||||
|
p.row = base
|
||||||
|
for _, it := range col.items() {
|
||||||
|
for li := range it.ranges {
|
||||||
|
p.emit(it, li)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.row = base + h
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *paginator) emitCue(cue *item, contd bool) {
|
||||||
|
if !contd {
|
||||||
|
for li := range cue.ranges {
|
||||||
|
p.emit(cue, li)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strings.TrimSpace(string(cue.runes))
|
||||||
|
if !strings.Contains(name, "(CONT'D)") {
|
||||||
|
name += " (CONT'D)"
|
||||||
|
}
|
||||||
|
p.emitText(specs[screenplay.Character].left, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sentenceSplit returns how many lines (from start) to keep on the current
|
||||||
|
// page, or 0 if the element cannot be split cleanly within avail lines.
|
||||||
|
func sentenceSplit(it *item, start, avail int) int {
|
||||||
|
rem := len(it.ranges) - start
|
||||||
|
for k := min(avail, rem-2); k >= 2; k-- {
|
||||||
|
if endsSentence(it.runes, it.ranges[start+k-1]) {
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func dialogueSplit(flat []dline, pos, avail int) int {
|
||||||
|
rem := len(flat) - pos
|
||||||
|
for k := min(avail, rem-2); k >= 2; k-- {
|
||||||
|
last := flat[pos+k-1]
|
||||||
|
if last.it.typ == screenplay.Parenthetical {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if last.li == len(last.it.ranges)-1 || endsSentence(last.it.runes, last.it.ranges[last.li]) {
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func endsSentence(r []rune, rg [2]int) bool {
|
||||||
|
if rg[1] < len(r) && r[rg[1]] == '\n' {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
s := strings.TrimRight(string(r[rg[0]:rg[1]]), " \"'”’»)")
|
||||||
|
for _, end := range []string{".", "!", "?", "…", ":", "--"} {
|
||||||
|
if strings.HasSuffix(s, end) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// TitlePage lays out the cover page: title block centred in the upper half,
|
||||||
|
// contact bottom-left, draft date and notes bottom-right.
|
||||||
|
func TitlePage(tp screenplay.TitlePage, paper screenplay.Paper) Page {
|
||||||
|
lastRow := PaperGeometry(paper).Lines
|
||||||
|
var lines []Line
|
||||||
|
centered := func(row int, s string) int {
|
||||||
|
for _, para := range strings.Split(s, "\n") {
|
||||||
|
r := []rune(para)
|
||||||
|
for _, rg := range Wrap(r, 60, 60) {
|
||||||
|
n := float64(rg[1] - rg[0])
|
||||||
|
lines = append(lines, Line{Row: row, X: 1.5 + (60-n)*CharWidth/2, Segments: []Segment{{Text: string(r[rg[0]:rg[1]])}}})
|
||||||
|
row++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return row
|
||||||
|
}
|
||||||
|
bottom := func(s string, width int, right bool) {
|
||||||
|
var texts []string
|
||||||
|
for _, para := range strings.Split(strings.TrimSpace(s), "\n") {
|
||||||
|
r := []rune(para)
|
||||||
|
for _, rg := range Wrap(r, width, width) {
|
||||||
|
texts = append(texts, string(r[rg[0]:rg[1]]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
row := lastRow - len(texts)
|
||||||
|
for _, t := range texts {
|
||||||
|
x := 1.5
|
||||||
|
if right {
|
||||||
|
x = RightEdge - float64(len([]rune(t)))*CharWidth
|
||||||
|
}
|
||||||
|
lines = append(lines, Line{Row: row, X: x, Segments: []Segment{{Text: t}}})
|
||||||
|
row++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
row := 18
|
||||||
|
if tp.Title != "" {
|
||||||
|
row = centered(row, tp.Title) + 3
|
||||||
|
}
|
||||||
|
if tp.Credit != "" {
|
||||||
|
row = centered(row, tp.Credit) + 1
|
||||||
|
}
|
||||||
|
if tp.Author != "" {
|
||||||
|
row = centered(row, tp.Author) + 3
|
||||||
|
}
|
||||||
|
if tp.Source != "" {
|
||||||
|
centered(row, tp.Source)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(tp.Contact) != "" {
|
||||||
|
bottom(tp.Contact, 35, false)
|
||||||
|
}
|
||||||
|
right := strings.TrimSpace(strings.TrimSpace(tp.Notes) + "\n" + strings.TrimSpace(tp.DraftDate))
|
||||||
|
if right != "" {
|
||||||
|
bottom(right, 25, true)
|
||||||
|
}
|
||||||
|
return Page{Lines: lines}
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package layout
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWrap(t *testing.T) {
|
||||||
|
r := []rune("the quick brown fox jumps")
|
||||||
|
got := Wrap(r, 10, 10)
|
||||||
|
var lines []string
|
||||||
|
for _, rg := range got {
|
||||||
|
lines = append(lines, string(r[rg[0]:rg[1]]))
|
||||||
|
}
|
||||||
|
want := []string{"the quick", "brown fox", "jumps"}
|
||||||
|
if strings.Join(lines, "|") != strings.Join(want, "|") {
|
||||||
|
t.Errorf("got %q", lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func el(t screenplay.ElementType, s string) screenplay.Element {
|
||||||
|
return screenplay.NewElement(t, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSceneHeadingNotOrphaned(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
// 51 one-line actions (each with a blank line before) fill most of page 1.
|
||||||
|
for i := 0; i < 26; i++ {
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Action, "Something happens."))
|
||||||
|
}
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Scene, "INT. HOUSE - DAY"), el(screenplay.Action, "A\nB\nC"))
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
if len(res.Pages) != 2 {
|
||||||
|
t.Fatalf("pages = %d", len(res.Pages))
|
||||||
|
}
|
||||||
|
if b := res.Breaks[0]; b.Element != 26 || b.Offset != 0 {
|
||||||
|
t.Errorf("scene heading should start page 2, break = %+v", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDialogueMoreContd(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
for i := 0; i < 24; i++ {
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Action, "Something happens."))
|
||||||
|
}
|
||||||
|
long := strings.Repeat("This is a sentence that goes on. ", 12)
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Character, "Margot"), el(screenplay.Dialogue, long))
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
if len(res.Pages) != 2 {
|
||||||
|
t.Fatalf("pages = %d", len(res.Pages))
|
||||||
|
}
|
||||||
|
text := func(p Page, i int) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, s := range p.Lines[i].Segments {
|
||||||
|
b.WriteString(s.Text)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
p1, p2 := res.Pages[0], res.Pages[1]
|
||||||
|
if got := text(p1, len(p1.Lines)-1); got != "(MORE)" {
|
||||||
|
t.Errorf("last line of page 1 = %q", got)
|
||||||
|
}
|
||||||
|
if got := text(p2, 0); got != "MARGOT (CONT'D)" {
|
||||||
|
t.Errorf("first line of page 2 = %q", got)
|
||||||
|
}
|
||||||
|
if res.Breaks[0].Element != 25 || res.Breaks[0].Offset == 0 {
|
||||||
|
t.Errorf("break should be inside the dialogue: %+v", res.Breaks[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDualDialogue(t *testing.T) {
|
||||||
|
right := el(screenplay.Character, "Bob")
|
||||||
|
right.Dual = true
|
||||||
|
doc := &screenplay.Document{Elements: []screenplay.Element{
|
||||||
|
el(screenplay.Character, "Alice"), el(screenplay.Dialogue, "Hello there, how are you doing today?"),
|
||||||
|
right, el(screenplay.Dialogue, "Fine."),
|
||||||
|
el(screenplay.Action, "They stop."),
|
||||||
|
}}
|
||||||
|
lines := Paginate(doc, Options{}).Pages[0].Lines
|
||||||
|
byRow := map[int][]float64{}
|
||||||
|
for _, l := range lines {
|
||||||
|
byRow[l.Row] = append(byRow[l.Row], l.X)
|
||||||
|
}
|
||||||
|
if len(byRow[0]) != 2 || byRow[0][0] != 2.5 || byRow[0][1] != 5.5 {
|
||||||
|
t.Errorf("cues should share row 0 at 2.5in and 5.5in: %v", byRow[0])
|
||||||
|
}
|
||||||
|
// Left dialogue wraps to 2 lines at 27 chars; action follows after a blank line.
|
||||||
|
if last := lines[len(lines)-1]; last.Row != 4 || last.X != 1.5 {
|
||||||
|
t.Errorf("action line = %+v", last)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShotKeptWithNext(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
for i := 0; i < 26; i++ {
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Action, "Something happens."))
|
||||||
|
}
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Shot, "insert - the letter"), el(screenplay.Action, "A\nB\nC"))
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
if b := res.Breaks[0]; b.Element != 26 || b.Offset != 0 {
|
||||||
|
t.Errorf("insert should move to page 2 with its action, break = %+v", b)
|
||||||
|
}
|
||||||
|
if len(res.Scenes) != 0 {
|
||||||
|
t.Errorf("an insert is not a scene: %+v", res.Scenes)
|
||||||
|
}
|
||||||
|
line := res.Pages[1].Lines[0]
|
||||||
|
if line.X != 1.5 || line.Segments[0].Text != "INSERT - THE LETTER" {
|
||||||
|
t.Errorf("insert line = %+v", line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIntertitleCentered(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{Elements: []screenplay.Element{el(screenplay.Intertitle, "Paris, 1942")}}
|
||||||
|
line := Paginate(doc, Options{}).Pages[0].Lines[0]
|
||||||
|
if line.Segments[0].Text != "PARIS, 1942" || line.X != 1.5+(60-11)*CharWidth/2 {
|
||||||
|
t.Errorf("intertitle line = %+v", line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func lineText(l Line) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, s := range l.Segments {
|
||||||
|
b.WriteString(s.Text)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNotPrinted(t *testing.T) {
|
||||||
|
section := el(screenplay.Section, "Act One")
|
||||||
|
section.Level = 1
|
||||||
|
action := screenplay.Element{Type: screenplay.Action, Runs: []screenplay.Run{
|
||||||
|
{Text: "He waits."}, {Text: " (fix this)", Note: true}, {Text: "\n"}, {Text: "a whole line of notes", Note: true}, {Text: "\nThen he goes."},
|
||||||
|
}}
|
||||||
|
doc := &screenplay.Document{Elements: []screenplay.Element{
|
||||||
|
section, el(screenplay.Synopsis, "Where it starts."), el(screenplay.Scene, "INT. HOUSE - DAY"), action,
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{{Text: "only a note", Note: true}}},
|
||||||
|
el(screenplay.Scene, "EXT. ROAD - NIGHT"),
|
||||||
|
}}
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
var got []string
|
||||||
|
for _, l := range res.Pages[0].Lines {
|
||||||
|
got = append(got, lineText(l))
|
||||||
|
}
|
||||||
|
want := []string{"INT. HOUSE - DAY", "He waits.", "Then he goes.", "EXT. ROAD - NIGHT"}
|
||||||
|
if strings.Join(got, "|") != strings.Join(want, "|") {
|
||||||
|
t.Errorf("printed %q", got)
|
||||||
|
}
|
||||||
|
if res.Pages[0].Lines[3].Row != 6 {
|
||||||
|
t.Errorf("the note-only action should leave no gap: %+v", res.Pages[0].Lines)
|
||||||
|
}
|
||||||
|
if res.Scenes[0].Number != "1" || res.Scenes[1].Number != "2" {
|
||||||
|
t.Errorf("scenes: %+v", res.Scenes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBreakOffsetSkipsNotes(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
for i := 0; i < 26; i++ {
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Action, "Line."))
|
||||||
|
}
|
||||||
|
long := screenplay.Element{Type: screenplay.Action, Runs: []screenplay.Run{
|
||||||
|
{Text: "N", Note: true}, {Text: strings.Repeat("One sentence here. ", 20)},
|
||||||
|
}}
|
||||||
|
doc.Elements = append(doc.Elements, long)
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
b := res.Breaks[0]
|
||||||
|
text := []rune(doc.Elements[26].Text())
|
||||||
|
if b.Element != 26 || b.Offset != 1 || text[b.Offset] != 'O' {
|
||||||
|
t.Errorf("the page should start after the note: %+v", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestA4(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{Settings: screenplay.Settings{Paper: screenplay.A4}}
|
||||||
|
for i := 0; i < 120; i++ {
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Action, "Line."))
|
||||||
|
}
|
||||||
|
// 29 actions (57 rows) fit on an A4 page, 27 (53 rows) on US Letter.
|
||||||
|
a4 := Paginate(doc, Options{})
|
||||||
|
doc.Settings.Paper = screenplay.Letter
|
||||||
|
letter := Paginate(doc, Options{})
|
||||||
|
if a4.Breaks[0].Element != 29 || letter.Breaks[0].Element != 27 {
|
||||||
|
t.Errorf("first break: A4 %+v, Letter %+v", a4.Breaks[0], letter.Breaks[0])
|
||||||
|
}
|
||||||
|
if g := PaperGeometry(screenplay.A4); g.Width != 8.27 || g.Lines != 58 {
|
||||||
|
t.Errorf("A4 geometry %+v", g)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func labels(res *Result) []string {
|
||||||
|
var out []string
|
||||||
|
for _, p := range res.Pages {
|
||||||
|
out = append(out, p.Label)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLockedPages(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{}
|
||||||
|
for i := 0; i < 81; i++ {
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Action, "Line."))
|
||||||
|
}
|
||||||
|
// Lock the current pagination: 27 actions per page.
|
||||||
|
for _, b := range Paginate(doc, Options{}).Breaks {
|
||||||
|
doc.Elements[b.Element].Locked = []screenplay.PageLock{{Offset: b.Offset, Page: b.Label}}
|
||||||
|
}
|
||||||
|
doc.Settings.Locked = true
|
||||||
|
if got := labels(Paginate(doc, Options{})); strings.Join(got, " ") != "1 2 3" {
|
||||||
|
t.Fatalf("locked, unchanged: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Material added to page 1 goes to page 1A; page 2 does not move.
|
||||||
|
grown := *doc
|
||||||
|
grown.Elements = append(append(append([]screenplay.Element{}, doc.Elements[:5]...),
|
||||||
|
el(screenplay.Action, "New."), el(screenplay.Action, "New.")), doc.Elements[5:]...)
|
||||||
|
res := Paginate(&grown, Options{})
|
||||||
|
if got := labels(res); strings.Join(got, " ") != "1 1A 2 3" {
|
||||||
|
t.Fatalf("added material: %v", got)
|
||||||
|
}
|
||||||
|
if b := res.Breaks[1]; b.Element != 29 || b.Label != "2" {
|
||||||
|
t.Errorf("page 2 should still start with its first line: %+v", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page 2 emptied: merged into page 1.
|
||||||
|
shrunk := *doc
|
||||||
|
shrunk.Elements = append([]screenplay.Element{}, doc.Elements...)
|
||||||
|
for i := 27; i < 54; i++ {
|
||||||
|
shrunk.Elements[i] = screenplay.Element{Type: screenplay.Action, Locked: doc.Elements[i].Locked}
|
||||||
|
}
|
||||||
|
res = Paginate(&shrunk, Options{})
|
||||||
|
if got := labels(res); strings.Join(got, " ") != "1-2 3" {
|
||||||
|
t.Errorf("removed page: %v", got)
|
||||||
|
}
|
||||||
|
if b := res.Breaks[0]; b.Label != "3" || b.Page != 2 {
|
||||||
|
t.Errorf("break after the merged page: %+v", b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page 3 emptied: page 2 becomes 2-3, and its break says so.
|
||||||
|
shrunk.Elements = append([]screenplay.Element{}, doc.Elements...)
|
||||||
|
for i := 54; i < 81; i++ {
|
||||||
|
shrunk.Elements[i] = screenplay.Element{Type: screenplay.Action, Locked: doc.Elements[i].Locked}
|
||||||
|
}
|
||||||
|
res = Paginate(&shrunk, Options{})
|
||||||
|
if got := labels(res); strings.Join(got, " ") != "1 2-3" || res.Breaks[0].Label != "2-3" {
|
||||||
|
t.Errorf("removed last page: %v %+v", got, res.Breaks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLockedPageInsideDialogue(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{Settings: screenplay.Settings{Locked: true}}
|
||||||
|
doc.Elements = append(doc.Elements, el(screenplay.Character, "Margot"),
|
||||||
|
screenplay.Element{Type: screenplay.Dialogue, Runs: []screenplay.Run{{Text: "First part. Second part."}},
|
||||||
|
Locked: []screenplay.PageLock{{Offset: 12, Page: "2"}}})
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
if len(res.Pages) != 2 {
|
||||||
|
t.Fatalf("pages = %d", len(res.Pages))
|
||||||
|
}
|
||||||
|
p1, p2 := res.Pages[0].Lines, res.Pages[1].Lines
|
||||||
|
if lineText(p1[1]) != "First part." || lineText(p1[2]) != "(MORE)" {
|
||||||
|
t.Errorf("page 1: %+v", p1)
|
||||||
|
}
|
||||||
|
if lineText(p2[0]) != "MARGOT (CONT'D)" || lineText(p2[1]) != "Second part." {
|
||||||
|
t.Errorf("page 2: %+v", p2)
|
||||||
|
}
|
||||||
|
if b := res.Breaks[0]; b.Element != 1 || b.Offset != 12 || b.Label != "2" {
|
||||||
|
t.Errorf("break %+v", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionLevels(t *testing.T) {
|
||||||
|
doc := &screenplay.Document{Elements: []screenplay.Element{
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{{Text: "Old text. "}, {Text: "New text.", Rev: 2}}},
|
||||||
|
{Type: screenplay.Action, Runs: []screenplay.Run{{Text: "Blue text.", Rev: 1}}},
|
||||||
|
}}
|
||||||
|
page := Paginate(doc, Options{}).Pages[0]
|
||||||
|
if page.Lines[0].Rev != 2 || page.Lines[1].Rev != 1 || page.Rev() != 2 {
|
||||||
|
t.Errorf("revisions: %+v", page.Lines)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestForcedPageBreak(t *testing.T) {
|
||||||
|
scene := el(screenplay.Scene, "EXT. ROAD - NIGHT")
|
||||||
|
scene.NewPage = true
|
||||||
|
right := el(screenplay.Character, "Bob")
|
||||||
|
right.Dual, right.NewPage = true, true
|
||||||
|
cue := el(screenplay.Character, "Alice")
|
||||||
|
doc := &screenplay.Document{Elements: []screenplay.Element{
|
||||||
|
el(screenplay.Action, "He waits."), scene, el(screenplay.Action, "A car."),
|
||||||
|
cue, el(screenplay.Dialogue, "Hi."), right, el(screenplay.Dialogue, "Hey."),
|
||||||
|
{Type: screenplay.Section, Level: 1, Runs: []screenplay.Run{{Text: "Act Two"}}, NewPage: true},
|
||||||
|
el(screenplay.Action, "Later."),
|
||||||
|
}}
|
||||||
|
doc.Elements[0].NewPage = true // at the top of page 1: no effect
|
||||||
|
res := Paginate(doc, Options{})
|
||||||
|
var starts []int
|
||||||
|
for _, b := range res.Breaks {
|
||||||
|
starts = append(starts, b.Element)
|
||||||
|
}
|
||||||
|
// The right column's page break starts the page above the dual dialogue;
|
||||||
|
// the section's goes to the next printed element.
|
||||||
|
if len(res.Pages) != 4 || !slices.Equal(starts, []int{1, 3, 8}) {
|
||||||
|
t.Errorf("pages %d, breaks at %v", len(res.Pages), starts)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
// Package pdf renders laid-out pages to PDF. It writes the file by hand
|
||||||
|
// using the standard Courier fonts that every PDF reader ships with, so no
|
||||||
|
// font is embedded and there is no external dependency.
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"compress/zlib"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf16"
|
||||||
|
|
||||||
|
"plotzilla/internal/layout"
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
Title string
|
||||||
|
Author string
|
||||||
|
Paper screenplay.Paper
|
||||||
|
// Revisions are the document's revision sets. When set, a page whose
|
||||||
|
// text was revised gets a header naming its revision, and its revised
|
||||||
|
// lines an asterisk in the right margin.
|
||||||
|
Revisions []screenplay.Revision
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
fontSize = 12.0
|
||||||
|
ptPerIn = 72.0
|
||||||
|
)
|
||||||
|
|
||||||
|
var fontNames = []string{"Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique"}
|
||||||
|
|
||||||
|
// Render writes pages to w. The title page, if any, must be the first page
|
||||||
|
// and have Number 0 so that it is not numbered.
|
||||||
|
func Render(w io.Writer, pages []layout.Page, opt Options) error {
|
||||||
|
geo := layout.PaperGeometry(opt.Paper)
|
||||||
|
var objs [][]byte // objs[i] is object number i+1
|
||||||
|
add := func(s string) int {
|
||||||
|
objs = append(objs, []byte(s))
|
||||||
|
return len(objs)
|
||||||
|
}
|
||||||
|
// 1: catalog, 2: page tree, 3-6: fonts, 7: info. Pages follow.
|
||||||
|
add("<< /Type /Catalog /Pages 2 0 R >>")
|
||||||
|
add("") // page tree, filled once the kids are known
|
||||||
|
for _, f := range fontNames {
|
||||||
|
add("<< /Type /Font /Subtype /Type1 /BaseFont /" + f + " /Encoding /WinAnsiEncoding >>")
|
||||||
|
}
|
||||||
|
add(fmt.Sprintf("<< /Title %s /Author %s /Creator (Plotzilla) /Producer (Plotzilla) >>", textString(opt.Title), textString(opt.Author)))
|
||||||
|
|
||||||
|
var kids []string
|
||||||
|
for _, pg := range pages {
|
||||||
|
stream, err := deflate(pageContent(pg, geo, opt.Revisions))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
content := add(fmt.Sprintf("<< /Length %d /Filter /FlateDecode >>\nstream\n%s\nendstream", len(stream), stream))
|
||||||
|
page := add(fmt.Sprintf("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %g %g] "+
|
||||||
|
"/Resources << /Font << /F1 3 0 R /F2 4 0 R /F3 5 0 R /F4 6 0 R >> >> /Contents %d 0 R >>",
|
||||||
|
points(geo.Width), points(geo.Height), content))
|
||||||
|
kids = append(kids, fmt.Sprintf("%d 0 R", page))
|
||||||
|
}
|
||||||
|
objs[1] = []byte(fmt.Sprintf("<< /Type /Pages /Kids [%s] /Count %d >>", strings.Join(kids, " "), len(kids)))
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
buf.WriteString("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
|
||||||
|
offsets := make([]int, len(objs))
|
||||||
|
for i, o := range objs {
|
||||||
|
offsets[i] = buf.Len()
|
||||||
|
fmt.Fprintf(&buf, "%d 0 obj\n", i+1)
|
||||||
|
buf.Write(o)
|
||||||
|
buf.WriteString("\nendobj\n")
|
||||||
|
}
|
||||||
|
xref := buf.Len()
|
||||||
|
fmt.Fprintf(&buf, "xref\n0 %d\n0000000000 65535 f \n", len(objs)+1)
|
||||||
|
for _, off := range offsets {
|
||||||
|
fmt.Fprintf(&buf, "%010d 00000 n \n", off)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&buf, "trailer\n<< /Size %d /Root 1 0 R /Info 7 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(objs)+1, xref)
|
||||||
|
_, err := w.Write(buf.Bytes())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// points converts inches to PDF points, rounded to 1/100 pt.
|
||||||
|
func points(in float64) float64 { return math.Round(in*ptPerIn*100) / 100 }
|
||||||
|
|
||||||
|
// baseline returns the PDF y coordinate of the baseline of a body row.
|
||||||
|
func baseline(geo layout.Geometry, row int) float64 {
|
||||||
|
top := (geo.Height - layout.TopMargin) * ptPerIn
|
||||||
|
return top - float64(row)*fontSize - 9
|
||||||
|
}
|
||||||
|
|
||||||
|
func text(b *bytes.Buffer, x, y float64, s string) {
|
||||||
|
fmt.Fprintf(b, "BT /F1 12 Tf %.2f %.2f Td %s Tj ET\n", x, y, pdfString(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageContent(pg layout.Page, geo layout.Geometry, revisions []screenplay.Revision) []byte {
|
||||||
|
var b bytes.Buffer
|
||||||
|
header := (geo.Height-0.5)*ptPerIn - 9
|
||||||
|
if pg.Number > 0 && pg.Label != "" && pg.Label != "1" {
|
||||||
|
num := pg.Label + "."
|
||||||
|
text(&b, layout.RightEdge*ptPerIn-float64(len([]rune(num)))*fontSize*0.6, header, num)
|
||||||
|
}
|
||||||
|
// A revised page names its revision; its latest changes are starred.
|
||||||
|
rev := pg.Rev()
|
||||||
|
if rev > len(revisions) {
|
||||||
|
rev = 0
|
||||||
|
}
|
||||||
|
if rev > 0 {
|
||||||
|
r := revisions[rev-1]
|
||||||
|
label := r.Name + " Revision"
|
||||||
|
if r.Date != "" {
|
||||||
|
label += " - " + r.Date
|
||||||
|
}
|
||||||
|
text(&b, 1.5*ptPerIn, header, label)
|
||||||
|
}
|
||||||
|
for _, ln := range pg.Lines {
|
||||||
|
y := baseline(geo, ln.Row)
|
||||||
|
x := ln.X * ptPerIn
|
||||||
|
if ln.SceneNumber != "" {
|
||||||
|
text(&b, 0.75*ptPerIn, y, ln.SceneNumber)
|
||||||
|
text(&b, geo.SceneNumber*ptPerIn, y, ln.SceneNumber)
|
||||||
|
}
|
||||||
|
if rev > 0 && ln.Rev == rev {
|
||||||
|
text(&b, geo.RevisionMark*ptPerIn, y, "*")
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, "BT %.2f %.2f Td ", x, y)
|
||||||
|
cursor := x
|
||||||
|
var underlines [][2]float64
|
||||||
|
for _, s := range ln.Segments {
|
||||||
|
font := 1
|
||||||
|
if s.Bold {
|
||||||
|
font++
|
||||||
|
}
|
||||||
|
if s.Italic {
|
||||||
|
font += 2
|
||||||
|
}
|
||||||
|
width := float64(len([]rune(s.Text))) * fontSize * 0.6
|
||||||
|
if s.Underline {
|
||||||
|
underlines = append(underlines, [2]float64{cursor, cursor + width})
|
||||||
|
}
|
||||||
|
cursor += width
|
||||||
|
fmt.Fprintf(&b, "/F%d 12 Tf %s Tj ", font, pdfString(s.Text))
|
||||||
|
}
|
||||||
|
b.WriteString("ET\n")
|
||||||
|
for _, u := range underlines {
|
||||||
|
fmt.Fprintf(&b, "0.6 w %.2f %.2f m %.2f %.2f l S\n", u[0], y-1.8, u[1], y-1.8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func deflate(data []byte) ([]byte, error) {
|
||||||
|
var b bytes.Buffer
|
||||||
|
zw := zlib.NewWriter(&b)
|
||||||
|
if _, err := zw.Write(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return b.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pdfString encodes s as a WinAnsi literal string for the Courier fonts.
|
||||||
|
func pdfString(s string) string {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteByte('(')
|
||||||
|
for _, r := range s {
|
||||||
|
c := winAnsi(r)
|
||||||
|
if c == '(' || c == ')' || c == '\\' {
|
||||||
|
b.WriteByte('\\')
|
||||||
|
}
|
||||||
|
b.WriteByte(c)
|
||||||
|
}
|
||||||
|
b.WriteByte(')')
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// textString encodes s for the document info dictionary.
|
||||||
|
func textString(s string) string {
|
||||||
|
ascii := true
|
||||||
|
for _, r := range s {
|
||||||
|
if r > 0x7e || r < 0x20 {
|
||||||
|
ascii = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ascii {
|
||||||
|
return pdfString(s)
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("<FEFF")
|
||||||
|
for _, u := range utf16.Encode([]rune(s)) {
|
||||||
|
fmt.Fprintf(&b, "%04X", u)
|
||||||
|
}
|
||||||
|
b.WriteString(">")
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var cp1252 = map[rune]byte{
|
||||||
|
'€': 0x80, '‚': 0x82, 'ƒ': 0x83, '„': 0x84, '…': 0x85, '†': 0x86, '‡': 0x87,
|
||||||
|
'ˆ': 0x88, '‰': 0x89, 'Š': 0x8a, '‹': 0x8b, 'Œ': 0x8c, 'Ž': 0x8e,
|
||||||
|
'‘': 0x91, '’': 0x92, '“': 0x93, '”': 0x94, '•': 0x95, '–': 0x96, '—': 0x97,
|
||||||
|
'˜': 0x98, '™': 0x99, 'š': 0x9a, '›': 0x9b, 'œ': 0x9c, 'ž': 0x9e, 'Ÿ': 0x9f,
|
||||||
|
}
|
||||||
|
|
||||||
|
func winAnsi(r rune) byte {
|
||||||
|
switch {
|
||||||
|
case r >= 0x20 && r < 0x7f:
|
||||||
|
return byte(r)
|
||||||
|
case r >= 0xa0 && r <= 0xff:
|
||||||
|
return byte(r)
|
||||||
|
}
|
||||||
|
if c, ok := cp1252[r]; ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
if r == ' ' || r == ' ' {
|
||||||
|
return ' ' // narrow spaces used before French punctuation
|
||||||
|
}
|
||||||
|
return '?'
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"compress/zlib"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"plotzilla/internal/fountain"
|
||||||
|
"plotzilla/internal/layout"
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
const sample = `Title: Le Dernier Rouleau
|
||||||
|
Credit: Written by
|
||||||
|
Author: Jane Doe
|
||||||
|
Contact: jane@example.com
|
||||||
|
Draft date: 28/09/2026
|
||||||
|
|
||||||
|
INT. CABINE DE PROJECTION - NUIT
|
||||||
|
|
||||||
|
La poussière danse dans le **faisceau** du projecteur. Élodie _entre_.
|
||||||
|
|
||||||
|
ÉLODIE (V.O.)
|
||||||
|
(à voix basse)
|
||||||
|
Ça finit toujours *ici*.
|
||||||
|
|
||||||
|
MARC ^
|
||||||
|
(criant)
|
||||||
|
Non ! Pas encore, pas ce soir.
|
||||||
|
|
||||||
|
CUT TO:
|
||||||
|
`
|
||||||
|
|
||||||
|
func TestRender(t *testing.T) {
|
||||||
|
doc := fountain.Parse(sample)
|
||||||
|
pages := []layout.Page{layout.TitlePage(doc.TitlePage, doc.Settings.Paper)}
|
||||||
|
pages = append(pages, layout.Paginate(doc, layout.Options{SceneNumbers: true}).Pages...)
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := Render(&buf, pages, Options{Title: doc.TitlePage.Title, Author: doc.TitlePage.Author}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.HasPrefix(out, "%PDF-1.4") || !strings.HasSuffix(out, "%%EOF\n") || !strings.Contains(out, "/Count 2") {
|
||||||
|
t.Fatalf("malformed PDF:\n%.300s", out)
|
||||||
|
}
|
||||||
|
// PLOTZILLA_PDF=/tmp/x.pdf go test ./internal/pdf keeps the file for inspection.
|
||||||
|
if path := os.Getenv("PLOTZILLA_PDF"); path != "" {
|
||||||
|
if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRevisionsAndA4(t *testing.T) {
|
||||||
|
doc := fountain.Parse(sample)
|
||||||
|
doc.Settings.Paper = screenplay.A4
|
||||||
|
doc.Settings.Revisions = []screenplay.Revision{{Name: "Blue", Color: "blue", Date: "09/28/26"}}
|
||||||
|
doc.Elements[1].Runs[0].Rev = 1
|
||||||
|
var buf bytes.Buffer
|
||||||
|
pages := layout.Paginate(doc, layout.Options{}).Pages
|
||||||
|
if err := Render(&buf, pages, Options{Paper: doc.Settings.Paper, Revisions: doc.Settings.Revisions}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
stream := uncompressed(t, buf.Bytes())
|
||||||
|
if !strings.Contains(buf.String(), "/MediaBox [0 0 595.44 841.68]") {
|
||||||
|
t.Errorf("not an A4 page")
|
||||||
|
}
|
||||||
|
if !strings.Contains(stream, "(Blue Revision - 09/28/26) Tj") || strings.Count(stream, "(*) Tj") != 1 {
|
||||||
|
t.Errorf("revision header or mark missing:\n%s", stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without revisions in the options, nothing is marked.
|
||||||
|
buf.Reset()
|
||||||
|
if err := Render(&buf, pages, Options{Paper: doc.Settings.Paper}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if stream := uncompressed(t, buf.Bytes()); strings.Contains(stream, "Revision") || strings.Contains(stream, "(*)") {
|
||||||
|
t.Errorf("unexpected revision marks:\n%s", stream)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// uncompressed returns the content streams of a PDF written by Render.
|
||||||
|
func uncompressed(t *testing.T, pdf []byte) string {
|
||||||
|
var out strings.Builder
|
||||||
|
for _, part := range bytes.Split(pdf, []byte(">>\nstream\n"))[1:] {
|
||||||
|
end := bytes.Index(part, []byte("\nendstream"))
|
||||||
|
r, err := zlib.NewReader(bytes.NewReader(part[:end]))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, _ := io.ReadAll(r)
|
||||||
|
out.Write(data)
|
||||||
|
}
|
||||||
|
return out.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
// Package screenplay holds the in-memory model of a screenplay: an ordered
|
||||||
|
// list of typed elements (scene heading, action, character, ...) plus a
|
||||||
|
// title page. Every file format and renderer converts to and from this model.
|
||||||
|
package screenplay
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ElementType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Scene ElementType = "scene"
|
||||||
|
Action ElementType = "action"
|
||||||
|
Character ElementType = "character"
|
||||||
|
Parenthetical ElementType = "parenthetical"
|
||||||
|
Dialogue ElementType = "dialogue"
|
||||||
|
Transition ElementType = "transition"
|
||||||
|
Centered ElementType = "centered"
|
||||||
|
// Shot is an insert or camera direction ("INSERT - THE LETTER",
|
||||||
|
// "CLOSE ON", "POV"): set like a scene heading but not a scene.
|
||||||
|
Shot ElementType = "shot"
|
||||||
|
// Intertitle is on-screen text: a title card, centred in capitals.
|
||||||
|
Intertitle ElementType = "intertitle"
|
||||||
|
// Section is an outline heading (Fountain "#", "##"…) and Synopsis a
|
||||||
|
// summary line (Fountain "="). Neither is printed.
|
||||||
|
Section ElementType = "section"
|
||||||
|
Synopsis ElementType = "synopsis"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Printed reports whether the element appears on the printed page.
|
||||||
|
func (t ElementType) Printed() bool {
|
||||||
|
return t != Section && t != Synopsis
|
||||||
|
}
|
||||||
|
|
||||||
|
// Uppercase reports whether the element is always printed in capitals.
|
||||||
|
func (t ElementType) Uppercase() bool {
|
||||||
|
return t == Scene || t == Character || t == Transition || t == Shot || t == Intertitle
|
||||||
|
}
|
||||||
|
|
||||||
|
// InDialogue reports whether the element belongs to a dialogue block
|
||||||
|
// (the lines that follow a character cue).
|
||||||
|
func (t ElementType) InDialogue() bool {
|
||||||
|
return t == Parenthetical || t == Dialogue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run is a span of text sharing the same emphasis. A "\n" inside Text is a
|
||||||
|
// hard line break within the element.
|
||||||
|
type Run struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
Bold bool `json:"b,omitempty"`
|
||||||
|
Italic bool `json:"i,omitempty"`
|
||||||
|
Underline bool `json:"u,omitempty"`
|
||||||
|
// Note marks a writer's note (Fountain "[[…]]"): kept and shown in the
|
||||||
|
// editor, never printed.
|
||||||
|
Note bool `json:"n,omitempty"`
|
||||||
|
// Rev is the revision set (1 = the first, see Settings.Revisions) in
|
||||||
|
// which the text was added or changed; 0 is original text.
|
||||||
|
Rev int `json:"rev,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Run) SameStyle(o Run) bool {
|
||||||
|
return r.Bold == o.Bold && r.Italic == o.Italic && r.Underline == o.Underline && r.Note == o.Note && r.Rev == o.Rev
|
||||||
|
}
|
||||||
|
|
||||||
|
type Element struct {
|
||||||
|
Type ElementType `json:"type"`
|
||||||
|
Runs []Run `json:"runs"`
|
||||||
|
// SceneNumber is a locked scene number ("12A"). Empty means automatic.
|
||||||
|
SceneNumber string `json:"sceneNumber,omitempty"`
|
||||||
|
// Dual, on a character cue, puts its dialogue block beside the
|
||||||
|
// previous one (dual dialogue, Fountain's "^").
|
||||||
|
Dual bool `json:"dual,omitempty"`
|
||||||
|
// Level is the depth of a section, from 1 ("#").
|
||||||
|
Level int `json:"level,omitempty"`
|
||||||
|
// NewPage forces a page break before the element (Fountain "===").
|
||||||
|
// On a dialogue part it applies to the whole dialogue block.
|
||||||
|
NewPage bool `json:"newPage,omitempty"`
|
||||||
|
// Locked lists the locked pages that start inside this element, in
|
||||||
|
// offset order (see Settings.Locked).
|
||||||
|
Locked []PageLock `json:"locked,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PageLock fixes where a page starts once pages are locked: the page
|
||||||
|
// labelled Page starts at rune Offset of the element's text.
|
||||||
|
type PageLock struct {
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
Page string `json:"page"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewElement(t ElementType, text string) Element {
|
||||||
|
e := Element{Type: t, Runs: []Run{}}
|
||||||
|
if text != "" {
|
||||||
|
e.Runs = append(e.Runs, Run{Text: text})
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text returns the element's plain text, without emphasis.
|
||||||
|
func (e Element) Text() string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range e.Runs {
|
||||||
|
b.WriteString(r.Text)
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Element) IsEmpty() bool {
|
||||||
|
return strings.TrimSpace(e.Text()) == ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrintedText returns the text that is printed: without notes.
|
||||||
|
func (e Element) PrintedText() string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range e.Runs {
|
||||||
|
if !r.Note {
|
||||||
|
b.WriteString(r.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type TitlePage struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
Credit string `json:"credit"`
|
||||||
|
Author string `json:"author"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
DraftDate string `json:"draftDate"`
|
||||||
|
Contact string `json:"contact"`
|
||||||
|
Notes string `json:"notes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t TitlePage) IsEmpty() bool {
|
||||||
|
return strings.TrimSpace(t.Title+t.Author+t.Source+t.DraftDate+t.Contact+t.Notes) == ""
|
||||||
|
}
|
||||||
|
|
||||||
|
type Document struct {
|
||||||
|
TitlePage TitlePage `json:"titlePage"`
|
||||||
|
Elements []Element `json:"elements"`
|
||||||
|
Settings Settings `json:"settings"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paper is the page size: "" for US Letter, or A4.
|
||||||
|
type Paper string
|
||||||
|
|
||||||
|
const (
|
||||||
|
Letter Paper = ""
|
||||||
|
A4 Paper = "a4"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Settings are the document's production settings. The zero value is a
|
||||||
|
// US Letter script without revisions.
|
||||||
|
type Settings struct {
|
||||||
|
Paper Paper `json:"paper,omitempty"`
|
||||||
|
// Revisions are the revision sets issued so far, in order: the text
|
||||||
|
// of set n carries Run.Rev == n.
|
||||||
|
Revisions []Revision `json:"revisions,omitempty"`
|
||||||
|
// Revising marks new text with the latest revision set.
|
||||||
|
Revising bool `json:"revising,omitempty"`
|
||||||
|
// Locked keeps the page numbers of Element.Locked: added material goes
|
||||||
|
// to A pages (12A), removed material leaves shorter or merged pages.
|
||||||
|
Locked bool `json:"locked,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Settings) IsZero() bool {
|
||||||
|
return s.Paper == Letter && len(s.Revisions) == 0 && !s.Revising && !s.Locked
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revision is a revision set, named after the colour of its pages.
|
||||||
|
type Revision struct {
|
||||||
|
Name string `json:"name"` // "Blue", "Double Pink"
|
||||||
|
Color string `json:"color"` // "blue", "pink"…: the paper colour
|
||||||
|
Date string `json:"date"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// revisionColors is the industry order of revision pages. The first cycle
|
||||||
|
// starts at Blue (the original draft is White); later cycles start again
|
||||||
|
// at White, as "Double White", "Double Blue"…
|
||||||
|
var revisionColors = []string{"White", "Blue", "Pink", "Yellow", "Green", "Goldenrod", "Buff", "Salmon", "Cherry"}
|
||||||
|
|
||||||
|
// RevisionSet returns the name and colour of revision set n (from 1).
|
||||||
|
func RevisionSet(n int) Revision {
|
||||||
|
n = max(n, 1)
|
||||||
|
cycle, i := n/len(revisionColors), n%len(revisionColors)
|
||||||
|
name := revisionColors[i]
|
||||||
|
r := Revision{Name: name, Color: strings.ToLower(name)}
|
||||||
|
switch cycle {
|
||||||
|
case 0:
|
||||||
|
case 1:
|
||||||
|
r.Name = "Double " + name
|
||||||
|
case 2:
|
||||||
|
r.Name = "Triple " + name
|
||||||
|
default:
|
||||||
|
r.Name = ordinal(cycle+1) + " " + name
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func ordinal(n int) string {
|
||||||
|
suffix := "th"
|
||||||
|
if n%100 < 11 || n%100 > 13 {
|
||||||
|
switch n % 10 {
|
||||||
|
case 1:
|
||||||
|
suffix = "st"
|
||||||
|
case 2:
|
||||||
|
suffix = "nd"
|
||||||
|
case 3:
|
||||||
|
suffix = "rd"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strconv.Itoa(n) + suffix
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns an empty screenplay, ready to receive its first scene heading.
|
||||||
|
func New() *Document {
|
||||||
|
return &Document{
|
||||||
|
TitlePage: TitlePage{Credit: "Written by"},
|
||||||
|
Elements: []Element{NewElement(Scene, "")},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NormalizeRuns drops empty runs and merges neighbours with the same style.
|
||||||
|
func NormalizeRuns(runs []Run) []Run {
|
||||||
|
out := make([]Run, 0, len(runs))
|
||||||
|
for _, r := range runs {
|
||||||
|
if r.Text == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if n := len(out); n > 0 && out[n-1].SameStyle(r) {
|
||||||
|
out[n-1].Text += r.Text
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// CharacterName extracts the bare name from a character cue:
|
||||||
|
// "John (V.O.)" -> "JOHN".
|
||||||
|
func CharacterName(cue string) string {
|
||||||
|
cue = strings.TrimSuffix(strings.TrimSpace(cue), "^")
|
||||||
|
if i := strings.Index(cue, "("); i >= 0 {
|
||||||
|
cue = cue[:i]
|
||||||
|
}
|
||||||
|
return strings.ToUpper(strings.TrimSpace(cue))
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpperRunes upper-cases rune by rune so that offsets are preserved
|
||||||
|
// (strings.ToUpper may change the length, e.g. "ß" -> "SS").
|
||||||
|
func UpperRunes(s string) string {
|
||||||
|
r := []rune(s)
|
||||||
|
for i, c := range r {
|
||||||
|
r[i] = unicode.ToUpper(c)
|
||||||
|
}
|
||||||
|
return string(r)
|
||||||
|
}
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
package spell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
type letterCase int
|
||||||
|
|
||||||
|
const (
|
||||||
|
lowerCase letterCase = iota
|
||||||
|
titleCase // "Paris"
|
||||||
|
upperCase // "PARIS"
|
||||||
|
mixedCase // "iPhone", "McDonald"
|
||||||
|
)
|
||||||
|
|
||||||
|
func caseOf(w string) letterCase {
|
||||||
|
upper, lower, firstUpper := 0, 0, false
|
||||||
|
for i, r := range w {
|
||||||
|
switch {
|
||||||
|
case unicode.IsUpper(r):
|
||||||
|
upper++
|
||||||
|
if i == 0 {
|
||||||
|
firstUpper = true
|
||||||
|
}
|
||||||
|
case unicode.IsLower(r):
|
||||||
|
lower++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case upper == 0:
|
||||||
|
return lowerCase
|
||||||
|
case lower == 0:
|
||||||
|
return upperCase
|
||||||
|
case upper == 1 && firstUpper:
|
||||||
|
return titleCase
|
||||||
|
}
|
||||||
|
return mixedCase
|
||||||
|
}
|
||||||
|
|
||||||
|
func capitalize(w string) string {
|
||||||
|
r, size := utf8.DecodeRuneInString(w)
|
||||||
|
return string(unicode.ToTitle(r)) + w[size:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check reports whether word is spelled correctly. As in Hunspell, a
|
||||||
|
// capitalised or all-caps word is also accepted in its lower-case form
|
||||||
|
// ("Door", "DOOR"), but a lower-case proper noun is not ("paris").
|
||||||
|
func (d *Dictionary) Check(word string) bool {
|
||||||
|
w := d.iconv.Replace(word)
|
||||||
|
if d.accepts(w, false) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
switch caseOf(w) {
|
||||||
|
case titleCase:
|
||||||
|
return d.accepts(strings.ToLower(w), true)
|
||||||
|
case upperCase:
|
||||||
|
lower := strings.ToLower(w)
|
||||||
|
return d.accepts(capitalize(lower), true) || d.accepts(lower, true)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// accepts checks one exact spelling, as a word or as a compound word.
|
||||||
|
func (d *Dictionary) accepts(w string, caseChanged bool) bool {
|
||||||
|
if d.valid(w, caseChanged) || (d.compound.enabled() && d.compoundOf(w, 0, "", caseChanged)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, r := range d.compound.rules {
|
||||||
|
if d.matchesRule(w, r, 0, 0, caseChanged) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchesRule reports whether w splits into dictionary words (without
|
||||||
|
// affixes, as in Hunspell) whose flags follow rule from step i; parts
|
||||||
|
// counts the words already matched.
|
||||||
|
func (d *Dictionary) matchesRule(w string, rule compoundRule, i, parts int, cc bool) bool {
|
||||||
|
if i < len(rule) && rule[i].rep != 0 && d.matchesRule(w, rule, i+1, parts, cc) {
|
||||||
|
return true // an optional step left out
|
||||||
|
}
|
||||||
|
if w == "" {
|
||||||
|
return i == len(rule) && parts >= 2
|
||||||
|
}
|
||||||
|
if i == len(rule) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
step := rule[i]
|
||||||
|
next := i + 1
|
||||||
|
if step.rep == '*' {
|
||||||
|
next = i
|
||||||
|
}
|
||||||
|
runes := []rune(w)
|
||||||
|
for n := d.compound.min; n <= len(runes); n++ {
|
||||||
|
part := string(runes[:n])
|
||||||
|
if d.isForbidden(part) || !d.stemHas(part, cc, func(f flagSet) bool { return f.has(step.flag) }) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if d.matchesRule(string(runes[n:]), rule, next, parts+1, cc) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where a part sits in a compound word.
|
||||||
|
const (
|
||||||
|
partBegin = iota
|
||||||
|
partMiddle
|
||||||
|
partLast
|
||||||
|
)
|
||||||
|
|
||||||
|
// compoundOf reports whether w splits into compound parts, the first of
|
||||||
|
// which follows parts earlier ones (prev is the last of them).
|
||||||
|
func (d *Dictionary) compoundOf(w string, parts int, prev string, cc bool) bool {
|
||||||
|
c := d.compound
|
||||||
|
runes := []rune(w)
|
||||||
|
fits := func(n int) bool { return c.maxWords == 0 || n <= c.maxWords }
|
||||||
|
for i := c.min; i <= len(runes)-c.min; i++ {
|
||||||
|
head, rest := string(runes[:i]), string(runes[i:])
|
||||||
|
if c.checkDup && head == prev {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if c.checkCase && (unicode.IsUpper(runes[i]) || unicode.IsUpper(runes[i-1])) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pos := partBegin
|
||||||
|
if parts > 0 {
|
||||||
|
pos = partMiddle
|
||||||
|
}
|
||||||
|
if !d.compoundPart(head, pos, cc) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fits(parts+2) && !(c.checkDup && rest == head) && d.compoundPart(rest, partLast, cc) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if fits(parts+3) && d.compoundOf(rest, parts+1, head, cc) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// compoundPart checks one part of a compound word. The first part may take
|
||||||
|
// a prefix and the last one a suffix; other affixes need COMPOUNDPERMITFLAG.
|
||||||
|
func (d *Dictionary) compoundPart(w string, pos int, cc bool) bool {
|
||||||
|
c := d.compound
|
||||||
|
allowed := func(f flagSet) bool {
|
||||||
|
return f.has(c.any) || (pos == partBegin && f.has(c.begin)) ||
|
||||||
|
(pos == partMiddle && f.has(c.middle)) || (pos == partLast && f.has(c.last))
|
||||||
|
}
|
||||||
|
if d.isForbidden(w) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if d.stemHas(w, cc, func(f flagSet) bool { return !f.has(d.needAffix) && allowed(f) }) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
affixOK := func(a *affix, at int) bool {
|
||||||
|
return !a.cont.has(c.forbid) && (pos == at || a.cont.has(c.permit))
|
||||||
|
}
|
||||||
|
if d.matchingSuffixes(w, func(s *affix, stem string) bool {
|
||||||
|
return affixOK(s, partLast) && d.stemHas(stem, cc, func(f flagSet) bool { return f.has(s.flag) && allowed(f) })
|
||||||
|
}) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return d.matchingPrefixes(w, func(p *affix, rest string) bool {
|
||||||
|
if !affixOK(p, partBegin) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if d.stemHas(rest, cc, func(f flagSet) bool { return f.has(p.flag) && allowed(f) }) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// Both: a prefix and a suffix that combine (cross product).
|
||||||
|
return p.cross && d.matchingSuffixes(rest, func(s *affix, stem string) bool {
|
||||||
|
return s.cross && affixOK(s, partLast) &&
|
||||||
|
d.stemHas(stem, cc, func(f flagSet) bool { return f.has(p.flag) && f.has(s.flag) && allowed(f) })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// valid checks one exact spelling. caseChanged is set when the word was
|
||||||
|
// lower-cased to be looked up, which KEEPCASE words forbid.
|
||||||
|
func (d *Dictionary) valid(w string, caseChanged bool) bool {
|
||||||
|
if w == "" || d.isForbidden(w) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if d.stemHas(w, caseChanged, func(f flagSet) bool { return !f.has(d.needAffix) && !f.has(d.onlyInComp) }) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return d.suffixed(w, caseChanged) || d.prefixed(w, caseChanged)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dictionary) isForbidden(w string) bool {
|
||||||
|
if d.forbidden == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, f := range d.words[w] {
|
||||||
|
if f.has(d.forbidden) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// stemHas reports whether one of the homonyms of stem satisfies ok.
|
||||||
|
func (d *Dictionary) stemHas(stem string, caseChanged bool, ok func(flagSet) bool) bool {
|
||||||
|
for _, f := range d.words[stem] {
|
||||||
|
if f.has(d.forbidden) || (caseChanged && f.has(d.keepCase)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ok(f) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// matchingSuffixes calls fn for every suffix that w can end with, with the
|
||||||
|
// stem it leaves once the suffix is removed and the stripped text restored.
|
||||||
|
func (d *Dictionary) matchingSuffixes(w string, fn func(a *affix, stem string) bool) bool {
|
||||||
|
for n := 0; n <= min(d.maxSuffix, len(w)); n++ {
|
||||||
|
for _, a := range d.suffixes[w[len(w)-n:]] {
|
||||||
|
base := w[:len(w)-n]
|
||||||
|
if base == "" && !d.fullStrip {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stem := base + a.strip
|
||||||
|
if stem == "" || !a.cond.matchEnd(stem) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fn(a, stem) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dictionary) matchingPrefixes(w string, fn func(a *affix, stem string) bool) bool {
|
||||||
|
for n := 0; n <= min(d.maxPrefix, len(w)); n++ {
|
||||||
|
for _, a := range d.prefixes[w[:n]] {
|
||||||
|
rest := w[n:]
|
||||||
|
if rest == "" && !d.fullStrip {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stem := a.strip + rest
|
||||||
|
if stem == "" || !a.cond.matchStart(stem) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fn(a, stem) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// suffixed accepts stem+suffix, and stem+suffix+suffix when the inner
|
||||||
|
// suffix lists the outer one as a continuation class.
|
||||||
|
func (d *Dictionary) suffixed(w string, cc bool) bool {
|
||||||
|
return d.matchingSuffixes(w, func(s *affix, stem string) bool {
|
||||||
|
if !s.cont.has(d.needAffix) && !s.cont.has(d.circumfix) &&
|
||||||
|
d.stemHas(stem, cc, func(f flagSet) bool { return f.has(s.flag) }) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if !d.contFlags[s.flag] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return d.matchingSuffixes(stem, func(inner *affix, root string) bool {
|
||||||
|
return inner.cont.has(s.flag) &&
|
||||||
|
d.stemHas(root, cc, func(f flagSet) bool { return f.has(inner.flag) })
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// prefixed accepts prefix+stem and prefix+stem+suffix.
|
||||||
|
func (d *Dictionary) prefixed(w string, cc bool) bool {
|
||||||
|
return d.matchingPrefixes(w, func(p *affix, rest string) bool {
|
||||||
|
if !p.cont.has(d.needAffix) && !p.cont.has(d.circumfix) &&
|
||||||
|
d.stemHas(rest, cc, func(f flagSet) bool { return f.has(p.flag) }) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return d.matchingSuffixes(rest, func(s *affix, stem string) bool {
|
||||||
|
if s.cont.has(d.circumfix) != p.cont.has(d.circumfix) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return d.stemHas(stem, cc, func(f flagSet) bool {
|
||||||
|
switch {
|
||||||
|
case f.has(s.flag) && f.has(p.flag):
|
||||||
|
return p.cross && s.cross
|
||||||
|
case f.has(s.flag):
|
||||||
|
return s.cont.has(p.flag) // the suffix allows the prefix
|
||||||
|
case f.has(p.flag):
|
||||||
|
return p.cont.has(s.flag)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxSuggestions is how many corrections Suggest returns at most.
|
||||||
|
const maxSuggestions = 8
|
||||||
|
|
||||||
|
// Suggest returns likely corrections for a misspelled word, best first,
|
||||||
|
// in the word's case ("TEH" gives "THE"). It tries the word with a capital
|
||||||
|
// (proper nouns), the dictionary's table of common misspellings (REP), then
|
||||||
|
// every spelling one edit away, the most frequent kinds of typo first:
|
||||||
|
// swapped letters, an extra letter, a wrong letter, a missing letter, and
|
||||||
|
// a missing space between two words of three letters or more.
|
||||||
|
func (d *Dictionary) Suggest(word string) []string {
|
||||||
|
w := d.iconv.Replace(word)
|
||||||
|
wc := caseOf(w)
|
||||||
|
base := w
|
||||||
|
if wc == titleCase || wc == upperCase {
|
||||||
|
base = strings.ToLower(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
var out, proper []string
|
||||||
|
seen := map[string]bool{w: true}
|
||||||
|
try := func(cand string) {
|
||||||
|
if len(out) >= maxSuggestions || seen[cand] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[cand] = true
|
||||||
|
if d.suggestable(cand) {
|
||||||
|
out = append(out, cand)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// A lower-case candidate may be a proper noun ("pariss" → "Paris"),
|
||||||
|
// offered after the common words.
|
||||||
|
if caseOf(cand) == lowerCase {
|
||||||
|
if cand = capitalize(cand); !seen[cand] && d.suggestable(cand) {
|
||||||
|
seen[cand] = true
|
||||||
|
proper = append(proper, cand)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if wc == lowerCase && d.suggestable(capitalize(base)) {
|
||||||
|
out = append(out, capitalize(base))
|
||||||
|
}
|
||||||
|
for _, r := range d.rep {
|
||||||
|
for i := 0; ; {
|
||||||
|
j := strings.Index(base[i:], r.from)
|
||||||
|
if j < 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
at := i + j
|
||||||
|
if (!r.start || at == 0) && (!r.end || at+len(r.from) == len(base)) {
|
||||||
|
try(base[:at] + r.to + base[at+len(r.from):])
|
||||||
|
}
|
||||||
|
i = at + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runes := []rune(base)
|
||||||
|
edit := func(i, del int, ins ...rune) string {
|
||||||
|
return string(runes[:i]) + string(ins) + string(runes[i+del:])
|
||||||
|
}
|
||||||
|
for i := 0; i+1 < len(runes); i++ {
|
||||||
|
if runes[i] != runes[i+1] {
|
||||||
|
try(edit(i, 2, runes[i+1], runes[i]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range runes {
|
||||||
|
try(edit(i, 1))
|
||||||
|
}
|
||||||
|
for i := range runes {
|
||||||
|
for _, c := range d.try {
|
||||||
|
if c != runes[i] && !unicode.IsUpper(c) {
|
||||||
|
try(edit(i, 1, c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 0; i <= len(runes); i++ {
|
||||||
|
for _, c := range d.try {
|
||||||
|
if !unicode.IsUpper(c) {
|
||||||
|
try(edit(i, 0, c))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Short words ("a", "re", "er") make most splits look valid but are
|
||||||
|
// rarely what was meant; REP tables cover the common cases ("a lot").
|
||||||
|
for i := 3; i+3 <= len(runes); i++ {
|
||||||
|
try(edit(i, 0, ' '))
|
||||||
|
}
|
||||||
|
|
||||||
|
out = append(out, proper...)
|
||||||
|
out = out[:min(len(out), maxSuggestions)]
|
||||||
|
for i, s := range out {
|
||||||
|
switch wc {
|
||||||
|
case upperCase:
|
||||||
|
s = strings.ToUpper(s)
|
||||||
|
case titleCase:
|
||||||
|
s = capitalize(s)
|
||||||
|
}
|
||||||
|
out[i] = d.oconv.Replace(s)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// suggestable checks a candidate, which may be two words separated by a
|
||||||
|
// space, and leaves out words marked NOSUGGEST (offensive words, mostly).
|
||||||
|
func (d *Dictionary) suggestable(cand string) bool {
|
||||||
|
for _, w := range strings.Split(cand, " ") {
|
||||||
|
if w == "" || strings.HasPrefix(w, "-") || strings.HasSuffix(w, "-") || !d.valid(w, false) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, f := range d.words[w] {
|
||||||
|
if f.has(d.noSuggest) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
package spell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Word is a word found in a text. Offset and Length count runes, like
|
||||||
|
// every offset exchanged with the editor.
|
||||||
|
type Word struct {
|
||||||
|
Text string
|
||||||
|
Offset int
|
||||||
|
Length int
|
||||||
|
}
|
||||||
|
|
||||||
|
func isApostrophe(r rune) bool { return r == '\'' || r == '’' }
|
||||||
|
|
||||||
|
func isWordRune(r rune) bool {
|
||||||
|
return unicode.IsLetter(r) || unicode.IsMark(r) || unicode.IsDigit(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Words splits text into words: runs of letters and digits, with the
|
||||||
|
// apostrophes inside them ("don't", "l'homme"). Hyphens, slashes and
|
||||||
|
// dots separate words, so each half of "well-known" is checked alone.
|
||||||
|
func Words(text string) []Word {
|
||||||
|
var words []Word
|
||||||
|
runes := []rune(text)
|
||||||
|
for i := 0; i < len(runes); {
|
||||||
|
if !isWordRune(runes[i]) {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
start := i
|
||||||
|
for i < len(runes) && (isWordRune(runes[i]) ||
|
||||||
|
(isApostrophe(runes[i]) && i+1 < len(runes) && isWordRune(runes[i+1]))) {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
words = append(words, Word{Text: string(runes[start:i]), Offset: start, Length: i - start})
|
||||||
|
}
|
||||||
|
return words
|
||||||
|
}
|
||||||
|
|
||||||
|
// Misspelling locates a misspelled word: the index of its element in
|
||||||
|
// document order (as layout.Break) and its rune offset and length.
|
||||||
|
type Misspelling struct {
|
||||||
|
Element int `json:"element"`
|
||||||
|
Offset int `json:"offset"`
|
||||||
|
Length int `json:"length"`
|
||||||
|
Word string `json:"word"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// jargon lists screenplay abbreviations that no dictionary knows.
|
||||||
|
var jargon = map[string]bool{
|
||||||
|
"int": true, "ext": true, "est": true, "cont'd": true, "contd": true,
|
||||||
|
"pov": true, "vo": true, "os": true, "oc": true, "ecu": true, "mos": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
var sceneOpener = regexp.MustCompile(`(?i)^\s*(int\.?/ext|ext\.?/int|int|ext|est|i/e)\b`)
|
||||||
|
|
||||||
|
// Checker checks screenplays against one dictionary plus the user's own
|
||||||
|
// words, and remembers the answers: a script repeats the same words.
|
||||||
|
type Checker struct {
|
||||||
|
dict *Dictionary
|
||||||
|
mu sync.Mutex
|
||||||
|
cache map[string]bool
|
||||||
|
personal map[string]bool // lower-case
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewChecker(d *Dictionary, personal []string) *Checker {
|
||||||
|
c := &Checker{dict: d, cache: map[string]bool{}, personal: map[string]bool{}}
|
||||||
|
for _, w := range personal {
|
||||||
|
c.personal[strings.ToLower(w)] = true
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add accepts word from now on, in any letter case.
|
||||||
|
func (c *Checker) Add(word string) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
c.personal[strings.ToLower(normalize(word))] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalize(w string) string { return strings.ReplaceAll(w, "’", "'") }
|
||||||
|
|
||||||
|
// Check reports whether word is correct. Words with digits ("3rd", "R2D2")
|
||||||
|
// and single letters are always accepted.
|
||||||
|
func (c *Checker) Check(word string) bool {
|
||||||
|
if len([]rune(word)) < 2 || strings.IndexFunc(word, unicode.IsDigit) >= 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(normalize(word))
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if jargon[lower] || c.personal[lower] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
ok, found := c.cache[word]
|
||||||
|
if !found {
|
||||||
|
ok = c.dict.Check(word)
|
||||||
|
c.cache[word] = ok
|
||||||
|
}
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Checker) Suggest(word string) []string { return c.dict.Suggest(word) }
|
||||||
|
|
||||||
|
// Misspellings returns the misspelled words of a script. Character cues
|
||||||
|
// hold names, so they are not checked, and the names they introduce are
|
||||||
|
// accepted everywhere else (an action line often spells them in capitals).
|
||||||
|
func (c *Checker) Misspellings(doc *screenplay.Document) []Misspelling {
|
||||||
|
names := map[string]bool{}
|
||||||
|
for _, el := range doc.Elements {
|
||||||
|
if el.Type == screenplay.Character {
|
||||||
|
for _, w := range Words(screenplay.CharacterName(el.PrintedText())) {
|
||||||
|
names[strings.ToLower(normalize(w.Text))] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := []Misspelling{}
|
||||||
|
for i, el := range doc.Elements {
|
||||||
|
if el.Type == screenplay.Character {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text := el.Text()
|
||||||
|
skip := 0 // runes of a scene heading's "INT./EXT."
|
||||||
|
if el.Type == screenplay.Scene {
|
||||||
|
if m := sceneOpener.FindString(text); m != "" {
|
||||||
|
skip = len([]rune(m))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, w := range Words(text) {
|
||||||
|
if w.Offset < skip || isName(names, w.Text) || c.Check(w.Text) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, Misspelling{Element: i, Offset: w.Offset, Length: w.Length, Word: w.Text})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// isName reports whether w is one of the names, possibly possessive
|
||||||
|
// ("ELODIE's").
|
||||||
|
func isName(names map[string]bool, w string) bool {
|
||||||
|
lower := strings.ToLower(normalize(w))
|
||||||
|
return names[lower] || names[strings.TrimSuffix(lower, "'s")]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Language is an installed dictionary, named after its files ("en_US").
|
||||||
|
type Language struct {
|
||||||
|
Code string
|
||||||
|
Aff string
|
||||||
|
Dic string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Available lists the dictionaries found in dirs; when the same language
|
||||||
|
// is in several directories, the first one wins.
|
||||||
|
func Available(dirs []string) []Language {
|
||||||
|
seen := map[string]bool{}
|
||||||
|
var out []Language
|
||||||
|
for _, dir := range dirs {
|
||||||
|
matches, _ := filepath.Glob(filepath.Join(dir, "*.dic"))
|
||||||
|
sort.Strings(matches)
|
||||||
|
for _, dic := range matches {
|
||||||
|
code := strings.TrimSuffix(filepath.Base(dic), ".dic")
|
||||||
|
aff := strings.TrimSuffix(dic, ".dic") + ".aff"
|
||||||
|
if seen[code] || strings.HasPrefix(code, "hyph_") || strings.HasPrefix(code, "th_") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(aff); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[code] = true
|
||||||
|
out = append(out, Language{Code: code, Aff: aff, Dic: dic})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preferred picks the dictionary that suits a locale such as
|
||||||
|
// "fr_FR.UTF-8": the same language and region, then the same language,
|
||||||
|
// then American English, then the first one.
|
||||||
|
func Preferred(codes []string, locale string) string {
|
||||||
|
if len(codes) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
locale, _, _ = strings.Cut(locale, ".")
|
||||||
|
locale, _, _ = strings.Cut(locale, "@")
|
||||||
|
lang, _, _ := strings.Cut(locale, "_")
|
||||||
|
for _, want := range []func(string) bool{
|
||||||
|
func(c string) bool { return locale != "" && c == locale },
|
||||||
|
func(c string) bool { return lang != "" && (c == lang || strings.HasPrefix(c, lang+"_")) },
|
||||||
|
func(c string) bool { return c == "en_US" },
|
||||||
|
func(c string) bool { return strings.HasPrefix(c, "en_") || c == "en" },
|
||||||
|
} {
|
||||||
|
for _, c := range codes {
|
||||||
|
if want(c) {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return codes[0]
|
||||||
|
}
|
||||||
@@ -0,0 +1,555 @@
|
|||||||
|
// Package spell checks spelling with Hunspell dictionaries (the .aff and
|
||||||
|
// .dic files shipped by Linux distributions and LibreOffice). It implements
|
||||||
|
// the part of the Hunspell format that ordinary words need: prefixes and
|
||||||
|
// suffixes with their conditions, cross products, two-level suffixes,
|
||||||
|
// flag aliases and the usual word flags, plus compound words built with
|
||||||
|
// COMPOUNDFLAG or COMPOUNDBEGIN/MIDDLE/LAST (German, Dutch, Scandinavian
|
||||||
|
// dictionaries) or described by COMPOUNDRULE patterns.
|
||||||
|
package spell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
type flag uint16
|
||||||
|
|
||||||
|
// flagSet is a sorted list of flags; words and affixes carry only a few.
|
||||||
|
type flagSet []flag
|
||||||
|
|
||||||
|
func (s flagSet) has(f flag) bool {
|
||||||
|
if f == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
i := sort.Search(len(s), func(i int) bool { return s[i] >= f })
|
||||||
|
return i < len(s) && s[i] == f
|
||||||
|
}
|
||||||
|
|
||||||
|
// condition is a Hunspell affix condition: a sequence of characters, "."
|
||||||
|
// or bracket classes ("[^aeiou]y"), matched against one end of the stem.
|
||||||
|
type condition []condUnit
|
||||||
|
|
||||||
|
type condUnit struct {
|
||||||
|
any bool
|
||||||
|
neg bool
|
||||||
|
chars string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u condUnit) match(r rune) bool {
|
||||||
|
if u.any {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return strings.ContainsRune(u.chars, r) != u.neg
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseCondition(s string) condition {
|
||||||
|
if s == "" || s == "." {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var c condition
|
||||||
|
runes := []rune(s)
|
||||||
|
for i := 0; i < len(runes); i++ {
|
||||||
|
switch runes[i] {
|
||||||
|
case '.':
|
||||||
|
c = append(c, condUnit{any: true})
|
||||||
|
case '[':
|
||||||
|
u := condUnit{}
|
||||||
|
i++
|
||||||
|
if i < len(runes) && runes[i] == '^' {
|
||||||
|
u.neg = true
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
start := i
|
||||||
|
for i < len(runes) && runes[i] != ']' {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
u.chars = string(runes[start:i])
|
||||||
|
c = append(c, u)
|
||||||
|
default:
|
||||||
|
c = append(c, condUnit{chars: string(runes[i])})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c condition) matchStart(s string) bool {
|
||||||
|
for _, u := range c {
|
||||||
|
r, size := utf8.DecodeRuneInString(s)
|
||||||
|
if size == 0 || !u.match(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
s = s[size:]
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c condition) matchEnd(s string) bool {
|
||||||
|
for i := len(c) - 1; i >= 0; i-- {
|
||||||
|
r, size := utf8.DecodeLastRuneInString(s)
|
||||||
|
if size == 0 || !c[i].match(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
s = s[:len(s)-size]
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type affix struct {
|
||||||
|
flag flag
|
||||||
|
cross bool
|
||||||
|
strip string
|
||||||
|
add string
|
||||||
|
cond condition
|
||||||
|
cont flagSet // continuation classes: affixes allowed on top of this one
|
||||||
|
}
|
||||||
|
|
||||||
|
// compounding holds the rules for words made of several dictionary words
|
||||||
|
// ("Haustür" = "Haus" + "Tür").
|
||||||
|
type compounding struct {
|
||||||
|
any, begin, middle, last flag // COMPOUNDFLAG, COMPOUNDBEGIN, COMPOUNDMIDDLE, COMPOUNDLAST
|
||||||
|
permit, forbid flag // affixes allowed or forbidden inside a compound
|
||||||
|
min int // shortest part, in characters (COMPOUNDMIN, 3 by default)
|
||||||
|
maxWords int // most parts (COMPOUNDWORDMAX, 0 = no limit)
|
||||||
|
checkDup bool // CHECKCOMPOUNDDUP: no part repeated twice in a row
|
||||||
|
checkCase bool // CHECKCOMPOUNDCASE: no capital letter at a boundary
|
||||||
|
rules []compoundRule
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c compounding) enabled() bool { return c.any != 0 || c.begin != 0 || c.last != 0 }
|
||||||
|
|
||||||
|
// compoundRule is a COMPOUNDRULE pattern: a sequence of flags, each
|
||||||
|
// optionally followed by "*" (any number of parts) or "?" (at most one).
|
||||||
|
// A compound matches when its parts, in order, carry those flags.
|
||||||
|
type compoundRule []ruleStep
|
||||||
|
|
||||||
|
type ruleStep struct {
|
||||||
|
flag flag
|
||||||
|
rep byte // 0, '*' or '?'
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseRule reads a pattern such as "n*1t" or, with long or numeric flags,
|
||||||
|
// "(aa)(bb)*".
|
||||||
|
func (d *Dictionary) parseRule(s string) compoundRule {
|
||||||
|
var r compoundRule
|
||||||
|
runes := []rune(s)
|
||||||
|
for i := 0; i < len(runes); i++ {
|
||||||
|
name := string(runes[i])
|
||||||
|
if runes[i] == '(' {
|
||||||
|
end := i + 1
|
||||||
|
for end < len(runes) && runes[end] != ')' {
|
||||||
|
end++
|
||||||
|
}
|
||||||
|
name = string(runes[i+1 : min(end, len(runes))])
|
||||||
|
i = end
|
||||||
|
}
|
||||||
|
if name == "*" || name == "?" || name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
step := ruleStep{flag: d.flagID(name)}
|
||||||
|
if i+1 < len(runes) && (runes[i+1] == '*' || runes[i+1] == '?') {
|
||||||
|
step.rep = byte(runes[i+1])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
r = append(r, step)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
type replacement struct {
|
||||||
|
from, to string
|
||||||
|
start bool // "^" anchor
|
||||||
|
end bool // "$" anchor
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dictionary is a loaded Hunspell dictionary. It is safe for concurrent
|
||||||
|
// use once loaded.
|
||||||
|
type Dictionary struct {
|
||||||
|
words map[string][]flagSet // homonyms keep separate flag sets
|
||||||
|
|
||||||
|
// Affixes are indexed by the text they add, so a word is only tested
|
||||||
|
// against the affixes that can have produced it.
|
||||||
|
prefixes map[string][]*affix
|
||||||
|
suffixes map[string][]*affix
|
||||||
|
maxPrefix int // longest added text, in bytes
|
||||||
|
maxSuffix int
|
||||||
|
contFlags map[flag]bool // suffix flags used as a continuation class
|
||||||
|
fullStrip bool
|
||||||
|
needAffix flag
|
||||||
|
forbidden flag
|
||||||
|
keepCase flag
|
||||||
|
noSuggest flag
|
||||||
|
onlyInComp flag
|
||||||
|
circumfix flag
|
||||||
|
compound compounding
|
||||||
|
try []rune
|
||||||
|
rep []replacement
|
||||||
|
iconv *strings.Replacer
|
||||||
|
oconv *strings.Replacer
|
||||||
|
flagMode string
|
||||||
|
flagIDs map[string]flag
|
||||||
|
flagAliases []flagSet
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads a dictionary from its .aff and .dic files.
|
||||||
|
func Load(affPath, dicPath string) (*Dictionary, error) {
|
||||||
|
aff, err := os.ReadFile(affPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading affix file: %w", err)
|
||||||
|
}
|
||||||
|
dic, err := os.ReadFile(dicPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading dictionary: %w", err)
|
||||||
|
}
|
||||||
|
return Parse(aff, dic)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse builds a dictionary from the contents of .aff and .dic files, in
|
||||||
|
// the encoding named by the affix file's SET directive.
|
||||||
|
func Parse(aff, dic []byte) (*Dictionary, error) {
|
||||||
|
enc := encodingOf(aff)
|
||||||
|
affText, err := decode(aff, enc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
dicText, err := decode(dic, enc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
d := &Dictionary{
|
||||||
|
compound: compounding{min: 3},
|
||||||
|
words: map[string][]flagSet{},
|
||||||
|
prefixes: map[string][]*affix{},
|
||||||
|
suffixes: map[string][]*affix{},
|
||||||
|
contFlags: map[flag]bool{},
|
||||||
|
flagIDs: map[string]flag{},
|
||||||
|
}
|
||||||
|
if err := d.parseAff(affText); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
d.parseDic(dicText)
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func encodingOf(aff []byte) string {
|
||||||
|
for _, line := range bytes.Split(aff, []byte("\n")) {
|
||||||
|
if f := bytes.Fields(line); len(f) >= 2 && string(f[0]) == "SET" {
|
||||||
|
return strings.ToUpper(string(f[1]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "ISO8859-1" // Hunspell's default
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISO 8859-15 differs from Latin-1 in eight positions (€, Š, Ž, Œ…).
|
||||||
|
var latin9 = map[byte]rune{
|
||||||
|
0xA4: '€', 0xA6: 'Š', 0xA8: 'š', 0xB4: 'Ž', 0xB8: 'ž', 0xBC: 'Œ', 0xBD: 'œ', 0xBE: 'Ÿ',
|
||||||
|
}
|
||||||
|
|
||||||
|
func decode(b []byte, enc string) (string, error) {
|
||||||
|
switch strings.ReplaceAll(enc, "-", "") {
|
||||||
|
case "UTF8":
|
||||||
|
return strings.TrimPrefix(string(b), "\uFEFF"), nil
|
||||||
|
case "ISO88591", "ISO885915":
|
||||||
|
isLatin9 := strings.HasSuffix(enc, "15")
|
||||||
|
var sb strings.Builder
|
||||||
|
sb.Grow(len(b))
|
||||||
|
for _, c := range b {
|
||||||
|
r, ok := latin9[c]
|
||||||
|
if !ok || !isLatin9 {
|
||||||
|
r = rune(c) // Latin-1 bytes are the first 256 code points
|
||||||
|
}
|
||||||
|
sb.WriteRune(r)
|
||||||
|
}
|
||||||
|
return sb.String(), nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("unsupported dictionary encoding %s", enc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// flagID interns a flag name ("A", "L'", "123") as a small integer.
|
||||||
|
func (d *Dictionary) flagID(name string) flag {
|
||||||
|
if id, ok := d.flagIDs[name]; ok {
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
id := flag(len(d.flagIDs) + 1)
|
||||||
|
d.flagIDs[name] = id
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseFlags reads a flag field, which is either an alias number (AF) or
|
||||||
|
// flags written in the dictionary's FLAG format.
|
||||||
|
func (d *Dictionary) parseFlags(s string) flagSet {
|
||||||
|
if len(d.flagAliases) > 0 {
|
||||||
|
if n, err := strconv.Atoi(s); err == nil {
|
||||||
|
if n >= 1 && n <= len(d.flagAliases) {
|
||||||
|
return d.flagAliases[n-1]
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return d.plainFlags(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// plainFlags reads flags written in the dictionary's FLAG format.
|
||||||
|
func (d *Dictionary) plainFlags(s string) flagSet {
|
||||||
|
var names []string
|
||||||
|
switch d.flagMode {
|
||||||
|
case "long":
|
||||||
|
r := []rune(s)
|
||||||
|
for i := 0; i+1 < len(r); i += 2 {
|
||||||
|
names = append(names, string(r[i:i+2]))
|
||||||
|
}
|
||||||
|
case "num":
|
||||||
|
names = strings.Split(s, ",")
|
||||||
|
default: // single characters, "UTF-8" included
|
||||||
|
for _, r := range s {
|
||||||
|
names = append(names, string(r))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
set := make(flagSet, 0, len(names))
|
||||||
|
for _, n := range names {
|
||||||
|
if n = strings.TrimSpace(n); n != "" {
|
||||||
|
set = append(set, d.flagID(n))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(set, func(i, j int) bool { return set[i] < set[j] })
|
||||||
|
return set
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dictionary) oneFlag(s string) flag {
|
||||||
|
if f := d.parseFlags(s); len(f) > 0 {
|
||||||
|
return f[0]
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// pairs collects the pairs of a table directive such as ICONV or REP.
|
||||||
|
func pairs(lines [][]string, key string) [][2]string {
|
||||||
|
var out [][2]string
|
||||||
|
for _, f := range lines {
|
||||||
|
if len(f) >= 3 && f[0] == key {
|
||||||
|
out = append(out, [2]string{f[1], f[2]})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dictionary) parseAff(text string) error {
|
||||||
|
var lines [][]string
|
||||||
|
sc := bufio.NewScanner(strings.NewReader(text))
|
||||||
|
sc.Buffer(make([]byte, 64*1024), 1024*1024)
|
||||||
|
for sc.Scan() {
|
||||||
|
f := strings.Fields(sc.Text())
|
||||||
|
if len(f) == 0 || strings.HasPrefix(f[0], "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
lines = append(lines, f)
|
||||||
|
}
|
||||||
|
if err := sc.Err(); err != nil {
|
||||||
|
return fmt.Errorf("reading affix file: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FLAG and AF change how every other flag is read: take them first.
|
||||||
|
for _, f := range lines {
|
||||||
|
if f[0] == "FLAG" && len(f) >= 2 {
|
||||||
|
d.flagMode = f[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var aliases []flagSet
|
||||||
|
counted := false
|
||||||
|
for _, f := range lines {
|
||||||
|
if f[0] == "AF" && len(f) >= 2 {
|
||||||
|
if !counted {
|
||||||
|
counted = true // the first line holds the number of aliases
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
aliases = append(aliases, d.plainFlags(f[1]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.flagAliases = aliases
|
||||||
|
|
||||||
|
// COMPOUNDRULE: the first line holds the number of rules.
|
||||||
|
counted = false
|
||||||
|
for _, f := range lines {
|
||||||
|
if f[0] == "COMPOUNDRULE" && len(f) >= 2 {
|
||||||
|
if !counted {
|
||||||
|
counted = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r := d.parseRule(f[1]); len(r) > 0 {
|
||||||
|
d.compound.rules = append(d.compound.rules, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pending := map[string]int{} // affix entries still expected per "PFX A"
|
||||||
|
cross := map[string]bool{}
|
||||||
|
for _, f := range lines {
|
||||||
|
switch f[0] {
|
||||||
|
case "TRY":
|
||||||
|
if len(f) >= 2 {
|
||||||
|
d.try = []rune(f[1])
|
||||||
|
}
|
||||||
|
case "FULLSTRIP":
|
||||||
|
d.fullStrip = true
|
||||||
|
case "NEEDAFFIX", "PSEUDOROOT":
|
||||||
|
d.needAffix = d.flagArg(f)
|
||||||
|
case "FORBIDDENWORD":
|
||||||
|
d.forbidden = d.flagArg(f)
|
||||||
|
case "KEEPCASE":
|
||||||
|
d.keepCase = d.flagArg(f)
|
||||||
|
case "NOSUGGEST":
|
||||||
|
d.noSuggest = d.flagArg(f)
|
||||||
|
case "ONLYINCOMPOUND":
|
||||||
|
d.onlyInComp = d.flagArg(f)
|
||||||
|
case "CIRCUMFIX":
|
||||||
|
d.circumfix = d.flagArg(f)
|
||||||
|
case "COMPOUNDFLAG":
|
||||||
|
d.compound.any = d.flagArg(f)
|
||||||
|
case "COMPOUNDBEGIN":
|
||||||
|
d.compound.begin = d.flagArg(f)
|
||||||
|
case "COMPOUNDMIDDLE":
|
||||||
|
d.compound.middle = d.flagArg(f)
|
||||||
|
case "COMPOUNDLAST", "COMPOUNDEND":
|
||||||
|
d.compound.last = d.flagArg(f)
|
||||||
|
case "COMPOUNDPERMITFLAG":
|
||||||
|
d.compound.permit = d.flagArg(f)
|
||||||
|
case "COMPOUNDFORBIDFLAG":
|
||||||
|
d.compound.forbid = d.flagArg(f)
|
||||||
|
case "COMPOUNDMIN":
|
||||||
|
if len(f) >= 2 {
|
||||||
|
if n, err := strconv.Atoi(f[1]); err == nil {
|
||||||
|
d.compound.min = max(n, 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "COMPOUNDWORDMAX":
|
||||||
|
if len(f) >= 2 {
|
||||||
|
d.compound.maxWords, _ = strconv.Atoi(f[1])
|
||||||
|
}
|
||||||
|
case "CHECKCOMPOUNDDUP":
|
||||||
|
d.compound.checkDup = true
|
||||||
|
case "CHECKCOMPOUNDCASE":
|
||||||
|
d.compound.checkCase = true
|
||||||
|
case "PFX", "SFX":
|
||||||
|
if len(f) < 4 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
key := f[0] + " " + f[1]
|
||||||
|
if pending[key] == 0 {
|
||||||
|
n, err := strconv.Atoi(f[3])
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pending[key] = n
|
||||||
|
cross[key] = f[2] == "Y"
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pending[key]--
|
||||||
|
d.addAffix(f, cross[key])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range pairs(lines, "REP") {
|
||||||
|
r := replacement{from: p[0], to: strings.ReplaceAll(p[1], "_", " ")}
|
||||||
|
r.start = strings.HasPrefix(r.from, "^")
|
||||||
|
r.end = strings.HasSuffix(r.from, "$")
|
||||||
|
r.from = strings.TrimSuffix(strings.TrimPrefix(r.from, "^"), "$")
|
||||||
|
r.from = strings.ReplaceAll(r.from, "_", " ")
|
||||||
|
if r.from != "" {
|
||||||
|
d.rep = append(d.rep, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.iconv = replacer(pairs(lines, "ICONV"))
|
||||||
|
d.oconv = replacer(pairs(lines, "OCONV"))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dictionary) flagArg(f []string) flag {
|
||||||
|
if len(f) < 2 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return d.oneFlag(f[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
func replacer(table [][2]string) *strings.Replacer {
|
||||||
|
var args []string
|
||||||
|
for _, p := range table {
|
||||||
|
args = append(args, p[0], p[1])
|
||||||
|
}
|
||||||
|
return strings.NewReplacer(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// addAffix reads one entry line: "SFX flag strip add[/cont] [condition]".
|
||||||
|
func (d *Dictionary) addAffix(f []string, cross bool) {
|
||||||
|
a := &affix{flag: d.oneFlag(f[1]), cross: cross}
|
||||||
|
if f[2] != "0" {
|
||||||
|
a.strip = f[2]
|
||||||
|
}
|
||||||
|
add := f[3]
|
||||||
|
if i := strings.IndexByte(add, '/'); i >= 0 {
|
||||||
|
a.cont = d.parseFlags(add[i+1:])
|
||||||
|
add = add[:i]
|
||||||
|
}
|
||||||
|
if add != "0" {
|
||||||
|
a.add = add
|
||||||
|
}
|
||||||
|
if len(f) >= 5 {
|
||||||
|
a.cond = parseCondition(f[4])
|
||||||
|
}
|
||||||
|
if f[0] == "PFX" {
|
||||||
|
d.prefixes[a.add] = append(d.prefixes[a.add], a)
|
||||||
|
d.maxPrefix = max(d.maxPrefix, len(a.add))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.suffixes[a.add] = append(d.suffixes[a.add], a)
|
||||||
|
d.maxSuffix = max(d.maxSuffix, len(a.add))
|
||||||
|
for _, c := range a.cont {
|
||||||
|
d.contFlags[c] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dictionary) parseDic(text string) {
|
||||||
|
first := true
|
||||||
|
for _, line := range strings.Split(text, "\n") {
|
||||||
|
line = strings.TrimRight(line, "\r")
|
||||||
|
if first {
|
||||||
|
first = false
|
||||||
|
if _, err := strconv.Atoi(strings.TrimSpace(line)); err == nil {
|
||||||
|
continue // approximate word count
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if line == "" || line[0] == '\t' || strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// Morphological fields follow a tab or a space.
|
||||||
|
if i := strings.IndexAny(line, "\t "); i >= 0 {
|
||||||
|
line = line[:i]
|
||||||
|
}
|
||||||
|
word, flags := splitEntry(line)
|
||||||
|
if word == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var set flagSet
|
||||||
|
if flags != "" {
|
||||||
|
set = d.parseFlags(flags)
|
||||||
|
}
|
||||||
|
d.words[word] = append(d.words[word], set)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitEntry separates "word/flags", where "\/" is a literal slash.
|
||||||
|
func splitEntry(s string) (word, flags string) {
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] == '\\' && i+1 < len(s) && s[i+1] == '/' {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if s[i] == '/' {
|
||||||
|
return strings.ReplaceAll(s[:i], `\/`, "/"), s[i+1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.ReplaceAll(s, `\/`, "/"), ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,360 @@
|
|||||||
|
package spell
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
)
|
||||||
|
|
||||||
|
const enAff = `SET UTF-8
|
||||||
|
TRY esianrtolcdugmphbyfvkwz'
|
||||||
|
ICONV 1
|
||||||
|
ICONV ’ '
|
||||||
|
NOSUGGEST !
|
||||||
|
KEEPCASE K
|
||||||
|
FORBIDDENWORD F
|
||||||
|
NEEDAFFIX N
|
||||||
|
REP 1
|
||||||
|
REP alot a_lot
|
||||||
|
|
||||||
|
PFX U Y 1
|
||||||
|
PFX U 0 un .
|
||||||
|
|
||||||
|
SFX S Y 4
|
||||||
|
SFX S y ies [^aeiou]y
|
||||||
|
SFX S 0 s [aeiou]y
|
||||||
|
SFX S 0 s [^sxzy]
|
||||||
|
SFX S 0 es [sxz]
|
||||||
|
|
||||||
|
SFX D Y 2
|
||||||
|
SFX D 0 ed [^e]
|
||||||
|
SFX D 0 d e
|
||||||
|
|
||||||
|
SFX M Y 1
|
||||||
|
SFX M 0 's .
|
||||||
|
|
||||||
|
# "ness" allows a plural on top of it: kindnesses.
|
||||||
|
SFX Q Y 1
|
||||||
|
SFX Q 0 ness/S .
|
||||||
|
`
|
||||||
|
|
||||||
|
const enDic = `16
|
||||||
|
kind/QU
|
||||||
|
open/SD
|
||||||
|
for
|
||||||
|
door/S
|
||||||
|
city/SM
|
||||||
|
play/SD
|
||||||
|
love/DS
|
||||||
|
the
|
||||||
|
a
|
||||||
|
lot
|
||||||
|
Paris/M
|
||||||
|
iPhone
|
||||||
|
OpenGL/K
|
||||||
|
walkd/F
|
||||||
|
realis/N
|
||||||
|
rude/!
|
||||||
|
`
|
||||||
|
|
||||||
|
func testDict(t *testing.T) *Dictionary {
|
||||||
|
t.Helper()
|
||||||
|
d, err := Parse([]byte(enAff), []byte(enDic))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheck(t *testing.T) {
|
||||||
|
d := testDict(t)
|
||||||
|
for word, want := range map[string]bool{
|
||||||
|
"door": true,
|
||||||
|
"doors": true,
|
||||||
|
"cities": true,
|
||||||
|
"citys": false, // condition [^y] rejects it
|
||||||
|
"plays": true,
|
||||||
|
"played": true,
|
||||||
|
"loved": true,
|
||||||
|
"loveed": false,
|
||||||
|
"unkind": true,
|
||||||
|
"kindness": true,
|
||||||
|
"kindnesses": true, // two suffixes
|
||||||
|
"unkindness": true, // cross product
|
||||||
|
"undoor": false,
|
||||||
|
"city's": true,
|
||||||
|
"city’s": true, // typographic apostrophe
|
||||||
|
"Door": true,
|
||||||
|
"DOORS": true,
|
||||||
|
"Paris": true,
|
||||||
|
"PARIS": true,
|
||||||
|
"Paris's": true,
|
||||||
|
"paris": false, // proper nouns keep their capital
|
||||||
|
"iPhone": true,
|
||||||
|
"OpenGL": true,
|
||||||
|
"OPENGL": false, // KEEPCASE
|
||||||
|
"walkd": false, // FORBIDDENWORD
|
||||||
|
"realis": false, // NEEDAFFIX
|
||||||
|
"cty": false,
|
||||||
|
"": false,
|
||||||
|
"rude": true,
|
||||||
|
"UnKind": false,
|
||||||
|
"the": true,
|
||||||
|
"supercalifrag": false,
|
||||||
|
} {
|
||||||
|
if got := d.Check(word); got != want {
|
||||||
|
t.Errorf("Check(%q) = %v, want %v", word, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSuggest(t *testing.T) {
|
||||||
|
d := testDict(t)
|
||||||
|
for word, want := range map[string][]string{
|
||||||
|
"teh": {"the"},
|
||||||
|
"dor": {"for", "door"},
|
||||||
|
"doorz": {"door", "doors"},
|
||||||
|
"DOOR'S": {"DOORS"},
|
||||||
|
"Citys": {"City", "City's"},
|
||||||
|
"paris": {"Paris"},
|
||||||
|
"alot": {"a lot", "lot"},
|
||||||
|
"thedoor": {"the door"},
|
||||||
|
"rudee": nil, // NOSUGGEST
|
||||||
|
"luve": {"love"},
|
||||||
|
} {
|
||||||
|
if got := d.Suggest(word); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Suggest(%q) = %q, want %q", word, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Long flags, flag aliases and prefixes allowed by a suffix's
|
||||||
|
// continuation class, as in the French dictionary ("l'homme", "d'hommes").
|
||||||
|
func TestAliasesAndLongFlags(t *testing.T) {
|
||||||
|
aff := `SET UTF-8
|
||||||
|
FLAG long
|
||||||
|
AF 2
|
||||||
|
AF L'S.
|
||||||
|
AF S.
|
||||||
|
|
||||||
|
PFX L' Y 1
|
||||||
|
PFX L' 0 l' [aeiouh]
|
||||||
|
|
||||||
|
SFX S. Y 1
|
||||||
|
SFX S. 0 s/L' [^sxz]
|
||||||
|
`
|
||||||
|
dic := "2\nhomme/1\nami/2\n"
|
||||||
|
d, err := Parse([]byte(aff), []byte(dic))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for word, want := range map[string]bool{
|
||||||
|
"homme": true, "hommes": true, "l'homme": true, "l'hommes": true,
|
||||||
|
"L'homme": true, "amis": true, "l'ami": false, "l'amis": true,
|
||||||
|
} {
|
||||||
|
if got := d.Check(word); got != want {
|
||||||
|
t.Errorf("Check(%q) = %v, want %v", word, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatin1(t *testing.T) {
|
||||||
|
aff := []byte("SET ISO8859-1\nTRY ae\xe4\n")
|
||||||
|
dic := []byte("1\nH\xe4user\n")
|
||||||
|
d, err := Parse(aff, dic)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !d.Check("Häuser") || d.Check("Hauser") {
|
||||||
|
t.Error("Latin-1 dictionary not decoded")
|
||||||
|
}
|
||||||
|
if got := d.Suggest("Hauser"); !slices.Contains(got, "Häuser") {
|
||||||
|
t.Errorf("Suggest(Hauser) = %q", got)
|
||||||
|
}
|
||||||
|
if _, err := Parse([]byte("SET KOI8-R\n"), nil); err == nil {
|
||||||
|
t.Error("unsupported encoding accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWords(t *testing.T) {
|
||||||
|
got := Words("Élise's well-known R2D2, l’homme… 'quoted' x")
|
||||||
|
want := []Word{
|
||||||
|
{"Élise's", 0, 7}, {"well", 8, 4}, {"known", 13, 5}, {"R2D2", 19, 4},
|
||||||
|
{"l’homme", 25, 7}, {"quoted", 35, 6}, {"x", 43, 1},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Words = %+v\nwant %+v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMisspellings(t *testing.T) {
|
||||||
|
c := NewChecker(testDict(t), []string{"Zorblax"})
|
||||||
|
doc := &screenplay.Document{Elements: []screenplay.Element{
|
||||||
|
screenplay.NewElement(screenplay.Scene, "INT. THE CTY - DAY"),
|
||||||
|
screenplay.NewElement(screenplay.Action, "GRUNDLE opens the dor for Zorblax."),
|
||||||
|
screenplay.NewElement(screenplay.Character, "Grundle (CONT'D)"),
|
||||||
|
screenplay.NewElement(screenplay.Dialogue, "Élan loves 3rd doors"),
|
||||||
|
screenplay.NewElement(screenplay.Action, "GRUNDLE's door."),
|
||||||
|
}}
|
||||||
|
got := c.Misspellings(doc)
|
||||||
|
want := []Misspelling{
|
||||||
|
{Element: 0, Offset: 9, Length: 3, Word: "CTY"},
|
||||||
|
{Element: 0, Offset: 15, Length: 3, Word: "DAY"},
|
||||||
|
{Element: 1, Offset: 18, Length: 3, Word: "dor"},
|
||||||
|
{Element: 3, Offset: 0, Length: 4, Word: "Élan"},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Misspellings = %+v\nwant %+v", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Add("élan")
|
||||||
|
c.Add("day")
|
||||||
|
if got := c.Misspellings(doc); len(got) != 2 {
|
||||||
|
t.Errorf("after Add, Misspellings = %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAvailable(t *testing.T) {
|
||||||
|
a, b := t.TempDir(), t.TempDir()
|
||||||
|
for _, f := range []string{
|
||||||
|
filepath.Join(a, "fr_FR.aff"), filepath.Join(a, "fr_FR.dic"),
|
||||||
|
filepath.Join(a, "de.dic"), // no .aff: skipped
|
||||||
|
filepath.Join(a, "hyph_fr.dic"), filepath.Join(a, "hyph_fr.aff"),
|
||||||
|
filepath.Join(b, "fr_FR.aff"), filepath.Join(b, "fr_FR.dic"),
|
||||||
|
filepath.Join(b, "en_US.aff"), filepath.Join(b, "en_US.dic"),
|
||||||
|
} {
|
||||||
|
if err := os.WriteFile(f, nil, 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
got := Available([]string{a, b, filepath.Join(a, "missing")})
|
||||||
|
want := []Language{
|
||||||
|
{"fr_FR", filepath.Join(a, "fr_FR.aff"), filepath.Join(a, "fr_FR.dic")},
|
||||||
|
{"en_US", filepath.Join(b, "en_US.aff"), filepath.Join(b, "en_US.dic")},
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Available = %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreferred(t *testing.T) {
|
||||||
|
codes := []string{"de_DE_frami", "en_GB", "en_US", "fr"}
|
||||||
|
for locale, want := range map[string]string{
|
||||||
|
"fr_FR.UTF-8": "fr",
|
||||||
|
"en_GB.UTF-8": "en_GB",
|
||||||
|
"de_AT.UTF-8": "de_DE_frami",
|
||||||
|
"C": "en_US",
|
||||||
|
"": "en_US",
|
||||||
|
} {
|
||||||
|
if got := Preferred(codes, locale); got != want {
|
||||||
|
t.Errorf("Preferred(%q) = %q, want %q", locale, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := Preferred(nil, "fr_FR"); got != "" {
|
||||||
|
t.Errorf("Preferred(nil) = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompounds(t *testing.T) {
|
||||||
|
// German-style compounds: parts marked for the start, middle or end,
|
||||||
|
// a linking "s" that only exists inside compounds, and an affix that
|
||||||
|
// lower-cases a noun inside a compound (COMPOUNDPERMITFLAG).
|
||||||
|
aff := `SET UTF-8
|
||||||
|
COMPOUNDBEGIN B
|
||||||
|
COMPOUNDMIDDLE M
|
||||||
|
COMPOUNDLAST E
|
||||||
|
ONLYINCOMPOUND O
|
||||||
|
COMPOUNDPERMITFLAG P
|
||||||
|
COMPOUNDMIN 1
|
||||||
|
COMPOUNDWORDMAX 3
|
||||||
|
CHECKCOMPOUNDDUP
|
||||||
|
|
||||||
|
PFX L Y 3
|
||||||
|
PFX L T t/P T
|
||||||
|
PFX L S s/P S
|
||||||
|
PFX L Z z/P Z
|
||||||
|
|
||||||
|
SFX N Y 1
|
||||||
|
SFX N 0 en .
|
||||||
|
`
|
||||||
|
dic := `6
|
||||||
|
Haus/BM
|
||||||
|
Tür/LMEN
|
||||||
|
Schlüssel/BMLE
|
||||||
|
s/MO
|
||||||
|
Arbeit/BM
|
||||||
|
Zeit/LE
|
||||||
|
`
|
||||||
|
d, err := Parse([]byte(aff), []byte(dic))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, w := range []string{"Haus", "Haustür", "Haustüren", "Haustürschlüssel", "Arbeitszeit", "HAUSTÜR"} {
|
||||||
|
if !d.Check(w) {
|
||||||
|
t.Errorf("%q should be correct", w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, w := range []string{"s", "Türhaus", "Hausshaus", "Haushaus", "Arbeitsarbeitszeit", "Haustürx"} {
|
||||||
|
if d.Check(w) {
|
||||||
|
t.Errorf("%q should be wrong", w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// COMPOUNDFLAG: any marked word can go anywhere.
|
||||||
|
d, err = Parse([]byte("SET UTF-8\nCOMPOUNDFLAG X\n"), []byte("2\nfoot/X\nball/X\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !d.Check("football") || !d.Check("ballfoot") || d.Check("footbal") {
|
||||||
|
t.Errorf("COMPOUNDFLAG compounds")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompoundRule(t *testing.T) {
|
||||||
|
// en_US style: numbers built from digits, ordinal endings that only
|
||||||
|
// exist in compounds, and a word pattern with long flags.
|
||||||
|
aff := `SET UTF-8
|
||||||
|
ONLYINCOMPOUND c
|
||||||
|
COMPOUNDMIN 1
|
||||||
|
COMPOUNDRULE 2
|
||||||
|
COMPOUNDRULE n*1t
|
||||||
|
COMPOUNDRULE n*mp
|
||||||
|
`
|
||||||
|
dic := `8
|
||||||
|
0/nm
|
||||||
|
1/n1
|
||||||
|
2/nm
|
||||||
|
3/nm
|
||||||
|
st/tc
|
||||||
|
nd/pc
|
||||||
|
th/pc
|
||||||
|
rd/pc
|
||||||
|
`
|
||||||
|
d, err := Parse([]byte(aff), []byte(dic))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, w := range []string{"1st", "21st", "2nd", "33rd", "20th"} {
|
||||||
|
if !d.Check(w) {
|
||||||
|
t.Errorf("%q should be correct", w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, w := range []string{"st", "1nd", "2st", "st1"} {
|
||||||
|
if d.Check(w) {
|
||||||
|
t.Errorf("%q should be wrong", w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
d, err = Parse([]byte("SET UTF-8\nFLAG long\nCOMPOUNDRULE 1\nCOMPOUNDRULE (aa)(bb)?(cc)\n"),
|
||||||
|
[]byte("3\nsun/aa\nflower/cc\nlit/bb\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !d.Check("sunflower") || !d.Check("sunlitflower") || d.Check("flowersun") || d.Check("sunlit") {
|
||||||
|
t.Errorf("long-flag COMPOUNDRULE")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/wailsapp/wails/v2"
|
||||||
|
"github.com/wailsapp/wails/v2/pkg/options"
|
||||||
|
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
|
||||||
|
"github.com/wailsapp/wails/v2/pkg/options/linux"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed all:frontend/dist
|
||||||
|
var assets embed.FS
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// The UI is in English: make GTK's own strings (file chooser buttons and
|
||||||
|
// places) match it instead of following the system language.
|
||||||
|
os.Setenv("LANGUAGE", "en")
|
||||||
|
|
||||||
|
app := NewApp()
|
||||||
|
for _, arg := range os.Args[1:] {
|
||||||
|
if !strings.HasPrefix(arg, "-") {
|
||||||
|
if _, err := os.Stat(arg); err == nil {
|
||||||
|
app.initialPath = arg
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
err := wails.Run(&options.App{
|
||||||
|
Title: "Plotzilla",
|
||||||
|
Width: 1320,
|
||||||
|
Height: 920,
|
||||||
|
MinWidth: 900,
|
||||||
|
MinHeight: 600,
|
||||||
|
AssetServer: &assetserver.Options{Assets: assets},
|
||||||
|
// The header bar is drawn by the page, like a GNOME header bar; the
|
||||||
|
// transparent background lets the page round the window corners.
|
||||||
|
Frameless: true,
|
||||||
|
BackgroundColour: &options.RGBA{R: 0, G: 0, B: 0, A: 0},
|
||||||
|
OnStartup: app.startup,
|
||||||
|
OnBeforeClose: app.beforeClose,
|
||||||
|
Bind: []interface{}{app},
|
||||||
|
Linux: &linux.Options{
|
||||||
|
ProgramName: "plotzilla",
|
||||||
|
WindowIsTranslucent: true,
|
||||||
|
WebviewGpuPolicy: linux.WebviewGpuPolicyOnDemand,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 361 KiB |
|
After Width: | Height: | Size: 350 KiB |
|
After Width: | Height: | Size: 422 KiB |
|
After Width: | Height: | Size: 294 KiB |
|
After Width: | Height: | Size: 371 KiB |
|
After Width: | Height: | Size: 287 KiB |
|
After Width: | Height: | Size: 376 KiB |
|
After Width: | Height: | Size: 356 KiB |
|
After Width: | Height: | Size: 188 KiB |
|
After Width: | Height: | Size: 411 KiB |
|
After Width: | Height: | Size: 268 KiB |
|
After Width: | Height: | Size: 373 KiB |
|
After Width: | Height: | Size: 276 KiB |
|
After Width: | Height: | Size: 319 KiB |
@@ -0,0 +1,202 @@
|
|||||||
|
// Drives Firefox (WebDriver BiDi, through puppeteer-core) to capture the
|
||||||
|
// README screenshots. Run by main.go, which serves the app at $URL and
|
||||||
|
// passes $OUT (where to write the PNGs), $PROFILE and $FIREFOX.
|
||||||
|
import puppeteer from 'puppeteer-core'
|
||||||
|
|
||||||
|
const { URL: base, OUT, PROFILE, FIREFOX } = process.env
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||||
|
|
||||||
|
const browser = await puppeteer.launch({ browser: 'firefox', executablePath: FIREFOX, headless: true, userDataDir: PROFILE })
|
||||||
|
|
||||||
|
/** Opens the app on a script variant, with fresh preferences. */
|
||||||
|
async function open(variant = '') {
|
||||||
|
const page = await browser.newPage()
|
||||||
|
await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 2 })
|
||||||
|
page.on('pageerror', (e) => console.error('page error:', e.message))
|
||||||
|
const url = base + (variant ? `?v=${variant}` : '')
|
||||||
|
await page.goto(url)
|
||||||
|
await page.evaluate(() => localStorage.clear())
|
||||||
|
await page.goto(url)
|
||||||
|
await sleep(1200) // pagination and spelling
|
||||||
|
await page.evaluate(() => { document.getElementById('scroller').style.scrollBehavior = 'auto' })
|
||||||
|
return page
|
||||||
|
}
|
||||||
|
|
||||||
|
const ctrl = async (page, key, shift = false) => {
|
||||||
|
const k = page.keyboard
|
||||||
|
await k.down('Control')
|
||||||
|
if (shift) await k.down('Shift')
|
||||||
|
await k.press(key)
|
||||||
|
if (shift) await k.up('Shift')
|
||||||
|
await k.up('Control')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clicks the first element matching sel whose text contains text. */
|
||||||
|
async function clickText(page, sel, text) {
|
||||||
|
for (const el of await page.$$(sel)) if ((await el.evaluate((e) => e.textContent)).includes(text)) return el.click()
|
||||||
|
throw new Error(`no ${sel} containing "${text}"`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Puts the cursor at the end of the first element containing text. */
|
||||||
|
async function caretIn(page, text) {
|
||||||
|
await page.evaluate((text) => {
|
||||||
|
const el = [...document.querySelectorAll('.ProseMirror .el')].find((e) => e.textContent.includes(text))
|
||||||
|
const r = document.createRange()
|
||||||
|
r.selectNodeContents(el)
|
||||||
|
r.collapse(false)
|
||||||
|
getSelection().removeAllRanges()
|
||||||
|
getSelection().addRange(r)
|
||||||
|
document.querySelector('.ProseMirror').focus()
|
||||||
|
}, text)
|
||||||
|
await sleep(100)
|
||||||
|
await page.keyboard.press('End')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Selects the first occurrence of text in the script. */
|
||||||
|
async function select(page, text) {
|
||||||
|
await page.evaluate((text) => {
|
||||||
|
const walker = document.createTreeWalker(document.querySelector('.ProseMirror'), NodeFilter.SHOW_TEXT)
|
||||||
|
for (let n; (n = walker.nextNode()); ) {
|
||||||
|
const i = n.textContent.indexOf(text)
|
||||||
|
if (i < 0) continue
|
||||||
|
const r = document.createRange()
|
||||||
|
r.setStart(n, i)
|
||||||
|
r.setEnd(n, i + text.length)
|
||||||
|
getSelection().removeAllRanges()
|
||||||
|
getSelection().addRange(r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
const scrollTo = (page, y) => page.evaluate((y) => { document.getElementById('scroller').scrollTop = y }, y)
|
||||||
|
|
||||||
|
/** Captures the window, the pointer off the header (tooltips). */
|
||||||
|
async function shot(page, name, pointer = true) {
|
||||||
|
if (pointer) await page.mouse.move(1430, 600)
|
||||||
|
await sleep(400)
|
||||||
|
await page.screenshot({ path: `${OUT}/${name}.png` })
|
||||||
|
console.log('captured', name)
|
||||||
|
}
|
||||||
|
|
||||||
|
let page = await open()
|
||||||
|
await caretIn(page, 'It always ends')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await shot(page, 'editor')
|
||||||
|
|
||||||
|
await ctrl(page, 'F', true)
|
||||||
|
await shot(page, 'focus-mode')
|
||||||
|
await ctrl(page, 'F', true)
|
||||||
|
|
||||||
|
await caretIn(page, 'FADE IN:')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await page.evaluate(() => document.getElementById('type-button').dispatchEvent(new MouseEvent('mousedown', { bubbles: true })))
|
||||||
|
await shot(page, 'element-menu')
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
|
||||||
|
await caretIn(page, 'The film snaps')
|
||||||
|
await page.keyboard.press('Enter')
|
||||||
|
await page.keyboard.press('Tab')
|
||||||
|
await page.keyboard.type('EL')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await shot(page, 'autocomplete')
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
for (let i = 0; i < 4; i++) await ctrl(page, 'z')
|
||||||
|
await sleep(1500)
|
||||||
|
|
||||||
|
await caretIn(page, 'THE END')
|
||||||
|
await page.keyboard.press('Enter')
|
||||||
|
await page.keyboard.type('INT. ')
|
||||||
|
await page.keyboard.type('PROJECTION BOOTH - ')
|
||||||
|
await sleep(1600) // autosave: "Saved · auto"
|
||||||
|
await page.evaluate(() => { const s = document.getElementById('scroller'); s.scrollTop = s.scrollHeight })
|
||||||
|
await shot(page, 'scene-autocomplete')
|
||||||
|
await page.close()
|
||||||
|
|
||||||
|
page = await open()
|
||||||
|
await caretIn(page, 'FADE IN:')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await ctrl(page, 'h')
|
||||||
|
await sleep(100)
|
||||||
|
await page.keyboard.type('reel')
|
||||||
|
await page.keyboard.press('Enter')
|
||||||
|
await page.click('#replace-input')
|
||||||
|
await page.keyboard.type('spool')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await shot(page, 'find-replace')
|
||||||
|
await page.close()
|
||||||
|
|
||||||
|
page = await open()
|
||||||
|
await caretIn(page, 'It always ends')
|
||||||
|
await page.evaluate(() => {
|
||||||
|
const s = document.getElementById('scroller')
|
||||||
|
s.scrollTop += document.querySelector('.page-break').getBoundingClientRect().top - 390
|
||||||
|
})
|
||||||
|
await shot(page, 'page-break')
|
||||||
|
|
||||||
|
await caretIn(page, 'FADE IN:')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await ctrl(page, 'T', true)
|
||||||
|
await shot(page, 'title-page')
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await sleep(100)
|
||||||
|
|
||||||
|
await caretIn(page, 'FADE IN:')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await ctrl(page, 'p')
|
||||||
|
await shot(page, 'export-pdf')
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await sleep(100)
|
||||||
|
|
||||||
|
await page.click('.switch') // autosave off, so the change stays unsaved
|
||||||
|
await caretIn(page, 'line every shelf.')
|
||||||
|
await page.keyboard.type(' Then silence.')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await ctrl(page, 'n')
|
||||||
|
await shot(page, 'unsaved-changes')
|
||||||
|
await page.close()
|
||||||
|
|
||||||
|
page = await open('typos')
|
||||||
|
await caretIn(page, 'FADE IN:')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await sleep(700)
|
||||||
|
const typo = await page.evaluate(() => {
|
||||||
|
const r = document.querySelector('.misspelled').getBoundingClientRect()
|
||||||
|
return { x: r.left + r.width / 2, y: r.top + r.height / 2 }
|
||||||
|
})
|
||||||
|
await page.mouse.click(typo.x, typo.y, { button: 'right' })
|
||||||
|
await shot(page, 'spelling', false)
|
||||||
|
await page.close()
|
||||||
|
|
||||||
|
page = await open('outline')
|
||||||
|
await caretIn(page, 'Warmer light')
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await shot(page, 'outline')
|
||||||
|
|
||||||
|
// Locked pages, a Blue revision, then a Pink one, with the menu open.
|
||||||
|
await page.click('[data-action="revisions"]')
|
||||||
|
await sleep(150)
|
||||||
|
await clickText(page, 'ul.menu.popup li', 'Lock Pages')
|
||||||
|
await sleep(500)
|
||||||
|
await page.click('[data-action="revisions"]')
|
||||||
|
await sleep(150)
|
||||||
|
await clickText(page, 'ul.menu.popup li', 'Start Revisions')
|
||||||
|
await sleep(300)
|
||||||
|
await caretIn(page, 'line every shelf.')
|
||||||
|
await page.keyboard.type(' The lamp buzzes.')
|
||||||
|
await caretIn(page, 'every single night.')
|
||||||
|
await page.keyboard.press('Enter')
|
||||||
|
await page.keyboard.type('Then it starts again.')
|
||||||
|
await page.click('[data-action="revisions"]')
|
||||||
|
await sleep(150)
|
||||||
|
await clickText(page, 'ul.menu.popup li', 'New Revision Set')
|
||||||
|
await sleep(300)
|
||||||
|
await select(page, 'sleeves rolled up')
|
||||||
|
await page.keyboard.type('coat still on')
|
||||||
|
await sleep(900)
|
||||||
|
await scrollTo(page, 0)
|
||||||
|
await page.click('[data-action="revisions"]')
|
||||||
|
await sleep(250)
|
||||||
|
await shot(page, 'revisions')
|
||||||
|
|
||||||
|
await browser.close()
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
// Command screenshots regenerates the README images in screenshots/ from the
|
||||||
|
// sample script "The Last Reel". Run it from the repository root with
|
||||||
|
// `make screenshots`, which builds the frontend and installs puppeteer-core
|
||||||
|
// first.
|
||||||
|
//
|
||||||
|
// It serves frontend/dist with a stand-in for the Wails bridge whose calls are
|
||||||
|
// answered by the real internal packages, so pagination, locked pages and
|
||||||
|
// revision sets on the images are real. capture.mjs drives Firefox through it
|
||||||
|
// (1440×900, device scale 2); the window corners are then masked, since the
|
||||||
|
// browser cannot capture a transparent background. pdf-output.png is the
|
||||||
|
// PDF export of the script, rendered by pdftoppm and laid out on the app
|
||||||
|
// background.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/draw"
|
||||||
|
"image/png"
|
||||||
|
"log"
|
||||||
|
"math"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"plotzilla/internal/fountain"
|
||||||
|
"plotzilla/internal/layout"
|
||||||
|
"plotzilla/internal/pdf"
|
||||||
|
"plotzilla/internal/screenplay"
|
||||||
|
"plotzilla/internal/spell"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
dist = "frontend/dist"
|
||||||
|
sample = "tools/screenshots/the-last-reel.fountain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bridge replaces the Wails runtime in the page. Each call is posted to
|
||||||
|
// /api/<Method>, with the page's query string naming the script variant.
|
||||||
|
const bridge = `<script>
|
||||||
|
(() => {
|
||||||
|
const call = (name) => async (...args) => {
|
||||||
|
const r = await fetch('/api/' + name + location.search, { method: 'POST', body: JSON.stringify(args) })
|
||||||
|
return r.json()
|
||||||
|
}
|
||||||
|
window.go = { main: { App: new Proxy({}, { get: (_, n) => call(n) }) } }
|
||||||
|
window.runtime = { WindowSetTitle() {}, WindowMinimise() {}, WindowToggleMaximise() {},
|
||||||
|
WindowIsMaximised: async () => false, EventsOn: () => () => {}, Quit() {} }
|
||||||
|
// WebKitGTK does not spell-check the page; Firefox would.
|
||||||
|
document.documentElement.setAttribute('spellcheck', 'false')
|
||||||
|
})()
|
||||||
|
</script>
|
||||||
|
<style>*{animation:none!important;transition:none!important;caret-color:transparent!important}</style>
|
||||||
|
`
|
||||||
|
|
||||||
|
// typos are the misspellings of the "typos" variant, with their
|
||||||
|
// corrections: spelling.png needs no Hunspell dictionary.
|
||||||
|
var typos = map[string][]string{"projecter": {"projector", "projected"}, "thraeds": {"threads"}, "wacth": {"watch"}}
|
||||||
|
|
||||||
|
// variant returns the sample script, or one of its variants: "typos" for the
|
||||||
|
// spelling image, "outline" (sections, synopses, a note) for the outline and
|
||||||
|
// revision images.
|
||||||
|
func variant(src, name string) string {
|
||||||
|
var pairs []string
|
||||||
|
switch name {
|
||||||
|
case "typos":
|
||||||
|
pairs = []string{
|
||||||
|
"of the projector. ELODIE", "of the projecter. ELODIE",
|
||||||
|
"threads a reel by hand", "thraeds a reel by hand",
|
||||||
|
"Soldiers watch from", "Soldiers wacth from",
|
||||||
|
}
|
||||||
|
case "outline":
|
||||||
|
pairs = []string{
|
||||||
|
"FADE IN:\n", "# Act One\n\n= Elodie finds the reel her grandmother hid in 1942.\n\nFADE IN:\n",
|
||||||
|
"of the projector. ELODIE", "of the projector. [[Warmer light here?]] ELODIE",
|
||||||
|
"> PARIS, 1942 <\n", "> PARIS, 1942 <\n\n## The Rialto\n\n= The young woman smuggles the can into the cinema.\n",
|
||||||
|
"MATCH CUT TO:\n", "MATCH CUT TO:\n\n# Act Two\n",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := 0; i < len(pairs); i += 2 {
|
||||||
|
src = strings.Replace(src, pairs[i], pairs[i+1], 1)
|
||||||
|
}
|
||||||
|
return src
|
||||||
|
}
|
||||||
|
|
||||||
|
type server struct {
|
||||||
|
src string // the sample script
|
||||||
|
path string // its absolute path, shown as the file name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *server) call(name, v string, raw []json.RawMessage) any {
|
||||||
|
doc := func() *screenplay.Document {
|
||||||
|
var d screenplay.Document
|
||||||
|
if len(raw) > 0 {
|
||||||
|
json.Unmarshal(raw[0], &d)
|
||||||
|
}
|
||||||
|
return &d
|
||||||
|
}
|
||||||
|
switch name {
|
||||||
|
case "NewDocument":
|
||||||
|
return screenplay.New()
|
||||||
|
case "InitialFile":
|
||||||
|
return map[string]any{"path": s.path, "document": fountain.Parse(variant(s.src, v))}
|
||||||
|
case "Save", "SaveAs":
|
||||||
|
return s.path // nothing is written
|
||||||
|
case "Paginate":
|
||||||
|
res := layout.Paginate(doc(), layout.Options{})
|
||||||
|
return map[string]any{"pages": len(res.Pages), "breaks": res.Breaks, "scenes": res.Scenes}
|
||||||
|
case "ParseFountain":
|
||||||
|
var text string
|
||||||
|
json.Unmarshal(raw[0], &text)
|
||||||
|
return fountain.ParseText(text)
|
||||||
|
case "RevisionSet":
|
||||||
|
var n int
|
||||||
|
json.Unmarshal(raw[0], &n)
|
||||||
|
r := screenplay.RevisionSet(n)
|
||||||
|
r.Date = []string{"09/14/26", "09/28/26"}[min(max(n, 1), 2)-1]
|
||||||
|
return r
|
||||||
|
case "WindowFrame":
|
||||||
|
return map[string]any{"buttons": "appmenu:close", "rounded": true}
|
||||||
|
case "SpellLanguages":
|
||||||
|
return map[string]any{"languages": []string{"en_US"}, "default": "en_US"}
|
||||||
|
case "SpellCheck":
|
||||||
|
out := []spell.Misspelling{}
|
||||||
|
for i, el := range doc().Elements {
|
||||||
|
for _, w := range spell.Words(el.Text()) {
|
||||||
|
if _, ok := typos[w.Text]; ok {
|
||||||
|
out = append(out, spell.Misspelling{Element: i, Offset: w.Offset, Length: w.Length, Word: w.Text})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
case "SpellSuggest":
|
||||||
|
var word string
|
||||||
|
json.Unmarshal(raw[0], &word)
|
||||||
|
return typos[word]
|
||||||
|
}
|
||||||
|
return nil // Recovery, SetDirty…
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if name, ok := strings.CutPrefix(r.URL.Path, "/api/"); ok {
|
||||||
|
var raw []json.RawMessage
|
||||||
|
json.NewDecoder(r.Body).Decode(&raw)
|
||||||
|
json.NewEncoder(w).Encode(s.call(name, r.URL.Query().Get("v"), raw))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.URL.Path == "/" {
|
||||||
|
html, err := os.ReadFile(filepath.Join(dist, "index.html"))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html")
|
||||||
|
fmt.Fprint(w, strings.Replace(string(html), `<script type="module"`, bridge+`<script type="module"`, 1))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.ServeFile(w, r, filepath.Join(dist, filepath.Clean(r.URL.Path)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
out := flag.String("out", "screenshots", "directory of the README images")
|
||||||
|
firefox := flag.String("firefox", envOr("FIREFOX", "firefox"), "Firefox executable")
|
||||||
|
flag.Parse()
|
||||||
|
log.SetFlags(0)
|
||||||
|
|
||||||
|
src, err := os.ReadFile(sample)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("run from the repository root: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(dist, "index.html")); err != nil {
|
||||||
|
log.Fatal("build the frontend first (make frontend)")
|
||||||
|
}
|
||||||
|
browser, err := exec.LookPath(*firefox)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Firefox not found: %v", err)
|
||||||
|
}
|
||||||
|
abs, _ := filepath.Abs(sample)
|
||||||
|
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
go http.Serve(ln, &server{src: string(src), path: abs})
|
||||||
|
|
||||||
|
tmp, err := os.MkdirTemp("", "plotzilla-screenshots-")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(tmp)
|
||||||
|
raw := filepath.Join(tmp, "raw")
|
||||||
|
os.MkdirAll(raw, 0o755)
|
||||||
|
|
||||||
|
cmd := exec.Command("node", "tools/screenshots/capture.mjs")
|
||||||
|
cmd.Env = append(os.Environ(), "URL=http://"+ln.Addr().String()+"/", "OUT="+raw,
|
||||||
|
"PROFILE="+filepath.Join(tmp, "profile"), "FIREFOX="+browser)
|
||||||
|
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
log.Fatalf("capture: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
shots, _ := filepath.Glob(filepath.Join(raw, "*.png"))
|
||||||
|
for _, f := range shots {
|
||||||
|
img, err := readPNG(f)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := writePNG(filepath.Join(*out, filepath.Base(f)), roundCorners(img, 24)); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := pdfOutput(string(src), tmp, filepath.Join(*out, "pdf-output.png")); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("%d screenshots and pdf-output.png written to %s\n", len(shots), *out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func envOr(key, def string) string {
|
||||||
|
if v := os.Getenv(key); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
func readPNG(path string) (image.Image, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
return png.Decode(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writePNG(path string, img image.Image) error {
|
||||||
|
var b bytes.Buffer
|
||||||
|
enc := png.Encoder{CompressionLevel: png.BestCompression}
|
||||||
|
if err := enc.Encode(&b, img); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(path, b.Bytes(), 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// roundCorners makes the corners outside a rounded rectangle transparent:
|
||||||
|
// the window's 12 px corners, at device scale 2.
|
||||||
|
func roundCorners(src image.Image, radius float64) *image.NRGBA {
|
||||||
|
b := src.Bounds()
|
||||||
|
img := image.NewNRGBA(b)
|
||||||
|
draw.Draw(img, b, src, b.Min, draw.Src)
|
||||||
|
w, h := float64(b.Dx()), float64(b.Dy())
|
||||||
|
for y := 0; y < b.Dy(); y++ {
|
||||||
|
for x := 0; x < b.Dx(); x++ {
|
||||||
|
// Distance from the centre of the nearest corner circle.
|
||||||
|
cx := math.Min(math.Max(float64(x)+0.5, radius), w-radius)
|
||||||
|
cy := math.Min(math.Max(float64(y)+0.5, radius), h-radius)
|
||||||
|
d := math.Hypot(float64(x)+0.5-cx, float64(y)+0.5-cy)
|
||||||
|
if d <= radius-0.5 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
i := img.PixOffset(b.Min.X+x, b.Min.Y+y)
|
||||||
|
img.Pix[i+3] = uint8(float64(img.Pix[i+3]) * math.Max(0, radius+0.5-d))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return img
|
||||||
|
}
|
||||||
|
|
||||||
|
// pdfOutput renders the title page and the script pages of the sample
|
||||||
|
// side by side on the app background.
|
||||||
|
func pdfOutput(src, tmp, path string) error {
|
||||||
|
doc := fountain.Parse(src)
|
||||||
|
pages := append([]layout.Page{layout.TitlePage(doc.TitlePage, doc.Settings.Paper)},
|
||||||
|
layout.Paginate(doc, layout.Options{SceneNumbers: true}).Pages...)
|
||||||
|
var b bytes.Buffer
|
||||||
|
if err := pdf.Render(&b, pages, pdf.Options{Title: doc.TitlePage.Title, Author: doc.TitlePage.Author}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
file := filepath.Join(tmp, "sample.pdf")
|
||||||
|
if err := os.WriteFile(file, b.Bytes(), 0o644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
prefix := filepath.Join(tmp, "page")
|
||||||
|
if out, err := exec.Command("pdftoppm", "-png", "-r", "110", file, prefix).CombinedOutput(); err != nil {
|
||||||
|
return fmt.Errorf("pdftoppm (poppler) is needed for pdf-output.png: %v %s", err, out)
|
||||||
|
}
|
||||||
|
files, _ := filepath.Glob(prefix + "-*.png")
|
||||||
|
const margin = 60
|
||||||
|
var imgs []image.Image
|
||||||
|
for _, f := range files {
|
||||||
|
img, err := readPNG(f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
imgs = append(imgs, img)
|
||||||
|
}
|
||||||
|
if len(imgs) == 0 {
|
||||||
|
return fmt.Errorf("pdftoppm produced no page")
|
||||||
|
}
|
||||||
|
pw, ph := imgs[0].Bounds().Dx(), imgs[0].Bounds().Dy()
|
||||||
|
canvas := image.NewNRGBA(image.Rect(0, 0, margin+len(imgs)*(pw+margin), ph+2*margin))
|
||||||
|
bg := color.NRGBA{7, 12, 24, 255} // --bg
|
||||||
|
draw.Draw(canvas, canvas.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)
|
||||||
|
for i, img := range imgs {
|
||||||
|
r := image.Rect(margin+i*(pw+margin), margin, margin+i*(pw+margin)+pw, margin+ph)
|
||||||
|
shadow(canvas, r, bg)
|
||||||
|
draw.Draw(canvas, r, img, img.Bounds().Min, draw.Src)
|
||||||
|
}
|
||||||
|
return writePNG(path, canvas)
|
||||||
|
}
|
||||||
|
|
||||||
|
// shadow darkens the background around a page, fading over 24 px.
|
||||||
|
func shadow(img *image.NRGBA, r image.Rectangle, bg color.NRGBA) {
|
||||||
|
const spread = 24
|
||||||
|
for y := r.Min.Y - spread; y < r.Max.Y+spread; y++ {
|
||||||
|
for x := r.Min.X - spread; x < r.Max.X+spread; x++ {
|
||||||
|
if !(image.Point{x, y}).In(img.Bounds()) || (image.Point{x, y}).In(r) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dx := max(r.Min.X-x, 0, x-r.Max.X+1)
|
||||||
|
dy := max(r.Min.Y-y, 0, y-r.Max.Y+1)
|
||||||
|
k := 1 - 0.3*(1-math.Min(math.Hypot(float64(dx), float64(dy))/spread, 1))
|
||||||
|
img.SetNRGBA(x, y, color.NRGBA{uint8(float64(bg.R) * k), uint8(float64(bg.G) * k), uint8(float64(bg.B) * k), 255})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
{
|
||||||
|
"name": "plotzilla-screenshots",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "plotzilla-screenshots",
|
||||||
|
"devDependencies": {
|
||||||
|
"puppeteer-core": "^25.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@puppeteer/browsers": {
|
||||||
|
"version": "3.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",
|
||||||
|
"integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"modern-tar": "^0.8.4",
|
||||||
|
"yargs": "^18.0.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"browsers": "lib/main-cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.12.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"proxy-agent": ">=8.0.1",
|
||||||
|
"yauzl": "^2.10.0 || ^3.4.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"proxy-agent": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"yauzl": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ansi-regex": {
|
||||||
|
"version": "6.4.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",
|
||||||
|
"integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ansi-styles": {
|
||||||
|
"version": "6.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
|
||||||
|
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/chromium-bidi": {
|
||||||
|
"version": "17.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",
|
||||||
|
"integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"mitt": "^3.0.1",
|
||||||
|
"zod": "^3.24.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.19.0 <22.0.0 || >=22.12.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"devtools-protocol": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cliui": {
|
||||||
|
"version": "9.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
|
||||||
|
"integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"dependencies": {
|
||||||
|
"string-width": "^7.2.0",
|
||||||
|
"strip-ansi": "^7.1.0",
|
||||||
|
"wrap-ansi": "^9.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/cliui/node_modules/string-width": {
|
||||||
|
"version": "7.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
|
||||||
|
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"emoji-regex": "^10.3.0",
|
||||||
|
"get-east-asian-width": "^1.0.0",
|
||||||
|
"strip-ansi": "^7.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/devtools-protocol": {
|
||||||
|
"version": "0.0.1687809",
|
||||||
|
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",
|
||||||
|
"integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/emoji-regex": {
|
||||||
|
"version": "10.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
|
||||||
|
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/escalade": {
|
||||||
|
"version": "3.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||||
|
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-caller-file": {
|
||||||
|
"version": "2.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||||
|
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": "6.* || 8.* || >= 10.*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/get-east-asian-width": {
|
||||||
|
"version": "1.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
|
||||||
|
"integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/mitt": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/modern-tar": {
|
||||||
|
"version": "0.8.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",
|
||||||
|
"integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/puppeteer-core": {
|
||||||
|
"version": "25.12.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",
|
||||||
|
"integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@puppeteer/browsers": "3.2.3",
|
||||||
|
"chromium-bidi": "17.0.2",
|
||||||
|
"devtools-protocol": "0.0.1687809",
|
||||||
|
"typed-query-selector": "^2.12.2",
|
||||||
|
"webdriver-bidi-protocol": "0.4.3",
|
||||||
|
"ws": "^8.21.3"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.12.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/string-width": {
|
||||||
|
"version": "8.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",
|
||||||
|
"integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"get-east-asian-width": "^1.5.0",
|
||||||
|
"strip-ansi": "^7.1.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/strip-ansi": {
|
||||||
|
"version": "7.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
|
||||||
|
"integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-regex": "^6.2.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/typed-query-selector": {
|
||||||
|
"version": "2.12.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",
|
||||||
|
"integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/webdriver-bidi-protocol": {
|
||||||
|
"version": "0.4.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",
|
||||||
|
"integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0"
|
||||||
|
},
|
||||||
|
"node_modules/wrap-ansi": {
|
||||||
|
"version": "9.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
|
||||||
|
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ansi-styles": "^6.2.1",
|
||||||
|
"string-width": "^7.0.0",
|
||||||
|
"strip-ansi": "^7.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/wrap-ansi/node_modules/string-width": {
|
||||||
|
"version": "7.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
|
||||||
|
"integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"emoji-regex": "^10.3.0",
|
||||||
|
"get-east-asian-width": "^1.0.0",
|
||||||
|
"strip-ansi": "^7.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/ws": {
|
||||||
|
"version": "8.22.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
|
||||||
|
"integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"bufferutil": "^4.0.1",
|
||||||
|
"utf-8-validate": ">=5.0.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"bufferutil": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"utf-8-validate": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/y18n": {
|
||||||
|
"version": "5.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||||
|
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/yargs": {
|
||||||
|
"version": "18.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",
|
||||||
|
"integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cliui": "^9.0.1",
|
||||||
|
"escalade": "^3.1.1",
|
||||||
|
"get-caller-file": "^2.0.5",
|
||||||
|
"string-width": "^8.2.1",
|
||||||
|
"y18n": "^5.0.5",
|
||||||
|
"yargs-parser": "^22.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || ^22.12.0 || >=23"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/yargs-parser": {
|
||||||
|
"version": "22.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",
|
||||||
|
"integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": "^20.19.0 || ^22.12.0 || >=23"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/zod": {
|
||||||
|
"version": "3.25.76",
|
||||||
|
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
|
||||||
|
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"name": "plotzilla-screenshots",
|
||||||
|
"private": true,
|
||||||
|
"description": "Captures the README screenshots (make screenshots)",
|
||||||
|
"type": "module",
|
||||||
|
"devDependencies": {
|
||||||
|
"puppeteer-core": "^25.12.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
Title: THE LAST REEL
|
||||||
|
Credit: Written by
|
||||||
|
Author: Jane Doe
|
||||||
|
Source: Based on a true story
|
||||||
|
Draft date: September 28, 2026
|
||||||
|
Contact:
|
||||||
|
Jane Doe
|
||||||
|
jane@example.com
|
||||||
|
+1 555 0100
|
||||||
|
|
||||||
|
FADE IN:
|
||||||
|
|
||||||
|
INT. PROJECTION BOOTH - NIGHT
|
||||||
|
|
||||||
|
Dust hangs in the **beam** of the projector. ELODIE (40s), sleeves rolled up, threads a reel by hand. Old film cans line every shelf.
|
||||||
|
|
||||||
|
INSERT - THE FILM CAN
|
||||||
|
|
||||||
|
A faded label: _"The Last Reel - 1942"_.
|
||||||
|
|
||||||
|
BACK TO SCENE
|
||||||
|
|
||||||
|
ELODIE (V.O.)
|
||||||
|
(quietly)
|
||||||
|
It always ends *here*. Same frame, same scratch, every single night.
|
||||||
|
|
||||||
|
MARC
|
||||||
|
You say that every night.
|
||||||
|
|
||||||
|
ELODIE ^
|
||||||
|
Because it's true every night.
|
||||||
|
|
||||||
|
The film snaps. Below them, the screen floods with white light.
|
||||||
|
|
||||||
|
CUT TO:
|
||||||
|
|
||||||
|
> PARIS, 1942 <
|
||||||
|
|
||||||
|
EXT. CINEMA LE RIALTO - DAY
|
||||||
|
|
||||||
|
A crowd queues under a hand-painted marquee. Soldiers watch from across the street.
|
||||||
|
|
||||||
|
A YOUNG WOMAN, a younger ELODIE's grandmother, slips a film can into her coat.
|
||||||
|
|
||||||
|
YOUNG WOMAN
|
||||||
|
(to the usher)
|
||||||
|
Two tickets. The late show.
|
||||||
|
|
||||||
|
USHER
|
||||||
|
There is no late show anymore, mademoiselle. Curfew.
|
||||||
|
|
||||||
|
YOUNG WOMAN
|
||||||
|
Then the last one. Whatever is playing, I want to see how it ends.
|
||||||
|
|
||||||
|
The usher hesitates, glances at the soldiers, then tears two tickets.
|
||||||
|
|
||||||
|
INT. CINEMA LE RIALTO - AUDITORIUM - CONTINUOUS
|
||||||
|
|
||||||
|
Rows of red velvet seats, half empty. The lights dim. On screen, a newsreel flickers.
|
||||||
|
|
||||||
|
The young woman finds a seat in the last row and pulls the can from her coat.
|
||||||
|
|
||||||
|
MATCH CUT TO:
|
||||||
|
|
||||||
|
INT. PROJECTION BOOTH - NIGHT
|
||||||
|
|
||||||
|
Elodie holds the same can, its edges rusted, the label almost gone.
|
||||||
|
|
||||||
|
ELODIE
|
||||||
|
Eighty years. And you never told anyone what was on it.
|
||||||
|
|
||||||
|
She opens the lid. Inside, a single reel and a folded letter.
|
||||||
|
|
||||||
|
INSERT - THE LETTER
|
||||||
|
|
||||||
|
Handwritten, in French: _"If you are reading this, run it to the end."_
|
||||||
|
|
||||||
|
BACK TO SCENE
|
||||||
|
|
||||||
|
Elodie looks at the projector, then at the reel. She makes her choice.
|
||||||
|
|
||||||
|
MARC (O.S.)
|
||||||
|
Elodie? The audience is waiting.
|
||||||
|
|
||||||
|
ELODIE
|
||||||
|
Let them wait. Tonight we show something new.
|
||||||
|
|
||||||
|
She laces the old reel into the machine and throws the switch.
|
||||||
|
|
||||||
|
> FADE OUT.
|
||||||
|
|
||||||
|
> THE END <
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://wails.io/schemas/config.v2.json",
|
||||||
|
"name": "plotzilla",
|
||||||
|
"outputfilename": "plotzilla",
|
||||||
|
"frontend:install": "npm install",
|
||||||
|
"frontend:build": "npm run build",
|
||||||
|
"frontend:dev:watcher": "npm run dev",
|
||||||
|
"frontend:dev:serverUrl": "auto",
|
||||||
|
"author": {
|
||||||
|
"name": "Sandro Cazzaniga",
|
||||||
|
"email": "sandro@cazzaniga.fr"
|
||||||
|
}
|
||||||
|
}
|
||||||