culto

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

editor.go (6403B)


      1 package app
      2 
      3 import (
      4 	"fmt"
      5 	"os"
      6 	"os/exec"
      7 	"strconv"
      8 	"strings"
      9 	"time"
     10 
     11 	"culto/internal/culto"
     12 	tea "github.com/charmbracelet/bubbletea"
     13 )
     14 
     15 type editorFinishedMsg struct {
     16 	title         string
     17 	path          string
     18 	livePath      string
     19 	original      string
     20 	projectionErr error
     21 	err           error
     22 }
     23 
     24 func (m *model) openEditor(title string, stanzas []string) tea.Cmd {
     25 	editor, err := findEditor()
     26 	if err != nil {
     27 		m.status = err.Error()
     28 		return nil
     29 	}
     30 
     31 	file, err := os.CreateTemp("", "culto-*.md")
     32 	if err != nil {
     33 		m.status = fmt.Sprintf("não foi possível criar o arquivo temporário: %v", err)
     34 		return nil
     35 	}
     36 	path := file.Name()
     37 	original := songEditorText(title, stanzas)
     38 	if _, err := file.WriteString(original); err != nil {
     39 		file.Close()
     40 		os.Remove(path)
     41 		m.status = fmt.Sprintf("não foi possível preparar a letra para edição: %v", err)
     42 		return nil
     43 	}
     44 	if err := file.Close(); err != nil {
     45 		os.Remove(path)
     46 		m.status = fmt.Sprintf("não foi possível fechar o arquivo temporário: %v", err)
     47 		return nil
     48 	}
     49 
     50 	liveFile, err := os.CreateTemp("", "culto-live-*.md")
     51 	if err != nil {
     52 		os.Remove(path)
     53 		m.status = fmt.Sprintf("não foi possível criar o arquivo de projeção ao vivo: %v", err)
     54 		return nil
     55 	}
     56 	livePath := liveFile.Name()
     57 	if _, err := liveFile.WriteString(original); err != nil {
     58 		liveFile.Close()
     59 		os.Remove(path)
     60 		os.Remove(livePath)
     61 		m.status = fmt.Sprintf("não foi possível preparar a projeção ao vivo: %v", err)
     62 		return nil
     63 	}
     64 	if err := liveFile.Close(); err != nil {
     65 		os.Remove(path)
     66 		os.Remove(livePath)
     67 		m.status = fmt.Sprintf("não foi possível fechar o arquivo de projeção ao vivo: %v", err)
     68 		return nil
     69 	}
     70 
     71 	autocmd := fmt.Sprintf("autocmd TextChanged,TextChangedI <buffer> call writefile(getline(1, '$'), %s)", strconv.Quote(livePath))
     72 	stopProjection := watchSongProjection(m.config, livePath, title, original)
     73 	cmd := exec.Command(editor, "-c", autocmd, path)
     74 	return tea.ExecProcess(cmd, func(err error) tea.Msg {
     75 		return editorFinishedMsg{
     76 			title: title, path: path, livePath: livePath, original: original,
     77 			projectionErr: stopProjection(), err: err,
     78 		}
     79 	})
     80 }
     81 
     82 func watchSongProjection(config culto.Config, path, title, original string) func() error {
     83 	stop := make(chan struct{})
     84 	done := make(chan error, 1)
     85 
     86 	go func() {
     87 		ticker := time.NewTicker(100 * time.Millisecond)
     88 		defer ticker.Stop()
     89 
     90 		lastContent := original
     91 		pendingContent := ""
     92 		pending := false
     93 		var changedAt time.Time
     94 		for {
     95 			select {
     96 			case <-stop:
     97 				content, err := os.ReadFile(path)
     98 				if err != nil {
     99 					done <- fmt.Errorf("lendo a letra para a projeção ao vivo: %w", err)
    100 					return
    101 				}
    102 				if contentChanged(content, lastContent) {
    103 					done <- projectSongEditorText(config, title, string(content))
    104 					return
    105 				}
    106 				if pending && contentChanged([]byte(pendingContent), lastContent) {
    107 					done <- projectSongEditorText(config, title, pendingContent)
    108 					return
    109 				}
    110 				done <- nil
    111 				return
    112 			case <-ticker.C:
    113 				content, err := os.ReadFile(path)
    114 				if err != nil {
    115 					done <- fmt.Errorf("lendo a letra para a projeção ao vivo: %w", err)
    116 					return
    117 				}
    118 				switch {
    119 				case !contentChanged(content, lastContent):
    120 					pending = false
    121 				case !pending || string(content) != pendingContent:
    122 					pendingContent = string(content)
    123 					changedAt = time.Now()
    124 					pending = true
    125 				case time.Since(changedAt) >= 150*time.Millisecond:
    126 					if err := projectSongEditorText(config, title, pendingContent); err != nil {
    127 						done <- err
    128 						return
    129 					}
    130 					lastContent = pendingContent
    131 					pending = false
    132 				}
    133 			}
    134 		}
    135 	}()
    136 
    137 	var stopped bool
    138 	return func() error {
    139 		if !stopped {
    140 			close(stop)
    141 			stopped = true
    142 		}
    143 		return <-done
    144 	}
    145 }
    146 
    147 func contentChanged(content []byte, previous string) bool {
    148 	return string(content) != previous
    149 }
    150 
    151 func projectSongEditorText(config culto.Config, title, content string) error {
    152 	lyrics := songEditorLyrics(content, title)
    153 	var stanzas []string
    154 	for _, stanza := range strings.Split(strings.ReplaceAll(lyrics, "\r\n", "\n"), "\n\n") {
    155 		if stanza = strings.TrimSpace(stanza); stanza != "" {
    156 			stanzas = append(stanzas, stanza)
    157 		}
    158 	}
    159 	return culto.Present(config, culto.RenderSong(title, stanzas))
    160 }
    161 
    162 func findEditor() (string, error) {
    163 	for _, name := range []string{"nvim", "vim"} {
    164 		if path, err := exec.LookPath(name); err == nil {
    165 			return path, nil
    166 		}
    167 	}
    168 	return "", fmt.Errorf("não encontrei o Vim nem o Neovim no PATH")
    169 }
    170 
    171 func (m *model) finishEditor(msg editorFinishedMsg) tea.Cmd {
    172 	defer os.Remove(msg.path)
    173 	defer os.Remove(msg.livePath)
    174 	if msg.err != nil {
    175 		m.status = fmt.Sprintf("o editor foi encerrado com erro: %v", msg.err)
    176 		return nil
    177 	}
    178 	content, err := os.ReadFile(msg.path)
    179 	if err != nil {
    180 		m.status = fmt.Sprintf("não foi possível ler a letra editada: %v", err)
    181 		return nil
    182 	}
    183 	if string(content) == msg.original {
    184 		m.editSong = ""
    185 		m.popMenu()
    186 		liveContent, err := os.ReadFile(msg.livePath)
    187 		if err != nil {
    188 			m.status = fmt.Sprintf("Edição cancelada, mas não foi possível verificar a projeção ao vivo: %v", err)
    189 			return nil
    190 		}
    191 		if string(liveContent) != msg.original {
    192 			if err := projectSongEditorText(m.config, msg.title, msg.original); err != nil {
    193 				m.status = fmt.Sprintf("Edição descartada, mas não foi possível restaurar a projeção: %v", err)
    194 				return nil
    195 			}
    196 			m.status = "Edição descartada; projeção restaurada."
    197 			return nil
    198 		}
    199 		m.status = "Edição cancelada ou sem alterações."
    200 		return nil
    201 	}
    202 	if err := culto.SaveSong(m.config.MusicFile, msg.title, songEditorLyrics(string(content), msg.title)); err != nil {
    203 		m.status = fmt.Sprintf("erro ao salvar a música: %v", err)
    204 		return nil
    205 	}
    206 	m.editSong = ""
    207 	m.popMenu()
    208 	m.status = fmt.Sprintf("Música %q salva.", msg.title)
    209 	if msg.projectionErr != nil {
    210 		m.status += fmt.Sprintf(" Erro na projeção ao vivo: %v", msg.projectionErr)
    211 	}
    212 	return nil
    213 }
    214 
    215 func songEditorText(title string, stanzas []string) string {
    216 	var body string
    217 	if len(stanzas) > 0 {
    218 		body = strings.Join(stanzas, "\n\n")
    219 	}
    220 	return "# " + title + "\n\n" + body
    221 }
    222 
    223 func songEditorLyrics(content, title string) string {
    224 	lines := strings.SplitN(strings.ReplaceAll(content, "\r\n", "\n"), "\n", 2)
    225 	if len(lines) == 0 || lines[0] != "# "+title {
    226 		return content
    227 	}
    228 	if len(lines) == 1 {
    229 		return ""
    230 	}
    231 	return strings.TrimLeft(lines[1], "\n")
    232 }