// Copyright 2026 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "fmt" "os" "unicode/utf8" "github.com/gdamore/tcell/v3" "github.com/gdamore/tcell/v3/color" ) var clipboard []byte func displayHelloWorld(s tcell.Screen) { w, h := s.Size() s.Clear() style := tcell.StyleDefault.Foreground(color.CadetBlue.TrueColor()).Background(color.White) has := "does NOT claim" if s.HasClipboard() { has = "claims to" } term, version := s.Terminal() termId := "(unidentified)" if term != "" { termId = fmt.Sprintf("(%s %s)", term, version) } line := fmt.Sprintf("Your terminal %s %s to allow clipboard access.", termId, has) s.PutStrStyled(w/2-14, h/2, "Press 1 to set clipboard", style) s.PutStrStyled(w/2-14, h/2+1, "Press 2 to get clipboard", style) s.PutStr((w-len(line))/2, h/2+9, line) msg := "" if utf8.Valid(clipboard) { cp := string(clipboard) if len(cp) >= w-25 { cp = cp[:21] + " ..." } msg = fmt.Sprintf("Clipboard (%d bytes): %s", len(clipboard), cp) } else if clipboard != nil { msg = fmt.Sprintf("Clipboard (%d bytes) Not Valid UTF-8", len(clipboard)) } else { msg = "No clipboard data" } s.PutStr((w-len(msg))/2, h/2+3, msg) line = "Press Control-Q to exit." s.PutStr((w-len(line))/2, h/2+5, line) s.Show() } // This program demonstrates access to the clipboard. // Not all terminals support, and many only support write access. // (Read access to the clipboard is often restricted for security reasons.) func main() { s, e := tcell.NewScreen() if e != nil { fmt.Fprintf(os.Stderr, "%v\n", e) os.Exit(1) } if e := s.Init(); e != nil { fmt.Fprintf(os.Stderr, "%v\n", e) os.Exit(1) } defer s.Fini() defStyle := tcell.StyleDefault. Background(color.Black). Foreground(color.White) s.SetStyle(defStyle) displayHelloWorld(s) for { ev1 := <-s.EventQ() switch ev := ev1.(type) { case *tcell.EventResize: s.Sync() displayHelloWorld(s) case *tcell.EventKey: switch ev.Key() { case tcell.KeyRune: switch ev.Str() { case "1": s.SetClipboard([]byte("Enjoy your new clipboard content!")) case "2": s.GetClipboard() } case tcell.KeyEscape, tcell.KeyCtrlQ: return } case *tcell.EventClipboard: clipboard = ev.Data() displayHelloWorld(s) } } }