Files
FWS-DeskManger/src/session-catalog.cpp
T
BlackAngelTV f7789cd639 feat(session): read session state and greeter entries from logind
Switching needs to know whether a session owns the seat, is closing, or is
the greeter, and which session file the greeter will list for a desktop.
The catalog now keeps the logind State, exposes targeted lookups, and prefers
the active session so a closing one is never activated. Session ids are
compared numerically without std::stoi.
2026-11-04 15:42:22 +01:00

306 lines
9.4 KiB
C++

#include "session-catalog.h"
#include "process.h"
#include <unistd.h>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <utility>
namespace fws {
namespace {
struct DesktopFile {
std::string name;
std::string exec;
std::string desktops;
};
DesktopFile parseDesktopFile(const std::filesystem::path& path) {
DesktopFile fields;
std::ifstream stream(path);
std::string line;
bool inDesktopEntry = false;
while (std::getline(stream, line)) {
line = trim(line);
if (line.empty() || line[0] == '#') {
continue;
}
if (line.front() == '[' && line.back() == ']') {
// Only the main group carries the session metadata.
inDesktopEntry = line == "[Desktop Entry]";
continue;
}
if (!inDesktopEntry) {
continue;
}
const auto separator = line.find('=');
if (separator == std::string::npos) {
continue;
}
const std::string key = trim(line.substr(0, separator));
const std::string value = trim(line.substr(separator + 1));
if (key == "Name") {
fields.name = value;
} else if (key == "Exec") {
fields.exec = value;
} else if (key == "DesktopNames") {
fields.desktops = value;
}
}
return fields;
}
std::string lower(std::string value) {
std::transform(value.begin(), value.end(), value.begin(),
[](unsigned char character) { return static_cast<char>(std::tolower(character)); });
return value;
}
std::string valueForKey(const std::vector<std::string>& lines, const std::string& key) {
const std::string prefix = key + "=";
for (const std::string& line : lines) {
if (line.rfind(prefix, 0) == 0) {
return line.substr(prefix.size());
}
}
return {};
}
bool isSessionId(const std::string& value) {
return !value.empty() &&
std::all_of(value.begin(), value.end(),
[](unsigned char character) { return std::isdigit(character) != 0; });
}
struct SessionRow {
std::string id;
std::string uid;
std::string user;
std::string seat;
std::string tty;
};
// Every logind session, whatever its owner: greeter sessions belong to the
// display manager account, not to the person in front of the screen.
std::vector<SessionRow> listSessionRows() {
std::vector<SessionRow> rows;
const CommandResult listing = runCommand({"loginctl", "list-sessions", "--no-legend"});
if (!listing.started || listing.exitCode != 0) {
return rows;
}
for (const std::string& line : splitLines(listing.output)) {
std::istringstream stream(line);
SessionRow row;
if (!(stream >> row.id >> row.uid >> row.user >> row.seat >> row.tty)) {
continue;
}
if (!isSessionId(row.id)) {
continue;
}
rows.push_back(std::move(row));
}
return rows;
}
std::vector<std::string> sessionProperties(const std::string& id,
const std::vector<std::string>& names) {
std::vector<std::string> arguments = {"loginctl", "show-session", id};
for (const std::string& name : names) {
arguments.push_back("-p");
arguments.push_back(name);
}
const CommandResult details = runCommand(arguments);
if (!details.started || details.exitCode != 0) {
return {};
}
return splitLines(details.output);
}
SessionInfo describeSession(const SessionRow& row) {
SessionInfo info;
info.id = row.id;
info.user = row.user;
info.seat = row.seat;
info.tty = row.tty;
const std::vector<std::string> properties =
sessionProperties(row.id, {"Type", "Class", "Active", "Desktop", "TTY", "Seat", "State"});
if (properties.empty()) {
return info;
}
info.type = valueForKey(properties, "Type");
// logind is authoritative: the list columns can lag behind a VT switch.
info.seat = valueForKey(properties, "Seat");
info.tty = valueForKey(properties, "TTY");
info.desktop = valueForKey(properties, "Desktop");
info.state = valueForKey(properties, "State");
info.active = valueForKey(properties, "Active") == "yes";
info.graphical = valueForKey(properties, "Class") == "user" &&
(info.type == "x11" || info.type == "wayland");
return info;
}
// Session ids are numeric, so comparing length first keeps the order numeric
// without parsing (and without std::stoi throwing on an unexpected value).
bool idBefore(const std::string& left, const std::string& right) {
return left.size() != right.size() ? left.size() < right.size() : left < right;
}
} // namespace
std::vector<DesktopEntry> listInstalledDesktops() {
std::vector<DesktopEntry> entries;
const std::vector<std::pair<std::filesystem::path, bool>> directories = {
{"/usr/share/xsessions", false},
{"/usr/local/share/xsessions", false},
{"/usr/share/wayland-sessions", true},
{"/usr/local/share/wayland-sessions", true},
};
for (const auto& [directory, wayland] : directories) {
std::error_code error;
if (!std::filesystem::is_directory(directory, error)) {
continue;
}
for (const auto& item : std::filesystem::directory_iterator(directory, error)) {
if (error) {
break;
}
if (!item.is_regular_file() || item.path().extension() != ".desktop") {
continue;
}
const DesktopFile fields = parseDesktopFile(item.path());
if (fields.name.empty() || fields.exec.empty()) {
continue;
}
DesktopEntry entry;
entry.id = item.path().stem().string();
entry.name = fields.name;
entry.exec = fields.exec;
entry.desktops = fields.desktops;
entry.wayland = wayland;
entries.push_back(std::move(entry));
}
}
std::sort(entries.begin(), entries.end(), [](const DesktopEntry& left, const DesktopEntry& right) {
return lower(left.name) < lower(right.name);
});
return entries;
}
std::string greeterSessionName(const std::vector<std::string>& desktopNames) {
std::string fromDesktopNames;
for (const DesktopEntry& entry : listInstalledDesktops()) {
for (const std::string& name : desktopNames) {
const std::string wanted = lower(name);
if (lower(entry.id) == wanted || lower(entry.name) == wanted) {
return entry.name;
}
// DesktopNames is a semicolon separated list, e.g. "XFCE".
std::istringstream values(lower(entry.desktops));
std::string value;
while (std::getline(values, value, ';')) {
if (trim(value) == wanted && fromDesktopNames.empty()) {
fromDesktopNames = entry.name;
}
}
}
}
// DesktopNames also matches the other session files of the same desktop, so
// the id/name match above wins and this is only the fallback.
return fromDesktopNames;
}
std::vector<SessionInfo> listGraphicalSessions() {
std::vector<SessionInfo> sessions;
const std::string uid = std::to_string(getuid());
for (const SessionRow& row : listSessionRows()) {
if (row.uid != uid) {
continue;
}
SessionInfo info = describeSession(row);
if (!info.graphical) {
continue;
}
sessions.push_back(std::move(info));
}
std::sort(sessions.begin(), sessions.end(),
[](const SessionInfo& left, const SessionInfo& right) { return idBefore(left.id, right.id); });
return sessions;
}
bool findGraphicalSession(const std::string& id, SessionInfo& session) {
if (!isSessionId(id)) {
return false;
}
for (const SessionInfo& candidate : listGraphicalSessions()) {
if (candidate.id == id) {
session = candidate;
return true;
}
}
return false;
}
bool isSessionActive(const std::string& id) {
if (!isSessionId(id)) {
return false;
}
const std::vector<std::string> properties = sessionProperties(id, {"Active"});
return valueForKey(properties, "Active") == "yes";
}
std::string activeGraphicalSessionId() {
for (const SessionInfo& session : listGraphicalSessions()) {
if (session.active) {
return session.id;
}
}
return {};
}
std::string findGreeterSessionId(const std::string& seat) {
std::string inactive;
for (const SessionRow& row : listSessionRows()) {
const std::vector<std::string> properties = sessionProperties(row.id, {"Class", "Seat", "Active"});
if (properties.empty() || valueForKey(properties, "Class") != "greeter") {
continue;
}
if (!seat.empty() && valueForKey(properties, "Seat") != seat) {
continue;
}
if (valueForKey(properties, "Active") == "yes") {
return row.id;
}
if (inactive.empty()) {
inactive = row.id;
}
}
return inactive;
}
std::string currentSessionId() {
const char* value = std::getenv("XDG_SESSION_ID");
return value != nullptr ? value : "";
}
std::string currentDesktopName() {
const char* value = std::getenv("XDG_CURRENT_DESKTOP");
return value != nullptr ? value : "";
}
} // namespace fws