summaryrefslogtreecommitdiff
path: root/internal/gui/audio_player.go
blob: bc58bbebc517921d6226a96fe3abc90eb6d3e026 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
package gui

import (
	"context"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	ttwidget "github.com/dweymouth/fyne-tooltip/widget"
)

// AudioPlayer is a custom widget for playing audio files
type AudioPlayer struct {
	widget.BaseWidget

	container       *fyne.Container
	playButton      *ttwidget.Button
	playButtonLabel *widget.Label    // Label for front audio button
	playBackButton  *ttwidget.Button // Play back audio for bg-bg cards
	playBackLabel   *widget.Label    // Label for back audio button
	stopButton      *ttwidget.Button
	statusLabel     *widget.Label
	phoneticLabel   *widget.Label

	audioFile       string
	audioFileBack   string // Back audio file for bg-bg cards
	isBgBg          bool   // Track if this is a bg-bg card
	isPlaying       bool
	playCmd         *exec.Cmd
	voiceInfo       string          // Stores voice and speed info
	autoPlayEnabled *bool           // Pointer to parent's auto-play state
	ctx             context.Context // Application context; guards post-playback UI updates
}

type audioCommandCandidate struct {
	name string
	args []string
}

// NewAudioPlayer creates a new audio player widget. Call SetContext before use
// so that post-playback UI updates are guarded against the app shutting down.
func NewAudioPlayer() *AudioPlayer {
	p := &AudioPlayer{
		// Default to a background context so the player is usable even if
		// SetContext is never called (e.g. in unit tests).
		ctx: context.Background(),
	}

	// Create controls (tooltips will be set later after tooltip layer is created)
	p.playButton = ttwidget.NewButton("", p.onPlay)
	p.playButton.Icon = theme.MediaPlayIcon()

	p.playButtonLabel = widget.NewLabel("")
	p.playButtonLabel.TextStyle = fyne.TextStyle{Bold: true}

	p.playBackButton = ttwidget.NewButton("", p.onPlayBack)
	p.playBackButton.Icon = theme.MediaPlayIcon() // Same icon as front button

	p.playBackLabel = widget.NewLabel("")
	p.playBackLabel.TextStyle = fyne.TextStyle{Bold: true}

	p.stopButton = ttwidget.NewButton("", p.onStop)
	p.stopButton.Icon = theme.MediaStopIcon()

	p.statusLabel = widget.NewLabel("No audio loaded")

	// Create phonetic label — wraps so long IPA strings are never clipped.
	p.phoneticLabel = widget.NewLabel("")
	p.phoneticLabel.TextStyle = fyne.TextStyle{
		Bold:   true,
		Italic: true,
	}
	p.phoneticLabel.Wrapping = fyne.TextWrapWord

	// Initially disable controls
	p.playButton.Disable()
	p.playBackButton.Disable()
	p.playBackButton.Hide() // Only show for bg-bg cards
	p.playBackLabel.Hide()
	p.stopButton.Disable()

	// Layout: buttons on the left, status on the right, phonetic fills the middle.
	// Using NewBorder so the phonetic label expands horizontally rather than being
	// squeezed to its minimum width in an HBox.
	buttons := container.NewVBox(
		container.NewHBox(p.playButton, p.playButtonLabel),
		container.NewHBox(p.playBackButton, p.playBackLabel),
	)
	leftControls := container.NewHBox(buttons, p.stopButton)
	p.container = container.NewBorder(nil, nil, leftControls, p.statusLabel, p.phoneticLabel)

	p.ExtendBaseWidget(p)
	return p
}

// SetContext wires the application lifecycle context into the player.
// The post-playback UI update goroutine checks this context before calling
// fyne.Do, preventing writes to freed widgets after the window is closed
// (Go Mistake #62). Must be called before the first playback attempt.
func (p *AudioPlayer) SetContext(ctx context.Context) {
	p.ctx = ctx
}

// CreateRenderer implements fyne.Widget
func (p *AudioPlayer) CreateRenderer() fyne.WidgetRenderer {
	return widget.NewSimpleRenderer(p.container)
}

// SetAudioFile sets the audio file to play and optionally auto-plays it
func (p *AudioPlayer) SetAudioFile(audioFile string) {
	p.setAudioFileInternal(audioFile, true) // Enable auto-play
}

// SetAudioFileNoAutoPlay sets the audio file without auto-playing
// Used when regenerating audio on bg-bg cards - we only want to play when explicitly requested
func (p *AudioPlayer) SetAudioFileNoAutoPlay(audioFile string) {
	p.setAudioFileInternal(audioFile, false) // Disable auto-play
}

