├── .github └── workflows │ └── release.yml ├── .gitignore ├── .goreleaser.yml ├── LICENSE.md ├── Makefile ├── README.md ├── battery.go ├── go.mod ├── go.sum ├── ipc_socket.go ├── log.go ├── main.go ├── parameters.go ├── string_set.go ├── swaymsg.go ├── swaynag.go ├── version.go ├── version.sh └── watcher.go /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | push: 5 | branches-ignore: 6 | - '**' 7 | tags: 8 | - 'v*.*.*' 9 | 10 | jobs: 11 | goreleaser: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - 15 | name: Checkout 16 | uses: actions/checkout@v1 17 | - 18 | name: Set up Go 19 | uses: actions/setup-go@v1 20 | with: 21 | go-version: 1.18 22 | - 23 | name: Run GoReleaser 24 | uses: goreleaser/goreleaser-action@v1 25 | with: 26 | args: release --rm-dist 27 | key: ${{ secrets.RELEASE_KEY }} 28 | env: 29 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | bin/ 8 | dist/ 9 | 10 | # Test binary, built with `go test -c` 11 | *.test 12 | 13 | # Output of the go coverage tool, specifically when used with LiteIDE 14 | *.out 15 | 16 | # Dependency directories (remove the comment below to include it) 17 | # vendor/ 18 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | before: 2 | hooks: 3 | - go mod tidy 4 | - go generate version.go 5 | builds: 6 | - env: 7 | - CGO_ENABLED=0 8 | goos: 9 | - linux 10 | - darwin 11 | signs: 12 | - artifacts: checksum 13 | args: ["--batch", "-u", "B7704FFB48AC73A1", "--output", "${signature}", "--detach-sign", "${artifact}"] 14 | archives: 15 | - replacements: 16 | darwin: Darwin 17 | linux: Linux 18 | 386: i386 19 | amd64: x86_64 20 | checksum: 21 | name_template: 'checksums.txt' 22 | snapshot: 23 | name_template: "{{ .Tag }}-next" 24 | changelog: 25 | sort: asc 26 | filters: 27 | exclude: 28 | - '^docs:' 29 | - '^test:' 30 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) [2019] [m00qek] 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: run 2 | 3 | clean: 4 | @rm bin/ -rf 5 | 6 | run: 7 | @go run *.go 8 | 9 | build: clean 10 | @go build -o bin/swaynag-battery 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # swaynag-battery 2 | 3 | [![Release](https://img.shields.io/github/release/m00qek/swaynag-battery.svg?style=for-the-badge)](https://github.com/m00qek/swaynag-battery/releases/latest) 4 | [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=for-the-badge)](/LICENSE.md) 5 | 6 | Shows a message on top of all displays (using 7 | [swaynag](https://github.com/swaywm/sway/tree/master/swaynag)) when battery is 8 | discharging and bellow an appointed threshold. Also, closes the message when a 9 | power supply is plugged in. 10 | 11 | ## Installing 12 | 13 | Download the appropriate latest version binary from 14 | [releases](https://github.com/m00qek/swaynag-battery/releases) or clone this 15 | repo, run `make build` and copy `bin/swaynag-battery` to somewhere in your 16 | `PATH`. 17 | 18 | In order to automatically run `swaynag-battery` when you execute Sway, you can 19 | configure [Sway to start using systemd](https://github.com/swaywm/sway/wiki/Systemd-integration) 20 | and add a new user service file in 21 | `~/.config/systemd/user/swaynag-battery.service` with 22 | 23 | ``` 24 | [Unit] 25 | Description=Low battery notification 26 | PartOf=graphical-session.target 27 | 28 | [Service] 29 | Type=simple 30 | ExecStart=/absolute/path/to/swaynag-battery 31 | 32 | [Install] 33 | WantedBy=sway-session.target 34 | ``` 35 | 36 | and then 37 | 38 | ```bash 39 | systemctl --user enable swaynag-battery.service 40 | systemctl --user start swaynag-battery.service 41 | ``` 42 | 43 | ## API 44 | ``` 45 | Shows a message (using swaynag) when battery percentage is less then specified 46 | value. 47 | 48 | Usage: 49 | swaynag-battery [options] 50 | swaynag-battery -h | --help 51 | swaynag-battery --version 52 | 53 | Options: 54 | --displays Comma separated list of displays to show the 55 | alert - the default is to show in all displays. 56 | --threshold Percentual threshold to show notification. 57 | [default: 15] 58 | --interval Check battery at every interval. [default: 5m] 59 | --uevent Uevent path for reading battery stats. 60 | [default: /sys/class/power_supply/BAT0/uevent] 61 | -h --help Show this screen. 62 | --version Show version. 63 | ``` 64 | 65 | ## Release Signatures 66 | 67 | Releases are signed with 68 | [B7704FFB48AC73A1](https://keys.openpgp.org/vks/v1/by-fingerprint/2FC9D934AC901B875CAD71AAB7704FFB48AC73A1) 69 | and published [on GitHub](https://github.com/m00qek/swaynag-battery/releases). 70 | 71 | ## Acknowledgments 72 | 73 | A special thanks to [Egor Kovetskiy](https://github.com/kovetskiy) who created 74 | [i3-battery-nagbar](https://github.com/kovetskiy/i3-battery-nagbar), the program 75 | that inspired me to create this one. 76 | -------------------------------------------------------------------------------- /battery.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "os" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | type Status uint8 11 | 12 | const ( 13 | UNKNOWN Status = 0 14 | CHARGING Status = 1 15 | DISCHARGING Status = 2 16 | NOT_CHARGING Status = 3 17 | FULL Status = 4 18 | ) 19 | 20 | type Battery struct { 21 | Name string 22 | ModelName string 23 | Technology string 24 | Capacity int 25 | Status Status 26 | } 27 | 28 | func (battery *Battery) Charging() bool { 29 | return battery.Status == FULL || battery.Status == CHARGING 30 | } 31 | 32 | func parseStatus(value string) Status { 33 | switch value { 34 | case "Charging": 35 | return CHARGING 36 | case "Discharging": 37 | return DISCHARGING 38 | case "Not charging": 39 | return NOT_CHARGING 40 | case "Full": 41 | return FULL 42 | default: 43 | return UNKNOWN 44 | } 45 | } 46 | 47 | func load(path string) ([]string, error) { 48 | file, err := os.Open(path) 49 | if err != nil { 50 | return nil, err 51 | } 52 | defer file.Close() 53 | 54 | var lines []string 55 | scanner := bufio.NewScanner(file) 56 | for scanner.Scan() { 57 | lines = append(lines, scanner.Text()) 58 | } 59 | return lines, scanner.Err() 60 | } 61 | 62 | func parse(content []string) map[string]string { 63 | info := make(map[string]string) 64 | 65 | for _, line := range content { 66 | tokens := strings.SplitN(line, "=", 2) 67 | if len(tokens) != 2 { 68 | continue 69 | } 70 | 71 | key, value := tokens[0], tokens[1] 72 | info[key] = value 73 | } 74 | 75 | return info 76 | } 77 | 78 | func build(info map[string]string) (*Battery, error) { 79 | capacity, err := strconv.Atoi(info["POWER_SUPPLY_CAPACITY"]) 80 | if err != nil { 81 | return nil, err 82 | } 83 | 84 | return &Battery{ 85 | Name: info["POWER_SUPPLY_NAME"], 86 | Capacity: capacity, 87 | ModelName: info["POWER_SUPPLY_MODEL_NAME"], 88 | Status: parseStatus(info["POWER_SUPPLY_STATUS"]), 89 | Technology: info["POWER_SUPPLY_TECHNOLOGY"], 90 | }, nil 91 | } 92 | 93 | func LoadBatteryInfo(uevent string) (*Battery, error) { 94 | content, err := load(uevent) 95 | if err != nil { 96 | logError("ERROR: Could not load battery file '%s'.", uevent) 97 | return nil, err 98 | } 99 | 100 | battery, err := build(parse(content)) 101 | if err != nil { 102 | logError("Could not parse 'POWER_SUPPLY_CAPACITY' from battery file '%s'.", uevent) 103 | return nil, err 104 | } 105 | 106 | return battery, nil 107 | } 108 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module swaynag-battery 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 7 | github.com/logrusorgru/aurora/v4 v4.0.0 8 | github.com/mitchellh/go-ps v1.0.0 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815 h1:bWDMxwH3px2JBh6AyO7hdCn/PkvCZXii8TGj7sbtEbQ= 2 | github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= 3 | github.com/logrusorgru/aurora v2.0.3+incompatible h1:tOpm7WcpBTn4fjmVfgpQq0EfczGlG91VSDkswnjF5A8= 4 | github.com/logrusorgru/aurora v2.0.3+incompatible/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= 5 | github.com/logrusorgru/aurora/v4 v4.0.0 h1:sRjfPpun/63iADiSvGGjgA1cAYegEWMPCJdUpJYn9JA= 6 | github.com/logrusorgru/aurora/v4 v4.0.0/go.mod h1:lP0iIa2nrnT/qoFXcOZSrZQpJ1o6n2CUf/hyHi2Q4ZQ= 7 | github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc= 8 | github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= 9 | -------------------------------------------------------------------------------- /ipc_socket.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "io" 7 | "net" 8 | "os" 9 | "strings" 10 | "sync" 11 | ) 12 | 13 | // See https://github.com/swaywm/sway/blob/master/sway/sway-ipc.7.scd 14 | // or https://man.archlinux.org/man/sway-ipc.7.en for details. 15 | const( 16 | swayGetOutputs = 3 17 | ) 18 | 19 | var byteOrder binary.ByteOrder = binary.LittleEndian 20 | 21 | var currentSocket struct { 22 | mutex sync.Mutex 23 | connection net.Conn 24 | } 25 | 26 | // Send IPC call to sway 27 | func sendIpc(messageName uint32) (string, error) { 28 | currentSocket.mutex.Lock() 29 | defer currentSocket.mutex.Unlock() 30 | 31 | socketAddress, err := getSwaySock() 32 | if (err != nil) { 33 | return "", err 34 | } 35 | 36 | err = openSocket(socketAddress) 37 | if (err != nil) { 38 | return "", err 39 | } 40 | 41 | response, err := socketSendMessage(currentSocket.connection, messageName) 42 | 43 | if(currentSocket.connection != nil) { 44 | currentSocket.connection.Close() 45 | } 46 | 47 | return response, err 48 | } 49 | 50 | func getSwaySock() (string, error) { 51 | socket_from_env := strings.TrimSpace(os.Getenv("SWAYSOCK")) 52 | 53 | if (len(socket_from_env) == 0) { 54 | return "", fmt.Errorf("Failed to get socket path from SWAYSOCK environment variable") 55 | } 56 | 57 | return socket_from_env, nil 58 | } 59 | 60 | func openSocket(socketAdress string) (error) { 61 | if currentSocket.connection != nil { 62 | currentSocket.connection.Close() 63 | } 64 | 65 | socketConnection, err := net.Dial("unix", socketAdress) 66 | if (err == nil) { 67 | currentSocket.connection = socketConnection 68 | return nil 69 | } else { 70 | return err 71 | } 72 | } 73 | 74 | func socketSendMessage(socketConnection net.Conn, messageName uint32) (string, error) { 75 | // Send 76 | message := ipcHeader(messageName) 77 | err := binary.Write(socketConnection, byteOrder, &message) 78 | if (err != nil) { 79 | return "", err 80 | } 81 | 82 | // Receive header 83 | var header ipcMessageHeader 84 | err = binary.Read(socketConnection, byteOrder, &header) 85 | if (err != nil) { 86 | return "", err 87 | } 88 | 89 | // Receive payload 90 | responsePayload := make([]byte, header.Length) 91 | _, err = io.ReadFull(socketConnection, responsePayload) 92 | 93 | return string(responsePayload), err 94 | } 95 | 96 | type ipcMessageHeader struct { 97 | MagicString [6]byte 98 | Length uint32 99 | Type uint32 100 | } 101 | 102 | func ipcHeader(messageName uint32) (ipcMessageHeader) { 103 | return ipcMessageHeader{ 104 | MagicString: [6]byte{'i', '3', '-', 'i', 'p', 'c'}, 105 | Length: 0, 106 | Type: messageName, 107 | } 108 | } 109 | 110 | -------------------------------------------------------------------------------- /log.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | . "github.com/logrusorgru/aurora/v4" 6 | "log" 7 | "os" 8 | ) 9 | 10 | func logError(message string, v ...interface{}) { 11 | log.Println(Bold(Red("ERROR:")), fmt.Sprintf(message, v...)) 12 | } 13 | 14 | func logAndExit(exitCode int, message string, v ...interface{}) { 15 | log.Println(Bold(Red("FATAL:")), fmt.Sprintf(message, v...)) 16 | os.Exit(exitCode) 17 | } 18 | 19 | func logWarning(message string, v ...interface{}) { 20 | log.Println(Bold(Yellow("WARNING:")), fmt.Sprintf(message, v...)) 21 | } 22 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "time" 6 | ) 7 | 8 | func DesiredDisplays(displays StringSet, activeDisplays StringSet) StringSet { 9 | if len(displays) == 0 { 10 | return activeDisplays 11 | } 12 | 13 | return Intersection(displays, activeDisplays) 14 | } 15 | 16 | func tick(watcher *Watcher, params Parameters) { 17 | battery, err := LoadBatteryInfo(params.uevent) 18 | if err != nil { 19 | logWarning("Skipping this cycle due to errors occurred.") 20 | return 21 | } 22 | 23 | displays := DesiredDisplays(params.displays, ActiveDisplays()) 24 | 25 | if !battery.Charging() && battery.Capacity <= params.threshold { 26 | messages := ShowAll(params.message, watcher.MessagesFor(displays)) 27 | watcher.Update(messages, battery.Status) 28 | } 29 | 30 | if battery.Charging() && battery.Status != watcher.Status() { 31 | messages := watcher.Messages() 32 | CloseAll(messages) 33 | watcher.Update(messages, battery.Status) 34 | watcher.CleanUp(displays) 35 | } 36 | } 37 | 38 | func main() { 39 | params := CommandLineParameters(os.Args[1:]) 40 | watcher := NewWatcher() 41 | 42 | tick(&watcher, params) 43 | for range time.Tick(params.interval) { 44 | tick(&watcher, params) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /parameters.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "strconv" 6 | "strings" 7 | "time" 8 | 9 | docopt "github.com/docopt/docopt-go" 10 | ) 11 | 12 | type Parameters struct { 13 | displays StringSet 14 | interval time.Duration 15 | message string 16 | threshold int 17 | uevent string 18 | } 19 | 20 | var ( 21 | usage = ` 22 | Shows a message (using swaynag) when battery percentage is less then specified 23 | value. 24 | 25 | Usage: 26 | swaynag-battery [options] 27 | swaynag-battery -h | --help 28 | swaynag-battery --version 29 | 30 | Options: 31 | --displays Comma separated list of displays to show the 32 | alert - the default is to show in all displays. 33 | --threshold Percentual threshold to show notification. 34 | [default: 15] 35 | --interval Check battery at every interval. [default: 5m] 36 | --uevent Uevent path for reading battery stats. 37 | [default: /sys/class/power_supply/BAT0/uevent] 38 | --message Override the low battery message. 39 | -h --help Show this screen. 40 | --version Show version. 41 | ` 42 | ) 43 | 44 | func CommandLineParameters(arguments []string) Parameters { 45 | args, err := docopt.ParseArgs(usage, arguments, version) 46 | if err != nil { 47 | logAndExit(18, "Unable to parse input arguments.") 48 | } 49 | 50 | interval, err := time.ParseDuration(args["--interval"].(string)) 51 | if err != nil { 52 | logAndExit(28, "Unable to parse '--interval %s': the value must be a duration.", args["--interval"]) 53 | } 54 | 55 | threshold, err := strconv.Atoi(args["--threshold"].(string)) 56 | if err != nil { 57 | logAndExit(38, "Unable to parse '--threshold %s': the value must be an integer number.", args["--threshold"]) 58 | } 59 | 60 | displays := []string{} 61 | d, ok := args["--displays"].(string) 62 | if ok { 63 | displays = strings.Split(d, ",") 64 | } 65 | var message string = "Your battery is running low. Please plug in a power adapter" 66 | if args["--message"] != nil { 67 | message = args["--message"].(string) 68 | } 69 | 70 | uevent := args["--uevent"].(string) 71 | file, err := os.Open(uevent) 72 | if err != nil { 73 | logAndExit(42, "Could not load battery file '%s'.", uevent) 74 | } 75 | file.Close() 76 | 77 | return Parameters{ 78 | displays: SetFrom(displays), 79 | interval: interval, 80 | message: message, 81 | threshold: threshold, 82 | uevent: uevent} 83 | } 84 | -------------------------------------------------------------------------------- /string_set.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type StringSet map[string]struct{} 4 | 5 | func SetFrom(array []string) StringSet { 6 | set := make(StringSet) 7 | for _, item := range array { 8 | set[item] = struct{}{} 9 | } 10 | return set 11 | } 12 | 13 | func (set StringSet) ToArray() []string { 14 | keys := make([]string, 0, len(set)) 15 | for key := range set { 16 | keys = append(keys, key) 17 | } 18 | return keys 19 | } 20 | 21 | func (set StringSet) Contains(item string) bool { 22 | _, contains := set[item] 23 | return contains 24 | } 25 | 26 | func EmptySet() StringSet { 27 | return StringSet{} 28 | } 29 | 30 | func Intersection(set1 StringSet, set2 StringSet) StringSet { 31 | intersection := make(StringSet) 32 | for item := range set1 { 33 | if set2.Contains(item) { 34 | intersection[item] = struct{}{} 35 | } 36 | } 37 | return intersection 38 | } 39 | -------------------------------------------------------------------------------- /swaymsg.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | ) 6 | 7 | type Display struct { 8 | Name string 9 | Active bool 10 | } 11 | 12 | func run() (string, error) { 13 | response, err := sendIpc(swayGetOutputs) 14 | 15 | if err != nil { 16 | logError("Unable to get sway outputs.") 17 | return "", err 18 | } 19 | 20 | return response, nil 21 | } 22 | 23 | func filterActive(displays []Display) []string { 24 | var activeDisplays []string 25 | for _, display := range displays { 26 | if display.Active { 27 | activeDisplays = append(activeDisplays, display.Name) 28 | } 29 | } 30 | 31 | return activeDisplays 32 | } 33 | 34 | func ActiveDisplays() StringSet { 35 | var displays []Display 36 | jsonOutput, err := run() 37 | 38 | if err != nil { 39 | return EmptySet() 40 | } 41 | 42 | json.Unmarshal([]byte(jsonOutput), &displays) 43 | return SetFrom(filterActive(displays)) 44 | } 45 | -------------------------------------------------------------------------------- /swaynag.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "os/exec" 6 | "strings" 7 | 8 | ps "github.com/mitchellh/go-ps" 9 | ) 10 | 11 | type Message struct { 12 | PID int 13 | Display string 14 | } 15 | 16 | func show(text string, display string) (*Message, error) { 17 | cmd := exec.Command("swaynag", "--message", text, "--output", display, "--layer", "overlay") 18 | 19 | err := cmd.Start() 20 | if err != nil { 21 | logError("Unable to show swaynag in display '%s'.\n", display) 22 | return nil, err 23 | } 24 | 25 | go func() { 26 | cmd.Wait() 27 | }() 28 | 29 | return &Message{PID: cmd.Process.Pid, Display: display}, nil 30 | } 31 | 32 | func isSwaynag(process ps.Process, err error) bool { 33 | return err == nil && 34 | process != nil && 35 | strings.HasSuffix(process.Executable(), "swaynag") 36 | } 37 | 38 | func ShowMessage(text string, message Message) (*Message, error) { 39 | if isSwaynag(ps.FindProcess(message.PID)) { 40 | return &message, nil 41 | } 42 | 43 | return show(text, message.Display) 44 | } 45 | 46 | func CloseMessage(message Message) { 47 | process, err := os.FindProcess(message.PID) 48 | if err != nil { 49 | return 50 | } 51 | defer process.Release() 52 | process.Signal(os.Interrupt) 53 | } 54 | 55 | func ShowAll(text string, messages []Message) []Message { 56 | var openMessages []Message 57 | for _, message := range messages { 58 | newMessage, _ := ShowMessage(text, message) 59 | if newMessage == nil { 60 | openMessages = append(openMessages, message) 61 | } else { 62 | openMessages = append(openMessages, *newMessage) 63 | } 64 | } 65 | 66 | return openMessages 67 | } 68 | 69 | func CloseAll(messages []Message) { 70 | for _, message := range messages { 71 | CloseMessage(message) 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /version.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //go:generate bash ./version.sh 4 | var version = "[development version]" 5 | -------------------------------------------------------------------------------- /version.sh: -------------------------------------------------------------------------------- 1 | latest_tag=$(git describe `git rev-list --tags --max-count=1`) 2 | 3 | cat << EOF > version.go 4 | package main 5 | 6 | //go:generate bash ./version.sh 7 | var version = "$latest_tag" 8 | EOF 9 | -------------------------------------------------------------------------------- /watcher.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type Watcher struct { 4 | messages map[string]Message 5 | status Status 6 | } 7 | 8 | func NewWatcher() Watcher { 9 | messages := make(map[string]Message) 10 | return Watcher{ 11 | messages: messages, 12 | status: UNKNOWN, 13 | } 14 | } 15 | 16 | func (watcher *Watcher) Status() Status { 17 | return watcher.status 18 | } 19 | 20 | func (watcher *Watcher) Messages() []Message { 21 | var messages []Message 22 | for _, message := range watcher.messages { 23 | messages = append(messages, message) 24 | } 25 | return messages 26 | } 27 | 28 | func (watcher *Watcher) MessagesFor(displays StringSet) []Message { 29 | var messages []Message 30 | for display := range displays { 31 | message, contains := watcher.messages[display] 32 | if contains { 33 | messages = append(messages, message) 34 | } else { 35 | messages = append(messages, Message{PID: 0, Display: display}) 36 | } 37 | } 38 | return messages 39 | } 40 | 41 | func (watcher *Watcher) Update(messages []Message, status Status) { 42 | for _, message := range messages { 43 | watcher.messages[message.Display] = message 44 | } 45 | watcher.status = status 46 | } 47 | 48 | func (watcher *Watcher) CleanUp(activeDisplays StringSet) { 49 | var currentDisplays []string 50 | for display := range watcher.messages { 51 | currentDisplays = append(currentDisplays, display) 52 | } 53 | 54 | for _, display := range currentDisplays { 55 | if !activeDisplays.Contains(display) { 56 | delete(watcher.messages, display) 57 | } 58 | } 59 | } 60 | --------------------------------------------------------------------------------