presenter.go (7660B)
1 package culto 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 "os/exec" 8 "strconv" 9 "strings" 10 ) 11 12 const slideWidth = 40 13 14 func Present(config Config, content string) error { 15 if err := writeAtomic(config.SentFile, []byte(formatSlides(content))); err != nil { 16 return fmt.Errorf("preparando apresentação: %w", err) 17 } 18 return refreshOrStart(config.SentFile, true) 19 } 20 21 func ClearPresentation(config Config) error { 22 if err := writeAtomic(config.SentFile, []byte(" \n")); err != nil { 23 return fmt.Errorf("limpando apresentação: %w", err) 24 } 25 return refreshOrStart(config.SentFile, false) 26 } 27 28 func JumpToSlide(slide int) error { 29 if slide < 1 { 30 return fmt.Errorf("o número do slide deve ser maior que zero") 31 } 32 xdotool, err := exec.LookPath("xdotool") 33 if err != nil { 34 return fmt.Errorf("xdotool não foi encontrado") 35 } 36 window, err := findSentWindow(xdotool) 37 if err != nil { 38 return err 39 } 40 args := []string{"key", "--window", window, "--clearmodifiers", "g"} 41 for _, digit := range strconv.Itoa(slide) { 42 args = append(args, string(digit)) 43 } 44 args = append(args, "Return") 45 if err := exec.Command(xdotool, args...).Run(); err != nil { 46 return fmt.Errorf("não foi possível enviar o salto para o slide %d: %w", slide, err) 47 } 48 return nil 49 } 50 51 func MoveSlide(direction int) error { 52 key := "" 53 switch direction { 54 case -1: 55 key = "Left" 56 case 1: 57 key = "Right" 58 default: 59 return fmt.Errorf("a direção do slide deve ser -1 ou 1") 60 } 61 xdotool, err := exec.LookPath("xdotool") 62 if err != nil { 63 return fmt.Errorf("xdotool não foi encontrado") 64 } 65 window, err := findSentWindow(xdotool) 66 if err != nil { 67 return err 68 } 69 if err := exec.Command(xdotool, "key", "--window", window, "--clearmodifiers", key).Run(); err != nil { 70 return fmt.Errorf("não foi possível avançar ou voltar o slide: %w", err) 71 } 72 return nil 73 } 74 75 func findSentWindow(xdotool string) (string, error) { 76 output, err := exec.Command(xdotool, "search", "--onlyvisible", "--class", "sent").Output() 77 if err != nil { 78 return "", fmt.Errorf("não encontrei uma janela visível do sent") 79 } 80 windows := strings.Fields(string(output)) 81 if len(windows) == 0 { 82 return "", fmt.Errorf("não encontrei uma janela visível do sent") 83 } 84 window := windows[0] 85 if _, err := strconv.ParseUint(window, 10, 64); err != nil { 86 return "", fmt.Errorf("o identificador da janela do sent é inválido") 87 } 88 return window, nil 89 } 90 91 func formatSlides(content string) string { 92 paragraphs := strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n\n") 93 var slides []string 94 for _, paragraph := range paragraphs { 95 paragraph = strings.TrimSpace(paragraph) 96 if paragraph != "" { 97 var lines []string 98 for _, line := range strings.Split(paragraph, "\n") { 99 lines = append(lines, wrap(strings.ToUpper(strings.TrimSpace(line)), slideWidth)...) 100 } 101 slides = append(slides, strings.Join(lines, "\n")) 102 } 103 } 104 return strings.Join(slides, "\n\n") + "\n" 105 } 106 107 func NumberedSlidesPreview(content string) string { 108 formatted := strings.TrimSpace(formatSlides(content)) 109 if formatted == "" { 110 return "" 111 } 112 slides := strings.Split(formatted, "\n\n") 113 numbered := make([]string, len(slides)) 114 for i, slide := range slides { 115 numbered[i] = fmt.Sprintf("SLIDE %02d\n%s", i+1, slide) 116 } 117 return strings.Join(numbered, "\n\n") 118 } 119 120 func wrap(text string, width int) []string { 121 var lines []string 122 var line strings.Builder 123 for _, word := range strings.Fields(text) { 124 if line.Len() > 0 && line.Len()+1+len(word) > width { 125 lines = append(lines, line.String()) 126 line.Reset() 127 } 128 if line.Len() > 0 { 129 line.WriteByte(' ') 130 } 131 line.WriteString(word) 132 } 133 if line.Len() > 0 { 134 lines = append(lines, line.String()) 135 } 136 return lines 137 } 138 139 func refreshOrStart(path string, startIfMissing bool) error { 140 xdotool, xdotoolErr := exec.LookPath("xdotool") 141 if xdotoolErr == nil { 142 output, err := exec.Command(xdotool, "search", "--onlyvisible", "--class", "sent").Output() 143 if err == nil { 144 windows := strings.Fields(string(output)) 145 for _, window := range windows { 146 if _, parseErr := strconv.ParseUint(window, 10, 64); parseErr != nil { 147 continue 148 } 149 if err := exec.Command(xdotool, "key", "--window", window, "r").Run(); err == nil { 150 return nil 151 } 152 } 153 } 154 } 155 pgrep, err := exec.LookPath("pgrep") 156 if err != nil { 157 if !startIfMissing { 158 return nil 159 } 160 return fmt.Errorf("pgrep não foi encontrado; não é possível verificar se sent já está aberto") 161 } 162 running := exec.Command(pgrep, "-x", "sent").Run() == nil 163 if running { 164 if xdotoolErr != nil { 165 return fmt.Errorf("sent já está aberto, mas xdotool não foi encontrado") 166 } 167 return fmt.Errorf("sent já está aberto, mas não foi possível atualizar a apresentação") 168 } 169 if !startIfMissing { 170 return nil 171 } 172 sent, err := exec.LookPath("sent") 173 if err != nil { 174 return fmt.Errorf("sent não está aberto e não foi encontrado no PATH") 175 } 176 return startSent(sent, path) 177 } 178 179 func startSent(sent, slideFile string) error { 180 if os.Getenv("HYPRLAND_INSTANCE_SIGNATURE") == "" { 181 return startDetached(sent, slideFile) 182 } 183 184 hyprctl, err := exec.LookPath("hyprctl") 185 if err != nil { 186 return fmt.Errorf("hyprctl não foi encontrado; não é possível iniciar sent no monitor HDMI-A-1") 187 } 188 output, err := exec.Command(hyprctl, "monitors", "-j").Output() 189 if err != nil { 190 return fmt.Errorf("não foi possível consultar os monitores do Hyprland: %w", err) 191 } 192 var monitors []struct { 193 Name string `json:"name"` 194 } 195 if err := json.Unmarshal(output, &monitors); err != nil { 196 return fmt.Errorf("resposta inválida ao consultar monitores do Hyprland: %w", err) 197 } 198 found := false 199 for _, monitor := range monitors { 200 if monitor.Name == "HDMI-A-1" { 201 found = true 202 break 203 } 204 } 205 if !found { 206 return fmt.Errorf("o monitor HDMI-A-1 não está conectado; sent não foi iniciado") 207 } 208 209 command := shellQuote(sent) + " " + shellQuote(slideFile) 210 dispatch := fmt.Sprintf("hl.dsp.exec_cmd(%s, { monitor = %s })", 211 strconv.Quote(command), strconv.Quote("HDMI-A-1")) 212 output, err = exec.Command(hyprctl, "dispatch", dispatch).CombinedOutput() 213 if err != nil { 214 return fmt.Errorf("não foi possível iniciar sent no monitor HDMI-A-1: %w: %s", 215 err, strings.TrimSpace(string(output))) 216 } 217 if response := strings.TrimSpace(string(output)); response != "ok" { 218 return fmt.Errorf("Hyprland não confirmou a abertura do sent no monitor HDMI-A-1: %s", response) 219 } 220 return nil 221 } 222 223 func startDetached(sent, slideFile string) error { 224 cmd := exec.Command(sent, slideFile) 225 if err := cmd.Start(); err != nil { 226 return fmt.Errorf("iniciando sent: %w", err) 227 } 228 if err := cmd.Process.Release(); err != nil { 229 return fmt.Errorf("liberando processo do sent: %w", err) 230 } 231 return nil 232 } 233 234 func shellQuote(value string) string { 235 return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" 236 } 237 238 func OpenPix(path string) error { 239 info, err := os.Stat(path) 240 if err != nil { 241 return fmt.Errorf("verificando imagem PIX %q: %w", path, err) 242 } 243 if !info.Mode().IsRegular() { 244 return fmt.Errorf("o caminho PIX %q não é um arquivo regular", path) 245 } 246 opener, err := exec.LookPath("xdg-open") 247 if err != nil { 248 return fmt.Errorf("xdg-open não foi encontrado") 249 } 250 cmd := exec.Command(opener, path) 251 if err := cmd.Start(); err != nil { 252 return fmt.Errorf("abrindo imagem PIX: %w", err) 253 } 254 if err := cmd.Process.Release(); err != nil { 255 return fmt.Errorf("liberando processo do visualizador: %w", err) 256 } 257 return nil 258 } 259 260 func AgendaText() string { 261 return strings.Join([]string{ 262 "Terça (19:30) - Culto de oração", 263 "Quinta (19:30) - Culto de doutrina", 264 "Domingo (08:30) - EBD", 265 "Domingo (18:00) - Culto solene", 266 }, "\n") 267 }