// setAudioFileInternal is the internal implementation for setting audio files
func (p *AudioPlayer) setAudioFileInternal(audioFile string, allowAutoPlay bool) {
	p.audioFile = audioFile
	p.isPlaying = false

	if audioFile != "" {
		p.playButton.Enable()

		// Try to load voice metadata
		wordDir := filepath.Dir(audioFile)
		metadataFile := filepath.Join(wordDir, "audio_metadata.txt")
		voice := ""
		speed := ""

		if data, err := os.ReadFile(metadataFile); err == nil {
			lines := strings.Split(string(data), "\n")
			for _, line := range lines {
				if strings.HasPrefix(line, "voice=") {
					voice = strings.TrimPrefix(line, "voice=")
				} else if strings.HasPrefix(line, "speed=") {
					speed = strings.TrimPrefix(line, "speed=")
				}
			}
		}

		// Store voice info
		if voice != "" && speed != "" {
			p.voiceInfo = fmt.Sprintf(" (voice: %s, speed: %s)", voice, speed)
		} else {
			p.voiceInfo = ""
		}

		// Update button label based on whether this is bg-bg
		if p.isBgBg {
			p.playButtonLabel.SetText("Front")
		} else {
			p.playButtonLabel.SetText("")
		}

		// Format status text with voice and speed info
		statusText := fmt.Sprintf("Audio: %s%s", filepath.Base(audioFile), p.voiceInfo)
		p.statusLabel.SetText(statusText)

		// Auto-play if enabled and allowed. A short goroutine gives the UI a
		// chance to render and checks ctx.Done() so it won't write to freed
		// widgets if the window is closed before the delay expires (Go Mistake #62).
		if allowAutoPlay && p.autoPlayEnabled != nil && *p.autoPlayEnabled {
			ctx := p.ctx
			go func() {
				select {
				case <-ctx.Done():
					return
				case <-time.After(100 * time.Millisecond):
				}
				fyne.Do(p.onPlay)
			}()
		}
	} else {
		p.Clear()
	}
}

// SetBackAudioFile sets the back audio file for bg-bg cards
func (p *AudioPlayer) SetBackAudioFile(audioFile string) {
	p.audioFileBack = audioFile
	if audioFile != "" {
		p.isBgBg = true
		p.playBackButton.Enable()
		p.playBackButton.Show()
		p.playBackLabel.SetText("Back")
		p.playBackLabel.Show()
		// Update front label now that we know it's bg-bg
		p.playButtonLabel.SetText("Front")
		// NOTE: Do NOT auto-play back audio
		// Back audio regeneration just prepares the file
		// User should press 'P' to listen to it
	} else {
		p.isBgBg = false
		p.playBackButton.Disable()
		p.playBackButton.Hide()
		p.playBackLabel.SetText("")
		p.playBackLabel.Hide()
		// Clear front label if not bg-bg
		p.playButtonLabel.SetText("")
	}
	// Refresh container to update layout after show/hide
	if p.container != nil {
		p.container.Refresh()
	}
}

// Clear clears the audio player
func (p *AudioPlayer) Clear() {
	p.onStop()
	p.audioFile = ""
	p.audioFileBack = ""
	p.isBgBg = false
	p.isPlaying = false
	p.voiceInfo = ""
	p.playButton.Disable()
	p.playBackButton.Disable()
	p.playBackButton.Hide()
	p.playButtonLabel.SetText("")
	p.playBackLabel.SetText("")
	p.playBackLabel.Hide()
	p.stopButton.Disable()
	p.statusLabel.SetText("No audio loaded")
	p.phoneticLabel.SetText("")
	// Refresh container to update layout after hiding back button
	if p.container != nil {
		p.container.Refresh()
	}
}

// SetPhonetic sets the phonetic transcription text
func (p *AudioPlayer) SetPhonetic(phonetic string) {
	p.phoneticLabel.SetText(phonetic)
	p.phoneticLabel.Refresh()
	// Also refresh the container to ensure layout updates
	if p.container != nil {
		p.container.Refresh()
	}
}

// SetAutoPlayEnabled sets the reference to the auto-play state
func (p *AudioPlayer) SetAutoPlayEnabled(autoPlayEnabled *bool) {
	p.autoPlayEnabled = autoPlayEnabled
}

// onPlay handles play button click
func (p *AudioPlayer) onPlay() {
	if p.audioFile == "" {
		return
	}

	if p.isPlaying {
		// Pause functionality - just stop for now
		p.onStop()
		return
	}

	// Start playing
	if err := p.startPlayback(); err != nil {
		p.statusLabel.SetText(fmt.Sprintf("Error: %v", err))
		return
	}

	p.isPlaying = true
	p.playButton.SetIcon(theme.MediaPauseIcon())
	p.stopButton.Enable()
	p.statusLabel.SetText(fmt.Sprintf("Playing: %s%s", filepath.Base(p.audioFile), p.voiceInfo))
}

// onPlayBack handles back audio button click (for bg-bg cards)
func (p *AudioPlayer) onPlayBack() {
	if p.audioFileBack == "" {
		return
	}

	if p.isPlaying {
		p.onStop()
	}

	// Start playback using back audio file directly
	if err := p.startPlaybackForFile(p.audioFileBack); err != nil {
		p.statusLabel.SetText(fmt.Sprintf("Error: %v", err))
		return
	}

	p.isPlaying = true
	p.playBackButton.SetIcon(theme.MediaPauseIcon()) // Back button, not front
	p.stopButton.Enable()
	p.statusLabel.SetText(fmt.Sprintf("Playing back audio: %s", filepath.Base(p.audioFileBack)))
}

