swaymux/sway_bindings/Sway.cpp
2024-03-04 00:27:05 +01:00

38 lines
1.0 KiB
C++

//
// Created by grimmauld on 03.03.24.
//
#include "Sway.h"
swaymsg Sway::sendIPC(const swaymsg &query) const {
if (send(socketfd, query.asBuffer(), query.size(), 0) == -1) {
throw std::runtime_error("Swaysock: Error on send() call");
}
return swaymsg::fromSock(socketfd);
}
Sway::Sway() : socketfd(socket(AF_UNIX, SOCK_STREAM, 0)) {
initializeSocket();
}
void Sway::initializeSocket() const {
auto *sockaddr = std::getenv("SWAYSOCK");
if (sockaddr == nullptr) {
throw std::runtime_error("Binding socket: reading SWAYSOCK env var failed");
}
if (socketfd == -1) {
throw std::runtime_error("Binding socket: could not get file descriptor");
}
struct sockaddr_un swaysock{};
swaysock.sun_family = AF_UNIX;
strcpy(swaysock.sun_path, sockaddr);
auto dlen = strlen(swaysock.sun_path) + sizeof(swaysock.sun_family);
if (connect(socketfd, (struct sockaddr *) &swaysock, dlen) == -1) {
throw std::runtime_error("Binding socket: could not connect to socket");
}
}