From 69bc9fbb9e3f9892f7dbc6e2eb996212bedd5c3a Mon Sep 17 00:00:00 2001 From: GNocent <154062033+gnocent@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:35:48 +0100 Subject: [PATCH] Copy with pbcopy on a Mac outside SSH MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F2 and F9 copied only through the terminal (OSC 52), which macOS Terminal ignores: nothing reached the clipboard there. On a Mac the program runs on directly (none of SSH_CONNECTION, SSH_CLIENT, SSH_TTY set), they now go through pbcopy, which works in any terminal and confirms the copy: the status bar drops its "(OSC 52 — requires a compatible terminal)" reservation. Should pbcopy fail, the copy goes through the terminal, as elsewhere. Through SSH, pbcopy would fill the remote Mac's pasteboard, so the terminal stays the only way. pbcopy reads its input in the locale's encoding: it is run under LC_ALL=en_US.UTF-8, or anything but ASCII would arrive garbled under a locale that isn't UTF-8. TestPbcopyKeepsUnicode checks that on macOS, against the real pasteboard, whose text it puts back. The ui tests leave the pasteboard out (TestMain): on a Mac they would otherwise replace what the developer had copied, and couldn't check what goes to the terminal. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + CHANGELOG_fr.md | 1 + INSTALL.md | 2 +- INSTALL_fr.md | 2 +- SPEC.md | 2 +- SPEC_fr.md | 2 +- i18n/i18n.go | 13 +++-- ui/app.go | 20 +++---- ui/clipboard.go | 57 ++++++++++++++++++++ ui/clipboard_darwin_test.go | 38 +++++++++++++ ui/clipboard_test.go | 105 ++++++++++++++++++++++++++++++++++++ 11 files changed, 222 insertions(+), 21 deletions(-) create mode 100644 ui/clipboard.go create mode 100644 ui/clipboard_darwin_test.go create mode 100644 ui/clipboard_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 199cdce..72e4e80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ### What's new - **The help screen (`F1`) gives the versions**: TermDevTools' own, and the connected cluster's (`Elasticsearch 9.5.4`, `OpenSearch 2.19.6`) when detected — the two things a bug report asks for first. The status bar keeps showing the cluster's in short form (`ES 9.5.4`). +- **`F2` and `F9` copy in any terminal on a Mac**: outside SSH, the copy goes through the system's pasteboard (`pbcopy`) rather than the terminal — macOS Terminal, which doesn't support the terminal's way, included. The status bar then confirms the copy without reservation. Through SSH, nothing changes: the terminal remains the only way to the clipboard of the machine you're at. ### Fixes diff --git a/CHANGELOG_fr.md b/CHANGELOG_fr.md index 768d34c..fa6541d 100644 --- a/CHANGELOG_fr.md +++ b/CHANGELOG_fr.md @@ -7,6 +7,7 @@ ### Nouveautés - **L'écran d'aide (`F1`) donne les versions** : celle de TermDevTools, et celle du cluster connecté (`Elasticsearch 9.5.4`, `OpenSearch 2.19.6`) quand elle a été détectée — les deux choses qu'un rapport de bug demande en premier. La barre d'état continue d'afficher celle du cluster en forme courte (`ES 9.5.4`). +- **`F2` et `F9` copient dans n'importe quel terminal sur Mac** : hors SSH, la copie passe par le presse-papier du système (`pbcopy`) plutôt que par le terminal — y compris dans le Terminal de macOS, qui ne prend pas en charge la voie du terminal. La barre d'état confirme alors la copie sans réserve. À travers SSH, rien ne change : le terminal reste la seule voie vers le presse-papier de la machine où vous êtes. ### Corrections diff --git a/INSTALL.md b/INSTALL.md index b686339..5d936a3 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -355,7 +355,7 @@ Delete the binary and the configuration directory (§5): TermDevTools writes not | 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). | | `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). Windows Terminal, WezTerm, kitty, Alacritty and iTerm2 (once enabled in its settings) support it; PuTTY, macOS Terminal, GNOME Terminal and the other VTE-based terminals don't. In `tmux`: `set -g set-clipboard on`; `screen` needs to be configured for it. | +| `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. | | A request with a huge answer fails with "response larger than 64 MB" | Narrow it down: `filter_path`, `size`, or `h=` for `_cat` commands. | | A proxy is needed to reach the cluster | Set `HTTPS_PROXY`, or `proxy:` on the cluster's entry in `config.yaml` (§5). | | The message starts with `Through proxy …` | The attempt went through that proxy. If the cluster is reached without a proxy — which was the case up to 0.6, which ignored `HTTPS_PROXY` — add it to `NO_PROXY`, or set `proxy: none` on its entry in `config.yaml` (§5). | diff --git a/INSTALL_fr.md b/INSTALL_fr.md index 83e70c0..3574e61 100644 --- a/INSTALL_fr.md +++ b/INSTALL_fr.md @@ -357,7 +357,7 @@ Les messages sont cités en anglais, tels qu'un premier lancement les affiche, p | 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). | | `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). Windows Terminal, WezTerm, kitty, Alacritty et iTerm2 (une fois activé dans ses réglages) la prennent en charge ; PuTTY, le Terminal de macOS, GNOME Terminal et les autres terminaux basés sur VTE, non. Dans `tmux` : `set -g set-clipboard on` ; `screen` demande une configuration. | +| `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. | | Une requête sur une énorme réponse échoue avec « response larger than 64 MB » | Restreignez-la : `filter_path`, `size`, ou `h=` pour les commandes `_cat`. | | Un proxy est nécessaire pour atteindre le cluster | Définissez `HTTPS_PROXY`, ou `proxy:` sur l'entrée du cluster dans `config.yaml` (§5). | | Le message commence par `Through proxy …` / `Via le proxy …` | La tentative est passée par ce proxy. Si le cluster se joint sans proxy — c'était le cas jusqu'à la 0.6, qui ignorait `HTTPS_PROXY` — ajoutez-le à `NO_PROXY`, ou mettez `proxy: none` sur son entrée dans `config.yaml` (§5). | diff --git a/SPEC.md b/SPEC.md index 65c388c..5e2cf2b 100644 --- a/SPEC.md +++ b/SPEC.md @@ -127,7 +127,7 @@ On launch, a connection screen lists the URLs of known clusters (no separate nam - **Redirections**: a `3xx` answer is displayed for what it is — its status, and its `Location` header among the headers — never followed (§5). - **Nothing displayed is interpreted by the terminal**: a response body, its headers or an error message may hold escape sequences (writing to the clipboard, retitling the window, hiding text); the display library never writes a control character to the screen, which a test checks for every way in (`ui/terminal_safety_test.go`). - **Export (`Ctrl+S`, right panel focused)**: writes the currently displayed result (request reminder included) into the `exports/` subfolder of the user's configuration directory (§9.1, created if needed), a timestamped filename followed by a random number (`YYYYMMDD-HHMMSS-`), so that two exports in the same second, from one session or two, never overwrite each other, `.json` extension if the response body is valid JSON, `.txt` otherwise — note that the leading `#` reminder line means the exported `.json` file isn't itself strictly valid JSON, a deliberate trade-off for traceability. Confirmation (with path) shown in the status bar; error (e.g. nothing to export) shown the same way. -- **Copy to clipboard (`F2`)**: when `config.Mouse` is enabled, `tview.Application.EnableMouse(true)` prevents native terminal text selection (the app captures mouse events instead) — no mouse selection possible in this panel in that case. `F2` copies the entire displayed result regardless of the mouse setting, via the standard terminal mechanism **OSC 52** (`tcell.Screen.SetClipboard`): the local terminal receives an escape sequence asking it to copy to *its own* clipboard, which works even over SSH (the clipboard is never the remote server's). Confirmation shown in the status bar, but **with no guarantee the copy actually happened**: neither tcell nor the OSC 52 protocol return a confirmation, and support depends on the terminal: Windows Terminal, WezTerm, kitty, Alacritty, foot and iTerm2 (once enabled in its settings) support it; PuTTY, macOS Terminal, GNOME Terminal and the other VTE-based terminals don't. In tmux, `set -g set-clipboard on` is needed — the default, `external`, keeps the applications inside it from setting the clipboard —; `screen` needs its own configuration. To be verified in real-world use. +- **Copy to clipboard (`F2`)**: when `config.Mouse` is enabled, `tview.Application.EnableMouse(true)` prevents native terminal text selection (the app captures mouse events instead) — no mouse selection possible in this panel in that case. `F2` copies the entire displayed result regardless of the mouse setting, via the standard terminal mechanism **OSC 52** (`tcell.Screen.SetClipboard`): the local terminal receives an escape sequence asking it to copy to *its own* clipboard, which works even over SSH (the clipboard is never the remote server's). Confirmation shown in the status bar, but **with no guarantee the copy actually happened**: neither tcell nor the OSC 52 protocol return a confirmation, and support depends on the terminal: Windows Terminal, WezTerm, kitty, Alacritty, foot and iTerm2 (once enabled in its settings) support it; PuTTY, macOS Terminal, GNOME Terminal and the other VTE-based terminals don't. In tmux, `set -g set-clipboard on` is needed — the default, `external`, keeps the applications inside it from setting the clipboard —; `screen` needs its own configuration. To be verified in real-world use. **On a Mac, outside SSH** (none of `SSH_CONNECTION`, `SSH_CLIENT`, `SSH_TTY` set), `F2` and `F9` go through `pbcopy` instead (`ui/clipboard.go`): it works in any terminal, macOS Terminal included, and confirms the copy, so the status bar drops its reservation. Should `pbcopy` fail, the copy goes through the terminal, as elsewhere. Through SSH, `pbcopy` would fill the remote Mac's pasteboard: only the terminal reaches the user's. ## 4. Keyboard shortcuts diff --git a/SPEC_fr.md b/SPEC_fr.md index c416ecf..6889310 100644 --- a/SPEC_fr.md +++ b/SPEC_fr.md @@ -127,7 +127,7 @@ Au lancement, un écran de connexion liste les URLs des clusters connus (pas de - **Redirections** : une réponse `3xx` est affichée pour ce qu'elle est — son code, et son en-tête `Location` parmi les en-têtes — jamais suivie (§5). - **Rien de ce qui est affiché n'est interprété par le terminal** : le corps d'une réponse, ses en-têtes ou un message d'erreur peuvent contenir des séquences d'échappement (écriture dans le presse-papier, changement de titre, texte masqué) ; la bibliothèque d'affichage n'écrit jamais de caractère de contrôle à l'écran, ce qu'un test vérifie pour chaque point d'entrée (`ui/terminal_safety_test.go`). - **Export (`Ctrl+S`, focus panneau droit)** : écrit le résultat actuellement affiché (rappel de requête inclus) dans le sous-dossier `exports/` du dossier de configuration de l'utilisateur (§9.1, créé si besoin), nom de fichier horodaté suivi d'un nombre aléatoire (`AAAAMMJJ-HHMMSS-`), pour que deux exports dans la même seconde, d'une même session ou de deux, ne s'écrasent jamais, extension `.json` si le corps de la réponse est du JSON valide, `.txt` sinon — la ligne `#` en tête fait que le fichier `.json` exporté n'est lui-même plus strictement du JSON valide, un compromis assumé pour la traçabilité. Confirmation (avec chemin) affichée dans la status bar ; erreur (ex. rien à exporter) affichée de la même façon. -- **Copie dans le presse-papier (`F2`)** : quand `config.Mouse` est activé, `tview.Application.EnableMouse(true)` empêche la sélection de texte native du terminal (l'appli capte les événements souris à la place) — pas de sélection possible à la souris dans ce panneau dans ce cas. `F2` copie l'intégralité du résultat affiché quel que soit le réglage souris, via le mécanisme terminal standard **OSC 52** (`tcell.Screen.SetClipboard`) : le terminal local reçoit une séquence d'échappement lui demandant de copier vers *son propre* presse-papier, ce qui fonctionne même à travers SSH (le presse-papier n'est jamais celui du serveur distant). Confirmation affichée dans la status bar, mais **sans garantie que la copie a réellement eu lieu** : ni tcell ni le protocole OSC 52 ne renvoient de confirmation, et le support dépend du terminal : Windows Terminal, WezTerm, kitty, Alacritty, foot et iTerm2 (une fois activé dans ses réglages) le prennent en charge ; PuTTY, le Terminal de macOS, GNOME Terminal et les autres terminaux basés sur VTE, non. Dans tmux, il faut `set -g set-clipboard on` — la valeur par défaut, `external`, empêche les applications qu'il contient de remplir le presse-papier — ; `screen` demande sa propre configuration. À vérifier en usage réel. +- **Copie dans le presse-papier (`F2`)** : quand `config.Mouse` est activé, `tview.Application.EnableMouse(true)` empêche la sélection de texte native du terminal (l'appli capte les événements souris à la place) — pas de sélection possible à la souris dans ce panneau dans ce cas. `F2` copie l'intégralité du résultat affiché quel que soit le réglage souris, via le mécanisme terminal standard **OSC 52** (`tcell.Screen.SetClipboard`) : le terminal local reçoit une séquence d'échappement lui demandant de copier vers *son propre* presse-papier, ce qui fonctionne même à travers SSH (le presse-papier n'est jamais celui du serveur distant). Confirmation affichée dans la status bar, mais **sans garantie que la copie a réellement eu lieu** : ni tcell ni le protocole OSC 52 ne renvoient de confirmation, et le support dépend du terminal : Windows Terminal, WezTerm, kitty, Alacritty, foot et iTerm2 (une fois activé dans ses réglages) le prennent en charge ; PuTTY, le Terminal de macOS, GNOME Terminal et les autres terminaux basés sur VTE, non. Dans tmux, il faut `set -g set-clipboard on` — la valeur par défaut, `external`, empêche les applications qu'il contient de remplir le presse-papier — ; `screen` demande sa propre configuration. À vérifier en usage réel. **Sur un Mac, hors SSH** (aucune de `SSH_CONNECTION`, `SSH_CLIENT`, `SSH_TTY` définie), `F2` et `F9` passent plutôt par `pbcopy` (`ui/clipboard.go`) : ça fonctionne dans n'importe quel terminal, Terminal de macOS compris, et la copie est confirmée, si bien que la barre d'état abandonne sa réserve. Si `pbcopy` échoue, la copie passe par le terminal, comme ailleurs. À travers SSH, `pbcopy` remplirait le presse-papier du Mac distant : seul le terminal atteint celui de l'utilisateur. ## 4. Raccourcis clavier diff --git a/i18n/i18n.go b/i18n/i18n.go index bbc3226..42bf871 100644 --- a/i18n/i18n.go +++ b/i18n/i18n.go @@ -114,6 +114,9 @@ type Strings struct { ErrNothingToExport string // result.go's Export() ErrNoBodyToFormat string // F4 (reformat JSON body, SPEC.md §7 backlog #1): nothing under the cursor to reformat InfoCurlCopied string // F9 ("copy as cURL", SPEC.md §7 backlog #3) + // appended to InfoCopied/InfoCurlCopied when the copy went through the + // terminal (OSC 52), which can't confirm it + InfoCopiedViaTerminal string // F4: the body can't be re-indented because of "#" lines in or before it ErrFormatCommentsInBody string // Ctrl+C: "%s" — why the left panel wasn't saved; the next Ctrl+C quits anyway @@ -280,10 +283,11 @@ var fr = Strings{ ErrExportFailedFmt: "échec d'export : %s", InfoExportedFmt: "résultat exporté dans %s", ErrNothingToCopy: "aucun résultat à copier", - InfoCopied: "résultat copié (OSC 52 — nécessite un terminal compatible)", + InfoCopied: "résultat copié", ErrNothingToExport: "aucun résultat à exporter", ErrNoBodyToFormat: "aucun corps JSON à reformater", - InfoCurlCopied: "commande cURL copiée (OSC 52 — nécessite un terminal compatible)", + InfoCurlCopied: "commande cURL copiée", + InfoCopiedViaTerminal: " (OSC 52 — nécessite un terminal compatible)", ErrFormatCommentsInBody: "reformatage impossible : ligne # dans ou avant le corps JSON", ErrExitSaveFailedFmt: "non sauvegardé, Ctrl+C pour quitter quand même : %s", ErrSavedRequestsUnread: "requêtes existantes illisibles au démarrage (Ctrl+S pour les remplacer)", @@ -475,10 +479,11 @@ var en = Strings{ ErrExportFailedFmt: "export failed: %s", InfoExportedFmt: "result exported to %s", ErrNothingToCopy: "nothing to copy", - InfoCopied: "result copied (OSC 52 — requires a compatible terminal)", + InfoCopied: "result copied", ErrNothingToExport: "nothing to export", ErrNoBodyToFormat: "no JSON body to reformat", - InfoCurlCopied: "cURL command copied (OSC 52 — requires a compatible terminal)", + InfoCurlCopied: "cURL command copied", + InfoCopiedViaTerminal: " (OSC 52 — requires a compatible terminal)", ErrFormatCommentsInBody: "cannot reformat: # line inside or before the JSON body", ErrExitSaveFailedFmt: "not saved, Ctrl+C again to quit anyway: %s", ErrSavedRequestsUnread: "saved requests could not be read at startup (Ctrl+S to replace them)", diff --git a/ui/app.go b/ui/app.go index defcb65..2c16ac5 100644 --- a/ui/app.go +++ b/ui/app.go @@ -999,7 +999,7 @@ func (a *App) reformatBody() { // copyAsCurl implements F9 (SPEC.md §7 backlog #3, "copy as cURL"): copies // an equivalent curl command for the request under the cursor to the -// clipboard (OSC 52, same mechanism as F2/copyResult) — handy to replicate +// clipboard (copyToClipboard, as F2/copyResult) — handy to replicate // a call outside the tool (a script, a colleague, a bug report). See // esclient.Client.CurlCommand for why the actual secret (password, API key // secret, key passphrase) is replaced with a placeholder rather than @@ -1015,11 +1015,7 @@ func (a *App) copyAsCurl() { a.status.SetError(err.Error()) return } - cmd := a.client.CurlCommand(req.Method, path, body) - if a.screen != nil { - a.screen.SetClipboard([]byte(cmd)) - } - a.status.SetInfo(a.msgs.InfoCurlCopied) + a.copyToClipboard(a.client.CurlCommand(req.Method, path, body), a.msgs.InfoCurlCopied) } // resolveRequest applies variable substitution (${name}, SPEC.md §7 @@ -1440,21 +1436,19 @@ func (a *App) exportResult() { } // copyResult implements F2: copies the entire displayed result to the local -// clipboard via OSC 52 (SPEC.md §3.3) — the only way to copy from this +// clipboard (copyToClipboard, SPEC.md §3.3) — the only way to copy from this // panel when config.Mouse is enabled, since that captures mouse events for // the app instead of letting the terminal handle native text selection. -// Available either way, mouse or not. Best-effort: neither tcell nor OSC 52 -// return confirmation that the copy actually succeeded on the terminal side. +// Available either way, mouse or not. Best-effort through the terminal: +// neither tcell nor OSC 52 return confirmation that the copy actually +// succeeded on the terminal side. func (a *App) copyResult() { text := a.result.PlainText() if text == "" { a.status.SetError(a.msgs.ErrNothingToCopy) return } - if a.screen != nil { - a.screen.SetClipboard([]byte(text)) - } - a.status.SetInfo(a.msgs.InfoCopied) + a.copyToClipboard(text, a.msgs.InfoCopied) } // toggleLanguage implements F3: flips the interface language (fr/en), diff --git a/ui/clipboard.go b/ui/clipboard.go new file mode 100644 index 0000000..15e2a17 --- /dev/null +++ b/ui/clipboard.go @@ -0,0 +1,57 @@ +package ui + +import ( + "os" + "os/exec" + "runtime" + "strings" +) + +// pasteboard copies text to the clipboard of the machine the program runs +// on; nil where that isn't the user's own clipboard or can't be reached +// without a dependency — see localPasteboard. F2 and F9 fall back on the +// terminal (OSC 52) without it. +var pasteboard = localPasteboard(runtime.GOOS, os.Getenv) + +// localPasteboard is pbcopy on a Mac the program runs on directly, where it +// is always there and works in any terminal — macOS Terminal included, +// which ignores OSC 52. Nil anywhere else, and through SSH, where pbcopy +// would fill the remote Mac's pasteboard instead of the user's: only the +// terminal reaches theirs. +func localPasteboard(goos string, getenv func(string) string) func(string) error { + if goos != "darwin" { + return nil + } + for _, name := range []string{"SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY"} { + if getenv(name) != "" { + return nil + } + } + return pbcopy +} + +// pbcopy hands text to macOS's pbcopy command. +func pbcopy(text string) error { + cmd := exec.Command("pbcopy") + cmd.Stdin = strings.NewReader(text) + // pbcopy reads its input in the locale's encoding: under a locale that + // isn't UTF-8 (LANG unset, say), anything but ASCII would arrive garbled. + cmd.Env = append(os.Environ(), "LC_ALL=en_US.UTF-8") + return cmd.Run() +} + +// copyToClipboard implements the copy of F2 and F9: text goes to the +// pasteboard when there is one (see pasteboard), else through the terminal +// (OSC 52, SPEC.md §3.3), which can't confirm the copy — message +// (InfoCopied, InfoCurlCopied) then says it depends on the terminal. A +// pasteboard that fails also falls back on the terminal. +func (a *App) copyToClipboard(text, message string) { + if pasteboard != nil && pasteboard(text) == nil { + a.status.SetInfo(message) + return + } + if a.screen != nil { + a.screen.SetClipboard([]byte(text)) + } + a.status.SetInfo(message + a.msgs.InfoCopiedViaTerminal) +} diff --git a/ui/clipboard_darwin_test.go b/ui/clipboard_darwin_test.go new file mode 100644 index 0000000..5bd71b6 --- /dev/null +++ b/ui/clipboard_darwin_test.go @@ -0,0 +1,38 @@ +package ui + +import ( + "os" + "os/exec" + "testing" +) + +// pbpaste reads the pasteboard back as UTF-8, whatever the locale. +func pbpaste(t *testing.T) string { + t.Helper() + cmd := exec.Command("pbpaste") + cmd.Env = append(os.Environ(), "LC_ALL=en_US.UTF-8") + out, err := cmd.Output() + if err != nil { + t.Fatalf("pbpaste: %v", err) + } + return string(out) +} + +// TestPbcopyKeepsUnicode copies through the real pasteboard, under a locale +// that isn't UTF-8 — the case where pbcopy left to itself garbles anything +// but ASCII. The pasteboard's previous text is put back afterwards. +func TestPbcopyKeepsUnicode(t *testing.T) { + saved := pbpaste(t) + t.Cleanup(func() { _ = pbcopy(saved) }) + for _, name := range []string{"LC_ALL", "LC_CTYPE", "LANG"} { + t.Setenv(name, "") + } + + text := `{"index":"logs-été","node":"nœud-1 ✓"}` + if err := pbcopy(text); err != nil { + t.Fatalf("pbcopy: %v", err) + } + if got := pbpaste(t); got != text { + t.Errorf("expected the pasteboard to hold %q, got %q", text, got) + } +} diff --git a/ui/clipboard_test.go b/ui/clipboard_test.go new file mode 100644 index 0000000..a602087 --- /dev/null +++ b/ui/clipboard_test.go @@ -0,0 +1,105 @@ +package ui + +import ( + "errors" + "os" + "strings" + "testing" + + "github.com/gdamore/tcell/v2" +) + +func TestMain(m *testing.M) { + // The tests check what F2 and F9 send to the terminal (OSC 52). On a Mac + // they would go to the real pasteboard instead — and replace what the + // developer running them had copied. + pasteboard = nil + os.Exit(m.Run()) +} + +func TestLocalPasteboard(t *testing.T) { + for _, c := range []struct { + name string + goos string + env map[string]string + want bool + }{ + {"on a Mac", "darwin", nil, true}, + {"on Linux", "linux", nil, false}, + {"on Windows", "windows", nil, false}, + {"through SSH (SSH_CONNECTION)", "darwin", map[string]string{"SSH_CONNECTION": "10.0.0.1 52000 10.0.0.2 22"}, false}, + {"through SSH (SSH_CLIENT)", "darwin", map[string]string{"SSH_CLIENT": "10.0.0.1 52000 22"}, false}, + {"through SSH (SSH_TTY)", "darwin", map[string]string{"SSH_TTY": "/dev/ttys003"}, false}, + } { + t.Run(c.name, func(t *testing.T) { + got := localPasteboard(c.goos, func(name string) string { return c.env[name] }) != nil + if got != c.want { + t.Errorf("expected a pasteboard: %v, got %v", c.want, got) + } + }) + } +} + +// usePasteboard makes the tests' app copy through fake instead of the +// terminal, as on a Mac. +func usePasteboard(t *testing.T, fake func(string) error) { + t.Helper() + pasteboard = fake + t.Cleanup(func() { pasteboard = nil }) +} + +func TestCopyGoesToThePasteboard(t *testing.T) { + var copied []string + usePasteboard(t, func(text string) error { + copied = append(copied, text) + return nil + }) + app, screen := newTestApp(t) + + onUI(app, func() { app.result.Show("GET", "_cluster/health", nil, []byte(`{"status":"green"}`)) }) + waitForDraw(t, screen) + screen.InjectKey(tcell.KeyF2, 0, tcell.ModNone) + waitForDraw(t, screen) + + if want := uiValue(app, app.result.PlainText); len(copied) != 1 || copied[0] != want { + t.Errorf("expected F2 to copy %q to the pasteboard, got %q", want, copied) + } + if got := screen.GetClipboardData(); len(got) != 0 { + t.Errorf("expected nothing sent to the terminal once the pasteboard has it, got %q", got) + } + // The pasteboard confirms the copy: the message doesn't hedge. + if status := statusText(app); !strings.Contains(status, app.msgs.InfoCopied) || strings.Contains(status, "OSC 52") { + t.Errorf("expected the plain copy confirmation, got %q", status) + } + + injectText(screen, "GET _cat/health?v") + waitForDraw(t, screen) + screen.InjectKey(tcell.KeyF9, 0, tcell.ModNone) + waitForDraw(t, screen) + + if want := "curl -X GET 'http://127.0.0.1:1/_cat/health?v'"; len(copied) != 2 || copied[1] != want { + t.Errorf("expected F9 to copy %q to the pasteboard, got %q", want, copied) + } + if status := statusText(app); !strings.Contains(status, app.msgs.InfoCurlCopied) || strings.Contains(status, "OSC 52") { + t.Errorf("expected the plain copy confirmation, got %q", status) + } +} + +// TestCopyFallsBackOnTheTerminal: a pasteboard that fails (pbcopy missing, +// say) leaves the copy to the terminal, as anywhere else. +func TestCopyFallsBackOnTheTerminal(t *testing.T) { + usePasteboard(t, func(string) error { return errors.New("pbcopy: not found") }) + app, screen := newTestApp(t) + + onUI(app, func() { app.result.Show("GET", "_cluster/health", nil, []byte(`{"status":"green"}`)) }) + waitForDraw(t, screen) + screen.InjectKey(tcell.KeyF2, 0, tcell.ModNone) + waitForDraw(t, screen) + + if got, want := string(screen.GetClipboardData()), uiValue(app, app.result.PlainText); got != want { + t.Errorf("expected the terminal to get %q, got %q", want, got) + } + if status, want := statusText(app), app.msgs.InfoCopied+app.msgs.InfoCopiedViaTerminal; !strings.Contains(status, want) { + t.Errorf("expected the status bar to say %q, got %q", want, status) + } +}