// onStop handles stop button click
func (p *AudioPlayer) onStop() {
	if p.playCmd != nil && p.playCmd.Process != nil {
		if err := p.playCmd.Process.Kill(); err != nil {
			p.statusLabel.SetText(fmt.Sprintf("failed to stop playback: %v", err))
		}
		p.playCmd = nil
	}

	p.isPlaying = false
	// Set correct button icon based on which audio was playing
	if p.isBgBg && p.audioFileBack != "" {
		p.playBackButton.SetIcon(theme.MediaPlayIcon()) // Back button if it was playing
	} else {
		p.playButton.SetIcon(theme.MediaPlayIcon()) // Front button otherwise
	}
	p.stopButton.Disable()
	p.statusLabel.SetText(fmt.Sprintf("Stopped: %s%s", filepath.Base(p.audioFile), p.voiceInfo))
}

// Play triggers audio playback
func (p *AudioPlayer) Play() {
	if !p.playButton.Disabled() {
		fyne.Do(func() {
			p.onPlay()
		})
	}
}

// PlayBack triggers back audio playback (for bg-bg cards)
func (p *AudioPlayer) PlayBack() {
	if !p.playBackButton.Disabled() {
		fyne.Do(func() {
			p.onPlayBack()
		})
	}
}

// startPlayback starts audio playback using platform-specific commands
// This plays the front audio file (p.audioFile)
func (p *AudioPlayer) startPlayback() error {
	return p.startPlaybackForFile(p.audioFile)
}

// startPlaybackForFile starts playback of a specific audio file
// This allows playing either front or back audio without modifying state
func (p *AudioPlayer) startPlaybackForFile(audioFile string) error {
	cmd, err := audioPlaybackCommand(runtime.GOOS, audioFile, exec.LookPath)
	if err != nil {
		return err
	}

	// Store the command so we can stop it later
	p.playCmd = cmd

	// Start playback in background.
	// Capture which audio track is playing for correct icon reset on completion.
	// ctx.Done() is checked before fyne.Do so we never write to freed widgets
	// after the application window has been closed (Go Mistake #62).
	isPlayingBack := audioFile == p.audioFileBack
	ctx := p.ctx
	go func() {
		err := cmd.Run()
		if err == nil && ctx.Err() == nil {
			// Playback finished normally and the app is still alive.
			fyne.Do(func() {
				p.isPlaying = false
				// Reset correct button icon based on which audio was playing
				if isPlayingBack {
					p.playBackButton.SetIcon(theme.MediaPlayIcon())
					p.statusLabel.SetText(fmt.Sprintf("Finished: %s", filepath.Base(p.audioFileBack)))
				} else {
					p.playButton.SetIcon(theme.MediaPlayIcon())
					p.statusLabel.SetText(fmt.Sprintf("Finished: %s%s", filepath.Base(p.audioFile), p.voiceInfo))
				}
				p.stopButton.Disable()
			})
		}
	}()

	return nil
}

func audioPlaybackCommand(goos, audioFile string, lookPath func(string) (string, error)) (*exec.Cmd, error) {
	switch goos {
	case "darwin":
		return exec.Command("afplay", audioFile), nil
	case "linux":
		return linuxAudioPlaybackCommand(audioFile, lookPath)
	case "windows":
		return exec.Command("cmd", "/c", "start", "/min", audioFile), nil
	default:
		return nil, fmt.Errorf("unsupported platform: %s", goos)
	}
}

func linuxAudioPlaybackCommand(audioFile string, lookPath func(string) (string, error)) (*exec.Cmd, error) {
	candidates := linuxAudioCommandCandidates(audioFile)
	for _, candidate := range candidates {
		path, err := lookPath(candidate.name)
		if err != nil {
			continue
		}

		args := append([]string(nil), candidate.args...)
		return exec.Command(path, args...), nil
	}

	return nil, errors.New("no compatible audio player found. Install ffplay, sox, paplay, aplay, or mpg123 for mp3 files")
}

func linuxAudioCommandCandidates(audioFile string) []audioCommandCandidate {
	ext := strings.ToLower(filepath.Ext(audioFile))
	switch ext {
	case ".mp3":
		return []audioCommandCandidate{
			{name: "mpg123", args: []string{"-q", audioFile}},
			{name: "ffplay", args: []string{"-nodisp", "-autoexit", "-loglevel", "quiet", audioFile}},
			{name: "play", args: []string{"-q", audioFile}},
			{name: "paplay", args: []string{audioFile}},
			{name: "aplay", args: []string{"-q", audioFile}},
		}
	default:
		return []audioCommandCandidate{
			{name: "ffplay", args: []string{"-nodisp", "-autoexit", "-loglevel", "quiet", audioFile}},
			{name: "play", args: []string{"-q", audioFile}},
			{name: "paplay", args: []string{audioFile}},
			{name: "aplay", args: []string{"-q", audioFile}},
		}
	}
}