diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f5ffa9..38a85c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ # Changelog +## Unreleased + +### What's new + +- **A new look**: fixed colors on a dark background of their own, the same whatever the terminal's theme; a terminal without 24-bit colors gets the closest ones it has. The panel with the focus has a thick blue border. +- **A header**: the first line gives the product, in a badge that tells Elasticsearch from OpenSearch, the URL and the user. On a protected cluster, the whole line takes the red or the yellow of the former banner, which no longer costs a line of the panels. +- **The status line and the shortcuts on one line**: the message on the left, as many shortcuts as it leaves room for on the right. It no longer shares the line with the URL and the user, and the panels keep their height. At 80 columns, fewer shortcuts show at once, the ones used most first; `F1` still lists them all. +- **Methods colored in the editor**: `GET` in teal, `POST` and `PUT` in blue, `DELETE` in red, comments dimmed. +- **A `▼` says there is more below**: on the bottom border of the editor, of the result and of the help screen, for as long as there is something left to scroll to. + +### Before upgrading from 0.8.1 + +- **Nothing to do**: the shortcuts, the configuration and the saved files don't change. + ## 0.8.1 (beta) — October 2026 **In one sentence**: the help screen gives TermDevTools' version and the cluster's, and `F2` and `F9` copy in any terminal on a Mac. diff --git a/CHANGELOG_fr.md b/CHANGELOG_fr.md index 2f2403c..f3c7dc3 100644 --- a/CHANGELOG_fr.md +++ b/CHANGELOG_fr.md @@ -2,6 +2,20 @@ # Journal des versions +## Non publié + +### Nouveautés + +- **Un nouvel habillage** : des couleurs fixes sur un fond sombre qui lui est propre, les mêmes quel que soit le thème du terminal ; un terminal sans couleurs 24 bits reçoit les plus proches qu'il ait. Le panneau qui a le focus a une bordure épaisse et bleue. +- **Un en-tête** : la première ligne donne le produit, dans un badge qui distingue Elasticsearch d'OpenSearch, l'URL et l'utilisateur. Sur un cluster protégé, toute la ligne prend le rouge ou le jaune de l'ancien bandeau, qui ne coûte plus une ligne aux panneaux. +- **La ligne de statut et les raccourcis sur une seule ligne** : le message à gauche, autant de raccourcis qu'il laisse de place à droite. Il ne partage plus la ligne avec l'URL et l'utilisateur, et les panneaux gardent leur hauteur. À 80 colonnes, moins de raccourcis s'affichent à la fois, les plus utilisés d'abord ; `F1` les donne toujours tous. +- **Méthodes colorées dans l'éditeur** : `GET` en sarcelle, `POST` et `PUT` en bleu, `DELETE` en rouge, commentaires atténués. +- **Un `▼` signale qu'il y a une suite** : sur la bordure inférieure de l'éditeur, du résultat et de l'écran d'aide, tant qu'il reste de quoi défiler. + +### À savoir avant de mettre à jour depuis la 0.8.1 + +- **Rien à faire** : les raccourcis, la configuration et les fichiers sauvegardés ne changent pas. + ## 0.8.1 (bêta) — octobre 2026 **En une phrase** : l'écran d'aide donne la version de TermDevTools et celle du cluster, et `F2` et `F9` copient dans n'importe quel terminal sur Mac. diff --git a/INSTALL.md b/INSTALL.md index 5d936a3..7903949 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -352,7 +352,7 @@ Delete the binary and the configuration directory (§5): TermDevTools writes not | `The cluster responded HTTP 403` | The account isn't allowed to read the cluster's root (`GET /`): it needs at least the monitoring privilege (`monitor`). | | `The cluster responded HTTP 301` (or `302`…) followed by an address | The URL entered redirects elsewhere: use the address shown. Redirections are never followed. | | `No credentials in the URL…` | Remove `user:password@` from the URL and choose Basic Auth. | -| The status bar says `Cluster` instead of `ES …` or `OS …` | The cluster wasn't recognized: everything is offered, unfiltered. State `distribution` and `version` in `config.yaml` (§5). | +| The header says `Cluster` instead of `ES …` or `OS …` | The cluster wasn't recognized: everything is offered, unfiltered. State `distribution` and `version` in `config.yaml` (§5). | | `Tab` doesn't complete | Some terminals intercept `Tab`: use `F10`. | | `Ctrl+←/→` doesn't switch panel on macOS | The system intercepts it: use `Option+←/→`. | | `F2` or `F9` copies nothing | The copy goes through the terminal (OSC 52) — except on a Mac outside SSH, where it goes through `pbcopy` and works in any terminal. Windows Terminal, WezTerm, kitty, Alacritty and iTerm2 (once enabled in its settings) support it; PuTTY, macOS Terminal (through SSH), GNOME Terminal and the other VTE-based terminals don't. In `tmux`: `set -g set-clipboard on`; `screen` needs to be configured for it. | diff --git a/INSTALL_fr.md b/INSTALL_fr.md index 3574e61..7e49954 100644 --- a/INSTALL_fr.md +++ b/INSTALL_fr.md @@ -354,7 +354,7 @@ Les messages sont cités en anglais, tels qu'un premier lancement les affiche, p | `The cluster responded HTTP 403` / `Le cluster a répondu HTTP 403` | Le compte n'a pas le droit de lire la racine du cluster (`GET /`) : il lui faut au moins le privilège de supervision (`monitor`). | | `The cluster responded HTTP 301` (ou `302`…) suivi d'une adresse | L'URL saisie redirige ailleurs : utilisez l'adresse indiquée. Les redirections ne sont jamais suivies. | | `No credentials in the URL…` / `Pas d'identifiants dans l'URL…` | Retirez `utilisateur:motdepasse@` de l'URL et choisissez Basic Auth. | -| La barre de statut affiche `Cluster` au lieu de `ES …` ou `OS …` | Le cluster n'a pas été reconnu : tout est proposé sans filtrage. Indiquez `distribution` et `version` dans `config.yaml` (§5). | +| L'en-tête affiche `Cluster` au lieu de `ES …` ou `OS …` | Le cluster n'a pas été reconnu : tout est proposé sans filtrage. Indiquez `distribution` et `version` dans `config.yaml` (§5). | | `Tab` ne complète pas | Certains terminaux interceptent `Tab` : utilisez `F10`. | | `Ctrl+←/→` ne change pas de panneau sous macOS | Le système l'intercepte : utilisez `Option+←/→`. | | `F2` ou `F9` ne copie rien | La copie passe par le terminal (OSC 52) — sauf sur un Mac hors SSH, où elle passe par `pbcopy` et fonctionne dans n'importe quel terminal. Windows Terminal, WezTerm, kitty, Alacritty et iTerm2 (une fois activé dans ses réglages) la prennent en charge ; PuTTY, le Terminal de macOS (à travers SSH), GNOME Terminal et les autres terminaux basés sur VTE, non. Dans `tmux` : `set -g set-clipboard on` ; `screen` demande une configuration. | diff --git a/SPEC.md b/SPEC.md index 9bc5ce7..ba9606f 100644 --- a/SPEC.md +++ b/SPEC.md @@ -42,7 +42,7 @@ On launch, a connection screen lists the URLs of known clusters (no separate nam - "API Key" → the key's identifier, then its secret - "Bearer token" → only the token - "client certificate (mTLS)" → only the certificate fields (hides username/password); also hidden if the URL is `http://` (see above) -- **API key in its `encoded` form**: the secret field also takes the whole key as Kibana and the API creating it show it first — `base64(identifier:secret)`. It is recognized by its shape (two parts of the alphabet of Elasticsearch keys around a `:`, once decoded), including without its trailing `=` padding or pasted with a line break. The identifier it holds then replaces the form's, empty or not: that is the one saved in `config.yaml` and shown in the status bar. A secret alone with no identifier is refused before anything is sent, with a message saying what to enter. +- **API key in its `encoded` form**: the secret field also takes the whole key as Kibana and the API creating it show it first — `base64(identifier:secret)`. It is recognized by its shape (two parts of the alphabet of Elasticsearch keys around a `:`, once decoded), including without its trailing `=` padding or pasted with a line break. The identifier it holds then replaces the form's, empty or not: that is the one saved in `config.yaml` and shown in the header. A secret alone with no identifier is refused before anything is sent, with a message saying what to enter. - **Bearer token**: pasted as it is; the spaces or line break around it, and the word `Bearer` if it was copied along, are removed. - **Active field highlighted**: the field currently focused is displayed in inverted colors (background/text), so it stays identifiable even when the blinking cursor alone isn't enough. - **24-row terminal**: the longest form (https with a client certificate) only fits by dropping the blank line between two fields; it is dropped in that case alone, so that the buttons stay on screen. @@ -50,7 +50,7 @@ On launch, a connection screen lists the URLs of known clusters (no separate nam - In both cases, once the connection succeeds, the entry (new or existing) is moved/inserted at the **first position** of the `clusters` list in `config.yaml` — no secret is ever written there. - **Detection**: the answer to the `GET /` that validates the connection also tells which distribution and version the cluster runs (§5). Nothing to choose or fill in; a cluster that can't be identified is still connected to. - **One attempt at a time**: an attempt given up on (`Esc` or the Cancel button) or superseded by a newer one is ignored when its answer finally arrives — a cluster slow to answer can't replace the session opened on another one since, and pressing Connect twice opens a single session. -- **What is refused before any connection**: a URL carrying credentials (`https://user:password@host`). The URL is the one thing about a cluster that is saved and displayed as is — in `config.yaml`, in the status bar, in the `curl` commands copied: the password would end up there. The message points to Basic Auth. +- **What is refused before any connection**: a URL carrying credentials (`https://user:password@host`). The URL is the one thing about a cluster that is saved and displayed as is — in `config.yaml`, in the header, in the `curl` commands copied: the password would end up there. The message points to Basic Auth. - **What is not a connection**: a `3xx` answer. Redirections are never followed (§5); the screen shows the status and the address the answer points to, for the URL to be corrected. - **Proxy**: when the connection goes through a proxy (§5), the screen names it before anything is sent — "Connecting through proxy …", followed by where it comes from (`HTTPS_PROXY`, `HTTP_PROXY` or `config.yaml`). If the attempt fails, the proxy is recalled **in front of** the error's detail — often longer than the room there is — with the way to do without it when it comes from the environment. The message area is three lines high for that purpose. An HTTP status received through a proxy is announced the same way: the answer may be the proxy's own (`407`, `403`). A proxy that can't be used (§5) stops the attempt before anything is sent. - Once connected, you work against one cluster at a time, inside a general layout inspired by Kibana's DevTools. @@ -72,8 +72,10 @@ On launch, a connection screen lists the URLs of known clusters (no separate nam A related but distinct gap surfaced later: `TextArea.Select()` (used for the left panel's search matches) is correctly wrap-safe — it's the offset-based method just described — but its own doc comment is explicit that it "preserves" the scroll offset, unlike normal cursor movement (typing, arrow keys), which tview scrolls into view automatically. A match outside the visible viewport was therefore selected correctly internally while staying invisible on screen — indistinguishable, to the user, from search "landing in the wrong place". Fixed by `Editor.scrollToCursor` (`ui/editor.go`), replicating tview's own (unexported) auto-scroll logic using `GetCursor`'s display row (correct here, unlike for logical-line purposes) together with the public `GetOffset`/`SetOffset`. A further report — search actually *selecting the wrong text* (not just off-screen, e.g. matching content shifted a few characters away from the real match) — turned out to be a second, more fundamental bug in the same offset-based method, not a wrap issue at all: `TextArea.GetSelection`/`Select`/`Replace` all count **UTF-8 bytes** internally (confirmed by reading tview's own source — position tracking advances by `len(cluster)`, a string's byte length), a fact none of their doc comments spell out. This codebase's own offset arithmetic (`findNext` in `ui/search.go`, `lineColAt`/`CompletionPrefix` in `ui/editor.go`) used **rune** counts (`len([]rune(...))`) throughout instead. The two agree exactly as long as every character before the position in question is single-byte ASCII — and silently diverge, by however many extra bytes accumulate, as soon as any multi-byte UTF-8 character (an accented letter, typically) appears earlier in the buffer. Not a crash, just a wrong-looking result: search selecting a few characters away from the real match, endpoint completion replacing the wrong span, and — since `CursorLine` is built on the same `lineColAt` — potentially **`Ctrl+E` targeting the wrong request entirely** whenever an earlier line held non-ASCII text. Fixed by switching all of this codebase's own offset arithmetic to byte lengths (`len(s)`) instead of rune counts, matching tview's convention exactly; see `TestLineColAtByteOffsets` and `TestFindNextByteOffsets`, both of which fail against the pre-fix code with content reproducing the original report. One last case of the same kind: search ignores case, and lowercasing a whole text can change its length in bytes ("İ", two bytes, becomes "i̇", three) — so case is folded letter by letter, only where the lowercase form takes the same number of bytes (`foldCase`, `ui/search.go`). -- **Protection banner**: on a protected cluster (§5), a full-width line above the two panels — red background with "writes need confirmation", since writes remain possible, yellow with "read-only" — gives the label and the level ("PROD · read-only"), or the level alone, in capitals, without a label ("READ-ONLY"). The label is shown as typed, brackets included, and brought down to one line if written by hand over several; the level follows `F3`. Without protection, no banner: the layout stays exactly what it was in earlier versions. -- **Status bar**: connected cluster, current user, "request in progress..." status during the call, then HTTP code + response time once the request completes. From the first second on, the running message counts the seconds and says how to abandon the request (`request in progress... 12 s — Esc to abandon`, §3.2), updated every second — unless something else has been written to the line since (a save, an error), which it doesn't cover. The detected distribution and version, in short form (`ES 9.5.4`, `OS 2.19.6`), **take the place of the "Cluster" caption** in front of the URL rather than being added to the line: on an 80-column terminal the line has no room to spare. **The message comes first**: it is often the only sign of what just happened (a write refused in read-only, a send cancelled). When the line doesn't fit, the user goes first, then the URL is cut short (`https://es-prod.example.test:9…`), and as a last resort the cluster goes too; the message itself is only cut short, with a `…`, when it doesn't fit alone. Until now, a realistic URL and user name left the message a few columns on an 80-column terminal, and it was cut from its first word. +- **Header**: the first line of the main screen says which cluster this is: the name of the tool, then a badge with the detected distribution and version in short form (`ES 9.5.4`, `OS 2.19.6`, teal for the former and blue for the latter, so that two clusters can be told apart at a glance with `Ctrl+O`; the "Cluster" caption when it isn't known), the URL, and the user at the far right. When it doesn't fit, the name of the tool goes first, then the user, then the URL is cut short (`https://es-prod.ex…`), and last it goes too. On a protected cluster (§5), **the whole line** changes color and the name of the tool gives way to the label and the level ("PROD · read-only"), or the level alone, in capitals, without a label ("READ-ONLY"): red background with "writes need confirmation", since writes remain possible, yellow with "read-only". They stay whatever the width. The label is shown as typed, brackets included, and brought down to one line if written by hand over several; the level follows `F3`. +- **Status bar**: the last line of the screen. "request in progress..." status during the call, then HTTP code + response time once the request completes. From the first second on, the running message counts the seconds and says how to abandon the request (`request in progress... 12 s — Esc to abandon`, §3.2), updated every second — unless something else has been written to the line since (a save, an error), which it doesn't cover. **The message comes first**: it is often the only sign of what just happened (a write refused in read-only, a send cancelled). It takes the left of the line, and the shortcuts what it leaves on the right: as many as fit, in the order of the catalog, none cut in two. The message itself is only cut short, with a `…`, when it doesn't fit alone. With the header, that makes the same two lines as the former status line and help bar: the panels kept their height on an 80×24 terminal. +- **More below**: while the editor, the result or the help screen has more to show below, a `▼` sits on its bottom border, next to the right corner, and goes away at the end. Only what scrolls is marked, and what counts is the rows displayed, wrapping included. For the result and the help, `TextView` is asked by scrolling one row down and back (`scrollPanel`): counting its wrapped rows would wrap the whole text on the spot, which freezes the interface on a large result. +- **Theme**: fixed colors on a dark background of their own, the same whatever the terminal's theme (`ui/theme.go`); a terminal without 24-bit colors gets the closest ones it has, and `NO_COLOR` is honored (both by tcell). Red and yellow say something about the cluster or the last request and nothing else; the rest of the chrome keeps to blue and gray. The panel with the focus has a thick blue border and the other a thin gray one: its shape as well as its color, so that it still shows without colors. - **Help screen (`F1`)**: a popup overlaid on the layout (centered, height proportional to the terminal, scrollable if content overflows), opening on TermDevTools' version (the one `--version` prints) and the connected cluster's distribution and version in long form (`Elasticsearch 9.5.4`), the latter only when detected — what a bug report asks for first; then reminding how the two panels work, the list of shortcuts (§4), and the location of the files the user may create or edit (§9.1). Closes with `Esc`, with no effect on the editor's or result's content. ### 3.2 Editor (left panel) @@ -99,7 +101,7 @@ On launch, a connection screen lists the URLs of known clusters (no separate nam - Recipes that exist in two forms (index lifecycle: ILM on Elasticsearch, ISM on OpenSearch) share a title: only the form that applies is listed. When the cluster couldn't be identified, both are, each followed by the clusters it is meant for. - **The user's own recipes** are listed with the built-in ones, marked as added, the preview's border naming their file. Format, locations and merge rules: §9.1 and §9.5. - **Reloading (`F7`)**: re-reads everything the user or the team maintains by hand — the cluster's variables, recipes, endpoints — and forgets the `_cat` columns learned from the cluster. The status bar sums up what was loaded, or names the first problem found (file and line) and how many others there are. -- **Syntax highlighting: dropped, not just deferred** — `tview.TextArea` (the library's only widget supporting multi-line editing: cursor, selection, undo, clipboard) explicitly does not support multi-color text (official documentation: *"Multi-color text is not supported"*), unlike the read-only `TextView` used on the right (§3.3). Getting it would require rebuilding a custom editor on top of a colorable `TextView` (cursor/selection/editing reimplemented by hand) — judged disproportionate for this tool. Confirmed that no newer version of tview lifts this limitation (v0.42.0 = latest version as of 2026-08-12). +- **Syntax highlighting: dropped, not just deferred** — `tview.TextArea` (the library's only widget supporting multi-line editing: cursor, selection, undo, clipboard) explicitly does not support multi-color text (official documentation: *"Multi-color text is not supported"*), unlike the read-only `TextView` used on the right (§3.3). Getting it would require rebuilding a custom editor on top of a colorable `TextView` (cursor/selection/editing reimplemented by hand) — judged disproportionate for this tool. Confirmed that no newer version of tview lifts this limitation (v0.42.0 = latest version as of 2026-08-12). Two things are colored all the same, which take no editor of their own: the method of each request line (teal for `GET`, blue for `POST` and `PUT`, red for `DELETE`) and comments, by changing the color of the cells `TextArea` has just drawn (`Editor.paintRequests`, on the display rows the gutter already computes). The selection keeps its colors. - **Auto-completion (`Tab` or `F10`, left panel focused)**: offered only when the cursor is in the middle of typing a `METHOD partial_endpoint` line (not in a JSON body or anywhere else — `Tab` keeps its standard tab-insertion behavior there; `F10` has no such fallback meaning and is simply swallowed). `F10` was added after confirming Tab itself gets swallowed before reaching the app on some terminals (see §4); no fallback modifier detection can work around a key that never reaches the app at all. Case-insensitive comparison of the typed prefix against the **list of endpoints known for the connected cluster**, centered on administration/operations (`_cat/*`, `_cluster/*`, `_nodes/*`, index admin endpoints...) — no dynamic discovery of real index names (noted as an idea for a future version, see §7). - 0 match → message in the status bar, nothing else. - 1 match → direct completion, no further interaction. @@ -131,7 +133,7 @@ On launch, a connection screen lists the URLs of known clusters (no separate nam ## 4. Keyboard shortcuts -A help bar under the status bar reminds the shortcuts; `F1` lists them all. +The status bar reminds the main shortcuts, as far as its message leaves room for them; `F1` lists them all. | Action | Key | Status | |---|---|---| @@ -193,9 +195,9 @@ A help bar under the status bar reminds the shortcuts; `F1` lists them all. - **Keeping it safe is the user's job**: the file, or whatever sets the variable, lies outside what the program writes; whoever can read it can connect. `F9` keeps its placeholder (above). Like the URL it is sent to, these keys come from `config.yaml`: a file taken over from someone else deserves a look at them before connecting. - Checked against a real Elasticsearch with security on (`ui/secret_integration_test.go`): Basic Auth, API key and Bearer token, each from a variable and from a file. - **Production guardrails**: a protection level per cluster, chosen in the connection form (§3.0) and saved in `config.yaml` (`protection`, §9.2), against a slip on a cluster that matters — a request sent with one `Ctrl+E` to production instead of the test cluster. - - **`none`** (default): everything is sent, with no banner, as before. - - **`confirm`**: red banner (§3.1). A request that writes opens a "Write to a protected cluster" popup, 70 columns wide, naming the cluster (label and URL) and the resolved request (the body stays in sight in the editor). A path longer than 120 characters is shortened without losing its API, what says what the request does: the query string goes first, then what precedes the API — a long list of indices — is cut in its middle, its first and last names staying in sight (`logs-2026.10.01,…,logs-2026.10.15/_delete_by_query`), with two buttons: "Cancel", which has the focus, and "Send". `Enter` pressed out of habit or `Esc` sends nothing, and the status bar says so; only "Send" (`Tab` or `→`, then `Enter`; the arrows don't go round from one end of the row to the other) sends the request, as it was resolved on `Ctrl+E`. No letter triggers sending. While the popup is open, the other shortcuts have no effect, except `Ctrl+C`. - - **`read_only`**: yellow banner. A request that writes isn't sent; the status bar names the request and says how to allow it (connect again with "writes need confirmation"), and the right panel doesn't change. + - **`none`** (default): everything is sent, under the plain header, as before. + - **`confirm`**: red header (§3.1). A request that writes opens a "Write to a protected cluster" popup, 70 columns wide, naming the cluster (label and URL) and the resolved request (the body stays in sight in the editor). A path longer than 120 characters is shortened without losing its API, what says what the request does: the query string goes first, then what precedes the API — a long list of indices — is cut in its middle, its first and last names staying in sight (`logs-2026.10.01,…,logs-2026.10.15/_delete_by_query`), with two buttons: "Cancel", which has the focus, and "Send". `Enter` pressed out of habit or `Esc` sends nothing, and the status bar says so; only "Send" (`Tab` or `→`, then `Enter`; the arrows don't go round from one end of the row to the other) sends the request, as it was resolved on `Ctrl+E`. No letter triggers sending. While the popup is open, the other shortcuts have no effect, except `Ctrl+C`. + - **`read_only`**: yellow header. A request that writes isn't sent; the status bar names the request and says how to allow it (connect again with "writes need confirmation"), and the right panel doesn't change. - **Read or write** (`esclient.IsRead`): the resolved method and path decide — after variable substitution, since a variable may hold the API itself; the body isn't read. The path classified is the one sent: like Go's HTTP client, what follows a `#` is removed (a fragment, never sent: classifying the whole of `_security/user/bob#/_has_privileges` would take for a read the `POST _security/user/bob` that is sent), then the query string. `GET` reads, except `_refresh`, `_flush` and `_flush/synced`, which both distributions also take as `GET`, and OpenSearch's SQL and PPL (`_plugins/_sql`, `_plugins/_ppl` and their `_opendistro` equivalents), which read their query from the URL too; `PUT` and `DELETE` write, whatever the path; a `POST` only reads if the API part of its path — from the first segment that starts with `_` without being `_all` — matches a pattern of the built-in allowlist as a whole (`_search`, `_count`, `_msearch`, `_mget`, `_field_caps`, `_analyze`, `_explain/*`, `_ingest/pipeline/*/_simulate`, `_sql`, `_query`, `_pit`…, full list in `esclient/readonly.go`), where `*` stands for exactly one segment, neither empty nor holding an encoded `/`. A path holding a `.` or `..` segment, even encoded, always writes: a proxy normalizing paths would send another one (`_mvt/../../logs/_bulk` would become `logs/_bulk`). Everything else writes, including what loses no data but acts on the cluster (`_refresh`, `_flush`, `_forcemerge`, `_cache/clear`, `_cluster/reroute`): `confirm` covers every write, a `_bulk` or a `PUT _mapping` being able to break as much as a `DELETE`. An allowlist rather than a denylist, because a forgotten read is blocked for nothing (a nuisance) whereas a forgotten write would go through (a danger). One list for both distributions: a pattern only Elasticsearch knows, sent to OpenSearch, just gets a 404 there. Left out on purpose: OpenSearch's `_plugins/_sql`, which runs a `DELETE` statement when `plugins.sql.delete.enabled` is set — something that can't be known from here —, and `_plugins/_ppl`, whose machine-learning commands leave a doubt. A `_` written as `%5F` isn't decoded: the request is classified as a write. The list can't be extended by the user; a forgotten read gets fixed in a release. - **What isn't affected**: `F9` (nothing is sent), `F4`, completion and the `GET _cat/?help` it sends, recipes, the connection's `GET /`. Nor is load: an expensive search or a `_nodes/hot_threads` are reads. - **Set at connection**: to change level, quit and connect again (requests are saved per cluster) — `Ctrl+O` goes back to the connection already open without making it again (§3.0). No shortcut lifts the protection mid-session: a guard that comes off with one key no longer protects against reflexes. @@ -215,7 +217,7 @@ A help bar under the status bar reminds the shortcuts; `F1` lists them all. What isn't done, by choice or not yet: - Dynamic auto-completion of the connected cluster's real index names (completion is limited to known endpoints and `_cat` columns, see §3.2) — item 10 below. -- Syntax highlighting in the editor (dropped, see §3.2). +- Syntax highlighting in the editor, beyond methods and comments (dropped, see §3.2). **Candidates inspired by Kibana Dev Tools** — all shipped as of this writing, roughly in decreasing-interest order as originally proposed: ~~Reformat the request body's JSON in place~~ (Kibana's "auto indent") as `F4` (§4); ~~Show the response's HTTP headers~~ as part of the result panel (§3.3); ~~"Copy as cURL"~~ as `F9` (§4) — secrets redacted, see `esclient.Client.CurlCommand`; ~~Line numbers in the editor gutter~~ as part of the editor panel (§3.2); ~~Reusable variables~~ as `${name}` substitution, reloaded with `F7` (§3.2, §9.1); ~~Auto-closing brackets/quotes~~ while typing in the editor (§3.2, `ui/autoclose.go`). @@ -279,7 +281,7 @@ default_client_cert_dir: "" # the same for the client cert/key fields (mTLS) — clusters: - url: https://es-prod.example.com:9200 protection: confirm # optional: none (default, key then left out) | confirm | read_only (§5) — an unknown value counts as read_only - label: PROD # optional: names the cluster on a protected cluster's banner (§3.1) + label: PROD # optional: names the cluster in a protected cluster's header (§3.1) auth_type: basic # none | basic | api_key | bearer | mtls (a Bearer token is never stored) username: svc_devtools # used if auth_type: basic (password never stored) api_key_id: "" # used if auth_type: api_key (secret never stored); taken from the key when it is entered in its encoded form @@ -343,7 +345,9 @@ termdevtools/ │ ├── completion.go // prefix filtering, h=/s= detection for _cat commands │ ├── recipes.go // recipe catalog popup (F8) │ ├── result.go // right panel (TextView + JSON highlighting) -│ └── statusbar.go // status bar + shortcuts help bar +│ ├── header.go // first line of the main screen: product, URL, user, protection +│ ├── theme.go // the palette, applied to tview and to the color tags +│ └── statusbar.go // last line of the main screen: message + shortcuts ├── tools/ // developer tools, not shipped │ ├── genrefdata/ // generates refdata/data/endpoints.txt and cat_columns.txt │ └── testclusters.sh // starts/stops the real clusters the integration tests run against diff --git a/SPEC_fr.md b/SPEC_fr.md index 10217ac..34ad744 100644 --- a/SPEC_fr.md +++ b/SPEC_fr.md @@ -42,7 +42,7 @@ Au lancement, un écran de connexion liste les URLs des clusters connus (pas de - "API Key" → l'identifiant de la clé, puis son secret - "jeton Bearer" → uniquement le jeton - "certificat client (mTLS)" → uniquement les champs certificat (masque username/mot de passe) ; masqués eux aussi si l'URL est en `http://` (cf. ci-dessus) -- **Clé d'API sous sa forme `encoded`** : le champ du secret accepte aussi la clé entière telle que Kibana et l'API de création l'affichent en premier — `base64(identifiant:secret)`. Elle est reconnue à sa forme (deux parties de l'alphabet des clés Elasticsearch autour d'un `:`, une fois décodée), y compris sans son remplissage `=` final ou collée avec un saut de ligne. L'identifiant qu'elle contient remplace alors celui du formulaire, vide ou non : c'est lui qui est enregistré dans `config.yaml` et affiché dans la barre de statut. Un secret seul sans identifiant est refusé avant tout envoi, avec un message qui dit quoi saisir. +- **Clé d'API sous sa forme `encoded`** : le champ du secret accepte aussi la clé entière telle que Kibana et l'API de création l'affichent en premier — `base64(identifiant:secret)`. Elle est reconnue à sa forme (deux parties de l'alphabet des clés Elasticsearch autour d'un `:`, une fois décodée), y compris sans son remplissage `=` final ou collée avec un saut de ligne. L'identifiant qu'elle contient remplace alors celui du formulaire, vide ou non : c'est lui qui est enregistré dans `config.yaml` et affiché dans l'en-tête. Un secret seul sans identifiant est refusé avant tout envoi, avec un message qui dit quoi saisir. - **Jeton Bearer** : collé tel quel ; les espaces ou le saut de ligne qui l'entourent, et le mot `Bearer` s'il a été copié avec, sont retirés. - **Champ actif mis en évidence** : le champ ayant le focus est affiché en couleurs inversées (fond/texte), pour rester repérable même quand le seul curseur clignotant ne suffit pas. - **Terminal de 24 lignes** : le formulaire le plus long (https avec certificat client) n'y tient qu'en retirant la ligne vide entre deux champs ; elle n'est retirée que dans ce cas, pour que les boutons restent à l'écran. @@ -50,7 +50,7 @@ Au lancement, un écran de connexion liste les URLs des clusters connus (pas de - Dans les deux cas, une fois la connexion réussie, l'entrée (nouvelle ou existante) est déplacée/insérée en **première position** de la liste `clusters` dans `config.yaml` — aucun secret n'y est jamais écrit. - **Détection** : la réponse au `GET /` qui valide la connexion indique aussi quelle distribution et quelle version le cluster exécute (§5). Rien à choisir ni à saisir ; un cluster qui ne peut pas être identifié est connecté malgré tout. - **Une tentative à la fois** : une tentative abandonnée (`Echap` ou le bouton Annuler) ou supplantée par une plus récente est ignorée quand sa réponse finit par arriver — un cluster lent à répondre ne peut pas remplacer la session ouverte entre-temps sur un autre, et appuyer deux fois sur Se connecter n'ouvre qu'une session. -- **Ce qui est refusé avant toute connexion** : une URL contenant des identifiants (`https://utilisateur:motdepasse@hôte`). L'URL est la seule chose d'un cluster qui soit enregistrée et affichée telle quelle — dans `config.yaml`, dans la barre de statut, dans les commandes `curl` copiées : le mot de passe s'y retrouverait. Le message renvoie à l'authentification Basic Auth. +- **Ce qui est refusé avant toute connexion** : une URL contenant des identifiants (`https://utilisateur:motdepasse@hôte`). L'URL est la seule chose d'un cluster qui soit enregistrée et affichée telle quelle — dans `config.yaml`, dans l'en-tête, dans les commandes `curl` copiées : le mot de passe s'y retrouverait. Le message renvoie à l'authentification Basic Auth. - **Ce qui n'est pas une connexion** : une réponse `3xx`. Les redirections ne sont jamais suivies (§5) ; l'écran affiche le code et l'adresse vers laquelle la réponse renvoie, à corriger dans l'URL. - **Proxy** : quand la connexion passe par un proxy (§5), l'écran le nomme avant d'envoyer quoi que ce soit — « Connexion en cours via le proxy … », suivi de sa provenance (`HTTPS_PROXY`, `HTTP_PROXY` ou `config.yaml`). Si la tentative échoue, le proxy est rappelé **devant** le détail de l'erreur — souvent plus long que la place disponible —, avec la façon de s'en passer quand il vient de l'environnement. La zone de message fait trois lignes pour cela. Un code HTTP reçu à travers un proxy est annoncé de la même façon : la réponse peut être celle du proxy (`407`, `403`). Un proxy inutilisable (§5) arrête la tentative avant tout envoi. - Une fois la connexion effectuée, on travaille sur un cluster à la fois, au sein d'un layout général inspiré des Dev Tools de Kibana. @@ -72,8 +72,10 @@ Au lancement, un écran de connexion liste les URLs des clusters connus (pas de Un souci apparenté mais distinct est apparu plus tard : `TextArea.Select()` (utilisé pour les résultats de recherche du panneau gauche) est bien à l'abri du problème de wrap — c'est justement la méthode par décalage absolu décrite ci-dessus — mais sa propre documentation est explicite : elle « préserve » le décalage de défilement, contrairement au déplacement normal du curseur (frappe, flèches), que tview fait défiler automatiquement à l'écran. Un résultat hors de la zone visible était donc bien sélectionné en interne, mais restait invisible à l'écran — indiscernable, du point de vue de l'utilisateur, d'une recherche « qui atterrit au mauvais endroit ». Corrigé par `Editor.scrollToCursor` (`ui/editor.go`), qui reproduit la logique de défilement automatique interne de tview (non exposée) via la ligne affichée de `GetCursor` (correcte ici, contrairement à un usage en ligne logique) combinée aux méthodes publiques `GetOffset`/`SetOffset`. Un rapport ultérieur — la recherche *sélectionnait carrément le mauvais texte* (pas juste hors écran, ex. un résultat décalé de quelques caractères par rapport au vrai match) — s'est révélé être un second bug, plus fondamental, dans cette même méthode par décalage, sans aucun rapport avec le wrap : `TextArea.GetSelection`/`Select`/`Replace` comptent tous en **octets UTF-8** en interne (confirmé en lisant le code source de tview — le suivi de position avance de `len(cluster)`, la longueur en octets d'une chaîne), un fait qu'aucune de leurs docs ne précise. Le calcul de décalage propre à ce code (`findNext` dans `ui/search.go`, `lineColAt`/`CompletionPrefix` dans `ui/editor.go`) comptait en **runes** (`len([]rune(...))`) partout à la place. Les deux concordent exactement tant que tout caractère précédant la position visée est de l'ASCII sur un seul octet — et divergent silencieusement, de tous les octets supplémentaires accumulés, dès qu'un caractère UTF-8 multi-octet (une lettre accentuée, typiquement) apparaît plus tôt dans le texte. Pas un crash, juste un résultat qui semble faux : une recherche qui sélectionne quelques caractères à côté du vrai match, une complétion d'endpoint qui remplace la mauvaise portion, et — puisque `CursorLine` repose sur le même `lineColAt` — potentiellement **`Ctrl+E` qui cible la mauvaise requête** dès qu'une ligne précédente contenait du texte non-ASCII. Corrigé en faisant compter tout le calcul de décalage propre à ce code en longueur d'octets (`len(s)`) plutôt qu'en runes, pour coller exactement à la convention de tview ; voir `TestLineColAtByteOffsets` et `TestFindNextByteOffsets`, qui échouent tous deux avec le code d'avant le correctif sur un contenu reproduisant le rapport d'origine. Dernier cas du même ordre : la recherche ignore la casse, et mettre tout le texte en minuscules peut en changer la longueur en octets (« İ », deux octets, devient « i̇ », trois) — la casse est donc repliée lettre par lettre, uniquement quand la minuscule occupe le même nombre d'octets (`foldCase`, `ui/search.go`). -- **Bandeau de protection** : sur un cluster protégé (§5), une ligne pleine largeur au-dessus des deux panneaux — fond rouge en « confirmation des écritures », puisque des écritures restent possibles, jaune en « lecture seule » — donne le libellé et le niveau (« PROD · lecture seule »), ou le niveau seul, en capitales, sans libellé (« LECTURE SEULE »). Le libellé est affiché tel que saisi, crochets compris, et ramené à une ligne s'il a été écrit à la main sur plusieurs ; le niveau suit `F3`. Sans protection, pas de bandeau : la mise en page reste exactement celle des versions précédentes. -- **Barre de statut** : cluster connecté, utilisateur courant, statut "requête en cours..." pendant l'appel, puis code HTTP + temps de réponse une fois la requête terminée. Dès la première seconde, le message de la requête en cours compte les secondes et dit comment l'abandonner (`requête en cours... 12 s — Echap pour abandonner`, §3.2), mis à jour chaque seconde — sauf si autre chose a été écrit sur la ligne entre-temps (une sauvegarde, une erreur), qu'il ne recouvre pas. La distribution et la version détectées, sous forme courte (`ES 9.5.4`, `OS 2.19.6`), **prennent la place du libellé « Cluster »** devant l'URL au lieu de s'ajouter à la ligne : sur un terminal de 80 colonnes la ligne n'a pas de place à perdre. **Le message passe avant le reste** : c'est souvent le seul signe de ce qui vient de se passer (une écriture refusée en lecture seule, un envoi annulé). Quand la ligne ne tient pas, l'utilisateur disparaît d'abord, puis l'URL est raccourcie (`https://es-prod.example.test:9…`), et en dernier recours le cluster disparaît aussi ; le message n'est coupé, avec un `…`, que s'il ne tient pas seul. Jusqu'ici, une URL et un nom d'utilisateur réalistes ne laissaient au message que quelques colonnes à 80 colonnes, et il était coupé dès son premier mot. +- **En-tête** : la première ligne de l'écran principal dit de quel cluster il s'agit : le nom de l'outil, puis un badge avec la distribution et la version détectées en forme courte (`ES 9.5.4`, `OS 2.19.6`, sarcelle pour l'une et bleu pour l'autre, pour distinguer deux clusters d'un coup d'œil avec `Ctrl+O` ; l'intitulé « Cluster » si elles ne sont pas connues), l'URL, et l'utilisateur tout à droite. Quand elle ne tient pas, le nom de l'outil part d'abord, puis l'utilisateur, puis l'URL est raccourcie (`https://es-prod.ex…`), et en dernier elle part aussi. Sur un cluster protégé (§5), **toute la ligne** change de couleur et le nom de l'outil laisse la place au libellé et au niveau (« PROD · lecture seule »), ou au niveau seul, en capitales, sans libellé (« LECTURE SEULE ») : fond rouge en « confirmation des écritures », puisque des écritures restent possibles, jaune en « lecture seule ». Ils restent quelle que soit la largeur. Le libellé s'affiche tel que saisi, crochets compris, et ramené à une ligne s'il a été écrit à la main sur plusieurs ; le niveau suit `F3`. +- **Barre de statut** : la dernière ligne de l'écran. Statut « requête en cours... » pendant l'appel, puis code HTTP + temps de réponse une fois la requête terminée. Dès la première seconde, le message en cours compte les secondes et dit comment abandonner la requête (`requête en cours... 12 s — Echap pour abandonner`, §3.2), mis à jour chaque seconde — sauf si autre chose a été écrit sur la ligne entre-temps (une sauvegarde, une erreur), qu'il ne recouvre pas. **Le message passe en premier** : c'est souvent le seul signe de ce qui vient de se passer (une écriture refusée en lecture seule, un envoi annulé). Il occupe la gauche de la ligne, et les raccourcis ce qu'il laisse à droite : autant qu'il en tient, dans l'ordre du catalogue, aucun coupé en deux. Le message lui-même n'est raccourci, avec un `…`, que s'il ne tient pas seul. Avec l'en-tête, cela fait les deux mêmes lignes que l'ancienne ligne de statut et la barre d'aide : les panneaux ont gardé leur hauteur sur un terminal 80×24. +- **Suite en dessous** : tant que l'éditeur, le résultat ou l'écran d'aide a de quoi afficher plus bas, un `▼` se place sur sa bordure inférieure, à côté du coin droit, et disparaît à la fin. Seul ce qui défile est signalé, et ce qui compte, ce sont les lignes affichées, retour à la ligne compris. Pour le résultat et l'aide, `TextView` est interrogé en descendant d'une ligne puis en revenant (`scrollPanel`) : compter ses lignes affichées reviendrait à découper tout le texte d'un coup, ce qui fige l'interface sur un gros résultat. +- **Thème** : des couleurs fixes sur un fond sombre qui lui est propre, les mêmes quel que soit le thème du terminal (`ui/theme.go`) ; un terminal sans couleurs 24 bits reçoit les plus proches qu'il ait, et `NO_COLOR` est respecté (les deux par tcell). Le rouge et le jaune disent quelque chose du cluster ou de la dernière requête, et rien d'autre ; le reste de l'habillage s'en tient au bleu et au gris. Le panneau qui a le focus a une bordure épaisse et bleue, l'autre une bordure fine et grise : sa forme autant que sa couleur, pour qu'il se voie encore sans couleurs. - **Écran d'aide (`F1`)** : popup superposé au layout (centré, hauteur proportionnelle au terminal, scrollable si le contenu déborde), s'ouvrant sur la version de TermDevTools (celle qu'affiche `--version`) et la distribution et la version du cluster connecté en forme longue (`Elasticsearch 9.5.4`), cette dernière seulement si elle a été détectée — ce qu'un rapport de bug demande en premier ; puis rappelant le fonctionnement des deux panneaux, la liste des raccourcis (§4) et l'emplacement des fichiers que l'utilisateur peut créer ou modifier (§9.1). Se ferme avec `Echap`, sans effet sur le contenu de l'éditeur ni du résultat. ### 3.2 Éditeur (panneau gauche) @@ -99,7 +101,7 @@ Au lancement, un écran de connexion liste les URLs des clusters connus (pas de - Les recettes qui existent sous deux formes (cycle de vie des index : ILM sur Elasticsearch, ISM sur OpenSearch) portent le même titre : seule la forme qui s'applique est listée. Quand le cluster n'a pas pu être identifié, les deux le sont, chacune suivie des clusters auxquels elle est destinée. - **Les recettes de l'utilisateur** sont listées avec celles du binaire, signalées comme ajoutées, la bordure de l'aperçu nommant leur fichier. Format, emplacements et règles de fusion : §9.1 et §9.5. - **Rechargement (`F7`)** : relit tout ce que l'utilisateur ou l'équipe maintient à la main — les variables du cluster, les recettes, les endpoints — et oublie les colonnes `_cat` apprises du cluster. La barre de statut résume ce qui a été chargé, ou nomme le premier problème rencontré (fichier et ligne) et le nombre des autres. -- **Coloration syntaxique : écartée, pas seulement différée** — `tview.TextArea` (seul widget de la bibliothèque permettant l'édition multi-ligne : curseur, sélection, undo, presse-papiers) ne supporte explicitement pas le texte multi-couleur (documentation officielle : *"Multi-color text is not supported"*), contrairement à `TextView` utilisé en lecture seule à droite (§3.3). L'obtenir nécessiterait de reconstruire un éditeur maison au-dessus d'un `TextView` colorable (curseur/sélection/édition réimplémentés à la main) — jugé disproportionné pour cet outil. Vérifié qu'aucune version plus récente de tview ne lève cette limite (v0.42.0 = dernière version au 2026-08-12). +- **Coloration syntaxique : écartée, pas seulement différée** — `tview.TextArea` (seul widget de la bibliothèque permettant l'édition multi-ligne : curseur, sélection, undo, presse-papiers) ne supporte explicitement pas le texte multi-couleur (documentation officielle : *"Multi-color text is not supported"*), contrairement à `TextView` utilisé en lecture seule à droite (§3.3). L'obtenir nécessiterait de reconstruire un éditeur maison au-dessus d'un `TextView` colorable (curseur/sélection/édition réimplémentés à la main) — jugé disproportionné pour cet outil. Vérifié qu'aucune version plus récente de tview ne lève cette limite (v0.42.0 = dernière version au 2026-08-12). Deux choses sont tout de même colorées, qui ne demandent pas d'éditeur à part : la méthode de chaque ligne de requête (sarcelle pour `GET`, bleu pour `POST` et `PUT`, rouge pour `DELETE`) et les commentaires, en changeant la couleur des cellules que `TextArea` vient de dessiner (`Editor.paintRequests`, sur les lignes affichées que la gouttière calcule déjà). La sélection garde ses couleurs. - **Auto-complétion (`Tab` ou `F10`, focus panneau gauche)** : proposée uniquement quand le curseur est en train de taper une ligne `MÉTHODE endpoint_partiel` (pas dans un corps JSON ni ailleurs — `Tab` y garde son comportement standard d'insertion d'une tabulation ; `F10` n'a pas cette signification de repli et est simplement absorbé sans effet). `F10` a été ajouté après avoir confirmé que `Tab` lui-même est absorbé avant d'atteindre l'appli sur certains terminaux (cf. §4) ; aucune logique de repli par modificateur ne peut contourner une touche qui n'atteint jamais l'appli. Comparaison insensible à la casse du préfixe tapé contre la **liste des endpoints connus pour le cluster connecté**, centrée sur l'administration/exploitation (`_cat/*`, `_cluster/*`, `_nodes/*`, endpoints d'admin d'index...) — pas de découverte dynamique des noms d'index réels (idée notée pour une version future, cf. §7). - 0 correspondance → message en status bar, rien d'autre. - 1 correspondance → complétion directe, sans interaction supplémentaire. @@ -131,7 +133,7 @@ Au lancement, un écran de connexion liste les URLs des clusters connus (pas de ## 4. Raccourcis clavier -Une barre d'aide, sous la barre d'état, rappelle les raccourcis ; `F1` en donne la liste complète. +La barre de statut rappelle les principaux raccourcis, autant que son message leur laisse de place ; `F1` en donne la liste complète. | Action | Touche | Statut | |---|---|---| @@ -193,9 +195,9 @@ Une barre d'aide, sous la barre d'état, rappelle les raccourcis ; `F1` en donne - **Sa garde revient à l'utilisateur** : le fichier, ou ce qui définit la variable, est hors de ce qu'écrit le programme ; qui peut le lire peut se connecter. `F9` garde son placeholder (ci-dessus). Comme l'URL à laquelle il est envoyé, ces clés viennent de `config.yaml` : un fichier repris de quelqu'un d'autre mérite qu'on les relise avant de se connecter. - Vérifié sur un Elasticsearch réel dont la sécurité est activée (`ui/secret_integration_test.go`) : Basic Auth, API key et jeton Bearer, chacun depuis une variable et depuis un fichier. - **Garde-fous de production** : un niveau de protection par cluster, choisi dans le formulaire de connexion (§3.0) et enregistré dans `config.yaml` (`protection`, §9.2), contre l'erreur de manipulation sur un cluster qui compte — une requête envoyée d'un `Ctrl+E` sur la production au lieu du cluster de test. - - **`none`** (défaut) : tout est envoyé, sans bandeau, comme avant. - - **`confirm`** : bandeau rouge (§3.1). Une requête qui écrit ouvre une fenêtre « Écriture sur un cluster protégé », large de 70 colonnes, qui nomme le cluster (libellé et URL) et la requête résolue (le corps reste visible dans l'éditeur). Un chemin de plus de 120 caractères est raccourci sans perdre son API, ce qui dit ce que fait la requête : la chaîne de requête disparaît d'abord, puis ce qui précède l'API — une longue liste d'index — est coupé en son milieu, ses premier et dernier noms restant visibles (`logs-2026.10.01,…,logs-2026.10.15/_delete_by_query`), avec deux boutons : « Annuler », qui a le focus, et « Envoyer ». `Entrée` pressé par réflexe ou `Echap` n'envoie rien, et la barre de statut le dit ; seul « Envoyer » (`Tab` ou `→`, puis `Entrée` ; les flèches ne reviennent pas d'un bouton à l'autre en bout de rangée) envoie la requête, telle qu'elle a été résolue au `Ctrl+E`. Aucune lettre ne déclenche l'envoi. Tant que la fenêtre est ouverte, les autres raccourcis sont sans effet, sauf `Ctrl+C`. - - **`read_only`** : bandeau jaune. Une requête qui écrit n'est pas envoyée ; la barre de statut nomme la requête et dit comment l'autoriser (se reconnecter en « confirmation des écritures »), et le panneau de droite ne change pas. + - **`none`** (défaut) : tout est envoyé, sous l'en-tête ordinaire, comme avant. + - **`confirm`** : en-tête rouge (§3.1). Une requête qui écrit ouvre une fenêtre « Écriture sur un cluster protégé », large de 70 colonnes, qui nomme le cluster (libellé et URL) et la requête résolue (le corps reste visible dans l'éditeur). Un chemin de plus de 120 caractères est raccourci sans perdre son API, ce qui dit ce que fait la requête : la chaîne de requête disparaît d'abord, puis ce qui précède l'API — une longue liste d'index — est coupé en son milieu, ses premier et dernier noms restant visibles (`logs-2026.10.01,…,logs-2026.10.15/_delete_by_query`), avec deux boutons : « Annuler », qui a le focus, et « Envoyer ». `Entrée` pressé par réflexe ou `Echap` n'envoie rien, et la barre de statut le dit ; seul « Envoyer » (`Tab` ou `→`, puis `Entrée` ; les flèches ne reviennent pas d'un bouton à l'autre en bout de rangée) envoie la requête, telle qu'elle a été résolue au `Ctrl+E`. Aucune lettre ne déclenche l'envoi. Tant que la fenêtre est ouverte, les autres raccourcis sont sans effet, sauf `Ctrl+C`. + - **`read_only`** : en-tête jaune. Une requête qui écrit n'est pas envoyée ; la barre de statut nomme la requête et dit comment l'autoriser (se reconnecter en « confirmation des écritures »), et le panneau de droite ne change pas. - **Lecture ou écriture** (`esclient.IsRead`) : la méthode et le chemin résolus en décident — après substitution des variables, puisqu'une variable peut porter l'API elle-même ; le corps n'est pas lu. Le chemin classé est celui qui part : comme le client HTTP de Go, on retire ce qui suit un `#` (un fragment, jamais envoyé : classer `_security/user/bob#/_has_privileges` en entier ferait passer pour une lecture le `POST _security/user/bob` envoyé), puis la chaîne de requête. `GET` lit, sauf `_refresh`, `_flush` et `_flush/synced`, que les deux distributions acceptent aussi en `GET`, et le SQL et le PPL d'OpenSearch (`_plugins/_sql`, `_plugins/_ppl` et leurs équivalents `_opendistro`), qui lisent aussi leur requête dans l'URL ; `PUT` et `DELETE` écrivent, quel que soit le chemin ; un `POST` ne lit que si la partie API de son chemin — à partir du premier segment qui commence par `_` sans être `_all` — correspond entièrement à un motif de la liste blanche intégrée (`_search`, `_count`, `_msearch`, `_mget`, `_field_caps`, `_analyze`, `_explain/*`, `_ingest/pipeline/*/_simulate`, `_sql`, `_query`, `_pit`…, liste complète dans `esclient/readonly.go`), où `*` vaut exactement un segment, ni vide ni porteur d'un `/` encodé. Un chemin qui contient un segment `.` ou `..`, même encodé, écrit toujours : un proxy qui normalise les chemins enverrait autre chose (`_mvt/../../logs/_bulk` deviendrait `logs/_bulk`). Tout le reste écrit, y compris ce qui ne perd aucune donnée mais agit sur le cluster (`_refresh`, `_flush`, `_forcemerge`, `_cache/clear`, `_cluster/reroute`) : `confirm` porte sur toutes les écritures, un `_bulk` ou un `PUT _mapping` pouvant casser autant qu'un `DELETE`. Une liste blanche plutôt qu'une liste noire, parce qu'une lecture oubliée est bloquée à tort (gênant) alors qu'une écriture oubliée passerait (dangereux). Une seule liste pour les deux distributions : un motif propre à Elasticsearch, envoyé à un OpenSearch, y reçoit simplement une 404. Exclus volontairement : `_plugins/_sql` d'OpenSearch, qui exécute un `DELETE` quand `plugins.sql.delete.enabled` est activé — ce qu'on ne peut pas savoir d'ici —, et `_plugins/_ppl`, dont les commandes d'apprentissage automatique laissent un doute. Un `_` encodé (`%5F`) n'est pas décodé : la requête est classée en écriture. La liste n'est pas extensible par l'utilisateur ; une lecture oubliée se corrige dans une version. - **Ce qui n'est pas concerné** : `F9` (rien n'est envoyé), `F4`, la complétion et les `GET _cat/?help` qu'elle envoie, les recettes, le `GET /` de la connexion. La charge non plus : une recherche coûteuse ou un `_nodes/hot_threads` sont des lectures. - **Fixée à la connexion** : pour changer de niveau, on quitte et on se reconnecte (les requêtes sont sauvegardées par cluster) — `Ctrl+O` ramène à la connexion déjà ouverte sans la refaire (§3.0). Pas de raccourci pour lever la protection en cours de session : un garde-fou qui se lève d'une touche ne protège plus du réflexe. @@ -215,7 +217,7 @@ Une barre d'aide, sous la barre d'état, rappelle les raccourcis ; `F1` en donne Ce qui n'est pas fait, par choix ou pas encore : - Auto-complétion dynamique des noms d'index réels du cluster connecté (la complétion se limite aux endpoints connus et aux colonnes `_cat`, cf. §3.2) — item 10 ci-dessous. -- Coloration syntaxique dans l'éditeur (écartée, cf. §3.2). +- Coloration syntaxique dans l'éditeur, au-delà des méthodes et des commentaires (écartée, cf. §3.2). **Candidats inspirés de Kibana Dev Tools** — tous livrés à ce stade, à peu près dans l'ordre d'intérêt décroissant proposé initialement : ~~Reformater sur place le JSON du corps de requête~~ ("auto indent" de Kibana) sous `F4` (§4) ; ~~Afficher les en-têtes HTTP de la réponse~~ dans le panneau de résultat (§3.3) ; ~~"Copier en cURL"~~ sous `F9` (§4) — secrets masqués, cf. `esclient.Client.CurlCommand` ; ~~Numéros de ligne dans la gouttière de l'éditeur~~ intégrés au panneau éditeur (§3.2) ; ~~Variables réutilisables~~ sous forme de substitution `${nom}`, rechargée avec `F7` (§3.2, §9.1) ; ~~Auto-fermeture des accolades/guillemets~~ en tapant dans l'éditeur (§3.2, `ui/autoclose.go`). @@ -279,7 +281,7 @@ default_client_cert_dir: "" # même chose pour les champs cert/clé client (mTLS clusters: - url: https://es-prod.example.com:9200 protection: confirm # facultatif : none (défaut, clé alors omise) | confirm | read_only (§5) — une valeur inconnue vaut read_only - label: PROD # facultatif : nomme le cluster dans le bandeau d'un cluster protégé (§3.1) + label: PROD # facultatif : nomme le cluster dans l'en-tête d'un cluster protégé (§3.1) auth_type: basic # none | basic | api_key | bearer | mtls (un jeton Bearer n'est jamais stocké) username: svc_devtools # utilisé si auth_type: basic (mot de passe jamais stocké) api_key_id: "" # utilisé si auth_type: api_key (secret jamais stocké) ; tiré de la clé quand elle est saisie sous sa forme encoded @@ -343,7 +345,9 @@ termdevtools/ │ ├── completion.go // filtrage par préfixe, détection h=/s= des commandes _cat │ ├── recipes.go // popup du catalogue de recettes (F8) │ ├── result.go // panneau droit (TextView + coloration JSON) -│ └── statusbar.go // barre de statut + barre d'aide raccourcis +│ ├── header.go // première ligne de l'écran principal : produit, URL, utilisateur, protection +│ ├── theme.go // la palette, appliquée à tview et aux balises de couleur +│ └── statusbar.go // dernière ligne de l'écran principal : message + raccourcis ├── tools/ // outils de développement, non livrés │ ├── genrefdata/ // génère refdata/data/endpoints.txt et cat_columns.txt │ └── testclusters.sh // démarre/arrête les clusters réels des tests d'intégration diff --git a/i18n/i18n.go b/i18n/i18n.go index 42bf871..a6aa05d 100644 --- a/i18n/i18n.go +++ b/i18n/i18n.go @@ -93,7 +93,6 @@ type Strings struct { SearchLabel string // Status bar (statusbar.go) - StatusUserCaption string // caption in front of the user StatusClusterCaption string // caption in front of the URL when the cluster's product isn't known StatusIdle string StatusRunning string @@ -259,21 +258,20 @@ var fr = Strings{ HelpViewTitle: " Aide (Echap pour fermer) ", SearchLabel: "Rechercher : ", - StatusUserCaption: "Utilisateur", StatusClusterCaption: "Cluster", StatusIdle: "prêt", StatusRunning: "requête en cours...", StatusResultFmt: "HTTP %d en %s", StatusRunningForFmt: "requête en cours... %d s — Echap pour abandonner", - // Deliberate order: the most essential commands (help, language, quit) - // come first, so they stay visible even on a narrow terminal where the - // end of the line gets cut off (only 1 row is allocated for this bar). + // Deliberate order: what is used all the time comes first, what the + // status bar shows of it depending on the room its message leaves + // (StatusBar.compose): entries are three spaces apart, and never cut. // "Ctrl(/Opt)" flags the shortcuts where Option also works, on macOS, // as an alternative to Ctrl (see HelpContent for why and its limits). - ShortcutsHelpBar: "[gray]F1[white] aide [gray]F3[white] langue [gray]Ctrl+C[white] quitter " + - "[gray]Ctrl+E[white] exécuter [gray]F8[white] recettes [gray]Tab/F10[white] compléter [gray]Ctrl(/Opt)+←/→[white] changer de panneau " + - "[gray]F5/F6[white] redimensionner [gray]Ctrl+F[white] rechercher [gray]Ctrl+S[white] sauvegarder/exporter " + - "[gray]F2[white] copier [gray]F4[white] reformater le JSON [gray]F9[white] copier en cURL [gray]F7[white] recharger vos fichiers", + ShortcutsHelpBar: "[aqua]F1[gray] aide [aqua]Ctrl+E[gray] exécuter [aqua]F8[gray] recettes [aqua]Ctrl+C[gray] quitter " + + "[aqua]F3[gray] langue [aqua]Tab/F10[gray] compléter [aqua]Ctrl(/Opt)+←/→[gray] changer de panneau " + + "[aqua]F5/F6[gray] redimensionner [aqua]Ctrl+F[gray] rechercher [aqua]Ctrl+S[gray] sauvegarder/exporter " + + "[aqua]F2[gray] copier [aqua]F4[gray] reformater le JSON [aqua]F9[gray] copier en cURL [aqua]F7[gray] recharger vos fichiers", ErrLoadFailedFmt: "échec du chargement de %s : %s", ErrNoMatchFound: "aucune occurrence trouvée", @@ -303,7 +301,7 @@ var fr = Strings{ InfoRecipeInsertedFmt: "recette insérée : %s", ErrUnknownVariablesFmt: "variable(s) inconnue(s) : %s", - HelpHeaderFmt: "[yellow]TermDevTools %s[white] — client Elasticsearch et OpenSearch en mode terminal", + HelpHeaderFmt: "[aqua]TermDevTools %s[white] — client Elasticsearch et OpenSearch en mode terminal", HelpClusterFmt: "Cluster : [green]%s[white]", HelpContent: `[green]Panneau gauche[white] : requêtes "MÉTHODE endpoint" + JSON optionnel sur les lignes suivantes. Lignes [gray]#[white] = commentaires. @@ -311,7 +309,7 @@ sur les lignes suivantes. Lignes [gray]#[white] = commentaires. [green]Panneau droit[white] : résultat de la dernière requête — JSON coloré, ou texte brut (ex. réponses _cat/*). -[yellow]Raccourcis clavier[white] +[green]Raccourcis clavier[white] [gray]PuTTY est connu pour mal gérer certains raccourcis : fortement déconseillé. Aucun souci sous macOS/Windows 10+ natifs. En cas de doute, préférez Ctrl+E, Alt+←/→, F5/F6 et Tab/F10.[white] @@ -340,7 +338,7 @@ doute, préférez Ctrl+E, Alt+←/→, F5/F6 et Tab/F10.[white] (chacun garde ses requêtes et sa requête en cours) [aqua]Ctrl+C[white] Quitter (sauvegarde chaque panneau gauche) -[yellow]Fichiers[white] +[green]Fichiers[white] [gray]Rien n'est requis à côté du binaire : recettes et endpoints y sont intégrés. Ces fichiers, tous facultatifs, s'y ajoutent.[white] @@ -455,21 +453,20 @@ var en = Strings{ HelpViewTitle: " Help (Esc to close) ", SearchLabel: "Search: ", - StatusUserCaption: "User", StatusClusterCaption: "Cluster", StatusIdle: "ready", StatusRunning: "request in progress...", StatusResultFmt: "HTTP %d in %s", StatusRunningForFmt: "request in progress... %d s — Esc to abandon", - // Deliberate order: the most essential commands (help, language, quit) - // come first, so they stay visible even on a narrow terminal where the - // end of the line gets cut off (only 1 row is allocated for this bar). + // Deliberate order: what is used all the time comes first, what the + // status bar shows of it depending on the room its message leaves + // (StatusBar.compose): entries are three spaces apart, and never cut. // "Ctrl(/Opt)" flags the shortcuts where Option also works, on macOS, // as an alternative to Ctrl (see HelpContent for why and its limits). - ShortcutsHelpBar: "[gray]F1[white] help [gray]F3[white] language [gray]Ctrl+C[white] quit " + - "[gray]Ctrl+E[white] execute [gray]F8[white] recipes [gray]Tab/F10[white] complete [gray]Ctrl(/Opt)+←/→[white] switch panel " + - "[gray]F5/F6[white] resize [gray]Ctrl+F[white] search [gray]Ctrl+S[white] save/export " + - "[gray]F2[white] copy [gray]F4[white] reformat JSON [gray]F9[white] copy as cURL [gray]F7[white] reload your files", + ShortcutsHelpBar: "[aqua]F1[gray] help [aqua]Ctrl+E[gray] execute [aqua]F8[gray] recipes [aqua]Ctrl+C[gray] quit " + + "[aqua]F3[gray] language [aqua]Tab/F10[gray] complete [aqua]Ctrl(/Opt)+←/→[gray] switch panel " + + "[aqua]F5/F6[gray] resize [aqua]Ctrl+F[gray] search [aqua]Ctrl+S[gray] save/export " + + "[aqua]F2[gray] copy [aqua]F4[gray] reformat JSON [aqua]F9[gray] copy as cURL [aqua]F7[gray] reload your files", ErrLoadFailedFmt: "failed to load %s: %s", ErrNoMatchFound: "no match found", @@ -499,7 +496,7 @@ var en = Strings{ InfoRecipeInsertedFmt: "recipe inserted: %s", ErrUnknownVariablesFmt: "unknown variable(s): %s", - HelpHeaderFmt: "[yellow]TermDevTools %s[white] — terminal-mode Elasticsearch and OpenSearch client", + HelpHeaderFmt: "[aqua]TermDevTools %s[white] — terminal-mode Elasticsearch and OpenSearch client", HelpClusterFmt: "Cluster: [green]%s[white]", HelpContent: `[green]Left panel[white]: "METHOD endpoint" requests + optional JSON on the following lines. Lines starting with [gray]#[white] = comments. @@ -507,7 +504,7 @@ on the following lines. Lines starting with [gray]#[white] = comments. [green]Right panel[white]: result of the last request — colorized JSON, or plain text (e.g. _cat/* responses). -[yellow]Keyboard shortcuts[white] +[green]Keyboard shortcuts[white] [gray]PuTTY is known to mishandle some shortcuts: strongly discouraged. No issues on native macOS/Windows 10+ terminals. When in doubt, prefer Ctrl+E, Alt+←/→, F5/F6, and Tab/F10.[white] @@ -536,7 +533,7 @@ Ctrl+E, Alt+←/→, F5/F6, and Tab/F10.[white] (each keeps its requests and its running request) [aqua]Ctrl+C[white] Quit (auto-saves every left panel) -[yellow]Files[white] +[green]Files[white] [gray]Nothing is required next to the binary: recipes and endpoints are built in. These files, all optional, add to them.[white] diff --git a/parser/parser.go b/parser/parser.go index a31d1e4..dd2687f 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -135,6 +135,12 @@ func collectBody(lines []string, start int) (body []byte, next int) { return []byte(strings.Join(bodyLines, "\n")), i } +// RequestMethod returns the method, in capitals, of a request line. +func RequestMethod(line string) (method string, ok bool) { + method, _, ok = parseRequestLine(line) + return method, ok +} + func parseRequestLine(line string) (method, path string, ok bool) { m := requestLineRe.FindStringSubmatch(line) if m == nil { diff --git a/ui/app.go b/ui/app.go index 2c16ac5..13e8d20 100644 --- a/ui/app.go +++ b/ui/app.go @@ -96,12 +96,11 @@ type App struct { // kept to reload them on demand (F7). reference refdata.Sources // protection is the connected cluster's protection level (one of the - // config.Protection* values) and label its name on the banner (SPEC.md - // §5) — the banner itself nil for an unprotected cluster. clusterURL - // names the cluster when a write is to be confirmed. + // config.Protection* values) and label its name in the header (SPEC.md + // §5). clusterURL names the cluster when a write is to be confirmed. protection string label string - banner *tview.TextView + header *header clusterURL string // confirmVisible is set while a write waits for confirmation // (confirmWrite): every key but Ctrl+C goes to the popup, to its @@ -128,6 +127,7 @@ type App struct { pages *tview.Pages helpView *tview.TextView + helpPanel *scrollPanel helpVisible bool palette *recipePalette @@ -181,7 +181,7 @@ func NewApp(tapp *tview.Application, cr ConnectResult, cfg *config.Config, paths msgs: msgs, editor: NewEditor(msgs), result: NewResultView(msgs), - status: NewStatusBar(cr.Target.Label(), cr.Cluster.URL, cr.DisplayUser, msgs), + status: NewStatusBar(msgs), target: cr.Target, focusedIsEditor: true, editorSearchPos: -1, @@ -228,7 +228,7 @@ func NewApp(tapp *tview.Application, cr ConnectResult, cfg *config.Config, paths a.searchBar.SetDoneFunc(a.handleSearchDone) a.completionList = tview.NewList().ShowSecondaryText(false) - a.completionList.SetBorder(true).SetTitle(msgs.CompletionTitle) + a.completionList.SetBorder(true).SetBorderColor(themeAccent).SetTitle(msgs.CompletionTitle) a.completionList.SetSelectedFunc(func(_ int, mainText, _ string, _ rune) { if a.completionNoMatch { return @@ -292,20 +292,19 @@ func NewApp(tapp *tview.Application, cr ConnectResult, cfg *config.Config, paths // restrictive one, and said so. a.protection, _ = config.NormalizeProtection(cr.Cluster.Protection) a.label = cr.Cluster.Label - a.banner = newProtectionBanner(a.protection, a.label, msgs) + a.header = newHeader(cr.Target, cr.Cluster.URL, cr.DisplayUser, a.protection, a.label, msgs) a.clusterURL = cr.Cluster.URL - a.root = tview.NewFlex().SetDirection(tview.FlexRow) - if a.banner != nil { - a.root.AddItem(a.banner, 1, 0, false) - } - a.root.AddItem(a.mainFlex, 0, 1, true). + a.root = tview.NewFlex().SetDirection(tview.FlexRow). + AddItem(a.header.Widget(), 1, 0, false). + AddItem(a.mainFlex, 0, 1, true). AddItem(a.searchBar, 0, 0, false). AddItem(a.completionList, 0, 0, false). - AddItem(a.status.Widget(), 2, 0, false) + AddItem(a.status.Widget(), 1, 0, false) a.helpView = tview.NewTextView().SetDynamicColors(true).SetWrap(true) a.helpView.SetBorder(true).SetTitle(msgs.HelpViewTitle) + a.helpPanel = &scrollPanel{TextView: a.helpView} a.helpView.SetText(a.helpText()) // Centered popup, margins around it to let the app show through in the @@ -323,7 +322,7 @@ func NewApp(tapp *tview.Application, cr ConnectResult, cfg *config.Config, paths AddItem(nil, 0, 1, false). AddItem(tview.NewFlex(). AddItem(nil, 0, 1, false). - AddItem(a.helpView, 76, 0, true). + AddItem(a.helpPanel, 76, 0, true). AddItem(nil, 0, 1, false), 0, 9, true). AddItem(nil, 0, 1, false)} @@ -1486,7 +1485,5 @@ func (a *App) applyLanguage() { a.helpView.SetTitle(a.msgs.HelpViewTitle) a.helpView.SetText(a.helpText()) a.palette.applyLanguage(a.msgs) - if a.banner != nil { - a.banner.SetText(bannerText(a.protection, a.label, a.msgs)) - } + a.header.SetLanguage(a.msgs) } diff --git a/ui/connect.go b/ui/connect.go index 9b41732..1b57d0a 100644 --- a/ui/connect.go +++ b/ui/connect.go @@ -202,7 +202,7 @@ func newConnectScreen(tapp *tview.Application, cfg *config.Config, onConnected f message: tview.NewTextView().SetDynamicColors(true).SetWordWrap(true), sessions: sessions, } - cs.list.SetBorder(true).SetTitle(cs.msgs.ConnectListTitle) + cs.list.SetBorder(true).SetBorderColor(themeAccent).SetTitle(cs.msgs.ConnectListTitle) cs.refreshList() cs.pages.AddPage("list", cs.listLayout(), true, true) return cs @@ -325,7 +325,7 @@ func (cs *connectScreen) buildForm(existing *config.Cluster, secret string) *hig } form := newHighlightForm() - form.SetBorder(true).SetTitle(title) + form.SetBorder(true).SetBorderColor(themeAccent).SetTitle(title) // Without SetCancelFunc, tview.Form falls back to a default behavior // (return to the first field) that turned out to freeze focus in // practice (e.g. Esc on the authentication dropdown). So we give Esc an @@ -477,7 +477,7 @@ func (cs *connectScreen) buildForm(existing *config.Cluster, secret string) *hig } // labelMaxLength bounds the label typed in the connection form: a few -// words on the banner, not a description. +// words in the header, not a description. const labelMaxLength = 30 // certPickerPageName is the tview.Pages key for the certificate-picker @@ -560,7 +560,7 @@ func (cs *connectScreen) openCertPicker(dir, settingName string, field *tview.In } list := tview.NewList().ShowSecondaryText(false) - list.SetBorder(true) + list.SetBorder(true).SetBorderColor(themeAccent) // currentDir tracks whichever directory render last drew — updated only // on success, so a read error while navigating (into a subdirectory, or @@ -697,7 +697,7 @@ func (cs *connectScreen) attemptConnect(cl config.Cluster, secrets connectSecret return } // "https://user:password@host" would work — and put the password in - // config.yaml, in the status bar and in every curl command copied: the + // config.yaml, in the header and in every curl command copied: the // URL is the one thing about a cluster that is saved and shown as is. if parsed, err := url.Parse(cl.URL); err == nil && parsed.User != nil { cs.setMessage(msgs.ErrURLCredentials, "red") @@ -705,7 +705,7 @@ func (cs *connectScreen) attemptConnect(cl config.Cluster, secrets connectSecret } if cl.AuthType == config.AuthAPIKey { // A key pasted in its encoded form brings its own identifier: that - // is the one saved, and shown in the status bar. + // is the one saved, and shown in the header. cl.APIKeyID, secrets.apiKeySecret = esclient.ResolveAPIKey(cl.APIKeyID, secrets.apiKeySecret) if cl.APIKeyID == "" { cs.setMessage(msgs.ErrAPIKeyIDRequired, "red") diff --git a/ui/connect_test.go b/ui/connect_test.go index 6b96d1d..21a9609 100644 --- a/ui/connect_test.go +++ b/ui/connect_test.go @@ -119,7 +119,7 @@ func checkFormRightBorder(t *testing.T, screen tcell.SimulationScreen) { cells, width, height := screenContents(screen) bottom := height - connectMessageLines - 1 // the form's bottom border for y := 1; y < bottom; y++ { - if got := string(cells[y*width+width-1].Runes); got != "║" { + if got := string(cells[y*width+width-1].Runes); got != "┃" { t.Errorf("row %d: expected the form's right border, got %q:\n%s", y, got, screenText(screen)) return } diff --git a/ui/gutter.go b/ui/gutter.go index 6d88f3f..0b3b0da 100644 --- a/ui/gutter.go +++ b/ui/gutter.go @@ -8,6 +8,8 @@ import ( "github.com/gdamore/tcell/v2" "github.com/rivo/tview" "github.com/rivo/uniseg" + + "github.com/gnocent/termdevtools/parser" ) // gutterPadding is the blank margin (in columns) added after the line @@ -41,8 +43,13 @@ type editorLayout struct { } func (l *editorLayout) Draw(screen tcell.Screen) { + l.SetBorderColor(panelBorderColor(l.HasFocus())) l.editor.refreshGutter() l.Flex.Draw(screen) + l.editor.paintRequests(screen) + if l.editor.moreBelow() { + markMoreBelow(screen, l) + } } // refreshGutter recomputes the gutter's displayed line numbers to match the @@ -81,6 +88,66 @@ func (e *Editor) refreshGutter() { e.gutter.SetText(gutterText(text, e.wrappedStarts, rowOffset, height, digits)) } +// moreBelow tells whether the text goes on below the rows shown, on the +// display rows of the last refreshGutter. +func (e *Editor) moreBelow() bool { + _, _, _, height := e.view.GetInnerRect() + rowOffset, _ := e.view.GetOffset() + return rowOffset+height < len(e.wrappedStarts) +} + +// paintRequests colors, in the cells TextArea has just drawn, what makes the +// requests easy to read: the method of each request line, by what it can do, +// and comments. TextArea itself only draws one color (SPEC.md §3.2), and +// offers no way around it short of rebuilding an editor; this keeps it, and +// changes nothing but the color of what it displays. Relies on the same +// display rows as the gutter (refreshGutter, just before the draw). +func (e *Editor) paintRequests(screen tcell.Screen) { + x, y, width, height := e.view.GetInnerRect() + rowOffset, _ := e.view.GetOffset() + text, rowStarts := e.wrappedText, e.wrappedStarts + if rowOffset >= len(rowStarts) { + return + } + // The first row shown may be the middle of a wrapped comment. Below it, + // lines are only looked at where they start: a line can be very long. + first := strings.LastIndexByte(text[:rowStarts[rowOffset]], '\n') + 1 + comment := strings.HasPrefix(strings.TrimLeft(text[first:], " "), "#") + for row := rowOffset; row < rowOffset+height && row < len(rowStarts); row++ { + start := rowStarts[row] + screenRow := y + row - rowOffset + if start == 0 || text[start-1] == '\n' { + line, _, _ := strings.Cut(text[start:], "\n") + request := strings.TrimLeft(line, " ") + comment = strings.HasPrefix(request, "#") + if method, ok := parser.RequestMethod(request); ok { + color, column := methodColor(method), len(line)-len(request) + paintCells(screen, x+column, screenRow, min(len(method), width-column), func(style tcell.Style) tcell.Style { + return style.Foreground(color).Bold(true) + }) + } + } + if comment { + paintCells(screen, x, screenRow, width, func(style tcell.Style) tcell.Style { + return style.Foreground(themeMuted) + }) + } + } +} + +// paintCells applies paint to the cells of a row showing the editor's plain +// text: not to the selection, or to a search match, which have a background +// of their own. +func paintCells(screen tcell.Screen, x, y, cells int, paint func(tcell.Style) tcell.Style) { + for end := x + cells; x < end; { + mainc, combc, style, width := screen.GetContent(x, y) + if _, background, _ := style.Decompose(); background == themeBackground { + screen.SetContent(x, y, mainc, combc, paint(style)) + } + x += max(width, 1) + } +} + // gutterText renders the gutter's content for the display rows [rowOffset, // rowOffset+height) out of rowStarts (see wrapRowStarts): one line per // visible row, either the logical line number (the row where that logical diff --git a/ui/header.go b/ui/header.go new file mode 100644 index 0000000..17991b9 --- /dev/null +++ b/ui/header.go @@ -0,0 +1,168 @@ +package ui + +import ( + "fmt" + "strings" + + "github.com/gdamore/tcell/v2" + "github.com/rivo/tview" + "github.com/rivo/uniseg" + + "github.com/gnocent/termdevtools/config" + "github.com/gnocent/termdevtools/i18n" + "github.com/gnocent/termdevtools/refdata" +) + +// headerBrand opens the header of an unprotected cluster. +const headerBrand = "TermDevTools" + +// headerUserGap is the fewest columns between the URL and the user. +const headerUserGap = 2 + +// minHeaderURLWidth is the fewest columns a URL cut short keeps in the +// header, "…" included: fewer wouldn't say which cluster it is. +const minHeaderURLWidth = 12 + +// header is the line across the top of the main screen (SPEC.md §3.1, §5): +// which cluster this is and, on a protected cluster, how it is protected. +type header struct { + line *composedLine + target refdata.Target + cluster, user string + protection, label string + msgs *i18n.Strings +} + +// newHeader creates the header of the given cluster. protection is a +// normalized level (config.NormalizeProtection). +func newHeader(target refdata.Target, cluster, user, protection, label string, msgs *i18n.Strings) *header { + h := &header{target: target, cluster: cluster, user: user, protection: protection, label: label, msgs: msgs} + background, foreground := h.colors() + view := tview.NewTextView().SetDynamicColors(true).SetWrap(false). + SetTextStyle(tcell.StyleDefault.Background(background).Foreground(foreground)) + view.SetBackgroundColor(background).SetBorderPadding(0, 0, 1, 1) + h.line = &composedLine{TextView: view, compose: h.compose} + return h +} + +// Widget returns the line to insert into the layout. +func (h *header) Widget() tview.Primitive { + return h.line +} + +// SetLanguage re-applies the header in msgs' language. +func (h *header) SetLanguage(msgs *i18n.Strings) { + h.msgs = msgs + h.line.SetText(h.compose(h.line.width)) +} + +// protected tells whether the cluster has a protection to show. +func (h *header) protected() bool { + return h.protection == config.ProtectionConfirm || h.protection == config.ProtectionReadOnly +} + +// colors are the header's background and text: the whole line says how the +// cluster is protected, red when writes can still be sent once confirmed, +// yellow when none can. +func (h *header) colors() (background, foreground tcell.Color) { + switch h.protection { + case config.ProtectionConfirm: + return themeDanger, themeWhite + case config.ProtectionReadOnly: + return themeYellow, themeBackground + } + return themeSurface, themeText +} + +// badgeColors are the colors of the badge naming the product: told apart +// from one distribution to the other, dark on a protected cluster to stand +// out from the line's own color. +func (h *header) badgeColors() (background, foreground tcell.Color) { + switch { + case h.protected(): + return themeBackground, themeText + case h.target.Distribution == refdata.Elasticsearch: + return themeTeal, themeBackground + case h.target.Distribution == refdata.OpenSearch: + return themeAccent, themeBackground + } + return themeField, themeText +} + +// badge is the product in short form ("ES 9.5.4"), or the generic caption +// when it isn't known. +func (h *header) badge() string { + product := h.target.Label() + if product == "" { + product = h.msgs.StatusClusterCaption + } + return " " + product + " " +} + +// compose builds the header for width columns: what opens it, the badge, the +// URL, and the user at the far right. When the whole line doesn't fit, the +// brand goes first — unlike a protection, which stays whatever happens —, +// then the user, then the URL is cut short, and last it goes too. A width of +// 0 (not drawn yet) gives the whole line. +func (h *header) compose(width int) string { + lead, keepLead := headerBrand, false + if h.protected() { + lead, keepLead = bannerText(h.protection, h.label, h.msgs), true + } + used := func(lead, url, user string) int { + columns := uniseg.StringWidth(h.badge()) + if lead != "" { + columns += uniseg.StringWidth(lead) + 1 + } + if url != "" { + columns += 1 + uniseg.StringWidth(url) + } + if user != "" { + columns += headerUserGap + uniseg.StringWidth(user) + } + return columns + } + + switch { + case width <= 0 || used(lead, h.cluster, h.user) <= width: + return h.render(lead, h.cluster, h.user, width) + case !keepLead && used("", h.cluster, h.user) <= width: + return h.render("", h.cluster, h.user, width) + } + if !keepLead { + lead = "" + } + room := width - used(lead, "", "") - 1 + if room >= min(minHeaderURLWidth, uniseg.StringWidth(h.cluster)) { + return h.render(lead, cutShort(h.cluster, room), "", width) + } + return h.render(lead, "", "", width) +} + +// render lays the given parts out on a line of width columns, the user +// pushed to its end. +func (h *header) render(lead, url, user string, width int) string { + var b strings.Builder + columns := 0 + if lead != "" { + fmt.Fprintf(&b, "[::b]%s[::-] ", tview.Escape(lead)) + columns += uniseg.StringWidth(lead) + 1 + } + background, foreground := h.badgeColors() + fmt.Fprintf(&b, "[%s:%s:b]%s[-:-:-]", foreground.CSS(), background.CSS(), tview.Escape(h.badge())) + columns += uniseg.StringWidth(h.badge()) + if url != "" { + b.WriteString(" " + tview.Escape(url)) + columns += 1 + uniseg.StringWidth(url) + } + if user != "" { + gap := max(headerUserGap, width-columns-uniseg.StringWidth(user)) + b.WriteString(strings.Repeat(" ", gap)) + if h.protected() { + b.WriteString(tview.Escape(user)) + } else { + b.WriteString("[gray]" + tview.Escape(user) + "[-]") + } + } + return b.String() +} diff --git a/ui/header_test.go b/ui/header_test.go new file mode 100644 index 0000000..44fcbc5 --- /dev/null +++ b/ui/header_test.go @@ -0,0 +1,184 @@ +package ui + +import ( + "strings" + "testing" + + "github.com/gdamore/tcell/v2" + "github.com/rivo/uniseg" + + "github.com/gnocent/termdevtools/config" + "github.com/gnocent/termdevtools/i18n" + "github.com/gnocent/termdevtools/refdata" +) + +// os2196 is the OpenSearch of the header's tests. +var os2196 = refdata.Target{Distribution: refdata.OpenSearch, Version: refdata.Version{Major: 2, Minor: 19, Patch: 6}, HasVersion: true} + +// headerText returns what app's header says, whatever its width. +func headerText(app *App) string { + return uiValue(app, func() string { return plainText(app.header.compose(0)) }) +} + +// TestHeaderGivesWayInOrder checks what the header keeps when it doesn't +// fit: the brand goes first, then the user, then the URL is cut short, and +// last it goes too. +func TestHeaderGivesWayInOrder(t *testing.T) { + const url, user = "https://es-prod.example.test:9200", "svc_devtools" + h := newHeader(es95, url, user, config.ProtectionNone, "", i18n.For(i18n.FR)) + cases := []struct { + width int + want string + }{ + {78, "TermDevTools ES 9.5.4 https://es-prod.example.test:9200 svc_devtools"}, + {71, "TermDevTools ES 9.5.4 https://es-prod.example.test:9200 svc_devtools"}, + {70, " ES 9.5.4 https://es-prod.example.test:9200" + strings.Repeat(" ", 14) + "svc_devtools"}, + {58, " ES 9.5.4 https://es-prod.example.test:9200 svc_devtools"}, + {57, " ES 9.5.4 https://es-prod.example.test:9200"}, + {30, " ES 9.5.4 https://es-prod.ex…"}, + {23, " ES 9.5.4 https://es-…"}, + {22, " ES 9.5.4 "}, + } + for _, c := range cases { + got := plainText(h.compose(c.width)) + if got != c.want { + t.Errorf("%d columns: expected\n%q, got\n%q", c.width, c.want, got) + } + if used := uniseg.StringWidth(got); used > c.width { + t.Errorf("%d columns: %d columns used", c.width, used) + } + } +} + +// TestHeaderKeepsTheProtection checks that a protection, unlike the brand, +// stays however little room there is. +func TestHeaderKeepsTheProtection(t *testing.T) { + h := newHeader(es95, "https://es-prod.example.test:9200", "svc_devtools", config.ProtectionConfirm, "PROD", i18n.For(i18n.FR)) + cases := []struct { + width int + want string + }{ + {78, "PROD · confirmation des écritures ES 9.5.4 https://es-prod.example.test:9200"}, + {60, "PROD · confirmation des écritures ES 9.5.4 https://es-pro…"}, + {50, "PROD · confirmation des écritures ES 9.5.4 "}, + } + for _, c := range cases { + if got := plainText(h.compose(c.width)); got != c.want { + t.Errorf("%d columns: expected\n%q, got\n%q", c.width, c.want, got) + } + } +} + +// TestHeaderKeepsAShortURL checks that the room a URL needs before it is +// worth cutting doesn't apply to one that fits whole. +func TestHeaderKeepsAShortURL(t *testing.T) { + h := newHeader(es95, "http://es:1", "svc_devtools", config.ProtectionNone, "", i18n.For(i18n.FR)) + if got, want := plainText(h.compose(22)), " ES 9.5.4 http://es:1"; got != want { + t.Errorf("expected %q, got %q", want, got) + } +} + +// TestHeaderIgnoresTheMouse checks that a click on the header, with the mouse +// on, leaves the focus where it is, and the same for the status line. +func TestHeaderIgnoresTheMouse(t *testing.T) { + app, screen := newTestAppWith(t, testAppOptions{mouse: true}) + _, _, height := screenContents(screen) + for _, y := range []int{0, height - 1} { + screen.InjectMouse(20, y, tcell.Button1, tcell.ModNone) + screen.InjectMouse(20, y, tcell.ButtonNone, tcell.ModNone) + waitForDraw(t, screen) + if got := uiValue(app, func() bool { return app.tapp.GetFocus() == app.editor.Primitive() }); !got { + t.Errorf("row %d: expected the focus to stay on the editor", y) + } + } +} + +// TestHeaderShowsWhatIsWritten checks that brackets in what a cluster's +// settings hold aren't taken for color tags. +func TestHeaderShowsWhatIsWritten(t *testing.T) { + h := newHeader(refdata.Target{}, "http://[::1]:9200", "[red]svc", config.ProtectionReadOnly, "[red]PROD", i18n.For(i18n.FR)) + got := plainText(h.compose(0)) + for _, want := range []string{"[red]PROD · lecture seule", "http://[::1]:9200", "[red]svc"} { + if !strings.Contains(got, want) { + t.Errorf("expected %q in %q", want, got) + } + } +} + +// TestHeaderBadgeTellsDistributionsApart checks the color of the badge, on +// the main screen: what tells two clusters apart at a glance with Ctrl+O. +func TestHeaderBadgeTellsDistributionsApart(t *testing.T) { + cases := []struct { + name string + opts testAppOptions + want string + bg tcell.Color + }{ + {"Elasticsearch", testAppOptions{target: es95}, " ES 9.5.4 ", themeTeal}, + {"OpenSearch", testAppOptions{target: os2196}, " OS 2.19.6 ", themeAccent}, + {"unknown", testAppOptions{undetected: true}, " Cluster ", themeField}, + {"protected", testAppOptions{target: es95, protection: config.ProtectionConfirm, label: "PROD"}, " ES 9.5.4 ", themeBackground}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, screen := newTestAppWith(t, c.opts) + column := strings.Index(screenRow(screen, 0), c.want) + if column < 0 { + t.Fatalf("expected %q on the first row, got %q", c.want, screenRow(screen, 0)) + } + column = uniseg.StringWidth(screenRow(screen, 0)[:column]) + for _, x := range []int{column, column + len(c.want) - 1} { + if got := screenBackground(screen, x, 0); got != c.bg { + t.Errorf("column %d: expected background %v, got %v", x, c.bg, got) + } + } + }) + } +} + +// TestHeaderAndStatusLineTakeOneRowEach checks what makes the header free: +// the panels keep the height they had with a status line and a help bar. +func TestHeaderAndStatusLineTakeOneRowEach(t *testing.T) { + _, screen := newTestApp(t) + _, _, height := screenContents(screen) + + if row := screenRow(screen, 1); !strings.Contains(row, "Requêtes") || !strings.Contains(row, "Résultat") { + t.Errorf("expected the top of the panels on the second row, got %q", row) + } + if row := screenRow(screen, height-2); !strings.Contains(row, "┗") { + t.Errorf("expected the bottom of the panels on the row before last, got %q", row) + } + if row := screenRow(screen, height-1); !strings.Contains(row, "prêt") || !strings.Contains(row, "F1 aide") { + t.Errorf("expected the message and the shortcuts on the last row, got %q", row) + } +} + +// TestFocusShowsOnThePanels checks that the panel with the focus stands out +// by its shape and its color, and that the focus moves with the keyboard. +func TestFocusShowsOnThePanels(t *testing.T) { + app, screen := newTestApp(t) + + borderColor := func(x int) tcell.Color { + cells, width, _ := screenContents(screen) + color, _, _ := cells[1*width+x].Style.Decompose() + return color + } + if row := screenRow(screen, 1); !strings.HasPrefix(row, "┏") || !strings.HasSuffix(row, "┐") { + t.Errorf("expected the editor's border to be the focused one, got %q", row) + } + if got := borderColor(0); got != themeAccent { + t.Errorf("expected the editor's border in the accent color, got %v", got) + } + if got := borderColor(79); got != themeBorder { + t.Errorf("expected the result's border in the plain color, got %v", got) + } + + onUI(app, app.focusResultPanel) + waitForDraw(t, screen) + if row := screenRow(screen, 1); !strings.HasPrefix(row, "┌") || !strings.HasSuffix(row, "┓") { + t.Errorf("expected the result's border to be the focused one, got %q", row) + } + if got := borderColor(79); got != themeAccent { + t.Errorf("expected the result's border in the accent color, got %v", got) + } +} diff --git a/ui/paint_test.go b/ui/paint_test.go new file mode 100644 index 0000000..55357c2 --- /dev/null +++ b/ui/paint_test.go @@ -0,0 +1,155 @@ +package ui + +import ( + "strings" + "testing" + + "github.com/gdamore/tcell/v2" + "github.com/rivo/tview" +) + +// editorCell returns the rune and style of a cell of the editor's text, at +// column and row within what it displays. +func editorCell(t *testing.T, app *App, screen tcell.SimulationScreen, column, row int) (rune, tcell.Style) { + t.Helper() + var left, top int + onUI(app, func() { left, top, _, _ = app.editor.view.GetInnerRect() }) + cells, width, _ := screenContents(screen) + cell := cells[(top+row)*width+left+column] + return cell.Runes[0], cell.Style +} + +// paintedApp opens an app whose editor shows text. +func paintedApp(t *testing.T, text string) (*App, tcell.SimulationScreen) { + t.Helper() + app, screen := newTestApp(t) + onUI(app, func() { app.editor.SetInitialText(text) }) + waitForDraw(t, screen) + return app, screen +} + +// expectCell checks the character, color and weight of a cell. +func expectCell(t *testing.T, app *App, screen tcell.SimulationScreen, column, row int, char rune, color tcell.Color, bold bool) { + t.Helper() + got, style := editorCell(t, app, screen, column, row) + foreground, _, attributes := style.Decompose() + if got != char || foreground != color || (attributes&tcell.AttrBold != 0) != bold { + t.Errorf("cell %d,%d: expected %q in %v (bold: %v), got %q in %v (bold: %v)", + column, row, char, color, bold, got, foreground, attributes&tcell.AttrBold != 0) + } +} + +func TestMethodsAndCommentsArePainted(t *testing.T) { + app, screen := paintedApp(t, "# health\nGET _cat/health\n\nPUT my-index\n{\n \"size\": 1\n}\n\nDELETE old\npost a/_search") + + expectCell(t, app, screen, 0, 0, '#', themeMuted, false) + expectCell(t, app, screen, 7, 0, 'h', themeMuted, false) + + expectCell(t, app, screen, 0, 1, 'G', themeTeal, true) + expectCell(t, app, screen, 2, 1, 'T', themeTeal, true) + expectCell(t, app, screen, 4, 1, '_', themeText, false) // the path stays plain + + expectCell(t, app, screen, 0, 3, 'P', themeAccent, true) + expectCell(t, app, screen, 0, 4, '{', themeText, false) // and so does a body + expectCell(t, app, screen, 3, 5, 's', themeText, false) + + expectCell(t, app, screen, 0, 8, 'D', themeRed, true) + expectCell(t, app, screen, 5, 8, 'E', themeRed, true) + expectCell(t, app, screen, 7, 8, 'o', themeText, false) + + expectCell(t, app, screen, 0, 9, 'p', themeAccent, true) // as the parser reads it +} + +// TestOnlyRequestLinesArePainted checks that a line that isn't a request is +// left alone, whatever it starts with: the color says what will be sent. +func TestOnlyRequestLinesArePainted(t *testing.T) { + app, screen := paintedApp(t, "GET\nDELETE two words\nGETTING there\n\tGET tabbed") + for row, char := range []rune{'G', 'D', 'G'} { + expectCell(t, app, screen, 0, row, char, themeText, false) + } + got, style := editorCell(t, app, screen, tview.TabSize, 3) + if foreground, _, _ := style.Decompose(); got != 'G' || foreground != themeText { + t.Errorf("expected a request behind a tab left alone, got %q in %v", got, foreground) + } +} + +func TestIndentedRequestIsPaintedWhereItIs(t *testing.T) { + app, screen := paintedApp(t, " DELETE old\n # note") + expectCell(t, app, screen, 0, 0, ' ', themeText, false) + expectCell(t, app, screen, 2, 0, 'D', themeRed, true) + expectCell(t, app, screen, 2, 1, '#', themeMuted, false) +} + +// TestPaintStaysInsideTheEditor checks that on a panel narrower than a +// method, what doesn't fit isn't painted over what stands next to the editor. +func TestPaintStaysInsideTheEditor(t *testing.T) { + app, screen := paintedApp(t, "DELETE old") + onUI(app, func() { + for app.leftWeight > splitMinWeight { + app.resizeSplit(-splitStep) + } + }) + waitForDraw(t, screen) + + var left, top, width int + onUI(app, func() { left, top, width, _ = app.editor.view.GetInnerRect() }) + if width >= len("DELETE") { + t.Fatalf("expected a panel narrower than the method, got %d columns", width) + } + cells, screenWidth, _ := screenContents(screen) + for x := left + width; x < left+len("DELETE"); x++ { + foreground, _, attributes := cells[top*screenWidth+x].Style.Decompose() + if foreground == themeRed || attributes&tcell.AttrBold != 0 { + t.Errorf("column %d: expected nothing painted outside the editor, got %v", x, foreground) + } + } +} + +// TestSelectionKeepsItsColors checks that the selection, which F-keys and +// the search act on, is drawn as usual over a method. +func TestSelectionKeepsItsColors(t *testing.T) { + app, screen := paintedApp(t, "GET _cat/health") + onUI(app, func() { app.editor.SelectRange(0, 2) }) + waitForDraw(t, screen) + + _, style := editorCell(t, app, screen, 0, 0) + if foreground, background, _ := style.Decompose(); foreground != themeBackground || background != themeText { + t.Errorf("expected the selection's colors, got %v on %v", foreground, background) + } + expectCell(t, app, screen, 2, 0, 'T', themeTeal, true) +} + +// TestPaintFollowsDisplayRows checks the painting against what the gutter +// also relies on: wrapped lines and scrolling. +func TestPaintFollowsDisplayRows(t *testing.T) { + t.Run("a wrapped comment, on all its rows", func(t *testing.T) { + app, screen := paintedApp(t, "# "+strings.Repeat("word ", 20)+"\nGET next") + expectCell(t, app, screen, 0, 1, 'w', themeMuted, false) + // The request comes after the comment's rows, wherever they end. + rows := uiValue(app, func() int { return len(app.editor.wrappedStarts) }) + expectCell(t, app, screen, 0, rows-1, 'G', themeTeal, true) + }) + + t.Run("a wrapped request, on its first row only", func(t *testing.T) { + app, screen := paintedApp(t, "GET "+strings.Repeat("a", 60)) + expectCell(t, app, screen, 0, 0, 'G', themeTeal, true) + expectCell(t, app, screen, 0, 1, 'a', themeText, false) + }) + + t.Run("scrolled into a wrapped comment", func(t *testing.T) { + app, screen := paintedApp(t, "# "+strings.Repeat("word ", 20)) + onUI(app, func() { app.editor.view.SetOffset(1, 0) }) + waitForDraw(t, screen) + expectCell(t, app, screen, 0, 0, 'w', themeMuted, false) + }) + + t.Run("scrolled", func(t *testing.T) { + text := strings.Repeat("plain line\n", 40) + "DELETE old\nGET next" + app, screen := paintedApp(t, text) + onUI(app, func() { app.editor.view.SetOffset(35, 0) }) + waitForDraw(t, screen) + expectCell(t, app, screen, 0, 0, 'p', themeText, false) + expectCell(t, app, screen, 0, 5, 'D', themeRed, true) + expectCell(t, app, screen, 0, 6, 'G', themeTeal, true) + }) +} diff --git a/ui/protection.go b/ui/protection.go index 4584483..ec66a07 100644 --- a/ui/protection.go +++ b/ui/protection.go @@ -13,29 +13,9 @@ import ( "github.com/gnocent/termdevtools/i18n" ) -// newProtectionBanner builds the line shown across the top of the main -// screen of a protected cluster (SPEC.md §5): red when writes can still be -// sent once confirmed, yellow when none can. nil for an unprotected cluster, -// whose layout stays exactly what it was before protection levels existed. -func newProtectionBanner(level, label string, msgs *i18n.Strings) *tview.TextView { - background, foreground := tcell.ColorRed, tcell.ColorWhite - switch level { - case config.ProtectionConfirm: - case config.ProtectionReadOnly: - background, foreground = tcell.ColorYellow, tcell.ColorBlack - default: - return nil - } - // No dynamic colors: the label is shown as typed, "[red]" included. - banner := tview.NewTextView().SetTextAlign(tview.AlignCenter).SetWrap(false). - SetTextStyle(tcell.StyleDefault.Background(background).Foreground(foreground).Bold(true)) - banner.SetBackgroundColor(background) - banner.SetText(bannerText(level, label, msgs)) - return banner -} - -// bannerText is what the banner says: the cluster's label and its level -// ("PROD · read-only"), or the level alone, in capitals, without a label. +// bannerText is what the header says of a protected cluster (SPEC.md §5): its +// label and its level ("PROD · read-only"), or the level alone, in capitals, +// without a label. func bannerText(level, label string, msgs *i18n.Strings) string { name := msgs.ProtectionConfirmName if level == config.ProtectionReadOnly { @@ -192,8 +172,8 @@ func (a *App) confirmWrite(method, path string, body []byte) { frame := tview.NewFlex().SetDirection(tview.FlexRow). AddItem(text, confirmTextHeight, 0, false). AddItem(buttons, 0, 1, true) - frame.SetBorder(true).SetBorderColor(tcell.ColorRed). - SetTitle(a.msgs.ConfirmWriteTitle).SetTitleColor(tcell.ColorRed) + frame.SetBorder(true).SetBorderColor(themeRed). + SetTitle(a.msgs.ConfirmWriteTitle).SetTitleColor(themeRed) overlay := modalPage{tview.NewFlex().SetDirection(tview.FlexRow). AddItem(nil, 0, 1, false). @@ -216,7 +196,7 @@ func (a *App) closeConfirm() { a.focusEditor() } -// bannerLabel makes a label fit on the banner's single line: a label written +// bannerLabel makes a label fit on the header's single line: a label written // by hand in config.yaml may span several lines, or hold control characters // that have no business reaching the terminal. func bannerLabel(label string) string { diff --git a/ui/protection_test.go b/ui/protection_test.go index d95010c..753e2ab 100644 --- a/ui/protection_test.go +++ b/ui/protection_test.go @@ -238,15 +238,15 @@ func TestConfirmWriteHidesWhatIsBehind(t *testing.T) { } for x, r := range line { switch r { - case '╔', '┌': + case '┏', '┌': left = x - case '╗', '┐': + case '┓', '┐': right = x } } continue } - if line[left] == '╚' || line[left] == '└' { + if line[left] == '┗' || line[left] == '└' { return } if inside := string(line[left+1 : right]); strings.Contains(inside, "X") { @@ -577,37 +577,37 @@ func screenBackground(screen tcell.SimulationScreen, x, y int) tcell.Color { return background } -// TestNoBannerWithoutProtection checks that an unprotected cluster's main -// screen is laid out as before protection levels existed: the panels start -// on the very first row. +// TestNoBannerWithoutProtection checks that the header of an unprotected +// cluster says nothing of a protection, its label included. func TestNoBannerWithoutProtection(t *testing.T) { for _, protection := range []string{"", config.ProtectionNone} { - app, screen := newTestAppWith(t, testAppOptions{protection: protection, label: "PROD"}) - if uiValue(app, func() bool { return app.banner != nil }) { - t.Errorf("protection %q: expected no banner", protection) + _, screen := newTestAppWith(t, testAppOptions{protection: protection, label: "PROD"}) + if row := screenRow(screen, 0); !strings.Contains(row, "TermDevTools") || strings.Contains(row, "PROD") { + t.Errorf("protection %q: expected the plain header on the first row, got %q", protection, row) } - if row := screenRow(screen, 0); !strings.Contains(row, "Requêtes") || strings.Contains(row, "PROD") { - t.Errorf("protection %q: expected the panels on the first row, got %q", protection, row) + if got := screenBackground(screen, 79, 0); got != themeSurface { + t.Errorf("protection %q: expected the plain header's background, got %v", protection, got) } } } -// TestProtectionBanner checks the banner a protected cluster gets across the -// top of the main screen: its text, with and without a label, its color, and -// the panels pushed down by one row. +// TestProtectionBanner checks what a protected cluster's header says across +// the top of the main screen: its text, with and without a label, the color +// of the whole line, and the panels right under it, on the same row as on an +// unprotected cluster. func TestProtectionBanner(t *testing.T) { cases := []struct { protection, label string want string background tcell.Color }{ - {config.ProtectionConfirm, "PROD", "PROD · confirmation des écritures", tcell.ColorRed}, - {config.ProtectionConfirm, "", "CONFIRMATION DES ÉCRITURES", tcell.ColorRed}, - {config.ProtectionReadOnly, "PROD", "PROD · lecture seule", tcell.ColorYellow}, - {config.ProtectionReadOnly, "", "LECTURE SEULE", tcell.ColorYellow}, + {config.ProtectionConfirm, "PROD", "PROD · confirmation des écritures", themeDanger}, + {config.ProtectionConfirm, "", "CONFIRMATION DES ÉCRITURES", themeDanger}, + {config.ProtectionReadOnly, "PROD", "PROD · lecture seule", themeYellow}, + {config.ProtectionReadOnly, "", "LECTURE SEULE", themeYellow}, // The form hands over a level it has already normalized; a label // written by hand may still span lines or hold control characters. - {config.ProtectionReadOnly, "PROD\n eu-west\x1b[31m", "PROD eu-west [31m · lecture seule", tcell.ColorYellow}, + {config.ProtectionReadOnly, "PROD\n eu-west\x1b[31m", "PROD eu-west [31m · lecture seule", themeYellow}, } for _, c := range cases { _, screen := newTestAppWith(t, testAppOptions{protection: c.protection, label: c.label}) @@ -615,7 +615,7 @@ func TestProtectionBanner(t *testing.T) { if !strings.Contains(row, c.want) { t.Errorf("%s/%q: expected %q on the first row, got %q", c.protection, c.label, c.want, row) } - for _, x := range []int{0, 40, 79} { + for _, x := range []int{0, 1, 78, 79} { if got := screenBackground(screen, x, 0); got != c.background { t.Errorf("%s/%q: expected background %v at column %d, got %v", c.protection, c.label, c.background, x, got) } diff --git a/ui/recipes.go b/ui/recipes.go index 5c5208a..8402b3b 100644 --- a/ui/recipes.go +++ b/ui/recipes.go @@ -60,7 +60,7 @@ func newRecipePalette(a *App) *recipePalette { AddItem(p.filter, 1, 0, true). AddItem(p.list, 0, 1, false). AddItem(p.preview, 0, 1, false) - p.frame.SetBorder(true) + p.frame.SetBorder(true).SetBorderColor(themeAccent) p.applyLanguage(a.msgs) return p diff --git a/ui/result.go b/ui/result.go index ce00bfe..6cf5b9b 100644 --- a/ui/result.go +++ b/ui/result.go @@ -27,6 +27,7 @@ const searchRegionID = "match" // text otherwise (e.g. `_cat` responses). See SPEC.md §3.3. type ResultView struct { view *tview.TextView + panel *scrollPanel plain string // displayed text without color tags, for search and export displayedText string // last text actually sent to SetText (with color tags), for HighlightLine isJSON bool @@ -62,12 +63,12 @@ func NewResultView(msgs *i18n.Strings) *ResultView { SetScrollable(true). SetRegions(true) view.SetBorder(true).SetTitle(msgs.ResultTitle) - return &ResultView{view: view, msgs: msgs} + return &ResultView{view: view, panel: &scrollPanel{TextView: view}, msgs: msgs} } // Widget returns the tview component to insert into the layout. func (r *ResultView) Widget() tview.Primitive { - return r.view + return r.panel } // Primitive returns the underlying TextView. @@ -294,16 +295,16 @@ func colorizeJSON(text string) string { switch { case strings.HasPrefix(tok, `"`): if isKeyToken(text, end) { - b.WriteString("[#5fafff]") + b.WriteString("[aqua]") } else { - b.WriteString("[#87d787]") + b.WriteString("[green]") } b.WriteString(tview.Escape(tok)) b.WriteString("[white]") case len(tok) == 1 && strings.ContainsRune("{}[],:", rune(tok[0])): b.WriteString(tview.Escape(tok)) case tok == "true" || tok == "false": - b.WriteString("[#d78700]") + b.WriteString("[fuchsia]") b.WriteString(tok) b.WriteString("[white]") case tok == "null": @@ -311,7 +312,7 @@ func colorizeJSON(text string) string { b.WriteString(tok) b.WriteString("[white]") default: // number - b.WriteString("[#af87ff]") + b.WriteString("[yellow]") b.WriteString(tok) b.WriteString("[white]") } diff --git a/ui/scroll.go b/ui/scroll.go new file mode 100644 index 0000000..9e44e69 --- /dev/null +++ b/ui/scroll.go @@ -0,0 +1,50 @@ +package ui + +import ( + "github.com/gdamore/tcell/v2" + "github.com/rivo/tview" +) + +// moreBelowMark is what a panel shows on its bottom border, next to the +// right corner, while there is more to see below (SPEC.md §3.1). +const moreBelowMark = '▼' + +// markMoreBelow draws moreBelowMark on panel's bottom border. +func markMoreBelow(screen tcell.Screen, panel tview.Primitive) { + x, y, width, height := panel.GetRect() + if width < 3 || height < 2 { + return + } + style := tcell.StyleDefault.Background(themeBackground).Foreground(themeText).Bold(true) + // For a terminal that isn't in UTF-8: over SSH, with LANG=C, say. + screen.RegisterRuneFallback(moreBelowMark, "v") + screen.SetContent(x+width-2, y+height-1, moreBelowMark, nil, style) +} + +// scrollPanel is a TextView with a border that follows the focus, which a +// border's color doesn't do by itself, and marks what is left below. +type scrollPanel struct { + *tview.TextView +} + +func (p *scrollPanel) Draw(screen tcell.Screen) { + p.SetBorderColor(panelBorderColor(p.HasFocus())) + p.TextView.Draw(screen) + if p.moreBelow(screen) { + markMoreBelow(screen, p) + } +} + +// moreBelow tells whether the panel can scroll further down, by trying to: +// TextView only says how many rows its text takes after wrapping all of it +// on the spot, which would freeze the interface on a large result, and not +// at the width it is drawn at. Drawing goes no further than the rows shown. +func (p *scrollPanel) moreBelow(screen tcell.Screen) bool { + row, column := p.GetScrollOffset() + p.ScrollTo(row+1, column) + p.TextView.Draw(screen) + reached, _ := p.GetScrollOffset() + p.ScrollTo(row, column) + p.TextView.Draw(screen) + return reached > row +} diff --git a/ui/scroll_test.go b/ui/scroll_test.go new file mode 100644 index 0000000..09790e2 --- /dev/null +++ b/ui/scroll_test.go @@ -0,0 +1,172 @@ +package ui + +import ( + "strconv" + "strings" + "testing" + + "github.com/gdamore/tcell/v2" + "github.com/rivo/tview" +) + +// markShown tells whether panel's bottom border carries moreBelowMark. +func markShown(t *testing.T, app *App, screen tcell.SimulationScreen, panel tview.Primitive) bool { + t.Helper() + var x, y, width, height int + onUI(app, func() { x, y, width, height = panel.GetRect() }) + cells, screenWidth, _ := screenContents(screen) + return cells[(y+height-1)*screenWidth+x+width-2].Runes[0] == moreBelowMark +} + +// TestMarkHasAFallback checks what a terminal that isn't in UTF-8 shows. +func TestMarkHasAFallback(t *testing.T) { + screen := tcell.NewSimulationScreen("US-ASCII") + if err := screen.Init(); err != nil { + t.Fatal(err) + } + defer screen.Fini() + panel := tview.NewBox() + panel.SetRect(0, 0, 10, 4) + + markMoreBelow(screen, panel) + screen.Show() + + cells, width, _ := screen.GetContents() + if got := string(cells[3*width+8].Bytes); got != "v" { + t.Errorf("expected the fallback, got %q", got) + } +} + +// numberedLines gives count lines of text, each of them different. +func numberedLines(count int) string { + var lines []string + for i := 1; i <= count; i++ { + lines = append(lines, "line "+strconv.Itoa(i)) + } + return strings.Join(lines, "\n") +} + +func TestEditorMarksWhatIsLeftBelow(t *testing.T) { + app, screen := newTestApp(t) + panel := app.editor.Widget() + if markShown(t, app, screen, panel) { + t.Error("expected no mark on an empty editor") + } + + var rows int + onUI(app, func() { _, _, _, rows = app.editor.view.GetInnerRect() }) + + onUI(app, func() { app.editor.SetInitialText(numberedLines(rows)) }) + waitForDraw(t, screen) + if markShown(t, app, screen, panel) { + t.Error("expected no mark when the text just fits") + } + + onUI(app, func() { app.editor.SetInitialText(numberedLines(rows + 1)) }) + waitForDraw(t, screen) + if !markShown(t, app, screen, panel) { + t.Error("expected a mark when a line is left below") + } + + onUI(app, func() { app.editor.view.SetOffset(1, 0) }) + waitForDraw(t, screen) + if markShown(t, app, screen, panel) { + t.Error("expected no mark once scrolled to the end") + } +} + +func TestResultMarksWhatIsLeftBelow(t *testing.T) { + app, screen := newTestApp(t) + panel := app.result.Widget() + var rows int + onUI(app, func() { _, _, _, rows = app.result.view.GetInnerRect() }) + + show := func(text string) { + t.Helper() + onUI(app, func() { app.result.Show("GET", "_cat/health", nil, []byte(text)) }) + waitForDraw(t, screen) + } + + show("short") + if markShown(t, app, screen, panel) { + t.Error("expected no mark on a short result") + } + + show(numberedLines(rows - 1)) // the request reminder takes a row + if markShown(t, app, screen, panel) { + t.Error("expected no mark when the result just fits") + } + + show(numberedLines(rows)) + if !markShown(t, app, screen, panel) { + t.Error("expected a mark when a line is left below") + } + + onUI(app, app.focusResultPanel) + screen.InjectKey(tcell.KeyDown, 0, tcell.ModNone) + waitForDraw(t, screen) + if markShown(t, app, screen, panel) { + t.Error("expected no mark once scrolled to the end") + } + screen.InjectKey(tcell.KeyUp, 0, tcell.ModNone) + waitForDraw(t, screen) + if !markShown(t, app, screen, panel) { + t.Error("expected the mark back after scrolling up") + } +} + +// TestResultMarkCountsWrappedRows checks that what counts is the rows +// displayed: a single line can overflow the panel, once wrapped. +func TestResultMarkCountsWrappedRows(t *testing.T) { + app, screen := newTestApp(t) + onUI(app, func() { app.result.Show("GET", "_cat/health", nil, []byte(strings.Repeat("a", 2000))) }) + waitForDraw(t, screen) + if !markShown(t, app, screen, app.result.Widget()) { + t.Error("expected a mark on a line wrapped past the bottom of the panel") + } +} + +// TestMarkLeavesScrollingAlone checks that finding out what is left below +// moves nothing: not the position, and not the next key's effect. +func TestMarkLeavesScrollingAlone(t *testing.T) { + app, screen := newTestApp(t) + onUI(app, func() { app.result.Show("GET", "_cat/health", nil, []byte(numberedLines(200))) }) + waitForDraw(t, screen) + onUI(app, app.focusResultPanel) + + offset := func() int { + return uiValue(app, func() int { + row, _ := app.result.view.GetScrollOffset() + return row + }) + } + if got := offset(); got != 0 { + t.Fatalf("expected the result at its top, got row %d", got) + } + screen.InjectKey(tcell.KeyDown, 0, tcell.ModNone) + waitForDraw(t, screen) + screen.InjectKey(tcell.KeyDown, 0, tcell.ModNone) + waitForDraw(t, screen) + if got := offset(); got != 2 { + t.Errorf("expected row 2 after two steps down, got %d", got) + } + screen.InjectKey(tcell.KeyEnd, 0, tcell.ModNone) + waitForDraw(t, screen) + if markShown(t, app, screen, app.result.Widget()) { + t.Error("expected no mark after End") + } +} + +func TestHelpMarksWhatIsLeftBelow(t *testing.T) { + app, screen := newTestApp(t) + screen.InjectKey(tcell.KeyF1, 0, tcell.ModNone) + waitForDraw(t, screen) + if !markShown(t, app, screen, app.helpPanel) { + t.Error("expected a mark on a help screen that doesn't fit") + } + screen.InjectKey(tcell.KeyEnd, 0, tcell.ModNone) + waitForDraw(t, screen) + if markShown(t, app, screen, app.helpPanel) { + t.Error("expected no mark at the end of the help screen") + } +} diff --git a/ui/sessions_test.go b/ui/sessions_test.go index 1ee1901..82d38ed 100644 --- a/ui/sessions_test.go +++ b/ui/sessions_test.go @@ -339,8 +339,8 @@ func TestSwitchKeepsEachConnectionAsItWas(t *testing.T) { if got := editorText(appB); got != "" { t.Errorf("expected beta's own (empty) left panel, got %q", got) } - if status := statusText(appB); !strings.Contains(status, b.url) { - t.Errorf("expected the status bar to name beta, got %q", status) + if header := headerText(appB); !strings.Contains(header, b.url) { + t.Errorf("expected the header to name beta, got %q", header) } h.key(t, tcell.KeyCtrlO) diff --git a/ui/statusbar.go b/ui/statusbar.go index 71d974c..7e9871b 100644 --- a/ui/statusbar.go +++ b/ui/statusbar.go @@ -2,6 +2,7 @@ package ui import ( "fmt" + "strings" "time" "github.com/gdamore/tcell/v2" @@ -11,27 +12,23 @@ import ( "github.com/gnocent/termdevtools/i18n" ) -// StatusBar displays the current state (cluster, request in progress, -// result) and a help bar reminding the shortcuts. See SPEC.md §3.1 and §4. +// StatusBar is the line at the bottom of the main screen: the state of the +// last operation (request in progress, result, error...) and, in the room +// that leaves, the shortcuts. See SPEC.md §3.1 and §4. type StatusBar struct { - // product is the cluster's detected distribution and version in short - // form ("ES 9.5.4"), empty when unknown. - product string - cluster string - user string - msgs *i18n.Strings - - status *statusLine - help *tview.TextView + msgs *i18n.Strings + + status *composedLine // renders counts what was written to the status line, see Version. renders int - // message and color are what the status line currently says, at its end. + // message and color are what the status line currently says. message, color string } -// statusLine is the status line's TextView, its text composed for the width -// it is drawn at (StatusBar.compose): the width is only known then. -type statusLine struct { +// composedLine is a one-line TextView whose text is composed for the width +// it is drawn at (StatusBar.compose, header.compose): the width is only +// known then. +type composedLine struct { *tview.TextView compose func(width int) string // width is the one the current text was composed for; 0 before the @@ -39,7 +36,7 @@ type statusLine struct { width int } -func (l *statusLine) Draw(screen tcell.Screen) { +func (l *composedLine) Draw(screen tcell.Screen) { if _, _, width, _ := l.GetInnerRect(); width != l.width { l.width = width l.SetText(l.compose(width)) @@ -47,6 +44,14 @@ func (l *statusLine) Draw(screen tcell.Screen) { l.TextView.Draw(screen) } +// MouseHandler ignores the mouse: a click on the line would otherwise give +// it the focus, which no panel would then have. +func (l *composedLine) MouseHandler() func(tview.MouseAction, *tcell.EventMouse, func(tview.Primitive)) (bool, tview.Primitive) { + return func(tview.MouseAction, *tcell.EventMouse, func(tview.Primitive)) (bool, tview.Primitive) { + return false, nil + } +} + // Version changes every time the status line is written: what lets a // background operation tell, when it ends, whether the line still shows what // it put there or something more recent that it must not cover. @@ -54,88 +59,83 @@ func (sb *StatusBar) Version() int { return sb.renders } -// NewStatusBar creates the status bar for the given cluster/user. product -// is the cluster's detected distribution and version ("ES 9.5.4"), or empty. -func NewStatusBar(product, cluster, user string, msgs *i18n.Strings) *StatusBar { - sb := &StatusBar{ - product: product, - cluster: cluster, - user: user, - msgs: msgs, - help: tview.NewTextView().SetDynamicColors(true).SetText(msgs.ShortcutsHelpBar), - } - sb.status = &statusLine{TextView: tview.NewTextView().SetDynamicColors(true), compose: sb.compose} +// NewStatusBar creates the status bar. +func NewStatusBar(msgs *i18n.Strings) *StatusBar { + sb := &StatusBar{msgs: msgs} + view := tview.NewTextView().SetDynamicColors(true).SetWrap(false) + view.SetBorderPadding(0, 0, 1, 1) + sb.status = &composedLine{TextView: view, compose: sb.compose} sb.SetIdle() return sb } -// SetLanguage re-applies the shortcuts help bar in msgs' language. The -// current status line is left untouched — it stays in the previous -// language until the next SetIdle/SetRunning/SetInfo/SetResult/SetError -// call re-renders it (the caller typically issues one right after -// SetLanguage to confirm the switch immediately). +// SetLanguage re-applies the shortcuts in msgs' language. The current +// message is left untouched — it stays in the previous language until the +// next SetIdle/SetRunning/SetInfo/SetResult/SetError call re-renders it (the +// caller typically issues one right after SetLanguage to confirm the switch +// immediately). func (sb *StatusBar) SetLanguage(msgs *i18n.Strings) { sb.msgs = msgs - sb.help.SetText(msgs.ShortcutsHelpBar) + sb.status.SetText(sb.compose(sb.status.width)) } -// Widget returns the container (status + help) to insert into the layout. +// Widget returns the line to insert into the layout. func (sb *StatusBar) Widget() tview.Primitive { - return tview.NewFlex().SetDirection(tview.FlexRow). - AddItem(sb.status, 1, 0, false). - AddItem(sb.help, 1, 0, false) + return sb.status } -// render writes message at the end of the status line. +// render writes message on the status line. func (sb *StatusBar) render(message, color string) { sb.renders++ - sb.message, sb.color = message, color + // One row: what follows a line break would not be displayed. + sb.message, sb.color = strings.ReplaceAll(message, "\n", " "), color sb.status.SetText(sb.compose(sb.status.width)) } -// statusSeparator separates the parts of the status line. -const statusSeparator = " | " - -// minStatusURLWidth is the fewest columns a URL cut short keeps on the status -// line, "…" included: fewer wouldn't say which cluster it is. -const minStatusURLWidth = 12 +const ( + // shortcutsSeparator separates the entries of msgs.ShortcutsHelpBar. + shortcutsSeparator = " " + // shortcutsGap is what separates them on the line, where room counts. + shortcutsGap = " " + // minStatusGap is the fewest columns between the message and the + // shortcuts. + minStatusGap = 3 +) -// compose builds the status line for width columns: the cluster, the user, -// then the message — the part that matters most, often the only sign that -// something happened (a write refused on a read-only cluster). When the -// whole line doesn't fit, the user goes first, then the URL is cut short, -// and last the cluster goes too, the message being cut short only when it -// doesn't fit alone. The detected product, when known, takes the place of -// the generic "Cluster" caption in front of the URL rather than being added -// to the line, for the same reason. A width of 0 (not drawn yet) gives the -// whole line. +// compose builds the status line for width columns: the message on the left +// — the part that matters most, often the only sign that something happened +// (a write refused on a read-only cluster) — and on the right as many +// shortcuts as the message leaves room for, in the order of the catalog and +// never one cut in two. The message is only cut short when it doesn't fit +// alone. A width of 0 (not drawn yet) gives the whole line. func (sb *StatusBar) compose(width int) string { - caption := sb.product - if caption == "" { - caption = sb.msgs.StatusClusterCaption - } - cluster := func(url string) string { - return fmt.Sprintf("[white]%s: [green]%s[white]", tview.Escape(caption), tview.Escape(url)) + messageWidth := uniseg.StringWidth(sb.message) + if width > 0 && messageWidth > width { + return fmt.Sprintf("[%s]%s[white]", sb.color, tview.Escape(cutShort(sb.message, width))) } - user := fmt.Sprintf("%s: [green]%s[white]", tview.Escape(sb.msgs.StatusUserCaption), tview.Escape(sb.user)) - message := func(text string) string { - return fmt.Sprintf("[%s]%s[white]", sb.color, tview.Escape(text)) + message := fmt.Sprintf("[%s]%s[white]", sb.color, tview.Escape(sb.message)) + + var shortcuts []string + columns := 0 + for _, entry := range strings.Split(sb.msgs.ShortcutsHelpBar, shortcutsSeparator) { + needed := tview.TaggedStringWidth(entry) + if len(shortcuts) > 0 { + needed += len(shortcutsGap) + } + if width > 0 && messageWidth+minStatusGap+columns+needed > width { + break + } + shortcuts = append(shortcuts, entry) + columns += needed } - - clusterWidth := uniseg.StringWidth(caption + ": " + sb.cluster) - userWidth := uniseg.StringWidth(sb.msgs.StatusUserCaption + ": " + sb.user) - messageWidth := uniseg.StringWidth(sb.message) - separator := len(statusSeparator) - switch { - case width <= 0 || clusterWidth+separator+userWidth+separator+messageWidth <= width: - return cluster(sb.cluster) + statusSeparator + user + statusSeparator + message(sb.message) - case clusterWidth+separator+messageWidth <= width: - return cluster(sb.cluster) + statusSeparator + message(sb.message) + if len(shortcuts) == 0 { + return message } - if room := width - separator - messageWidth - uniseg.StringWidth(caption+": "); room >= minStatusURLWidth { - return cluster(cutShort(sb.cluster, room)) + statusSeparator + message(sb.message) + gap := minStatusGap + if width > 0 { + gap = width - messageWidth - columns } - return message(cutShort(sb.message, width)) + return message + strings.Repeat(" ", gap) + strings.Join(shortcuts, shortcutsGap) } // SetIdle displays the default "ready" state. diff --git a/ui/statusbar_test.go b/ui/statusbar_test.go index eaa3043..b315b2b 100644 --- a/ui/statusbar_test.go +++ b/ui/statusbar_test.go @@ -16,42 +16,52 @@ func plainText(tagged string) string { } // TestStatusLineGivesWayToTheMessage checks what the status line keeps when -// it doesn't fit: the message, at the expense of the user, then of the URL, -// then of the cluster altogether. +// it doesn't fit: the message, at the expense of the shortcuts, dropped one +// by one and from the last, each of them whole. func TestStatusLineGivesWayToTheMessage(t *testing.T) { - sb := NewStatusBar("ES 9.5.4", "https://es-prod.example.test:9200", "svc_devtools", i18n.For(i18n.FR)) + sb := NewStatusBar(i18n.For(i18n.FR)) cases := []struct { message string width int want string }{ - {"prêt", 0, "ES 9.5.4: https://es-prod.example.test:9200 | Utilisateur: svc_devtools | prêt"}, - {"prêt", 82, "ES 9.5.4: https://es-prod.example.test:9200 | Utilisateur: svc_devtools | prêt"}, - {"prêt", 81, "ES 9.5.4: https://es-prod.example.test:9200 | prêt"}, - {"envoi annulé : rien n'a été envoyé", 82, "ES 9.5.4: https://es-prod.example.test:9200 | envoi annulé : rien n'a été envoyé"}, - {"envoi annulé : rien n'a été envoyé", 80, "ES 9.5.4: https://es-prod.example.test:9… | envoi annulé : rien n'a été envoyé"}, - {"envoi annulé : rien n'a été envoyé", 61, "ES 9.5.4: https://es-… | envoi annulé : rien n'a été envoyé"}, - {"envoi annulé : rien n'a été envoyé", 60, "envoi annulé : rien n'a été envoyé"}, + {"prêt", 40, "prêt F1 aide Ctrl+E exécuter"}, + {"prêt", 80, "prêt F1 aide Ctrl+E exécuter F8 recettes Ctrl+C quitter F3 langue"}, + {"HTTP 200 en 42ms", 78, "HTTP 200 en 42ms F1 aide Ctrl+E exécuter F8 recettes Ctrl+C quitter"}, + {"envoi annulé : rien n'a été envoyé", 78, "envoi annulé : rien n'a été envoyé F1 aide Ctrl+E exécuter F8 recettes"}, + {"envoi annulé : rien n'a été envoyé", 50, "envoi annulé : rien n'a été envoyé F1 aide"}, + {"envoi annulé : rien n'a été envoyé", 43, "envoi annulé : rien n'a été envoyé"}, {"envoi annulé : rien n'a été envoyé", 20, "envoi annulé : rien…"}, } for _, c := range cases { sb.SetInfo(c.message) - if got := plainText(sb.compose(c.width)); got != c.want { + got := plainText(sb.compose(c.width)) + if got != c.want { t.Errorf("%q in %d columns: expected\n%q, got\n%q", c.message, c.width, c.want, got) } - if got := plainText(sb.compose(c.width)); c.width > 0 && uniseg.StringWidth(got) > c.width { - t.Errorf("%q in %d columns: %d columns used", c.message, c.width, uniseg.StringWidth(got)) + if used := uniseg.StringWidth(got); used > c.width { + t.Errorf("%q in %d columns: %d columns used", c.message, c.width, used) } } } +// TestStatusLineStaysOnOneRow checks that a message with a line break, an +// error's text for instance, doesn't push the rest of the line out of sight. +func TestStatusLineStaysOnOneRow(t *testing.T) { + sb := NewStatusBar(i18n.For(i18n.FR)) + sb.SetError("échec\nde la requête") + if got, want := plainText(sb.compose(30)), "échec de la requête"; !strings.HasPrefix(got, want) || strings.Contains(got, "\n") { + t.Errorf("expected %q on one row, got %q", want, got) + } +} + // TestStatusLineKeepsColorsAndBrackets checks that the message keeps its // color once the line is cut short, and that brackets in it aren't taken // for color tags. func TestStatusLineKeepsColorsAndBrackets(t *testing.T) { - sb := NewStatusBar("ES 9.5.4", "https://es-prod.example.test:9200", "svc_devtools", i18n.For(i18n.FR)) + sb := NewStatusBar(i18n.For(i18n.FR)) sb.SetError("[red] HTTP 404 sur /my-index") - got := sb.compose(40) + got := sb.compose(30) if !strings.HasPrefix(got, "[red]") || plainText(got) != "[red] HTTP 404 sur /my-index" { t.Errorf("expected the message alone, in red and as written, got %q (%q)", got, plainText(got)) } diff --git a/ui/target_test.go b/ui/target_test.go index 82a8817..ae731fa 100644 --- a/ui/target_test.go +++ b/ui/target_test.go @@ -7,25 +7,25 @@ import ( "github.com/gnocent/termdevtools/refdata" ) -// TestStatusBarShowsDetectedTarget checks that the distribution and version +// TestHeaderShowsDetectedTarget checks that the distribution and version // detected at connection are visible in front of the cluster's URL, in place // of the generic "Cluster" caption. -func TestStatusBarShowsDetectedTarget(t *testing.T) { +func TestHeaderShowsDetectedTarget(t *testing.T) { _, screen := newTestAppWith(t, testAppOptions{ target: refdata.Target{Distribution: refdata.OpenSearch, Version: refdata.Version{Major: 2, Minor: 19, Patch: 6}, HasVersion: true}, }) - if text := screenText(screen); !strings.Contains(text, "OS 2.19.6: http://127.0.0.1:1") { - t.Errorf("expected the status bar to show the target in front of the URL, got:\n%s", text) + if text := screenText(screen); !strings.Contains(text, " OS 2.19.6 http://127.0.0.1:1") { + t.Errorf("expected the header to show the target in front of the URL, got:\n%s", text) } } -// TestStatusBarWithoutDetectedTarget checks the fallback when detection -// found nothing: the generic caption. -func TestStatusBarWithoutDetectedTarget(t *testing.T) { +// TestHeaderWithoutDetectedTarget checks the fallback when detection found +// nothing: the generic caption. +func TestHeaderWithoutDetectedTarget(t *testing.T) { _, screen := newTestAppWith(t, testAppOptions{undetected: true}) - if text := screenText(screen); !strings.Contains(text, "Cluster: http://127.0.0.1:1") { + if text := screenText(screen); !strings.Contains(text, " Cluster http://127.0.0.1:1") { t.Errorf("expected the generic caption in front of the URL, got:\n%s", text) } } diff --git a/ui/theme.go b/ui/theme.go new file mode 100644 index 0000000..751fb77 --- /dev/null +++ b/ui/theme.go @@ -0,0 +1,84 @@ +package ui + +import ( + "github.com/gdamore/tcell/v2" + "github.com/rivo/tview" +) + +// The interface's palette (SPEC.md §3.1): fixed colors on a dark background +// of its own, so that it reads the same whatever the terminal's theme. Red +// and yellow say something about the cluster or the last request and nothing +// else; the rest of the chrome keeps to blue and gray. A terminal without +// 24-bit colors gets the closest colors it has, from tcell. +var ( + themeBackground = tcell.NewHexColor(0x1D1E24) + themeSurface = tcell.NewHexColor(0x25262E) // the header + themeField = tcell.NewHexColor(0x343741) // form fields, buttons + themeText = tcell.NewHexColor(0xDFE5EF) + themeMuted = tcell.NewHexColor(0x98A2B3) + themeBorder = tcell.NewHexColor(0x69707D) + themeAccent = tcell.NewHexColor(0x1BA9F5) + themeTeal = tcell.NewHexColor(0x00BFB3) + themeYellow = tcell.NewHexColor(0xFEC514) + themePink = tcell.NewHexColor(0xF04E98) + themeRed = tcell.NewHexColor(0xF86B63) // on the dark background + themeDanger = tcell.NewHexColor(0xBD271E) // behind themeWhite + themeWhite = tcell.NewHexColor(0xFFFFFF) +) + +func init() { + tview.Styles = tview.Theme{ + PrimitiveBackgroundColor: themeBackground, + ContrastBackgroundColor: themeField, + MoreContrastBackgroundColor: themeField, + BorderColor: themeBorder, + TitleColor: themeText, + GraphicsColor: themeBorder, + PrimaryTextColor: themeText, + SecondaryTextColor: themeAccent, + TertiaryTextColor: themeMuted, + InverseTextColor: themeBackground, + ContrastSecondaryTextColor: themeMuted, + } + + // The color tags, here and in the i18n catalogs, keep the names that say + // what they mean ("[red]" an error, "[gray]" what stays in the + // background): the theme defines what the names stand for, "[white]" + // being the color of the text. + tcell.ColorNames["white"] = themeText + tcell.ColorNames["gray"] = themeMuted + tcell.ColorNames["aqua"] = themeAccent + tcell.ColorNames["green"] = themeTeal + tcell.ColorNames["yellow"] = themeYellow + tcell.ColorNames["fuchsia"] = themePink + tcell.ColorNames["red"] = themeRed + + // The panel with the focus is told apart by its shape as well as by its + // color (panelBorderColor), which a terminal may not show (NO_COLOR). + tview.Borders.HorizontalFocus = tview.BoxDrawingsHeavyHorizontal + tview.Borders.VerticalFocus = tview.BoxDrawingsHeavyVertical + tview.Borders.TopLeftFocus = tview.BoxDrawingsHeavyDownAndRight + tview.Borders.TopRightFocus = tview.BoxDrawingsHeavyDownAndLeft + tview.Borders.BottomLeftFocus = tview.BoxDrawingsHeavyUpAndRight + tview.Borders.BottomRightFocus = tview.BoxDrawingsHeavyUpAndLeft +} + +// panelBorderColor is the border color of a panel with or without the focus. +func panelBorderColor(focused bool) tcell.Color { + if focused { + return themeAccent + } + return themeBorder +} + +// methodColor is the color of an HTTP method in the editor (paintRequests): +// what can destroy data stands out from what only reads. +func methodColor(method string) tcell.Color { + switch method { + case "GET": + return themeTeal + case "DELETE": + return themeRed + } + return themeAccent +} diff --git a/ui/theme_test.go b/ui/theme_test.go new file mode 100644 index 0000000..5801973 --- /dev/null +++ b/ui/theme_test.go @@ -0,0 +1,113 @@ +package ui + +import ( + "math" + "testing" + + "github.com/gdamore/tcell/v2" +) + +// contrast is the WCAG contrast ratio between two colors. +func contrast(a, b tcell.Color) float64 { + luminance := func(c tcell.Color) float64 { + r, g, b := c.RGB() + channel := func(v int32) float64 { + s := float64(v) / 255 + if s <= 0.03928 { + return s / 12.92 + } + return math.Pow((s+0.055)/1.055, 2.4) + } + return 0.2126*channel(r) + 0.7152*channel(g) + 0.0722*channel(b) + } + la, lb := luminance(a), luminance(b) + return (math.Max(la, lb) + 0.05) / (math.Min(la, lb) + 0.05) +} + +// TestThemeIsReadable pins the contrast of what the interface puts on what: +// 4.5 for text (WCAG AA), 3 for the borders, which are chrome. +func TestThemeIsReadable(t *testing.T) { + cases := []struct { + name string + fg, bg tcell.Color + minimum float64 + }{ + {"text", themeText, themeBackground, 4.5}, + {"muted text", themeMuted, themeBackground, 4.5}, + {"accent", themeAccent, themeBackground, 4.5}, + {"teal", themeTeal, themeBackground, 4.5}, + {"yellow", themeYellow, themeBackground, 4.5}, + {"pink", themePink, themeBackground, 4.5}, + {"red", themeRed, themeBackground, 4.5}, + {"header", themeText, themeSurface, 4.5}, + {"header, muted", themeMuted, themeSurface, 4.5}, + {"form field", themeText, themeField, 4.5}, + {"Elasticsearch badge", themeBackground, themeTeal, 4.5}, + {"OpenSearch badge", themeBackground, themeAccent, 4.5}, + {"writes confirmed", themeWhite, themeDanger, 4.5}, + {"read-only", themeBackground, themeYellow, 4.5}, + {"border", themeBorder, themeBackground, 3}, + } + for _, c := range cases { + if got := contrast(c.fg, c.bg); got < c.minimum { + t.Errorf("%s: contrast %.1f, expected at least %.1f", c.name, got, c.minimum) + } + } +} + +// TestThemeSurvivesFewerColors checks that the colors that must stay apart +// still are once a terminal without 24-bit colors has picked its closest +// ones: tcell does that from the palette of the terminal's first colors. +func TestThemeSurvivesFewerColors(t *testing.T) { + for _, colors := range []int{8, 16, 256} { + palette := make([]tcell.Color, colors) + for i := range palette { + palette[i] = tcell.PaletteColor(i) + } + background := tcell.FindColor(themeBackground, palette) + for name, color := range map[string]tcell.Color{ + "text": themeText, "muted text": themeMuted, "border": themeBorder, "accent": themeAccent, + "teal": themeTeal, "yellow": themeYellow, "red": themeRed, + } { + if tcell.FindColor(color, palette) == background { + t.Errorf("%d colors: %s can't be told from the background", colors, name) + } + } + } +} + +// TestColorTagsFollowTheTheme guards what the theme relies on: tview reads +// a tag's color through tcell.ColorNames. +func TestColorTagsFollowTheTheme(t *testing.T) { + for name, want := range map[string]tcell.Color{ + "white": themeText, "gray": themeMuted, "aqua": themeAccent, "green": themeTeal, + "yellow": themeYellow, "fuchsia": themePink, "red": themeRed, + } { + if got := tcell.GetColor(name); got != want { + t.Errorf("[%s]: expected %v, got %v", name, want, got) + } + } +} + +// TestThemeLeavesNoHole checks that nothing on the main screen, a popup +// included, is left on the terminal's own background: it would show through +// as patches on anything but a black terminal. +func TestThemeLeavesNoHole(t *testing.T) { + check := func(t *testing.T, screen tcell.SimulationScreen) { + t.Helper() + _, width, height := screenContents(screen) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + if got := screenBackground(screen, x, y); got == tcell.ColorDefault || got == tcell.ColorBlack { + t.Fatalf("cell %d,%d: background %v", x, y, got) + } + } + } + } + + _, screen := newTestApp(t) + check(t, screen) + screen.InjectKey(tcell.KeyF1, 0, tcell.ModNone) + waitForDraw(t, screen) + check(t, screen) +}