culto

Repositório culto
git clone git://git.sivaldodavi.com/culto.git
Log | Files | Refs | README

commit e9b87b3d7221d5adf5ef22ef034b5aea8707b4c9
parent 5163169ac0ad4bc44fb34015f7580302e8f430e1
Author: Sivaldo Davi  <sivaldo@sivaldodavi>
Date:   Sun, 25 Oct 2026 08:25:48 -0300

feat(editor): projeta edições da música ao vivo durante a edição

- Envia automaticamente cada alteração da letra à projeção enquanto o
  editor permanece aberto, com debounce de ~150ms para evitar floods.
- Restaura a letra original na projeção quando a edição é descartada
  com `:q!`, informando o status ao usuário.
- Adiciona testes cobrindo a projeção em tempo real e a restauração
  após descarte, e documenta o comportamento no README.

Diffstat:
MREADME.md | 2+-
Minternal/app/app_test.go | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Minternal/app/editor.go | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
3 files changed, 211 insertions(+), 7 deletions(-)

diff --git a/README.md b/README.md @@ -53,7 +53,7 @@ Sobrescritas específicas: `CULTO_BIBLE_FILE`, `CULTO_MUSIC_FILE`, `CULTO_PIX_FI - No editor, use `:wq` para salvar e sair; `:q!` para descartar. - **Ctrl+C** encerra a interface. -Na visualização de uma música, cada parte é identificada com o número do slide e o número da estrofe. Se houver uma capa automática (hinos e salmos), ela aparece como slide 01 e a primeira estrofe como slide 02. Esses rótulos são apenas informativos e não aparecem na projeção. +Na visualização de uma música, cada parte é identificada com o número do slide e o número da estrofe. Se houver uma capa automática (hinos e salmos), ela aparece como slide 01 e a primeira estrofe como slide 02. Esses rótulos são apenas informativos e não aparecem na projeção. Ao editar a letra com **e**, cada alteração é enviada automaticamente à projeção enquanto o editor está aberto; a música continua sendo salva no arquivo JSON ao sair do editor. Se sair com `:q!`, a edição é descartada e a projeção volta à letra original. O menu inicial fica centralizado e evita repetir ações já acessíveis por atalhos globais. Erros aparecem na prévia, mas não podem ser enviados à projeção. diff --git a/internal/app/app_test.go b/internal/app/app_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" "testing" + "time" "culto/internal/culto" tea "github.com/charmbracelet/bubbletea" @@ -116,6 +117,82 @@ func TestFinishEditorSavesLyricsAndReturnsToSongList(t *testing.T) { } } +func TestSongEditorChangesReachProjectionBeforeEditorCloses(t *testing.T) { + dir := t.TempDir() + xdotool := filepath.Join(dir, "xdotool") + script := "#!/bin/sh\n" + + "if [ \"$1\" = search ]; then printf '4242\\n'; fi\n" + if err := os.WriteFile(xdotool, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + + title := "Cântico ao vivo" + original := songEditorText(title, []string{"Letra antiga"}) + liveFile := filepath.Join(dir, "live.md") + sentFile := filepath.Join(dir, "slides") + if err := os.WriteFile(liveFile, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + stop := watchSongProjection(culto.Config{SentFile: sentFile}, liveFile, title, original) + defer stop() + + edited := songEditorText(title, []string{"Primeira estrofe", "Segunda estrofe"}) + if err := os.WriteFile(liveFile, []byte(edited), 0o600); err != nil { + t.Fatal(err) + } + + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + projected, err := os.ReadFile(sentFile) + if err == nil && strings.Contains(string(projected), "SEGUNDA ESTROFE") { + if got, want := string(projected), "PRIMEIRA ESTROFE\n\nSEGUNDA ESTROFE\n"; got != want { + t.Fatalf("letra projetada = %q, esperado %q", got, want) + } + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("a letra editada não chegou à projeção antes de fechar o editor") +} + +func TestDiscardedSongEditRestoresProjection(t *testing.T) { + dir := t.TempDir() + xdotool := filepath.Join(dir, "xdotool") + if err := os.WriteFile(xdotool, []byte("#!/bin/sh\nif [ \"$1\" = search ]; then printf '4242\\n'; fi\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + + title := "Cântico descartado" + original := songEditorText(title, []string{"Letra original"}) + editorFile := filepath.Join(dir, "editor.md") + liveFile := filepath.Join(dir, "live.md") + sentFile := filepath.Join(dir, "slides") + if err := os.WriteFile(editorFile, []byte(original), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(liveFile, []byte(songEditorText(title, []string{"Letra temporária"})), 0o600); err != nil { + t.Fatal(err) + } + + m := New(culto.Config{SentFile: sentFile}).(*model) + m.finishEditor(editorFinishedMsg{ + title: title, path: editorFile, livePath: liveFile, original: original, + }) + + projected, err := os.ReadFile(sentFile) + if err != nil { + t.Fatal(err) + } + if got, want := string(projected), "LETRA ORIGINAL\n"; got != want { + t.Fatalf("projeção após descartar = %q, esperado %q", got, want) + } + if m.status != "Edição descartada; projeção restaurada." { + t.Fatalf("status após descartar: %q", m.status) + } +} + func TestSongListHasAddAndBackActions(t *testing.T) { m := New(culto.Config{MusicFile: t.TempDir() + "/missing.json"}).(*model) m.openSongs() diff --git a/internal/app/editor.go b/internal/app/editor.go @@ -4,17 +4,21 @@ import ( "fmt" "os" "os/exec" + "strconv" "strings" + "time" "culto/internal/culto" tea "github.com/charmbracelet/bubbletea" ) type editorFinishedMsg struct { - title string - path string - original string - err error + title string + path string + livePath string + original string + projectionErr error + err error } func (m *model) openEditor(title string, stanzas []string) tea.Cmd { @@ -43,12 +47,118 @@ func (m *model) openEditor(title string, stanzas []string) tea.Cmd { return nil } - cmd := exec.Command(editor, path) + liveFile, err := os.CreateTemp("", "culto-live-*.md") + if err != nil { + os.Remove(path) + m.status = fmt.Sprintf("não foi possível criar o arquivo de projeção ao vivo: %v", err) + return nil + } + livePath := liveFile.Name() + if _, err := liveFile.WriteString(original); err != nil { + liveFile.Close() + os.Remove(path) + os.Remove(livePath) + m.status = fmt.Sprintf("não foi possível preparar a projeção ao vivo: %v", err) + return nil + } + if err := liveFile.Close(); err != nil { + os.Remove(path) + os.Remove(livePath) + m.status = fmt.Sprintf("não foi possível fechar o arquivo de projeção ao vivo: %v", err) + return nil + } + + autocmd := fmt.Sprintf("autocmd TextChanged,TextChangedI <buffer> call writefile(getline(1, '$'), %s)", strconv.Quote(livePath)) + stopProjection := watchSongProjection(m.config, livePath, title, original) + cmd := exec.Command(editor, "-c", autocmd, path) return tea.ExecProcess(cmd, func(err error) tea.Msg { - return editorFinishedMsg{title: title, path: path, original: original, err: err} + return editorFinishedMsg{ + title: title, path: path, livePath: livePath, original: original, + projectionErr: stopProjection(), err: err, + } }) } +func watchSongProjection(config culto.Config, path, title, original string) func() error { + stop := make(chan struct{}) + done := make(chan error, 1) + + go func() { + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + + lastContent := original + pendingContent := "" + pending := false + var changedAt time.Time + for { + select { + case <-stop: + content, err := os.ReadFile(path) + if err != nil { + done <- fmt.Errorf("lendo a letra para a projeção ao vivo: %w", err) + return + } + if contentChanged(content, lastContent) { + done <- projectSongEditorText(config, title, string(content)) + return + } + if pending && contentChanged([]byte(pendingContent), lastContent) { + done <- projectSongEditorText(config, title, pendingContent) + return + } + done <- nil + return + case <-ticker.C: + content, err := os.ReadFile(path) + if err != nil { + done <- fmt.Errorf("lendo a letra para a projeção ao vivo: %w", err) + return + } + switch { + case !contentChanged(content, lastContent): + pending = false + case !pending || string(content) != pendingContent: + pendingContent = string(content) + changedAt = time.Now() + pending = true + case time.Since(changedAt) >= 150*time.Millisecond: + if err := projectSongEditorText(config, title, pendingContent); err != nil { + done <- err + return + } + lastContent = pendingContent + pending = false + } + } + } + }() + + var stopped bool + return func() error { + if !stopped { + close(stop) + stopped = true + } + return <-done + } +} + +func contentChanged(content []byte, previous string) bool { + return string(content) != previous +} + +func projectSongEditorText(config culto.Config, title, content string) error { + lyrics := songEditorLyrics(content, title) + var stanzas []string + for _, stanza := range strings.Split(strings.ReplaceAll(lyrics, "\r\n", "\n"), "\n\n") { + if stanza = strings.TrimSpace(stanza); stanza != "" { + stanzas = append(stanzas, stanza) + } + } + return culto.Present(config, culto.RenderSong(title, stanzas)) +} + func findEditor() (string, error) { for _, name := range []string{"nvim", "vim"} { if path, err := exec.LookPath(name); err == nil { @@ -60,6 +170,7 @@ func findEditor() (string, error) { func (m *model) finishEditor(msg editorFinishedMsg) tea.Cmd { defer os.Remove(msg.path) + defer os.Remove(msg.livePath) if msg.err != nil { m.status = fmt.Sprintf("o editor foi encerrado com erro: %v", msg.err) return nil @@ -72,6 +183,19 @@ func (m *model) finishEditor(msg editorFinishedMsg) tea.Cmd { if string(content) == msg.original { m.editSong = "" m.popMenu() + liveContent, err := os.ReadFile(msg.livePath) + if err != nil { + m.status = fmt.Sprintf("Edição cancelada, mas não foi possível verificar a projeção ao vivo: %v", err) + return nil + } + if string(liveContent) != msg.original { + if err := projectSongEditorText(m.config, msg.title, msg.original); err != nil { + m.status = fmt.Sprintf("Edição descartada, mas não foi possível restaurar a projeção: %v", err) + return nil + } + m.status = "Edição descartada; projeção restaurada." + return nil + } m.status = "Edição cancelada ou sem alterações." return nil } @@ -82,6 +206,9 @@ func (m *model) finishEditor(msg editorFinishedMsg) tea.Cmd { m.editSong = "" m.popMenu() m.status = fmt.Sprintf("Música %q salva.", msg.title) + if msg.projectionErr != nil { + m.status += fmt.Sprintf(" Erro na projeção ao vivo: %v", msg.projectionErr) + } return nil }