Compare commits

..

No commits in common. "49b3212c48194608edc4adef32f7fdaca47fd05e" and "51c7a983a0cce4ee55a44fd607d71d60313a90ca" have entirely different histories.

2 changed files with 76 additions and 305 deletions

2
.gitignore vendored
View File

@ -1,2 +1,2 @@
./main ./main
waybar-mpris ./waybar-mpris

379
main.go
View File

@ -7,7 +7,6 @@ import (
"net" "net"
"os" "os"
"os/signal" "os/signal"
"strconv"
"strings" "strings"
"time" "time"
@ -19,11 +18,10 @@ import (
// Various paths and values to use elsewhere. // Various paths and values to use elsewhere.
const ( const (
SOCK = "/tmp/waybar-mpris.sock" SOCK = "/tmp/waybar-mpris.sock"
LOGFILE = "/tmp/waybar-mpris.log" LOGFILE = "/tmp/waybar-mpris.log"
OUTFILE = "/tmp/waybar-mpris.out" // Used for sharing waybar output when args are the same. OUTFILE = "/tmp/waybar-mpris.out"
DATAFILE = "/tmp/waybar-mpris.data.out" // Used for sharing "\n"-separated player data between instances when args are different. POLL = 1
POLL = 1
) )
// Mostly default values for flag options. // Mostly default values for flag options.
@ -34,122 +32,16 @@ var (
ORDER = "SYMBOL:ARTIST:ALBUM:TITLE:POSITION" ORDER = "SYMBOL:ARTIST:ALBUM:TITLE:POSITION"
AUTOFOCUS = false AUTOFOCUS = false
// Available commands that can be sent to running instances. // Available commands that can be sent to running instances.
COMMANDS = []string{"player-next", "player-prev", "next", "prev", "toggle", "list"} COMMANDS = []string{"player-next", "player-prev", "next", "prev", "toggle", "list"}
SHOW_POS = false SHOW_POS = false
INTERPOLATE = false INTERPOLATE = false
REPLACE = false REPLACE = false
isSharing = false isSharing = false
isDataSharing = false WRITER io.Writer = os.Stdout
WRITER io.Writer = os.Stdout
SHAREWRITER, DATAWRITER io.Writer
) )
const (
cPlayerNext = "pn"
cPlayerPrev = "pp"
cNext = "mn"
cPrev = "mp"
cToggle = "mt"
cList = "ls"
cShare = "sh"
cPreShare = "ps"
cDataShare = "ds"
rSuccess = "sc"
rInvalidCommand = "iv"
rFailed = "fa"
)
func stringToCmd(str string) string {
switch str {
case "player-next":
return cPlayerNext
case "player-prev":
return cPlayerPrev
case "next":
return cNext
case "prev":
return cPrev
case "toggle":
return cToggle
case "list":
return cList
case "share":
return cShare
case "data-share":
return cDataShare
case "pre-share":
return cPreShare
}
return ""
}
// length-µS\nposition-µS\nplaying (0 or 1)\nartist\nalbum\ntitle\nplayer\n
func fromData(p *player, cmd string) {
p.Duplicate = true
values := make([]string, 7)
prev := 0
current := 0
for i := range cmd {
if current == len(values) {
break
}
if cmd[i] == '\n' {
values[current] = cmd[prev:i]
prev = i + 1
current++
}
}
l, err := strconv.ParseInt(values[0], 10, 64)
if err != nil {
l = -1
}
p.Length = int(l) / 1000000
pos, err := strconv.ParseInt(values[1], 10, 64)
if err != nil {
pos = -1
}
p.Position = pos
if values[2] == "1" {
p.Playing = true
} else {
p.Playing = false
}
p.Artist = values[3]
p.Album = values[4]
p.Title = values[5]
p.Name = values[6]
}
func toData(p *player) (cmd string) {
cmd += strconv.FormatInt(int64(p.Length*1000000), 10) + "\n"
cmd += strconv.FormatInt(p.Position, 10) + "\n"
if p.Playing {
cmd += "1"
} else {
cmd += "0"
}
cmd += "\n"
cmd += p.Artist + "\n"
cmd += p.Album + "\n"
cmd += p.Title + "\n"
cmd += p.Name + "\n"
return
}
type player struct {
*mpris2.Player
Duplicate bool
}
func secondsToString(seconds int) string {
minutes := int(seconds / 60)
seconds -= int(minutes * 60)
return fmt.Sprintf("%02d:%02d", minutes, seconds)
}
// JSON returns json for waybar to consume. // JSON returns json for waybar to consume.
func playerJSON(p *player) string { func playerJSON(p *mpris2.Player) string {
symbol := PLAY symbol := PLAY
out := "{\"class\": \"" out := "{\"class\": \""
if p.Playing { if p.Playing {
@ -160,14 +52,9 @@ func playerJSON(p *player) string {
} }
var pos string var pos string
if SHOW_POS { if SHOW_POS {
if !p.Duplicate { pos = p.StringPosition()
pos = p.StringPosition() if pos != "" {
if pos != "" { pos = "(" + pos + ")"
pos = "(" + pos + ")"
}
} else {
pos = "(" + secondsToString(int(p.Position/1000000)) + "/" + secondsToString(p.Length) + ")"
} }
} }
var items []string var items []string
@ -237,7 +124,7 @@ type players struct {
func (pl *players) JSON() string { func (pl *players) JSON() string {
if len(pl.mpris2.List) != 0 { if len(pl.mpris2.List) != 0 {
return playerJSON(&player{pl.mpris2.List[pl.mpris2.Current], false}) return playerJSON(pl.mpris2.List[pl.mpris2.Current])
} }
return "{}" return "{}"
} }
@ -253,8 +140,7 @@ func execCommand(cmd string) {
if err != nil { if err != nil {
log.Fatalln("Couldn't dial:", err) log.Fatalln("Couldn't dial:", err)
} }
shortCmd := stringToCmd(cmd) _, err = conn.Write([]byte(cmd))
_, err = conn.Write([]byte(shortCmd))
if err != nil { if err != nil {
log.Fatalln("Couldn't send command") log.Fatalln("Couldn't send command")
} }
@ -272,145 +158,69 @@ func execCommand(cmd string) {
os.Exit(0) os.Exit(0)
} }
func duplicateOutput() error { func duplicateOutput(conn net.Conn) {
// Print to stderr to avoid errors from waybar // Print to stderr to avoid errors from waybar
os.Stderr.WriteString("waybar-mpris is already running. This instance will clone its output.") os.Stderr.WriteString("waybar-mpris is already running. This instance will clone its output.")
// Tell other instance to share output in OUTFILE
conn, err := net.Dial("unix", SOCK) _, err := conn.Write([]byte("share"))
if err != nil {
return err
}
_, err = conn.Write([]byte(cPreShare))
if err != nil { if err != nil {
log.Fatalf("Couldn't send command: %v", err) log.Fatalf("Couldn't send command: %v", err)
return err
} }
buf := make([]byte, 512) buf := make([]byte, 512)
nr, err := conn.Read(buf) nr, err := conn.Read(buf)
if err != nil { if err != nil {
log.Fatalf("Couldn't read response: %v", err) log.Fatalf("Couldn't read response: %v", err)
return err
} }
argString := "" if resp := string(buf[0:nr]); resp == "success" {
for _, arg := range os.Args { // t, err := tail.TailFile(OUTFILE, tail.Config{
argString += arg + "|" // Follow: true,
} // MustExist: true,
conn.Close() // Logger: tail.DiscardingLogger,
conn, err = net.Dial("unix", SOCK) // })
if err != nil { // if err == nil {
return err // for line := range t.Lines {
} // fmt.Println(line.Text)
if string(buf[0:nr]) == argString { // }
// Tell other instance to share output in OUTFILE // }
_, err := conn.Write([]byte(cShare)) f, err := os.Open(OUTFILE)
if err != nil { if err != nil {
log.Fatalf("Couldn't send command: %v", err) log.Fatalf("Failed to open \"%s\": %v", OUTFILE, err)
} }
buf = make([]byte, 2) watcher, err := fsnotify.NewWatcher()
nr, err := conn.Read(buf)
if err != nil { if err != nil {
log.Fatalf("Couldn't read response: %v", err) log.Fatalf("Failed to start watcher: %v", err)
} }
if resp := string(buf[0:nr]); resp == rSuccess { defer watcher.Close()
// t, err := tail.TailFile(OUTFILE, tail.Config{ err = watcher.Add(OUTFILE)
// Follow: true, if err != nil {
// MustExist: true, log.Fatalf("Failed to watch file: %v", err)
// Logger: tail.DiscardingLogger, }
// }) for {
// if err == nil { select {
// for line := range t.Lines { case event, ok := <-watcher.Events:
// fmt.Println(line.Text) if !ok {
// } log.Printf("Watcher failed: %v", err)
// } return
f, err := os.Open(OUTFILE)
if err != nil {
log.Fatalf("Failed to open \"%s\": %v", OUTFILE, err)
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Failed to start watcher: %v", err)
}
defer watcher.Close()
err = watcher.Add(OUTFILE)
if err != nil {
log.Fatalf("Failed to watch file: %v", err)
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
log.Printf("Watcher failed: %v", err)
return err
}
if event.Op&fsnotify.Write == fsnotify.Write {
l, err := io.ReadAll(f)
if err != nil {
log.Printf("Failed to read file: %v", err)
return err
}
str := string(l)
// Trim extra newline is necessary
if str[len(str)-2:] == "\n\n" {
fmt.Print(str[:len(str)-1])
} else {
fmt.Print(str)
}
f.Seek(0, 0)
}
} }
} if event.Op&fsnotify.Write == fsnotify.Write {
} l, err := io.ReadAll(f)
} else { if err != nil {
_, err := conn.Write([]byte(cDataShare)) log.Printf("Failed to read file: %v", err)
if err != nil { return
log.Fatalf("Couldn't send command: %v", err)
}
buf = make([]byte, 2)
nr, err := conn.Read(buf)
if err != nil {
log.Fatalf("Couldn't read response: %v", err)
}
if resp := string(buf[0:nr]); resp == rSuccess {
f, err := os.Open(DATAFILE)
if err != nil {
log.Fatalf("Failed to open \"%s\": %v", DATAFILE, err)
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Failed to start watcher: %v", err)
}
defer watcher.Close()
err = watcher.Add(DATAFILE)
if err != nil {
log.Fatalf("Failed to watch file: %v", err)
}
p := &player{
&mpris2.Player{},
true,
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
log.Printf("Watcher failed: %v", err)
return err
} }
if event.Op&fsnotify.Write == fsnotify.Write { str := string(l)
l, err := io.ReadAll(f) // Trim extra newline is necessary
if err != nil { if str[len(str)-2:] == "\n\n" {
log.Printf("Failed to read file: %v", err) fmt.Print(str[:len(str)-1])
return err } else {
} fmt.Print(str)
str := string(l)
fromData(p, str)
fmt.Fprintln(WRITER, playerJSON(p))
f.Seek(0, 0)
} }
f.Seek(0, 0)
} }
} }
} }
} }
return nil
} }
func listenForCommands(players *players) { func listenForCommands(players *players) {
@ -436,7 +246,7 @@ func listenForCommands(players *players) {
log.Println("Couldn't accept:", err) log.Println("Couldn't accept:", err)
continue continue
} }
buf := make([]byte, 2) buf := make([]byte, 512)
nr, err := con.Read(buf) nr, err := con.Read(buf)
if err != nil { if err != nil {
log.Println("Couldn't read:", err) log.Println("Couldn't read:", err)
@ -444,7 +254,7 @@ func listenForCommands(players *players) {
} }
command := string(buf[0:nr]) command := string(buf[0:nr])
switch command { switch command {
case cPlayerNext: case "player-next":
length := len(players.mpris2.List) length := len(players.mpris2.List)
if length != 1 { if length != 1 {
if players.mpris2.Current < uint(length-1) { if players.mpris2.Current < uint(length-1) {
@ -454,7 +264,7 @@ func listenForCommands(players *players) {
} }
players.mpris2.Refresh() players.mpris2.Refresh()
} }
case cPlayerPrev: case "player-prev":
length := len(players.mpris2.List) length := len(players.mpris2.List)
if length != 1 { if length != 1 {
if players.mpris2.Current != 0 { if players.mpris2.Current != 0 {
@ -464,75 +274,32 @@ func listenForCommands(players *players) {
} }
players.mpris2.Refresh() players.mpris2.Refresh()
} }
case cNext: case "next":
players.Next() players.Next()
case cPrev: case "prev":
players.Prev() players.Prev()
case cToggle: case "toggle":
players.Toggle() players.Toggle()
case cList: case "list":
con.Write([]byte(players.mpris2.String())) con.Write([]byte(players.mpris2.String()))
case cDataShare: case "share":
if !isDataSharing {
f, err := os.OpenFile(DATAFILE, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
defer f.Close()
if err != nil {
fmt.Fprintf(con, "Failed: %v", err)
}
DATAWRITER = dataWrite{
emptyEveryWrite{file: f},
players,
}
if isSharing {
WRITER = io.MultiWriter(SHAREWRITER, DATAWRITER, os.Stdout)
} else {
WRITER = io.MultiWriter(DATAWRITER, os.Stdout)
}
isDataSharing = true
}
fmt.Fprint(con, rSuccess)
case cShare:
if !isSharing { if !isSharing {
f, err := os.OpenFile(OUTFILE, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666) f, err := os.OpenFile(OUTFILE, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
defer f.Close() defer f.Close()
if err != nil { if err != nil {
fmt.Fprintf(con, "Failed: %v", err) fmt.Fprintf(con, "Failed: %v", err)
} }
SHAREWRITER = emptyEveryWrite{file: f} var out io.Writer = emptyEveryWrite{file: f}
if isDataSharing { WRITER = io.MultiWriter(os.Stdout, out)
WRITER = io.MultiWriter(SHAREWRITER, DATAWRITER, os.Stdout)
} else {
WRITER = io.MultiWriter(SHAREWRITER, os.Stdout)
}
isSharing = true isSharing = true
} }
fmt.Fprint(con, rSuccess) fmt.Fprint(con, "success")
/* Prior to sharing, the first instance sends its os.Args.
If the second instances args are different, the first sends the raw data (artist, album, etc.)
If they are the same, the first instance just sends its output and the second prints it. */
case cPreShare:
out := ""
for _, arg := range os.Args {
out += arg + "|"
}
con.Write([]byte(out))
default: default:
fmt.Println("Invalid command") fmt.Println("Invalid command")
} }
con.Close()
} }
} }
type dataWrite struct {
emptyEveryWrite
Players *players
}
func (w dataWrite) Write(p []byte) (n int, err error) {
line := toData(&player{w.Players.mpris2.List[w.Players.mpris2.Current], true})
return w.emptyEveryWrite.Write([]byte(line))
}
type emptyEveryWrite struct { type emptyEveryWrite struct {
file *os.File file *os.File
} }
@ -589,9 +356,13 @@ func main() {
ignoreChoice = true ignoreChoice = true
// os.Remove(SOCK) // os.Remove(SOCK)
} }
} else if conn, err := net.Dial("unix", SOCK); err == nil {
// When waybar-mpris is already running, we attach to its output instead of launching a whole new instance. // When waybar-mpris is already running, we attach to its output instead of launching a whole new instance.
} else if err := duplicateOutput(); err != nil { duplicateOutput(conn)
os.Stdout.WriteString("Couldn't dial socket, deleting instead: " + err.Error()) } else {
if err != nil {
os.Stdout.WriteString("Couldn't dial socket, deleting instead: " + err.Error())
}
os.Remove(SOCK) os.Remove(SOCK)
os.Remove(OUTFILE) os.Remove(OUTFILE)
} }