itd/cmd/itgui/time.go

80 lines
1.9 KiB
Go
Raw Permalink Normal View History

2021-08-26 04:18:24 +00:00
package main
import (
"encoding/json"
"net"
"time"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/layout"
"fyne.io/fyne/v2/widget"
"go.arsenm.dev/itd/internal/types"
)
func timeTab(parent fyne.Window) *fyne.Container {
2021-08-26 15:47:17 +00:00
// Create new entry for time string
2021-08-26 04:18:24 +00:00
timeEntry := widget.NewEntry()
2021-08-26 15:47:17 +00:00
// Set text to current time formatter properly
2021-08-26 04:18:24 +00:00
timeEntry.SetText(time.Now().Format(time.RFC1123))
2021-08-26 15:47:17 +00:00
// Create button to set current time
2021-08-26 04:18:24 +00:00
currentBtn := widget.NewButton("Set Current", func() {
timeEntry.SetText(time.Now().Format(time.RFC1123))
setTime(true)
})
2021-08-26 15:47:17 +00:00
// Create button to set time inside entry
2021-08-26 04:18:24 +00:00
timeBtn := widget.NewButton("Set", func() {
2021-08-26 15:47:17 +00:00
// Parse time as RFC1123 string
2021-08-26 04:18:24 +00:00
parsedTime, err := time.Parse(time.RFC1123, timeEntry.Text)
if err != nil {
2021-08-27 15:47:24 +00:00
guiErr(err, "Error parsing time string", false, parent)
2021-08-26 04:18:24 +00:00
return
}
2021-08-26 15:47:17 +00:00
// Set time to parsed time
2021-08-26 04:18:24 +00:00
setTime(false, parsedTime)
})
2021-08-26 15:47:17 +00:00
// Return new container with all elements centered
2021-08-26 04:18:24 +00:00
return container.NewVBox(
layout.NewSpacer(),
timeEntry,
currentBtn,
timeBtn,
layout.NewSpacer(),
)
}
// setTime sets the first element in the variadic parameter
// if current is false, otherwise, it sets the current time.
func setTime(current bool, t ...time.Time) error {
2021-08-26 15:47:17 +00:00
// Dial UNIX socket
2021-08-26 04:18:24 +00:00
conn, err := net.Dial("unix", SockPath)
if err != nil {
return err
}
2021-08-26 15:47:17 +00:00
defer conn.Close()
2021-08-26 04:18:24 +00:00
var data string
2021-08-26 15:47:17 +00:00
// If current is true, use the string "now"
// otherwise, use the formatted time from the
// first element in the variadic parameter.
// "now" is more accurate than formatting
// current time as only seconds are preserved
// in that case.
2021-08-26 04:18:24 +00:00
if current {
data = "now"
} else {
data = t[0].Format(time.RFC3339)
}
2021-08-26 15:47:17 +00:00
// Encode SetTime request with above data
2021-08-26 04:18:24 +00:00
err = json.NewEncoder(conn).Encode(types.Request{
Type: types.ReqTypeSetTime,
Data: data,
})
if err != nil {
return err
}
return nil
}