From 7523cec0ce67c021e2a5c5392d52d0b41ef7469c Mon Sep 17 00:00:00 2001 From: Xun <58657914+eeeXun@users.noreply.github.com> Date: Wed, 26 Oct 2022 08:18:23 +0800 Subject: [PATCH] feat: copy text (#1) * copy key with `` `` `` --- README.md | 15 +++++++++++++++ ui.go | 30 ++++++++++++++++++++++++++++++ utils.go | 19 +++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/README.md b/README.md index acf2f06..504825c 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,15 @@ Swap language. `` Clear all text in left window. +`` +Copy selected text in left window. + +`` +Copy all text in left window. + +`` +Copy all text in right window. + `` Play sound on left window. @@ -47,6 +56,12 @@ Cycle through the pop out widget. `<1>`, `<2>`, `<3>` Switch pop out window. +## Dependencies + +`xclip` For Linux to copy text. + +`pbcopy` For macOS to copy text. + ## Credit [snsd0805/GoogleTranslate-TUI](https://github.com/snsd0805/GoogleTranslate-TUI) For inspiration. diff --git a/ui.go b/ui.go index ebd33bf..7341af7 100644 --- a/ui.go +++ b/ui.go @@ -20,6 +20,12 @@ const ( Swap language. [#%[1]s][-] Clear all text in left window. +[#%[1]s][-] + Copy selected text in left window. +[#%[1]s][-] + Copy all text in left window. +[#%[1]s][-] + Copy all text in right window. [#%[1]s][-] Play sound on left window. [#%[1]s][-] @@ -370,6 +376,30 @@ func translatePageHandler(event *tcell.EventKey) *tcell.EventKey { } case tcell.KeyCtrlQ: srcInput.SetText("", true) + case tcell.KeyCtrlY: + // copy selected text + text, _, _ := srcInput.GetSelection() + + // only copy when text selected + if len(text) > 0 { + CopyToClipboard(text) + } + case tcell.KeyCtrlG: + // copy all text in Input + text := srcInput.GetText() + + // only copy when text exist + if len(text) > 0 { + CopyToClipboard(text) + } + case tcell.KeyCtrlR: + // copy all text in Output + text := dstOutput.GetText(false) + + // only copy when text exist + if len(text) > 0 { + CopyToClipboard(text[:len(text)-1]) + } case tcell.KeyCtrlS: translator.SrcLang, translator.DstLang = translator.DstLang, translator.SrcLang updateTitle() diff --git a/utils.go b/utils.go index 39b0a17..7a35826 100644 --- a/utils.go +++ b/utils.go @@ -1,5 +1,11 @@ package main +import ( + "fmt" + "os/exec" + "runtime" +) + func IndexOf(candidate string, arr []string) int { for index, element := range arr { if element == candidate { @@ -12,3 +18,16 @@ func IndexOf(candidate string, arr []string) int { func SetTermTitle(title string) { print("\033]0;", title, "\007") } + +func CopyToClipboard(text string) { + switch runtime.GOOS { + case "linux": + exec.Command("sh", "-c", + fmt.Sprintf("echo -n '%s' | xclip -selection clipboard", text)). + Start() + case "darwin": + exec.Command("sh", "-c", + fmt.Sprintf("echo -n '%s' | pbcopy", text)). + Start() + } +}