cemantix-charm/main.go

256 lines
5.7 KiB
Go
Raw Normal View History

2022-04-28 18:18:18 +00:00
package main
import (
"context"
"fmt"
2022-04-28 19:18:20 +00:00
"github.com/charmbracelet/bubbles/progress"
2022-04-28 18:18:18 +00:00
"github.com/charmbracelet/bubbles/textinput"
2022-04-28 20:06:54 +00:00
"github.com/charmbracelet/bubbles/viewport"
2022-04-28 18:18:18 +00:00
tea "github.com/charmbracelet/bubbletea"
2022-04-28 20:06:54 +00:00
"github.com/charmbracelet/lipgloss"
2022-04-28 18:18:18 +00:00
"github.com/charmbracelet/wish"
bm "github.com/charmbracelet/wish/bubbletea"
lm "github.com/charmbracelet/wish/logging"
"github.com/gliderlabs/ssh"
"log"
2022-04-28 19:18:20 +00:00
"math"
"math/rand"
2022-04-28 18:18:18 +00:00
"os"
"os/signal"
2022-04-28 19:18:20 +00:00
"strings"
2022-04-28 18:18:18 +00:00
"syscall"
"time"
)
2022-04-28 20:06:54 +00:00
var (
titleStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Right = "├"
return lipgloss.NewStyle().BorderStyle(b).Padding(0, 1)
}()
infoStyle = func() lipgloss.Style {
b := lipgloss.RoundedBorder()
b.Left = "┤"
return titleStyle.Copy().BorderStyle(b)
}()
)
2022-04-28 18:18:18 +00:00
func main() {
log.Println("Welcome on Cemantics!")
s, err := wish.NewServer(
wish.WithAddress(fmt.Sprintf("%s:%d", "0.0.0.0", 2200)),
wish.WithAddress(fmt.Sprintf("%s:%d", "[::]", 2200)),
wish.WithHostKeyPath(".ssh/term_info_ed25519"),
wish.WithMiddleware(
lm.Middleware(),
bm.Middleware(teaHandler),
),
)
if err != nil {
log.Fatalln(err)
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
log.Printf("Starting SSH server on %s:%d", "[::]", 2200)
go func() {
if err = s.ListenAndServe(); err != nil {
log.Fatalln(err)
}
}()
<-done
log.Println("Stopping SSH server")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer func() { cancel() }()
if err := s.Shutdown(ctx); err != nil {
log.Fatalln(err)
}
}
func teaHandler(s ssh.Session) (tea.Model, []tea.ProgramOption) {
_, _, active := s.Pty()
if !active {
fmt.Println("no active terminal, skipping")
return nil, nil
}
log.Println(s.RemoteAddr())
ti := textinput.New()
ti.Placeholder = "Choisissez un mot ..."
ti.Focus()
2022-04-28 19:18:20 +00:00
ti.CharLimit = 26
ti.Width = 26
2022-04-28 18:18:18 +00:00
m := model{
2022-04-28 19:18:20 +00:00
textInput: ti,
err: nil,
ip: s.RemoteAddr().String(),
words: []word{},
progressBar: progress.New(progress.WithScaledGradient("#FF7CCB", "#FDFF8C")),
2022-04-28 18:18:18 +00:00
}
2022-04-28 20:06:54 +00:00
return m, []tea.ProgramOption{tea.WithAltScreen(), tea.WithMouseCellMotion()}
2022-04-28 18:18:18 +00:00
}
type errMsg error
2022-04-28 19:18:20 +00:00
type word struct {
content string
distance float64
ranking int
}
2022-04-28 18:18:18 +00:00
type model struct {
2022-04-28 20:06:54 +00:00
ready bool
err error
textInput textinput.Model
ip string
words []word
wordsViewport viewport.Model
progressBar progress.Model
maxLength int
lastWord string
2022-04-28 18:18:18 +00:00
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
2022-04-28 20:06:54 +00:00
var cmds []tea.Cmd
2022-04-28 18:18:18 +00:00
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.Type {
case tea.KeyEnter:
return m.InputWord()
case tea.KeyCtrlC, tea.KeyEsc:
return m, tea.Quit
}
2022-04-28 20:06:54 +00:00
case tea.WindowSizeMsg:
headerHeight := lipgloss.Height(m.headerView())
footerHeight := lipgloss.Height(m.footerView())
verticalMarginHeight := headerHeight + footerHeight
if !m.ready {
m.wordsViewport = viewport.New(msg.Width, msg.Height-verticalMarginHeight)
m.wordsViewport.YPosition = headerHeight
m.ready = true
} else {
m.wordsViewport.Width = msg.Width
m.wordsViewport.Height = msg.Height - verticalMarginHeight
}
2022-04-28 18:18:18 +00:00
case errMsg:
m.err = msg
return m, nil
}
2022-04-28 20:06:54 +00:00
m.wordsViewport, cmd = m.wordsViewport.Update(msg)
cmds = append(cmds, cmd)
2022-04-28 18:18:18 +00:00
m.textInput, cmd = m.textInput.Update(msg)
2022-04-28 20:06:54 +00:00
cmds = append(cmds, cmd)
return m, tea.Batch(cmds...)
2022-04-28 18:18:18 +00:00
}
func (m model) InputWord() (model, tea.Cmd) {
2022-04-28 19:18:20 +00:00
input := m.textInput.Value()
2022-04-28 18:18:18 +00:00
2022-04-28 19:18:20 +00:00
m.lastWord = input
if len(input) > m.maxLength {
m.maxLength = len(input)
}
// TODO: Get distance and ranking from a file
// TODO: Reorder the array
2022-04-28 20:06:54 +00:00
w := word{input, 200*rand.Float64() - 100, rand.Intn(1000)}
m.words = append(m.words, w)
var content string
for _, w := range m.words {
content += w.View(m)
}
m.wordsViewport.SetContent(content)
2022-04-28 18:18:18 +00:00
m.textInput.SetValue("")
m.textInput.CursorStart()
return m, nil
}
2022-04-28 19:18:20 +00:00
func (w word) View(m model) string {
var emoji string
if w.ranking == 1000 {
emoji = "\U0001F973"
} else if w.ranking == 999 {
emoji = "\U0001F631"
} else if w.ranking >= 990 {
emoji = "\U0001F525"
} else if w.ranking >= 900 {
emoji = "\U0001F975"
} else if w.ranking >= 1 {
emoji = "\U0001F60E"
} else {
emoji = "\U0001F976"
}
var progressBar string
if w.ranking > 0 {
progressBar = m.progressBar.ViewAs(float64(w.ranking) / 1000.0)
}
distStr := fmt.Sprintf("%.02f", w.distance)
if math.Abs(w.distance) < 10 {
distStr = " " + distStr
}
if w.distance >= 0 {
distStr = " " + distStr
}
return fmt.Sprintf(
"* %s\t%s %s\t%4d %s\n",
w.content+strings.Repeat(" ", m.maxLength-len(w.content)),
distStr,
emoji,
w.ranking,
progressBar,
)
}
2022-04-28 20:06:54 +00:00
func (m model) headerView() string {
var err string
if m.err != nil {
err = fmt.Sprintf("Erreur : %s", m.err)
}
2022-04-28 18:18:18 +00:00
msg := fmt.Sprintf(
2022-04-28 20:06:54 +00:00
"Veuillez choisir un mot :\n\n%s\n\nDernier mot essayé : %s%s\n%s\n\n",
2022-04-28 18:18:18 +00:00
m.textInput.View(),
2022-04-28 20:06:54 +00:00
m.lastWord,
strings.Repeat(" ", 26),
err,
)
2022-04-28 18:18:18 +00:00
2022-04-28 20:06:54 +00:00
title := titleStyle.Render("Mots précédents")
line := strings.Repeat("─", int(math.Max(0, float64(m.wordsViewport.Width-lipgloss.Width(title)))))
msg += lipgloss.JoinHorizontal(lipgloss.Center, title, line)
2022-04-28 18:18:18 +00:00
2022-04-28 20:06:54 +00:00
return msg
}
func (m model) footerView() string {
info := infoStyle.Render(fmt.Sprintf("%3.f%%", m.wordsViewport.ScrollPercent()*100))
line := strings.Repeat("─", int(math.Max(0, float64(m.wordsViewport.Width-lipgloss.Width(info)))))
return lipgloss.JoinHorizontal(lipgloss.Center, line, info)
}
func (m model) View() string {
if !m.ready {
return "\n\tInitializing..."
2022-04-28 18:18:18 +00:00
}
2022-04-28 20:06:54 +00:00
return fmt.Sprintf("%s\n%s\n%s", m.headerView(), m.wordsViewport.View(), m.footerView())
2022-04-28 18:18:18 +00:00
}