Run multiple instances by attaching to original

Fixes #1. When another instance is detected, a command is sent over the
socket for the original to write to stdout and to a temporary file, which is then
tailed by the new instance. Can be overridden with --replace.
This commit is contained in:
Harvey Tindall 2020-09-28 23:48:51 +01:00
parent b97a950582
commit 78ce37db9f
Signed by: hrfee
GPG Key ID: BBC65952848FB1A2
5 changed files with 101 additions and 38 deletions

View File

@ -42,10 +42,12 @@ When running, the program will pipe out json in waybar's format. Add something l
``` ```
Usage of waybar-mpris: Usage of waybar-mpris:
--autofocus Auto switch to currently playing music players. --autofocus Auto switch to currently playing music players.
--interpolate Interpolate track position (helpful for players that don't update regularly, e.g mpDris2)
--order string Element order. (default "SYMBOL:ARTIST:ALBUM:TITLE:POSITION") --order string Element order. (default "SYMBOL:ARTIST:ALBUM:TITLE:POSITION")
--pause string Pause symbol/text to use. (default "\uf8e3") --pause string Pause symbol/text to use. (default "\uf8e3")
--play string Play symbol/text to use. (default "▶") --play string Play symbol/text to use. (default "▶")
--position Show current position between brackets, e.g (04:50/05:00) --position Show current position between brackets, e.g (04:50/05:00)
--replace Replace any running instances
--send string send command to already runnning waybar-mpris instance. (options: player-next/player-prev/next/prev/toggle) --send string send command to already runnning waybar-mpris instance. (options: player-next/player-prev/next/prev/toggle)
--separator string Separator string to use between artist, album, and title. (default " - ") --separator string Separator string to use between artist, album, and title. (default " - ")
``` ```
@ -55,6 +57,8 @@ Usage of waybar-mpris:
* `--separator` specifies a string to separate the artist, album and title text. * `--separator` specifies a string to separate the artist, album and title text.
* `--autofocus` makes waybar-mpris automatically focus on currently playing music players. * `--autofocus` makes waybar-mpris automatically focus on currently playing music players.
* `--position` enables the display of the track position. * `--position` enables the display of the track position.
* `--interpolate` increments the track position every second. This is useful for players (e.g mpDris2) that don't regularly update the position.
* `--replace`: By default, new instances will attach to the existing one so that the output is identical. This lets this instance replace any others running. It isn't recommended.
* `--send` sends commands to an already running waybar-mpris instance via a unix socket. Commands: * `--send` sends commands to an already running waybar-mpris instance via a unix socket. Commands:
* `player-next`: Switch to displaying and controlling next available player. * `player-next`: Switch to displaying and controlling next available player.
* `player-prev`: Same as `player-next`, but for the previous player. * `player-prev`: Same as `player-next`, but for the previous player.

4
go.mod
View File

@ -4,5 +4,9 @@ go 1.15
require ( require (
github.com/godbus/dbus/v5 v5.0.3 github.com/godbus/dbus/v5 v5.0.3
github.com/hpcloud/tail v1.0.0
github.com/spf13/pflag v1.0.5 github.com/spf13/pflag v1.0.5
golang.org/x/sys v0.0.0-20200928205150-006507a75852 // indirect
gopkg.in/fsnotify.v1 v1.4.7 // indirect
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
) )

8
go.sum
View File

@ -1,4 +1,12 @@
github.com/godbus/dbus/v5 v5.0.3 h1:ZqHaoEF7TBzh4jzPmqVhE/5A1z9of6orkAe5uHoAeME= github.com/godbus/dbus/v5 v5.0.3 h1:ZqHaoEF7TBzh4jzPmqVhE/5A1z9of6orkAe5uHoAeME=
github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/sys v0.0.0-20200928205150-006507a75852 h1:sXxgOAXy8JwHhZnPuItAlUtwIlxrlEqi28mKhUR+zZY=
golang.org/x/sys v0.0.0-20200928205150-006507a75852/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=

79
main.go
View File

@ -15,6 +15,7 @@ import (
"time" "time"
"github.com/godbus/dbus/v5" "github.com/godbus/dbus/v5"
"github.com/hpcloud/tail"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
) )
@ -48,6 +49,7 @@ const (
MATCH_PC = "type='signal',path='/org/mpris/MediaPlayer2',interface='org.freedesktop.DBus.Properties'" MATCH_PC = "type='signal',path='/org/mpris/MediaPlayer2',interface='org.freedesktop.DBus.Properties'"
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"
POLL = 1 POLL = 1
) )
@ -60,6 +62,8 @@ var (
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
WRITER io.Writer = os.Stdout
) )
// NewPlayer returns a new player object. // NewPlayer returns a new player object.
@ -310,7 +314,7 @@ func (pl *PlayerList) Remove(fullName string) {
if !found { if !found {
pl.current = 0 pl.current = 0
pl.Refresh() pl.Refresh()
fmt.Println(pl.JSON()) fmt.Fprintln(WRITER, pl.JSON())
} }
} }
// ls[len(ls)-1], ls[i] = ls[i], ls[len(ls)-1] // ls[len(ls)-1], ls[i] = ls[i], ls[len(ls)-1]
@ -384,8 +388,10 @@ func main() {
flag.BoolVar(&AUTOFOCUS, "autofocus", AUTOFOCUS, "Auto switch to currently playing music players.") flag.BoolVar(&AUTOFOCUS, "autofocus", AUTOFOCUS, "Auto switch to currently playing music players.")
flag.BoolVar(&SHOW_POS, "position", SHOW_POS, "Show current position between brackets, e.g (04:50/05:00)") flag.BoolVar(&SHOW_POS, "position", SHOW_POS, "Show current position between brackets, e.g (04:50/05:00)")
flag.BoolVar(&INTERPOLATE, "interpolate", INTERPOLATE, "Interpolate track position (helpful for players that don't update regularly, e.g mpDris2)") flag.BoolVar(&INTERPOLATE, "interpolate", INTERPOLATE, "Interpolate track position (helpful for players that don't update regularly, e.g mpDris2)")
flag.BoolVar(&REPLACE, "replace", REPLACE, "replace existing waybar-mpris if found. When false, new instance will clone the original instances output.")
var command string var command string
flag.StringVar(&command, "send", "", "send command to already runnning waybar-mpris instance. (options: "+strings.Join(COMMANDS, "/")+")") flag.StringVar(&command, "send", "", "send command to already runnning waybar-mpris instance. (options: "+strings.Join(COMMANDS, "/")+")")
flag.Parse() flag.Parse()
if command != "" { if command != "" {
@ -402,7 +408,7 @@ func main() {
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.") log.Fatalln("Couldn't read response.")
} }
response := string(buf[0:nr]) response := string(buf[0:nr])
fmt.Println("Response:") fmt.Println("Response:")
@ -420,11 +426,12 @@ func main() {
players.Reload() players.Reload()
players.Sort() players.Sort()
players.Refresh() players.Refresh()
fmt.Println(players.JSON()) fmt.Fprintln(WRITER, players.JSON())
lastLine := "" lastLine := ""
// fmt.Println("New array", players) // fmt.Println("New array", players)
// Start command listener // Start command listener
if _, err := os.Stat(SOCK); err == nil { if _, err := os.Stat(SOCK); err == nil {
if REPLACE {
fmt.Printf("Socket %s already exists, this could mean waybar-mpris is already running.\nStarting this instance will overwrite the file, possibly stopping other instances from accepting commands.\n", SOCK) fmt.Printf("Socket %s already exists, this could mean waybar-mpris is already running.\nStarting this instance will overwrite the file, possibly stopping other instances from accepting commands.\n", SOCK)
var input string var input string
ignoreChoice := false ignoreChoice := false
@ -439,9 +446,40 @@ func main() {
if input == "" { if input == "" {
fmt.Printf("\nRemoving due to lack of input.\n") fmt.Printf("\nRemoving due to lack of input.\n")
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.
fmt.Println("waybar-mpris is already running. This instance will clone its output.")
if err != nil {
log.Fatalln("Couldn't dial:", err)
}
_, err = conn.Write([]byte("share"))
if err != nil {
log.Fatalln("Couldn't send command")
}
buf := make([]byte, 512)
nr, err := conn.Read(buf)
if err != nil {
log.Fatalln("Couldn't read response.")
}
if string(buf[0:nr]) == "success" {
t, err := tail.TailFile(OUTFILE, tail.Config{
Follow: true,
MustExist: true,
Logger: tail.DiscardingLogger,
})
if err == nil {
for line := range t.Lines {
fmt.Println(line.Text)
}
}
}
} else {
os.Remove(SOCK)
os.Remove(OUTFILE)
}
} }
go func() { go func() {
listener, err := net.Listen("unix", SOCK) listener, err := net.Listen("unix", SOCK)
@ -449,11 +487,12 @@ func main() {
signal.Notify(c, os.Interrupt) signal.Notify(c, os.Interrupt)
go func() { go func() {
<-c <-c
os.Remove(OUTFILE)
os.Remove(SOCK) os.Remove(SOCK)
os.Exit(1) os.Exit(1)
}() }()
if err != nil { if err != nil {
log.Fatalln("Couldn't establish socket connection at", SOCK) log.Fatalf("Couldn't establish socket connection at %s (error %s)\n", SOCK, err)
} }
defer func() { defer func() {
listener.Close() listener.Close()
@ -472,7 +511,8 @@ func main() {
continue continue
} }
command := string(buf[0:nr]) command := string(buf[0:nr])
if command == "player-next" { switch command {
case "player-next":
length := len(players.list) length := len(players.list)
if length != 1 { if length != 1 {
if players.current < uint(length-1) { if players.current < uint(length-1) {
@ -481,9 +521,9 @@ func main() {
players.current = 0 players.current = 0
} }
players.Refresh() players.Refresh()
fmt.Println(players.JSON()) fmt.Fprintln(WRITER, players.JSON())
} }
} else if command == "player-prev" { case "player-prev":
length := len(players.list) length := len(players.list)
if length != 1 { if length != 1 {
if players.current != 0 { if players.current != 0 {
@ -492,15 +532,15 @@ func main() {
players.current = uint(length - 1) players.current = uint(length - 1)
} }
players.Refresh() players.Refresh()
fmt.Println(players.JSON()) fmt.Fprintln(WRITER, players.JSON())
} }
} else if command == "next" { case "next":
players.Next() players.Next()
} else if command == "prev" { case "prev":
players.Prev() players.Prev()
} else if command == "toggle" { case "toggle":
players.Toggle() players.Toggle()
} else if command == "list" { case "list":
resp := "" resp := ""
pad := 0 pad := 0
i := len(players.list) i := len(players.list)
@ -516,7 +556,14 @@ func main() {
resp += fmt.Sprintf("%0"+strconv.Itoa(pad)+"d%s: Name: %s; Playing: %t; PID: %d\n", i, symbol, p.fullName, p.playing, p.pid) resp += fmt.Sprintf("%0"+strconv.Itoa(pad)+"d%s: Name: %s; Playing: %t; PID: %d\n", i, symbol, p.fullName, p.playing, p.pid)
} }
con.Write([]byte(resp)) con.Write([]byte(resp))
} else { case "share":
out, err := os.Create(OUTFILE)
if err != nil {
con.Write([]byte(fmt.Sprintf("Failed: %s", err)))
}
WRITER = io.MultiWriter(os.Stdout, out)
con.Write([]byte("success"))
default:
fmt.Println("Invalid command") fmt.Println("Invalid command")
} }
} }
@ -530,7 +577,7 @@ func main() {
time.Sleep(POLL * time.Second) time.Sleep(POLL * time.Second)
if len(players.list) != 0 { if len(players.list) != 0 {
if players.list[players.current].playing { if players.list[players.current].playing {
go fmt.Println(players.JSON()) go fmt.Fprintln(WRITER, players.JSON())
} }
} }
} }
@ -563,7 +610,7 @@ func main() {
} }
if l := players.JSON(); l != lastLine { if l := players.JSON(); l != lastLine {
lastLine = l lastLine = l
fmt.Println(l) fmt.Fprintln(WRITER, l)
} }
} }
} }

Binary file not shown.