Metadata-Version: 2.4
Name: apd-viewer-tui
Version: 0.1.0
Summary: A vim-like terminal UI for viewing and editing APD exported JSON.
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: textual>=8.2.8
Requires-Dist: pyte>=0.8.2
Dynamic: license-file

# apd-tui

A vim-like terminal UI for **viewing and editing APD (product design) exported JSON**.

Built with [Textual](https://textual.textualize.io/). It renders the APD JSON as a
navigable tree of *relationships* (nested objects / arrays) on the left, the
selected node's scalar fields and child relationships on the right, and a live
system shell on the far right.

> This document describes only the `apd-tui/` Python program. It does not cover
> the rest of the `gwpc-cloud-acc` repository.

---

## AI disclaimer

This program and its documentation were generated and iteratively refined with
the assistance of an AI coding agent (**Tencent HY3**). The code, behavior, and
text above should be reviewed and tested by a human before being relied upon in
production. No warranty, express or implied, is made regarding correctness,
security, or fitness for any particular purpose.

---

## Features

- **Relationship-only tree** — only nested `dict`/`list` nodes are shown as tree
  nodes; scalar properties (uuid/code/name/type/sequence…) stay in the detail
  panel. Array items are labeled with their semantic field (`name`/`code`/`uuid`)
  rather than a raw index. The root node is labeled with the root object's
  `description` (falls back to `name`/`code`/`uuid`, then the file name).
- **Two-section detail panel** — scalar properties, then a `RELATIONSHIPS`
  section listing each child relationship with its item count; clicking a
  relationship row focuses the matching tree node.
- **Schema-aware fields** — uses the `schema/ProductV10.schema.json` you supply via
  `--schema` to show declared-but-missing fields as `(not provided)` so the full
  field set of a level is always visible. The bundled `schema/ProductV10.schema.json`
  is the current/latest schema and matches the bundled `personal-umbrella.sample.json`.
- **Inline editing** — `Enter` on a field opens an inline editor; values are
  type-coerced (bool/int/float/None/str). A `category` field whose value matches
  a product-defined category code gets a dropdown; otherwise it is free text.
  `uuid` and `subtype` are **read-only** and cannot be edited.
- **Sequence reordering** — editing the `sequence` of an item physically moves
  it within its parent array (1-based, bounded by `1..N`) and renumbers the
  siblings to `1..N`.
- **Delete / paste** — `dd` deletes the selected node (saved to a clipboard),
  `p` pastes it as a sibling below the selection with type-compatibility checks.
- **Undo / redo** — `u` / `Ctrl+R`, whole-document snapshots (unbounded stack).
- **Full-text search** — `/` opens a bottom search bar; matches across keys and
  scalar values; `n`/`N` cycle through matches.
- **Vim-style panes** — `h`/`l` move focus left/right across the three panes.
- **Live terminal pane** — a real PTY running your `$SHELL`, rendered with
  `pyte`. Off by default; turn it on with `Ctrl+Shift+T` (or `terminal on` from
  the command palette / `--terminal-on`), off with `Ctrl+Shift+Y`, toggle with
  `Ctrl+T`, leave focus with `Ctrl+B`.
- **Themes** — bundled themes (catppuccin, everforest, apd_dark, apd_light),
  switchable at runtime and persisted across launches.
- **Safe persistence** — edits are written to a vim-style swap file
  (`temp/<basename>.lock`); `Ctrl+S`/`:w` atomically overwrites the source file.
  `F5` reloads the source from disk.
- **Command palette** — `:` opens it (quit/help + dynamic theme commands).

---

## Requirements

- Python 3 (developed on 3.14).
- Third-party packages (run inside the project's `.venv`):
  - `textual` (TUI framework)
  - `pyte` (terminal emulator for the shell pane)

> The virtual environment (`.venv`) is **not** committed to the repository (it is
> gitignored). You must create it yourself the first time — the launchers below
> do this for you automatically.

Set up the environment (one time):

```bash
# From the project root (apd-tui/):
python3 -m venv .venv
.venv/bin/pip install "textual>=8.2.8" "pyte>=0.8.2"
# or, to install this package so the `apd-tui` console script is available:
.venv/bin/pip install -e .
```

---

## Usage

### macOS / Linux

Run the bundled launcher (creates the `.venv` if missing, then uses its Python
and passes through arguments):

```bash
cd apd-tui

# Open the in-repo sample file (runTest passes --file for you)
./runTest

# Or specify a file / theme explicitly — --file is required
./run --file /path/to/apd.json
./run --file apd.json --theme everforest
```

You can also invoke the entry module directly with the same `.venv`:

```bash
.venv/bin/python apd_viewer.py --file PATH --schema PATH [--theme NAME]
```

`--file` and `--schema` are both mandatory: launching without either prints the
usage (listing every available argument) and exits.

### Windows (PowerShell)

Run `run.ps1`. It creates the `.venv` on first use (reusing it afterwards — no
need to `activate` manually) and forwards all arguments:

```powershell
# From the project root (apd-tui/):
.\run.ps1 --file .\personal-umbrella.sample.json
.\run.ps1 --file apd.json --theme everforest
```

> Note: the interactive terminal (shell) pane requires a Unix PTY and is
> unavailable on Windows. The tree and detail panes work fully; the terminal
> pane shows a placeholder instead of a live shell.

For **local testing without installing**, use the standalone `test.ps1` /
`testSample.ps1` launchers instead. They mirror the Unix `run` / `runTest`
scripts: they reuse an already-created `.venv` (and error out if it is
missing) rather than creating it. `testSample.ps1` opens the bundled sample
automatically. Because PowerShell blocks local scripts by default, run them
with `-ExecutionPolicy Bypass` (or relax the policy once with
`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`):

```powershell
# From the project root (apd-tui/):
powershell -ExecutionPolicy Bypass -File .\testSample.ps1                 # opens the bundled sample + schema
powershell -ExecutionPolicy Bypass -File .\testSample.ps1 --theme everforest
powershell -ExecutionPolicy Bypass -File .\test.ps1 --file apd.json --schema schema/ProductV10.schema.json
```

If the `.venv` does not exist yet, create it once:

```powershell
py -m venv .venv
.\.venv\Scripts\pip install "textual>=8.2.8" "pyte>=0.8.2"
```

| Argument     | Description                                                        |
| ------------ | ------------------------------------------------------------------ |
| `--file PATH`| APD JSON file to load. **Required** — omitting it prints the usage and exits. |
| `--schema PATH`| APD product JSON schema file. **Required** — omitting it prints the usage and exits. |
| `--theme NAME`| Initial theme. Defaults to the last-used theme (or `catppuccin`). |
| `--terminal-on` | Start with the terminal pane visible. |
| `--terminal-off`| Start with the terminal pane hidden (**default**). Mutually exclusive with `--terminal-on`. |

---

## Keyboard shortcuts

| Key           | Action                                                        |
| ------------- | ------------------------------------------------------------- |
| `j` / `k`     | Move selection down / up in the tree                          |
| `h` / `l`     | Move focus left / right across panes (tree → detail → terminal)|
| `t`           | Focus the terminal pane                                       |
| `Ctrl+Shift+T`| Show the terminal pane (TerminalOn; default off on startup)   |
| `Ctrl+Shift+Y`| Hide the terminal pane (TerminalOff)                          |
| `Ctrl+T`      | Toggle the terminal pane visibility                           |
| `Enter`       | Edit the selected detail field (inline editor)                |
| `dd`          | Delete the selected node (double-tap `d`; a lone `d` does nothing) |
| `p`           | Paste the last-deleted node as a sibling below the selection  |
| `u`           | Undo                                                          |
| `Ctrl+R`      | Redo                                                          |
| `F5`          | Reload the source file from disk                              |
| `Ctrl+S`      | Save (write swap file over the source)                        |
| `/`           | Open the full-text search bar                                 |
| `n` / `N`     | Jump to next / previous search match (cycles)                 |
| `Esc`         | Close the search bar (keeps results); cancel an inline edit   |
| `:`           | Open the command palette (quit / help / theme switching)       |
| `q`           | Quit                                                          |

**Inside the terminal pane** all keystrokes are forwarded verbatim to the shell.
Press `Ctrl+B` to return focus to the viewer.

---

## Editing model & persistence

1. Edits mutate the in-memory document and are flushed to a vim-style swap file
   `temp/<basename>.lock` immediately.
2. `Ctrl+S` (or `:w` via the command palette) atomically overwrites the original
   source file.
3. `F5` re-reads the source file from disk (useful after editing it externally
   in the terminal pane).
4. Every edit (`dd`, `p`, inline edit, sequence change) pushes a whole-document
   snapshot before mutating, enabling `u` / `Ctrl+R`. New edits clear the redo
   stack.

Read-only fields (`uuid`, `subtype`) are blocked both at the editor entry point
and at the write-back stage.

---

## Themes

Themes live in the `themes/` package — one module per theme exposing a `THEME`
instance. `ThemeManager` auto-discovers them, so adding a theme is just dropping
a new file.

The selected theme is persisted to `~/.config/apd-viewer/config.json` and
reused on the next launch. A `--theme` argument overrides it for that run.

---

## Architecture & design

### Layout

```
Header
Horizontal
├── Tree            #tree      (25%)  relationship-only structure
├── ScrollableContainer #detail (25%) └── DataTable #detail_table
└── TerminalPane    #terminal  (50%)  live PTY shell (toggleable)
Footer
```

Panes use percentage widths (not `fr`) so the ratio stays exact on resize. When
the terminal is hidden the detail pane reclaims its width (tree 25% / detail 75%).

### Data flow

```
--file → load_apd (normalizes U+00A0 NBSP → space) → _root_label (root description)
       → build_tree (recurse dict/list relationships only; each node .data stores
         the Python object + cached _schema_fields / _schema_path_key)
       → Tree.NodeSelected → render_detail (scalar props + RELATIONSHIPS)
       → detail row click → tree.select_node (focus matching node)
```

Each tree node stores the actual Python object in `.data`, giving O(1) access on
selection without re-walking the JSON. A `id(obj) → TreeNode` map (`_node_by_id`)
resolves full-text search hits back to tree nodes.

### Module structure

```
apd-tui/
├── apd_viewer.py            # Entry point: args, theme resolution, config,
│                            #   import wiring, launch MainScreen.
├── config.py                # User config (~/.config/apd-viewer/config.json):
│                            #   atomic theme persistence.
├── personal-umbrella.sample.json  # Sample APD product (dev fixture; not packaged).
├── schema/ProductV10.schema.json  # JSON schema used for field completion (NOT packaged; pass via --schema).
├── run / runTest            # Unix launcher scripts (use project .venv).
├── run.ps1                  # Windows (PowerShell) launcher (creates .venv if missing).
├── test.ps1 / testSample.ps1  # Windows local-test launchers (reuse existing .venv; do not install).
├── temp/                    # Vim-style swap files (<basename>.lock); gitignored.
├── screen/
│   ├── main_screen.py       # MainScreen: compose, tree/detail, editing,
│   │                        #   undo/redo, search, save/reload, terminal visibility.
│   ├── main_bindings.py     # MAIN_BINDINGS: the vim key map (single source).
│   ├── main_css.py          # MAIN_CSS: three-pane layout styles.
│   ├── shortcut_command.py  # Command pattern: ShortcutCommand interface,
│   │                        #   CommandRegistry, one class per shortcut,
│   │                        #   build_registry(). Keeps MainScreen thin.
│   ├── shared.py            # Tree/JSON helpers (load_apd, build_tree, labels,
│   │                        #   move_and_renumber, READONLY_FIELDS) and reusable
│   │                        #   widgets (HelpScreen, APDCommandProvider,
│   │                        #   EditInput, EditSelect, SpaceFriendlyInput).
│   └── terminal_pane.py     # TerminalPane: PTY + pyte shell, key-to-bytes
│                            #   forwarding, resize, pause/resume, cleanup.
└── themes/
    ├── manager.py           # ThemeManager: auto-discovers THEME modules.
    ├── __init__.py          # Exposes CUSTOM_THEMES.
    └── catppuccin.py / everforest.py / apd_dark.py / apd_light.py
```

### Design decisions

- **Command pattern for shortcuts** — every binding action maps to a
  `ShortcutCommand` instance in a `CommandRegistry`; `MainScreen.action_*`
  methods are thin forwards (`self._commands.dispatch(...)`). Adding a key means
  adding a command class, not editing the screen, and the import graph stays
  strictly one-directional.
- **Relationship-only tree** — scalars stay in the detail panel so a large APD
  document (≈136 KB sample) stays navigable; node `.data` holds object identity
  for O(1) selection.
- **Whole-document undo snapshots** — chosen over inverse-command or per-node
  diffs because APD files are small and `deepcopy` is cheap. After a restore the
  document object is brand new, so the cursor is re-located by **JSON path**
  (key/index chain), not object identity.
- **Real PTY terminal** — a genuine interactive shell via `pty.fork()` + `pyte`,
  with a background reader thread feeding the emulator and forwarding keys as raw
  bytes. Single-letter App bindings are re-declared as no-ops on the pane so the
  shell receives them verbatim (e.g. typing `q` must not quit the viewer).
- **iTerm2 input robustness** — `SpaceFriendlyInput` recovers punctuation/space
  keys delivered as keysyms (empty `event.character`) so inline editors work
  under iTerm2.

---

## Publishing & installation

The program is packaged with `pyproject.toml` (setuptools build backend) so it
can be built into a wheel/sdist and installed with `pip`.

### For users (install from an index)

```bash
pip install apd-tui
apd-tui --file /path/to/apd.json --schema /path/to/schema/ProductV10.schema.json
```

Neither the schema nor the sample document is bundled inside the wheel. The
schema drives field completion and the `(not provided)` field list and must be
supplied via the **required** `--schema` argument (it is **not** packaged, issue
#16). The sample document is a development fixture and is also **not** packaged,
so `--file` must always point at your own APD export; running `apd-tui` without
`--file` or `--schema` exits with a usage error.

### From source (development / local use)

```bash
cd apd-tui
../.venv/bin/pip install -e .        # editable install into the project venv
apd-tui --file personal-umbrella.sample.json --schema schema/ProductV10.schema.json
```

### Building the distribution

Requires the build tooling (install once in any venv):

```bash
pip install build twine
python -m build                      # creates dist/*.whl and dist/*.tar.gz
twine check dist/*                   # sanity-check the artifacts
```

### One-shot publish script

A `publish.sh` at the repo root wraps the whole release flow (pre-flight
checks → `python -m build` → `twine check` → interactive confirmation →
`twine upload -r pypi`). Your PyPI credentials must already be present in
`~/.pypirc` (a `[pypi]` section), per the official guide:

```bash
./publish.sh
```

The script aborts early (with a clear message) if `build`/`twine` are missing,
and asks for a `y/N` confirmation before any upload. It never deletes or
modifies `pyproject.toml`.

On **Windows (PowerShell)**, use the equivalent `publish.ps1`. It mirrors the
Unix flow (auto-installs `build`/`twine` if missing, then builds, runs
`twine check`, asks for confirmation, and uploads via `twine -r <repo>`) and
reads credentials from the `~/.pypirc` `[<repo>]` section — no token is
hard-coded in the script. PowerShell blocks local scripts by default, so run it
with `-ExecutionPolicy Bypass`:

```powershell
powershell -ExecutionPolicy Bypass -File .\publish.ps1            # upload to 'pypi'
powershell -ExecutionPolicy Bypass -File .\publish.ps1 -Repo testpypi
```

### Publishing to an index

- **Internal / private index (recommended here)** — this project pins a custom
  `textual>=8.2.8` build that may not exist on public PyPI:

  ```bash
  twine upload --repository-url http://<your-index>/simple/ dist/*
  ```

  Users then install from that index:

  ```bash
  pip install --index-url http://<your-index>/simple/ apd-tui
  ```

- **Public PyPI** (only if your `textual` is the public release):

  ```bash
  twine upload -r pypi dist/*        # needs a PyPI account + API token
  ```

### Dependency notes

- `textual` is pinned to `>=8.2.8` and `pyte` to `>=0.8.2`, matching the versions
  this was developed and tested against. If your `textual` is an internal build,
  publish and install through the internal index above.
- Requires Python 3.10+.
- The `apd-tui` console script maps to `apd_viewer:main`.

## Notes

- The program does not modify the sample JSON or the schema file you pass via `--schema`.
- `temp/` is gitignored; swap files are scratch working copies of unsaved edits.
- Parse errors (missing file / invalid JSON) surface as a `notify` error rather
  than crashing.
