gomodoro/main.go

411 lines
9.5 KiB
Go
Raw Normal View History

2018-01-19 01:42:41 +00:00
package main
import (
"fmt"
"os"
"os/exec"
2018-01-19 01:42:41 +00:00
"os/signal"
"strconv"
2024-10-18 19:21:55 +00:00
"strings"
2018-01-19 01:42:41 +00:00
"time"
"github.com/charmbracelet/bubbles/progress"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/urfave/cli/v2"
2018-01-19 01:42:41 +00:00
)
type screen int
var version = "dev"
2018-01-19 01:42:41 +00:00
const (
inputScreen screen = iota
timerScreen
2018-01-19 01:42:41 +00:00
)
type model struct {
focusIndex int
inputs []textinput.Model
progressBar progress.Model
state string
intervalNum int
timer *time.Timer
remaining time.Duration
totalTime time.Duration
currentScreen screen
intervals int
breakTime time.Duration
focusTime time.Duration
onFocusStart []string
onFocusEnd []string
onIntervalEnd []string
isFocus bool
fullscreen bool
width int
height int
2024-10-18 19:21:55 +00:00
err error
2018-01-19 01:42:41 +00:00
}
func initialModel(fullscreen bool, colorLeft string, colorRight string) model {
inputs := make([]textinput.Model, 3)
// Set up text input models for interval length, break length, and total intervals
for i := range inputs {
inputs[i] = textinput.New()
inputs[i].CharLimit = 10 // Increase char limit to allow duration strings
2024-10-18 19:21:55 +00:00
if i == 0 {
inputs[i].Focus() // Start focus on first input
}
}
2024-10-18 19:21:55 +00:00
validateDuration := func(text string) error {
_, err := parseDuration(text)
return err
}
validateInt := func(text string) error {
_, err := strconv.Atoi(text)
return fmt.Errorf("invalid int input: %w", err)
}
inputs[0].Placeholder = "Interval length (minutes or duration)"
2024-10-18 19:21:55 +00:00
inputs[0].Validate = validateDuration
inputs[1].Placeholder = "Break length (minutes or duration)"
2024-10-18 19:21:55 +00:00
inputs[1].Validate = validateDuration
inputs[2].Placeholder = "Number of intervals"
2024-10-18 19:21:55 +00:00
inputs[2].Validate = validateInt
return model{
inputs: inputs,
progressBar: progress.New(progress.WithScaledGradient(colorLeft, colorRight)),
state: "stopped",
intervalNum: 1,
remaining: 0,
totalTime: 0,
currentScreen: inputScreen, // Start on input screen
isFocus: true,
fullscreen: fullscreen,
}
2018-01-19 01:42:41 +00:00
}
func (m model) Init() tea.Cmd {
// Handle Ctrl+C for graceful exit
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
2024-10-18 19:21:55 +00:00
go func() {
<-c
fmt.Println("\nExiting...")
os.Exit(0)
}()
return textinput.Blink
2018-01-19 01:42:41 +00:00
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
// Gracefully exit
return m, tea.Quit
case "tab":
// Move to the next input field
m.focusIndex = (m.focusIndex + 1) % len(m.inputs)
m.updateFocus()
return m, nil
case "shift+tab":
// Move to the previous input field
m.focusIndex = (m.focusIndex - 1 + len(m.inputs)) % len(m.inputs)
m.updateFocus()
return m, nil
case "enter":
if m.currentScreen == inputScreen {
// Handle inputs and move to the timer screen
if m.focusIndex == len(m.inputs)-1 {
focusTime, err := parseDuration(m.inputs[0].Value())
if err != nil {
2024-10-18 19:21:55 +00:00
m.err = fmt.Errorf("error parsing focus time duration: %w", err)
return m, nil
}
breakTime, err := parseDuration(m.inputs[1].Value())
if err != nil {
2024-10-18 19:21:55 +00:00
m.err = fmt.Errorf("error parsing break time duration: %w", err)
return m, nil
}
m.intervals, err = strconv.Atoi(m.inputs[2].Value())
if err != nil {
m.err = fmt.Errorf("error parsing interval: %w", err)
return m, nil
}
m.focusTime = focusTime
m.breakTime = breakTime
m.remaining = focusTime
m.totalTime = focusTime
m.state = "Focus"
m.timer = time.NewTimer(time.Second)
m.currentScreen = timerScreen
// Run onFocusStart commands
m.runCommands(m.onFocusStart)
return m, tick()
} else {
// Move to next input field
m.focusIndex++
m.updateFocus()
}
}
}
case timeMsg:
// Handle timer update for each second
m.remaining -= time.Second
if m.remaining < 0 {
if m.isFocus {
// Focus period ends, switch to break
m.isFocus = false
m.remaining = m.remaining + m.breakTime
m.totalTime = m.breakTime
m.state = "Break"
// Run onFocusEnd commands
m.runCommands(m.onFocusEnd)
} else {
// Break ends, switch back to focus or next interval
m.isFocus = true
m.intervalNum++
2024-10-18 16:06:03 +00:00
m.runCommands(m.onIntervalEnd)
if m.intervalNum > m.intervals {
// All intervals completed
return m, tea.Quit
}
m.remaining = m.remaining + m.focusTime
m.totalTime = m.focusTime
m.state = "Focus"
// Run onFocusStart commands
m.runCommands(m.onFocusStart)
}
return m, tick()
}
return m, tick()
case tea.WindowSizeMsg:
if m.fullscreen {
m.width = msg.Width
m.height = msg.Height
}
}
// Update text inputs
cmds := make([]tea.Cmd, len(m.inputs))
for i := range m.inputs {
m.inputs[i], cmds[i] = m.inputs[i].Update(msg)
2018-01-19 01:42:41 +00:00
}
return m, tea.Batch(cmds...)
2018-01-19 01:42:41 +00:00
}
// Tick every second
type timeMsg time.Time
func tick() tea.Cmd {
return tea.Tick(time.Second, func(t time.Time) tea.Msg {
return timeMsg(t)
2018-01-19 01:42:41 +00:00
})
}
// View rendering for input and timer screens
func (m model) View() string {
2024-10-18 19:21:55 +00:00
var s strings.Builder
switch m.currentScreen {
case inputScreen:
2024-10-18 19:21:55 +00:00
s.WriteString(m.inputScreenView())
case timerScreen:
2024-10-18 19:21:55 +00:00
s.WriteString(m.timerScreenView())
}
2024-10-18 19:21:55 +00:00
if m.err != nil {
s.WriteString(fmt.Sprintf("\n\nError: %v", m.err))
}
return s.String()
}
// View for input screen
func (m model) inputScreenView() string {
2024-10-18 19:21:55 +00:00
var builder strings.Builder
builder.WriteString("Enter your Pomodoro settings:\n\n")
for i := range m.inputs {
2024-10-18 19:21:55 +00:00
builder.WriteString(m.inputs[i].View())
if m.inputs[i].Value() != "" && m.inputs[i].Err != nil {
builder.WriteString(fmt.Sprintf("Error: %v", m.inputs[i].Err))
}
builder.WriteString("\n")
}
2024-10-18 19:21:55 +00:00
builder.WriteString("\nUse TAB to navigate, ENTER to start.")
return builder.String()
}
// View for timer screen with optional fullscreen centering
func (m model) timerScreenView() string {
progressView := m.progressBar.ViewAs(float64(m.totalTime-m.remaining) / float64(m.totalTime))
status := lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("State: %s", m.state))
intervalInfo := fmt.Sprintf("Interval: %d / %d", m.intervalNum, m.intervals)
timeLeft := fmt.Sprintf("Time left: %s", m.remaining.String())
timerView := fmt.Sprintf("%s\n%s\n%s\n\n%s", status, intervalInfo, timeLeft, progressView)
if m.fullscreen {
return lipgloss.NewStyle().Width(m.width).Height(m.height).Align(lipgloss.Center, lipgloss.Center).Render(timerView)
}
2024-10-18 19:21:55 +00:00
return timerView
}
// Helper to update input focus
func (m *model) updateFocus() {
for i := range m.inputs {
if i == m.focusIndex {
m.inputs[i].Focus()
} else {
m.inputs[i].Blur()
2018-05-11 01:08:10 +00:00
}
}
}
2018-01-19 01:42:41 +00:00
// Helper to run shell commands
func (m *model) runCommands(commands []string) {
for _, cmdStr := range commands {
cmd := exec.Command("sh", "-c", cmdStr)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
2024-10-18 19:21:55 +00:00
if err := cmd.Run(); err != nil {
fmt.Printf("Error running command: %v\n", err)
}
2018-01-19 01:42:41 +00:00
}
}
// Helper to parse duration or treat an integer as minutes
func parseDuration(input string) (time.Duration, error) {
if minutes, err := strconv.Atoi(input); err == nil {
return time.Duration(minutes) * time.Minute, nil
}
2018-01-19 01:42:41 +00:00
2024-10-18 19:21:55 +00:00
d, err := time.ParseDuration(input)
if err != nil {
return d, fmt.Errorf("error parsing duration: %w", err)
}
return d, nil
2018-01-19 01:42:41 +00:00
}
func main() {
// Set up CLI app
app := &cli.App{
Name: "Gomodoro",
Usage: "A Pomodoro timer with customizable shell commands",
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "on-focus-start",
Usage: "Command(s) to run when focus starts",
},
&cli.StringSliceFlag{
Name: "on-focus-end",
Usage: "Command(s) to run when focus ends",
},
&cli.StringSliceFlag{
Name: "on-interval-end",
Usage: "Command(s) to run when any interval ends",
},
&cli.BoolFlag{
Name: "fullscreen",
Usage: "Enable fullscreen mode",
},
&cli.DurationFlag{
2024-10-18 19:21:55 +00:00
Name: "focus",
Usage: "Focus time duration",
DefaultText: "prompt for input",
},
&cli.DurationFlag{
2024-10-18 19:21:55 +00:00
Name: "break",
Usage: "Break time duration",
DefaultText: "prompt for input",
},
&cli.IntFlag{
2024-10-18 19:21:55 +00:00
Name: "intervals",
Usage: "Number of intervals",
DefaultText: "prompt for input",
},
&cli.StringFlag{
2024-10-18 19:21:55 +00:00
Name: "color-left",
Usage: "Left color for progress bar",
Value: "#ffdd57",
},
&cli.StringFlag{
2024-10-18 19:21:55 +00:00
Name: "color-right",
Usage: "Right color for progress bar",
Value: "#57ddff",
},
&cli.BoolFlag{
Name: "version",
Usage: "Show version",
},
},
Action: func(c *cli.Context) error {
if c.Bool("version") {
fmt.Println(version)
return nil
}
m := initialModel(c.Bool("fullscreen"), c.String("color-left"), c.String("color-right"))
// Collect command flags
m.onFocusStart = c.StringSlice("on-focus-start")
m.onFocusEnd = c.StringSlice("on-focus-end")
m.onIntervalEnd = c.StringSlice("on-interval-end")
// Set focus, break, and interval values if provided
if c.Duration("focus").String() != "0s" {
m.inputs[0].SetValue(c.String("focus"))
}
if c.Duration("break").String() != "0s" {
m.inputs[1].SetValue(c.String("break"))
}
if c.Int("intervals") != 0 {
m.inputs[2].SetValue(c.String("intervals"))
}
// Start tea program
p := tea.NewProgram(m, tea.WithAltScreen())
_, err := p.Run()
2024-10-18 19:21:55 +00:00
return err
},
2018-01-19 01:42:41 +00:00
}
err := app.Run(os.Args)
2018-01-19 01:42:41 +00:00
if err != nil {
fmt.Println("Error:", err)
2018-01-19 01:42:41 +00:00
}
}