hypr/get_clients.go

96 lines
1.9 KiB
Go
Raw Normal View History

2024-02-09 20:24:48 +01:00
package hypr
import (
2024-08-26 21:43:18 +02:00
"context"
2024-02-09 20:24:48 +01:00
"errors"
"fmt"
"io"
"io/fs"
"os"
"strconv"
"strings"
"git.milar.in/milarin/slices"
)
2024-02-15 14:41:37 +01:00
func GetClient(signature string) (*Client, error) {
lockFilePath := fmt.Sprintf("/run/user/1000/hypr/%s/hyprland.lock", signature)
2024-02-09 20:24:48 +01:00
file, err := os.Open(lockFilePath)
if err != nil {
return nil, err
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
return nil, err
}
lines := strings.Split(string(data), "\n")
pid, err := strconv.Atoi(lines[0])
if err != nil {
return nil, err
}
2024-02-15 14:41:37 +01:00
return &Client{
2024-02-09 20:24:48 +01:00
Signature: signature,
PID: pid,
WaylandSocket: lines[1],
}, nil
}
2024-02-15 14:41:37 +01:00
func GetDefaultClient() (*Client, error) {
2024-02-09 20:24:48 +01:00
signature, ok := os.LookupEnv("HYPRLAND_INSTANCE_SIGNATURE")
if !ok {
return nil, errors.New("default instance not found because HYPRLAND_INSTANCE_SIGNATURE is not set")
}
2024-02-15 14:41:37 +01:00
return GetClient(signature)
2024-02-09 20:24:48 +01:00
}
2024-02-15 14:41:37 +01:00
func GetClients() ([]*Client, error) {
entries, err := os.ReadDir("/run/user/1000/hypr")
2024-02-09 20:24:48 +01:00
if err != nil {
return nil, err
}
entries = slices.Filter(entries, fs.DirEntry.IsDir)
2024-02-15 14:41:37 +01:00
clients := make([]*Client, 0, len(entries))
2024-02-09 20:24:48 +01:00
for _, entry := range entries {
2024-02-15 14:41:37 +01:00
client, err := GetClient(entry.Name())
2024-02-09 20:24:48 +01:00
if err != nil {
fmt.Println(err)
continue
}
2024-02-15 14:41:37 +01:00
clients = append(clients, client)
2024-02-09 20:24:48 +01:00
}
2024-02-15 14:41:37 +01:00
return clients, nil
2024-02-09 20:24:48 +01:00
}
2024-08-26 21:43:18 +02:00
2024-08-26 21:48:18 +02:00
func WaitForClient(ctx context.Context, signature string) (*Client, error) {
2024-08-26 21:43:18 +02:00
lockFilePath := fmt.Sprintf("/run/user/1000/hypr/%s/hyprland.lock", signature)
2024-08-26 21:48:18 +02:00
lockFileExists := !waitFor(ctx, func() bool {
2024-08-26 21:43:18 +02:00
_, err := os.Stat(lockFilePath)
return !errors.Is(err, os.ErrNotExist)
})
2024-08-26 21:48:18 +02:00
if !lockFileExists {
return nil, errors.New("hyprland lock file not found")
}
client, err := GetClient(signature)
if err != nil {
return nil, err
}
if client.WaitUntilReachable(context.Background()) {
return nil, errors.New("hyprland not reachable")
}
return client, nil
2024-08-26 21:43:18 +02:00
}