summaryrefslogtreecommitdiff
path: root/home-config/waybar/custom_cmus.lua
blob: d03eb9c1ef6f1c7f00d2e2b1e7d435aa039a9efa (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
#!/usr/bin/lua

json = require("dkjson")
posix = require("posix")

function htmlescape(s)
    s = string.gsub(s, "&", "&")
    s = string.gsub(s, "<", "&lt;")
    s = string.gsub(s, ">", "&gt;")
    return s
end

function timefmt(n)
    local s = n % 60
    local m = math.floor(n / 60)
    return string.format("%d:%02d", m, s)
end

function output(text, tooltip)
    text = htmlescape(text)
    tooltip = htmlescape(tooltip)
    print(json.encode{text=text, tooltip=tooltip, class="custom-cmus"})
end

function getstat(status, name)
    for _, line in ipairs(status) do
        if string.match(line, "^" .. name) then
            return string.sub(line, string.len(name)+2)
        end
    end
end

while true do
    local pipe = io.popen("cmus-remote -Q")
    local status = {}
    for line in pipe:lines() do
        table.insert(status, line)
    end
    local success = pipe:close()
    if not success then
        output(" Not running", "Not running")
    elseif getstat(status, "status") == "stopped" then
        output(" Not running", "Not running")
    else
        local playing = getstat(status, "status")
        local symbol = ({playing="", paused=""})[playing]
        local title = getstat(status, "tag title")
        local artist = getstat(status, "tag artist")
        local duration = getstat(status, "duration")
        local position = getstat(status, "position")
        local text = string.format("%s %s (%s)", symbol, title, timefmt(position))
        local tooltip = string.format("%s - %s (%s / %s)", 
            artist, title, timefmt(position), timefmt(duration)
        )
        output(text, tooltip)
    end
    posix.sleep(1)
end