feat(session): switch desktop environments through logind sessions

Activate the target graphical session instead of rebooting, so a KDE or
GNOME session stays alive while another one is used. Switching relies on
logind VT activation, which needs no root privileges and never restarts
the display manager.
This commit is contained in:
BlackAngelTV committed 2026-11-04 13:06:26 +01:00
1 parent e8c44c6c86
commit 75c7c5c0ad
11 files changed
+883

No files matched your search

+4
View File
@@ -31,4 +31,8 @@
*.exe
*.out
*.app
.freebuff
# Build directories
build/
build-*/
+27
View File
@@ -0,0 +1,27 @@
cmake_minimum_required(VERSION 3.20)
project(FWS-DeskManager VERSION 0.1.0 LANGUAGES CXX)
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
message(FATAL_ERROR "FWS-DeskManager targets Linux with systemd-logind.")
endif()
add_executable(fws-deskmanager
src/main.cpp
src/process.cpp
src/session-catalog.cpp
src/session-switcher.cpp
src/user-interface.cpp
)
set_target_properties(fws-deskmanager PROPERTIES
OUTPUT_NAME "fws-deskmanager"
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
)
target_include_directories(fws-deskmanager PRIVATE src)
target_compile_options(fws-deskmanager PRIVATE -Wall -Wextra -Wpedantic)
install(TARGETS fws-deskmanager RUNTIME DESTINATION bin)
+253
View File
@@ -0,0 +1,253 @@
#include "process.h"
#include "session-catalog.h"
#include "session-switcher.h"
#include "user-interface.h"
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
namespace {
constexpr int kExitOk = 0;
constexpr int kExitUsage = 1;
constexpr int kExitNotFound = 2;
constexpr int kExitFailure = 3;
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;
}
void printUsage() {
std::cout << "FWS DeskManager - changer d'environnement de bureau sans redemarrage\n\n"
"Usage :\n"
" fws-deskmanager list [--json] inventaire des environnements et sessions\n"
" fws-deskmanager switch <id> activer une session graphique existante\n"
" fws-deskmanager greeter [--yes] revenir au gestionnaire d'affichage\n"
" fws-deskmanager ui selecteur zenity / kdialog / terminal\n"
" fws-deskmanager help afficher cette aide\n\n"
"Codes de sortie : 0 succes, 1 usage, 2 introuvable, 3 echec.\n";
}
std::string jsonEscape(const std::string& value) {
std::string escaped;
escaped.reserve(value.size() + 8);
for (const char character : value) {
switch (character) {
case '"':
escaped += "\\\"";
break;
case '\\':
escaped += "\\\\";
break;
case '\n':
escaped += "\\n";
break;
case '\r':
escaped += "\\r";
break;
case '\t':
escaped += "\\t";
break;
default:
if (static_cast<unsigned char>(character) < 0x20) {
escaped += '?';
} else {
escaped += character;
}
break;
}
}
return escaped;
}
void printSessions(const std::vector<fws::SessionInfo>& sessions) {
std::cout << "Sessions graphiques :\n";
if (sessions.empty()) {
std::cout << " (aucune)\n";
return;
}
std::cout << " ID ENVIRONNEMENT TYPE VT ACTIVE\n";
for (const fws::SessionInfo& session : sessions) {
std::cout << " " << session.id;
for (std::size_t i = session.id.size(); i < 5; ++i) {
std::cout << ' ';
}
std::cout << session.desktop;
for (std::size_t i = session.desktop.size(); i < 20; ++i) {
std::cout << ' ';
}
std::cout << session.type;
for (std::size_t i = session.type.size(); i < 10; ++i) {
std::cout << ' ';
}
std::cout << session.tty;
for (std::size_t i = session.tty.size(); i < 7; ++i) {
std::cout << ' ';
}
std::cout << (session.active ? "oui" : "non") << "\n";
}
}
void printDesktops(const std::vector<fws::DesktopEntry>& desktops) {
std::cout << "\nEnvironnements installes :\n";
if (desktops.empty()) {
std::cout << " (aucun fichier .desktop trouve)\n";
return;
}
for (const fws::DesktopEntry& desktop : desktops) {
std::cout << " " << desktop.id;
for (std::size_t i = desktop.id.size(); i < 24; ++i) {
std::cout << ' ';
}
std::cout << desktop.name << " (" << (desktop.wayland ? "wayland" : "x11") << ")\n";
}
}
void printJson(const std::vector<fws::SessionInfo>& sessions,
const std::vector<fws::DesktopEntry>& desktops) {
std::cout << "{\n \"sessions\": [\n";
for (std::size_t i = 0; i < sessions.size(); ++i) {
const fws::SessionInfo& session = sessions[i];
std::cout << " {\"id\": \"" << jsonEscape(session.id) << "\", \"desktop\": \""
<< jsonEscape(session.desktop) << "\", \"type\": \"" << jsonEscape(session.type)
<< "\", \"tty\": \"" << jsonEscape(session.tty) << "\", \"seat\": \""
<< jsonEscape(session.seat) << "\", \"active\": "
<< (session.active ? "true" : "false") << "}";
std::cout << (i + 1 < sessions.size() ? ",\n" : "\n");
}
std::cout << " ],\n \"desktops\": [\n";
for (std::size_t i = 0; i < desktops.size(); ++i) {
const fws::DesktopEntry& desktop = desktops[i];
std::cout << " {\"id\": \"" << jsonEscape(desktop.id) << "\", \"name\": \""
<< jsonEscape(desktop.name) << "\", \"wayland\": "
<< (desktop.wayland ? "true" : "false") << "}";
std::cout << (i + 1 < desktops.size() ? ",\n" : "\n");
}
std::cout << " ]\n}\n";
}
bool resolveSession(const std::string& target, const std::vector<fws::SessionInfo>& sessions,
const std::vector<fws::DesktopEntry>& desktops, std::string& sessionId) {
const bool numeric = !target.empty() &&
std::all_of(target.begin(), target.end(), [](unsigned char character) {
return std::isdigit(character) != 0;
});
if (numeric) {
for (const fws::SessionInfo& session : sessions) {
if (session.id == target) {
sessionId = session.id;
return true;
}
}
return false;
}
const std::string wanted = lower(target);
for (const fws::SessionInfo& session : sessions) {
if (lower(session.desktop) == wanted) {
sessionId = session.id;
return true;
}
}
// The desktop is installed but has no running session: point at the greeter.
for (const fws::DesktopEntry& desktop : desktops) {
if (lower(desktop.id) == wanted || lower(desktop.name).rfind(wanted, 0) == 0) {
return false;
}
}
return false;
}
bool confirmGreeter(bool assumeYes) {
if (assumeYes) {
return true;
}
std::cout << "La session graphique va etre fermee et les applications non enregistrees "
"seront perdues.\nContinuer ? [o/N] ";
std::string answer;
if (!std::getline(std::cin, answer)) {
return false;
}
return answer == "o" || answer == "O" || answer == "oui" || answer == "y" || answer == "Y";
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
printUsage();
return kExitUsage;
}
const std::string command = argv[1];
if (command == "help" || command == "--help" || command == "-h") {
printUsage();
return kExitOk;
}
if (command == "list") {
const bool asJson = argc >= 3 && std::string(argv[2]) == "--json";
const std::vector<fws::SessionInfo> sessions = fws::listGraphicalSessions();
const std::vector<fws::DesktopEntry> desktops = fws::listInstalledDesktops();
if (asJson) {
printJson(sessions, desktops);
} else {
printSessions(sessions);
printDesktops(desktops);
}
return kExitOk;
}
if (command == "switch") {
if (argc < 3) {
std::cerr << "Usage : fws-deskmanager switch <id-session|environnement>\n";
return kExitUsage;
}
const std::vector<fws::SessionInfo> sessions = fws::listGraphicalSessions();
const std::vector<fws::DesktopEntry> desktops = fws::listInstalledDesktops();
std::string sessionId;
if (!resolveSession(argv[2], sessions, desktops, sessionId)) {
std::cerr << "Aucune session active ne correspond a '" << argv[2] << "'.\n"
"Lancez d'abord une session pour cet environnement, ou utilisez "
"`fws-deskmanager greeter`.\n";
return kExitNotFound;
}
std::string error;
if (!fws::activateSession(sessionId, error)) {
std::cerr << "Echec de la bascule : " << error << "\n";
return kExitFailure;
}
return kExitOk;
}
if (command == "greeter") {
const bool assumeYes = argc >= 3 && std::string(argv[2]) == "--yes";
if (!confirmGreeter(assumeYes)) {
std::cout << "Annule.\n";
return kExitOk;
}
std::string error;
if (!fws::switchToGreeter(error)) {
std::cerr << "Echec du retour au greeter : " << error << "\n";
return kExitFailure;
}
return kExitOk;
}
if (command == "ui") {
return fws::runUi();
}
std::cerr << "Commande inconnue : " << command << "\n\n";
printUsage();
return kExitUsage;
}
+107
View File
@@ -0,0 +1,107 @@
#include "process.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <sstream>
namespace fws {
CommandResult runCommand(const std::vector<std::string>& arguments) {
CommandResult result;
if (arguments.empty()) {
return result;
}
int pipeFds[2];
if (pipe(pipeFds) != 0) {
return result;
}
const pid_t pid = fork();
if (pid < 0) {
close(pipeFds[0]);
close(pipeFds[1]);
return result;
}
if (pid == 0) {
close(pipeFds[0]);
dup2(pipeFds[1], STDOUT_FILENO);
dup2(pipeFds[1], STDERR_FILENO);
close(pipeFds[1]);
std::vector<char*> argv;
argv.reserve(arguments.size() + 1);
for (const std::string& argument : arguments) {
argv.push_back(const_cast<char*>(argument.c_str()));
}
argv.push_back(nullptr);
execvp(argv[0], argv.data());
_exit(127);
}
close(pipeFds[1]);
char buffer[4096];
ssize_t count = 0;
while ((count = read(pipeFds[0], buffer, sizeof(buffer))) > 0) {
result.output.append(buffer, static_cast<std::size_t>(count));
}
close(pipeFds[0]);
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
}
result.started = true;
result.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
return result;
}
std::string findExecutable(const std::string& name) {
const char* pathVariable = std::getenv("PATH");
if (pathVariable == nullptr) {
return {};
}
std::istringstream stream(pathVariable);
std::string directory;
while (std::getline(stream, directory, ':')) {
if (directory.empty()) {
directory = ".";
}
const std::string candidate = directory + "/" + name;
if (access(candidate.c_str(), X_OK) == 0) {
return candidate;
}
}
return {};
}
std::string trim(const std::string& value) {
const auto first = value.find_first_not_of(" \t\r\n");
if (first == std::string::npos) {
return {};
}
const auto last = value.find_last_not_of(" \t\r\n");
return value.substr(first, last - first + 1);
}
std::vector<std::string> splitLines(const std::string& text) {
std::vector<std::string> lines;
std::istringstream stream(text);
std::string line;
while (std::getline(stream, line)) {
line = trim(line);
if (!line.empty()) {
lines.push_back(line);
}
}
return lines;
}
} // namespace fws
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <string>
#include <vector>
namespace fws {
struct CommandResult {
bool started = false;
int exitCode = -1;
std::string output;
};
// Runs an executable directly (no shell) and captures stdout and stderr.
CommandResult runCommand(const std::vector<std::string>& arguments);
// Resolves a program name against PATH, returning an empty string when absent.
std::string findExecutable(const std::string& name);
std::string trim(const std::string& value);
std::vector<std::string> splitLines(const std::string& text);
} // namespace fws
+184
View File
@@ -0,0 +1,184 @@
#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 {};
}
} // 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::vector<SessionInfo> listGraphicalSessions() {
std::vector<SessionInfo> sessions;
const CommandResult listing = runCommand({"loginctl", "list-sessions", "--no-legend"});
if (!listing.started || listing.exitCode != 0) {
return sessions;
}
const std::string uid = std::to_string(getuid());
for (const std::string& line : splitLines(listing.output)) {
std::istringstream stream(line);
std::string id;
std::string sessionUid;
std::string user;
std::string seat;
std::string tty;
if (!(stream >> id >> sessionUid >> user >> seat >> tty)) {
continue;
}
if (sessionUid != uid) {
continue;
}
const CommandResult details = runCommand(
{"loginctl", "show-session", id, "-p", "Type", "-p", "Class", "-p", "Active",
"-p", "Desktop", "-p", "TTY", "-p", "Seat"});
if (!details.started || details.exitCode != 0) {
continue;
}
const std::vector<std::string> properties = splitLines(details.output);
const std::string type = valueForKey(properties, "Type");
const std::string sessionClass = valueForKey(properties, "Class");
if (sessionClass != "user" || (type != "x11" && type != "wayland")) {
continue;
}
SessionInfo info;
info.id = id;
info.user = user;
info.seat = valueForKey(properties, "Seat");
info.tty = valueForKey(properties, "TTY");
info.type = type;
info.desktop = valueForKey(properties, "Desktop");
info.active = valueForKey(properties, "Active") == "yes";
info.graphical = true;
sessions.push_back(std::move(info));
}
std::sort(sessions.begin(), sessions.end(), [](const SessionInfo& left, const SessionInfo& right) {
return std::stoi(left.id) < std::stoi(right.id);
});
return sessions;
}
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
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <string>
#include <vector>
namespace fws {
struct DesktopEntry {
std::string id;
std::string name;
std::string exec;
std::string desktops;
bool wayland = false;
};
struct SessionInfo {
std::string id;
std::string user;
std::string seat;
std::string tty;
std::string type; // x11, wayland, tty, ...
std::string desktop; // KDE, GNOME, Hyprland, ...
bool active = false;
bool graphical = false;
};
// Reads /usr/share/xsessions and /usr/share/wayland-sessions.
std::vector<DesktopEntry> listInstalledDesktops();
// Reads the current user's graphical sessions from systemd-logind.
std::vector<SessionInfo> listGraphicalSessions();
std::string currentSessionId();
std::string currentDesktopName();
} // namespace fws
+61
View File
@@ -0,0 +1,61 @@
#include "session-switcher.h"
#include "process.h"
#include <algorithm>
#include <cctype>
namespace fws {
namespace {
bool isSessionId(const std::string& value) {
return !value.empty() &&
std::all_of(value.begin(), value.end(),
[](unsigned char character) { return std::isdigit(character) != 0; });
}
} // namespace
bool activateSession(const std::string& sessionId, std::string& error) {
// loginctl is invoked directly, so a crafted id can never reach a shell.
if (!isSessionId(sessionId)) {
error = "The session id must be numeric.";
return false;
}
const CommandResult result = runCommand({"loginctl", "activate", sessionId});
if (!result.started) {
error = "Unable to run loginctl. Is systemd-logind available?";
return false;
}
if (result.exitCode != 0) {
error = trim(result.output);
if (error.empty()) {
error = "loginctl activate failed.";
}
return false;
}
return true;
}
bool switchToGreeter(std::string& error) {
// Freedesktop DisplayManager interface, implemented by SDDM and LightDM.
const CommandResult busctl = runCommand(
{"busctl", "--system", "call", "org.freedesktop.DisplayManager",
"/org/freedesktop/DisplayManager/Seat0", "org.freedesktop.DisplayManager.Seat",
"SwitchToGreeter"});
if (busctl.started && busctl.exitCode == 0) {
return true;
}
// LightDM's own helper, kept as a fallback for older setups.
const CommandResult dmTool = runCommand({"dm-tool", "switch-to-greeter"});
if (dmTool.started && dmTool.exitCode == 0) {
return true;
}
error = "No compatible display manager answered (SDDM/LightDM expected).";
return false;
}
} // namespace fws
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <string>
namespace fws {
// Switches the seat to the given logind session (VT activation).
bool activateSession(const std::string& sessionId, std::string& error);
// Returns to the display manager greeter without rebooting.
bool switchToGreeter(std::string& error);
} // namespace fws
+167
View File
@@ -0,0 +1,167 @@
#include "user-interface.h"
#include "process.h"
#include "session-catalog.h"
#include "session-switcher.h"
#include <exception>
#include <iostream>
#include <string>
#include <vector>
namespace fws {
namespace {
constexpr const char* kGreeterChoice = "greeter";
struct Choice {
std::string id;
std::string label;
};
std::vector<Choice> buildChoices(const std::vector<SessionInfo>& sessions) {
std::vector<Choice> choices;
for (const SessionInfo& session : sessions) {
Choice choice;
choice.id = session.id;
choice.label = session.desktop + " (" + session.type + ", " + session.tty + ")";
if (session.active) {
choice.label += " - active";
}
choices.push_back(std::move(choice));
}
choices.push_back({kGreeterChoice, "Changer d'environnement (deconnexion)"});
return choices;
}
bool confirm(const std::string& question) {
const std::string zenity = findExecutable("zenity");
if (!zenity.empty()) {
const CommandResult result =
runCommand({zenity, "--question", "--title=FWS DeskManager", "--text=" + question});
return result.started && result.exitCode == 0;
}
std::cout << question << " [o/N] ";
std::string answer;
if (!std::getline(std::cin, answer)) {
return false;
}
return answer == "o" || answer == "O" || answer == "oui" || answer == "y" || answer == "Y";
}
bool runGreeter() {
if (!confirm("La session graphique va etre fermee et les applications non enregistrees "
"seront perdues. Continuer ?")) {
std::cout << "Annule.\n";
return true;
}
std::string error;
if (!switchToGreeter(error)) {
std::cerr << "Echec du retour au greeter : " << error << "\n";
return false;
}
return true;
}
std::string chooseWithZenity(const std::string& zenity, const std::vector<Choice>& choices) {
std::vector<std::string> arguments = {zenity,
"--list",
"--title=FWS DeskManager",
"--text=Choisir une session graphique",
"--column=ID",
"--column=Session",
"--print-column=1"};
for (const Choice& choice : choices) {
arguments.push_back(choice.id);
arguments.push_back(choice.label);
}
const CommandResult result = runCommand(arguments);
if (!result.started || result.exitCode != 0) {
return {};
}
const std::string selection = trim(result.output);
const auto separator = selection.find('|');
return separator == std::string::npos ? selection : selection.substr(0, separator);
}
std::string chooseWithKdialog(const std::string& kdialog, const std::vector<Choice>& choices) {
std::vector<std::string> arguments = {kdialog, "--title", "FWS DeskManager",
"--menu", "Choisir une session graphique"};
for (const Choice& choice : choices) {
arguments.push_back(choice.id);
arguments.push_back(choice.label);
}
const CommandResult result = runCommand(arguments);
if (!result.started || result.exitCode != 0) {
return {};
}
return trim(result.output);
}
std::string chooseInTerminal(const std::vector<Choice>& choices) {
std::cout << "Sessions graphiques disponibles :\n";
for (std::size_t i = 0; i < choices.size(); ++i) {
std::cout << " " << (i + 1) << ". " << choices[i].label << "\n";
}
std::cout << "Choix (vide pour annuler) : ";
std::string answer;
if (!std::getline(std::cin, answer)) {
return {};
}
answer = trim(answer);
if (answer.empty()) {
return {};
}
try {
const std::size_t index = static_cast<std::size_t>(std::stoul(answer));
if (index < 1 || index > choices.size()) {
return {};
}
return choices[index - 1].id;
} catch (const std::exception&) {
return {};
}
}
} // namespace
int runUi() {
const std::vector<SessionInfo> sessions = listGraphicalSessions();
if (sessions.empty()) {
std::cerr << "Aucune session graphique active detectee pour cet utilisateur.\n"
"Ouvrez une session depuis le gestionnaire d'affichage, puis relancez.\n";
return 2;
}
const std::vector<Choice> choices = buildChoices(sessions);
std::string selection;
if (const std::string zenity = findExecutable("zenity"); !zenity.empty()) {
selection = chooseWithZenity(zenity, choices);
} else if (const std::string kdialog = findExecutable("kdialog"); !kdialog.empty()) {
selection = chooseWithKdialog(kdialog, choices);
} else {
selection = chooseInTerminal(choices);
}
if (selection.empty()) {
return 0;
}
if (selection == kGreeterChoice) {
return runGreeter() ? 0 : 3;
}
std::string error;
if (!activateSession(selection, error)) {
std::cerr << "Echec de la bascule : " << error << "\n";
return 3;
}
return 0;
}
} // namespace fws
+8
View File
@@ -0,0 +1,8 @@
#pragma once
namespace fws {
// Lightweight picker: zenity, else kdialog, else a terminal menu.
int runUi();
} // namespace fws