Compare commits
43 Commits
2d5b492da8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c70065bf6 | |||
| 9898c48c67 | |||
| 6d9f016350 | |||
| ed1a9a8605 | |||
| 49ac6cec90 | |||
| da9f167747 | |||
| 9404321249 | |||
| c742ca6d18 | |||
| bfc9369a5e | |||
| 8de6b2c0ef | |||
| 8873c4eb3c | |||
| 88e3c7a825 | |||
| eb6d5ba499 | |||
| 5320831c15 | |||
| 82769019f5 | |||
| 54eed7e7e1 | |||
| fc47a52a15 | |||
| 6e9301ac59 | |||
| e654683d4c | |||
| 66124fae8b | |||
| 7121b945d7 | |||
| 3a44910961 | |||
| 183b138658 | |||
| 2f2e476d74 | |||
| b447abca42 | |||
| a90db8588c | |||
| 4d4115012c | |||
| 03e0ce53d5 | |||
| dd312b9ec5 | |||
| f4a1dca281 | |||
| 49ab07cd6f | |||
| 817b9dd394 | |||
| 178a4451d4 | |||
| 17aef717b7 | |||
| dc325834c7 | |||
| caca94bc6a | |||
| 13278d518a | |||
| 8283531748 | |||
| f3b250759e | |||
| 7ad6f46b3c | |||
| ad5e678c5d | |||
| 0e613141da | |||
| ab7b3b3092 |
@@ -10,3 +10,6 @@ IncludeCategories:
|
||||
- Regex: '.*'
|
||||
Priority: 3
|
||||
IncludeBlocks: Regroup
|
||||
|
||||
# remove unused includes
|
||||
SortIncludes: true
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -55,4 +55,5 @@ test/test_runner
|
||||
|
||||
cmake-build-debug/**/*
|
||||
.idea
|
||||
|
||||
.cache/
|
||||
Testing/
|
||||
135
CMakeLists.txt
135
CMakeLists.txt
@@ -1,49 +1,65 @@
|
||||
cmake_minimum_required(VERSION 4.2.0)
|
||||
project(bar)
|
||||
|
||||
include(CTest)
|
||||
enable_testing()
|
||||
|
||||
option(ENABLE_COVERAGE "Enable coverage flags" OFF)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O2 -DNDEBUG -Wall -Wextra -Wpedantic -Werror")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG -Wall -Wextra -Wpedantic")
|
||||
|
||||
if(ENABLE_COVERAGE)
|
||||
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -g --coverage")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0 -g --coverage")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage")
|
||||
set(CTEST_COVERAGE_COMMAND "gcov")
|
||||
endif()
|
||||
|
||||
find_package(PkgConfig REQUIRED)
|
||||
|
||||
pkg_check_modules(GTKMM REQUIRED gtkmm-4.0)
|
||||
pkg_check_modules(LAYERSHELL REQUIRED gtk4-layer-shell-0)
|
||||
pkg_check_modules(WEBKIT REQUIRED webkitgtk-6.0)
|
||||
pkg_check_modules(SQLITE3 REQUIRED sqlite3)
|
||||
pkg_check_modules(CURL REQUIRED libcurl)
|
||||
|
||||
include_directories(${GTKMM_INCLUDE_DIRS} ${LAYERSHELL_INCLUDE_DIRS} ${WEBKIT_INCLUDE_DIRS} ${SQLITE3_INCLUDE_DIRS})
|
||||
link_directories(${GTKMM_LIBRARY_DIRS} ${LAYERSHELL_LIBRARY_DIRS} ${WEBKIT_LIBRARY_DIRS} ${SQLITE3_LIBRARY_DIRS})
|
||||
find_package(nlohmann_json 3.2.0 REQUIRED)
|
||||
|
||||
include_directories(${GTKMM_INCLUDE_DIRS} ${LAYERSHELL_INCLUDE_DIRS} ${WEBKIT_INCLUDE_DIRS} ${CURL_INCLUDE_DIRS} ${nlohmann_json_INCLUDE_DIRS})
|
||||
link_directories(${GTKMM_LIBRARY_DIRS} ${LAYERSHELL_LIBRARY_DIRS} ${WEBKIT_LIBRARY_DIRS} ${CURL_LIBRARY_DIRS})
|
||||
|
||||
add_library(bar_lib)
|
||||
target_sources(bar_lib
|
||||
PUBLIC
|
||||
src/app.cpp
|
||||
src/bar/bar.cpp
|
||||
src/app.cpp
|
||||
src/bar/bar.cpp
|
||||
|
||||
src/widgets/clock.cpp
|
||||
src/widgets/date.cpp
|
||||
src/widgets/workspaceIndicator.cpp
|
||||
src/widgets/volumeWidget.cpp
|
||||
src/widgets/webWidget.cpp
|
||||
src/widgets/clock.cpp
|
||||
src/widgets/date.cpp
|
||||
src/widgets/notification/baseNotification.cpp
|
||||
src/widgets/notification/notificationWindow.cpp
|
||||
src/widgets/notification/spotifyNotification.cpp
|
||||
src/widgets/volumeWidget.cpp
|
||||
src/widgets/webWidget.cpp
|
||||
|
||||
src/services/todo.cpp
|
||||
src/services/sqliteTodoAdapter.cpp
|
||||
src/services/hyprland.cpp
|
||||
src/services/tray.cpp
|
||||
src/services/notifications.cpp
|
||||
src/services/bluetooth.cpp
|
||||
src/services/hyprland.cpp
|
||||
src/services/notificationController.cpp
|
||||
src/services/textureCache.cpp
|
||||
src/services/tray.cpp
|
||||
src/services/dbus/notification.cpp
|
||||
src/services/dbus/mpris.cpp
|
||||
|
||||
src/widgets/tray.cpp
|
||||
src/widgets/todo.cpp
|
||||
src/widgets/bluetooth.cpp
|
||||
src/widgets/controlCenter.cpp
|
||||
src/widgets/tray.cpp
|
||||
src/widgets/controlCenter/controlCenter.cpp
|
||||
src/widgets/controlCenter/mediaControl.cpp
|
||||
|
||||
src/components/popover.cpp
|
||||
src/components/todoEntry.cpp
|
||||
src/components/base/button.cpp
|
||||
src/components/popover.cpp
|
||||
src/components/workspaceIndicator.cpp
|
||||
src/components/base/button.cpp
|
||||
)
|
||||
include_directories(bar_lib PRIVATE
|
||||
include
|
||||
@@ -51,30 +67,59 @@ include_directories(bar_lib PRIVATE
|
||||
|
||||
add_executable(bar main.cpp)
|
||||
|
||||
target_link_libraries(bar bar_lib ${GTKMM_LIBRARIES} ${LAYERSHELL_LIBRARIES} ${WEBKIT_LIBRARIES} ${SQLITE3_LIBRARIES})
|
||||
target_link_libraries(bar bar_lib ${GTKMM_LIBRARIES} ${LAYERSHELL_LIBRARIES} ${WEBKIT_LIBRARIES} ${CURL_LIBRARIES} nlohmann_json::nlohmann_json)
|
||||
|
||||
# Copy `resources/bar.css` into the build directory when it changes
|
||||
set(RES_SRC "${CMAKE_CURRENT_SOURCE_DIR}/resources/bar.css")
|
||||
set(RES_DST "${CMAKE_CURRENT_BINARY_DIR}/resources/bar.css")
|
||||
set(USER_CONFIG_CSS "$ENV{HOME}/.config/bar/bar.css")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${RES_DST}
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/resources"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${RES_SRC}" "${RES_DST}"
|
||||
DEPENDS "${RES_SRC}"
|
||||
COMMENT "Copy resources/bar.css to build directory"
|
||||
VERBATIM
|
||||
# add spdlog
|
||||
find_package(spdlog REQUIRED)
|
||||
target_link_libraries(bar_lib PRIVATE spdlog::spdlog)
|
||||
|
||||
|
||||
# ---- Testing shit
|
||||
find_package(Catch2 3 REQUIRED)
|
||||
|
||||
add_executable(bar_tests
|
||||
tests/string_helper_tests.cpp
|
||||
)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${USER_CONFIG_CSS}
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "$ENV{HOME}/.config/bar"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${RES_SRC}" "${USER_CONFIG_CSS}"
|
||||
DEPENDS "${RES_SRC}"
|
||||
COMMENT "Copy resources/bar.css to ~/.config/bar/bar.css"
|
||||
VERBATIM
|
||||
target_include_directories(bar_tests PRIVATE
|
||||
include
|
||||
)
|
||||
target_link_libraries(bar_tests PRIVATE Catch2::Catch2WithMain)
|
||||
|
||||
add_custom_target(copy_resources ALL DEPENDS ${RES_DST} ${USER_CONFIG_CSS})
|
||||
# Coverage flags are set globally when ENABLE_COVERAGE is ON.
|
||||
|
||||
include(Catch)
|
||||
catch_discover_tests(bar_tests)
|
||||
|
||||
# Copy all CSS files in resources/ into build and user config directories
|
||||
file(GLOB RES_CSS_FILES CONFIGURE_DEPENDS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/resources/*.css"
|
||||
)
|
||||
set(RES_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/resources")
|
||||
set(RES_USER_DIR "$ENV{HOME}/.config/bar")
|
||||
|
||||
set(RES_DST_FILES "")
|
||||
set(USER_DST_FILES "")
|
||||
|
||||
foreach(RES_FILE IN LISTS RES_CSS_FILES)
|
||||
get_filename_component(RES_NAME "${RES_FILE}" NAME)
|
||||
set(RES_DST "${RES_BUILD_DIR}/${RES_NAME}")
|
||||
set(USER_DST "${RES_USER_DIR}/${RES_NAME}")
|
||||
|
||||
list(APPEND RES_DST_FILES "${RES_DST}")
|
||||
list(APPEND USER_DST_FILES "${USER_DST}")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${RES_DST}" "${USER_DST}"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${RES_BUILD_DIR}"
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory "${RES_USER_DIR}"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${RES_FILE}" "${RES_DST}"
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${RES_FILE}" "${USER_DST}"
|
||||
DEPENDS "${RES_FILE}"
|
||||
COMMENT "Copy ${RES_NAME} to build and config directories"
|
||||
VERBATIM
|
||||
)
|
||||
endforeach()
|
||||
|
||||
add_custom_target(copy_resources ALL DEPENDS ${RES_DST_FILES} ${USER_DST_FILES})
|
||||
add_dependencies(bar copy_resources)
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
|
||||
#include "bar/bar.hpp"
|
||||
#include "services/hyprland.hpp"
|
||||
#include "services/notifications.hpp"
|
||||
#include "services/tray.hpp"
|
||||
#include "services/dbus/notification.hpp"
|
||||
|
||||
#include "glibmm/refptr.h"
|
||||
#include "gtkmm/application.h"
|
||||
|
||||
class MprisController;
|
||||
|
||||
class App {
|
||||
public:
|
||||
App();
|
||||
@@ -18,10 +19,11 @@ class App {
|
||||
|
||||
private:
|
||||
Glib::RefPtr<Gtk::Application> app;
|
||||
std::vector<Bar *> bars;
|
||||
HyprlandService *hyprlandService = HyprlandService::getInstance();
|
||||
NotificationService notificationService;
|
||||
TrayService *trayService = TrayService::getInstance();
|
||||
std::vector<std::shared_ptr<Bar>> bars;
|
||||
std::shared_ptr<NotificationService> notificationService = nullptr;
|
||||
std::shared_ptr<MprisController> mprisController = nullptr;
|
||||
HyprlandService *hyprlandService = nullptr;
|
||||
|
||||
TrayService *trayService = TrayService::getInstance();
|
||||
void setupServices();
|
||||
};
|
||||
@@ -2,23 +2,24 @@
|
||||
|
||||
#include <gtk4-layer-shell/gtk4-layer-shell.h>
|
||||
#include <gtkmm.h>
|
||||
#include <memory>
|
||||
|
||||
#include "icons.hpp"
|
||||
#include "widgets/clock.hpp"
|
||||
#include "widgets/date.hpp"
|
||||
#include "widgets/tray.hpp"
|
||||
#include "widgets/volumeWidget.hpp"
|
||||
#include "widgets/webWidget.hpp"
|
||||
#include "widgets/workspaceIndicator.hpp"
|
||||
#include "widgets/controlCenter.hpp"
|
||||
#include "widgets/controlCenter/controlCenter.hpp"
|
||||
|
||||
class Bar : public Gtk::Window {
|
||||
public:
|
||||
Bar(GdkMonitor *monitor, int monitorId);
|
||||
Bar(GdkMonitor *monitor);
|
||||
|
||||
void addLeftWidget(std::shared_ptr<Gtk::Widget> widget) { left_box.append(*widget); }
|
||||
void addCenterWidget(std::shared_ptr<Gtk::Widget> widget) { center_box.append(*widget); }
|
||||
void addRightWidget(std::shared_ptr<Gtk::Widget> widget) { right_box.append(*widget); }
|
||||
|
||||
private:
|
||||
int monitorId;
|
||||
|
||||
Gtk::CenterBox main_box{};
|
||||
Gtk::Box left_box{Gtk::Orientation::HORIZONTAL};
|
||||
Gtk::Box center_box{Gtk::Orientation::HORIZONTAL};
|
||||
@@ -26,12 +27,11 @@ class Bar : public Gtk::Window {
|
||||
|
||||
Clock clock;
|
||||
Date date;
|
||||
WebWidget homeAssistant{ICON_HOME, "Home Assistant", "https://home.rivercry.com"};
|
||||
ControlCenter controlCenter{"\ue8bb", "Control Center"};
|
||||
WebWidget homeAssistant{"\ue88a", "Home Assistant", "https://home.rivercry.com"};
|
||||
ControlCenter controlCenter{"\ue88a", "Control Center"};
|
||||
|
||||
WorkspaceIndicator *workspaceIndicator = nullptr;
|
||||
TrayWidget *trayWidget = nullptr;
|
||||
VolumeWidget *volumeWidget = nullptr;
|
||||
std::shared_ptr<TrayWidget> trayWidget = nullptr;
|
||||
std::shared_ptr<VolumeWidget> volumeWidget = nullptr;
|
||||
|
||||
|
||||
void setup_ui();
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "gtkmm/box.h"
|
||||
|
||||
class TodoEntry : public Gtk::Box {
|
||||
public:
|
||||
TodoEntry(int id, std::string text, sigc::signal<void(int)> signal_dismissed, sigc::signal<void(int, std::string)> signal_edited);
|
||||
|
||||
int get_id() const { return id; }
|
||||
std::string get_text() const { return text; }
|
||||
|
||||
private:
|
||||
int id;
|
||||
std::string text;
|
||||
sigc::signal<void(int)> signal_dismissed;
|
||||
sigc::signal<void(int, std::string)> signal_edited;
|
||||
|
||||
void on_dismiss_clicked();
|
||||
};
|
||||
35
include/components/workspaceIndicator.hpp
Normal file
35
include/components/workspaceIndicator.hpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "gtkmm/box.h"
|
||||
#include "gtkmm/button.h"
|
||||
#include "gtkmm/overlay.h"
|
||||
|
||||
class WorkspaceIndicator : public Gtk::Box {
|
||||
public:
|
||||
|
||||
enum InidicatorState {
|
||||
EMPTY,
|
||||
ALIVE,
|
||||
FOCUSED,
|
||||
PRESENTING,
|
||||
URGENT,
|
||||
};
|
||||
|
||||
// meh, Maybe try WorkspaceState struct later
|
||||
WorkspaceIndicator(int id, std::string label, sigc::slot<void(int)> onClick);
|
||||
void setIndicatorState(InidicatorState state);
|
||||
|
||||
private:
|
||||
void clearCssClass();
|
||||
InidicatorState currentState = EMPTY;
|
||||
std::shared_ptr<Gtk::Overlay> overlay;
|
||||
std::map<InidicatorState, std::string> stateToCssClass = {
|
||||
{FOCUSED, "workspace-pill-focused"},
|
||||
{URGENT, "workspace-pill-urgent"},
|
||||
{ALIVE, "workspace-pill-alive"},
|
||||
{PRESENTING, "workspace-pill-presenting"},
|
||||
{EMPTY, "workspace-pill-empty"}, // Default class
|
||||
};
|
||||
};
|
||||
31
include/helpers/command.hpp
Normal file
31
include/helpers/command.hpp
Normal file
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <cstdio>
|
||||
|
||||
class CommandHelper {
|
||||
public:
|
||||
static std::string exec(const char *cmd) {
|
||||
std::array<char, 128> buffer;
|
||||
std::string result;
|
||||
std::unique_ptr<FILE, int(*)(FILE*)> pipe(popen(cmd, "r"), pclose);
|
||||
if (!pipe) {
|
||||
throw std::runtime_error("popen() failed!");
|
||||
}
|
||||
while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr) {
|
||||
result += buffer.data();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static void execNoOutput(std::string cmd) {
|
||||
std::string command = cmd + " > /dev/null 2>&1";
|
||||
int ret = std::system(command.c_str());
|
||||
if (ret != 0) {
|
||||
throw std::runtime_error("Command failed with return code: " + std::to_string(ret));
|
||||
}
|
||||
}
|
||||
};
|
||||
69
include/helpers/hypr.hpp
Normal file
69
include/helpers/hypr.hpp
Normal file
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include "helpers/command.hpp"
|
||||
|
||||
class HyprctlHelper {
|
||||
public:
|
||||
static nlohmann::json getMonitorData() {
|
||||
std::string result = CommandHelper::exec("hyprctl -j monitors");
|
||||
assert(!result.empty() && "Failed to get monitor data from hyprctl");
|
||||
|
||||
auto json = nlohmann::json::parse(result);
|
||||
|
||||
assert(json.is_array());
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
static nlohmann::json getWorkspaceData() {
|
||||
std::string result = CommandHelper::exec("hyprctl -j workspaces");
|
||||
assert(!result.empty() && "Failed to get workspace data from hyprctl");
|
||||
|
||||
auto json = nlohmann::json::parse(result);
|
||||
|
||||
assert(json.is_array());
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
static nlohmann::json getClientData() {
|
||||
std::string result = CommandHelper::exec("hyprctl -j clients");
|
||||
assert(!result.empty() && "Failed to get client data from hyprctl");
|
||||
|
||||
auto json = nlohmann::json::parse(result);
|
||||
|
||||
assert(json.is_array());
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
static void dispatchWorkspace(int workspaceNumber) {
|
||||
std::string out = "hyprctl dispatch workspace " + std::to_string(workspaceNumber);
|
||||
CommandHelper::execNoOutput(out.c_str());
|
||||
}
|
||||
};
|
||||
|
||||
class HyprSocketHelper {
|
||||
public:
|
||||
static std::string getHyprlandSocketPath() {
|
||||
const char *hyprlandInstanceSignature = std::getenv("HYPRLAND_INSTANCE_SIGNATURE");
|
||||
const char *xdgRuntimeDir = std::getenv("XDG_RUNTIME_DIR");
|
||||
|
||||
if (!xdgRuntimeDir || !hyprlandInstanceSignature) {
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string basePath = std::string(xdgRuntimeDir) + "/hypr/" + std::string(hyprlandInstanceSignature) + "/";
|
||||
std::string sock1 = basePath + ".socket2.sock";
|
||||
if (access(sock1.c_str(), F_OK) == 0) {
|
||||
return sock1;
|
||||
}
|
||||
|
||||
return std::string();
|
||||
}
|
||||
};
|
||||
52
include/helpers/socket.hpp
Normal file
52
include/helpers/socket.hpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <cassert>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
#include <vector>
|
||||
|
||||
#include "helpers/string.hpp"
|
||||
|
||||
class SocketHelper {
|
||||
|
||||
public:
|
||||
typedef struct SocketMessage {
|
||||
std::string eventType;
|
||||
std::string eventData;
|
||||
} SocketMessage;
|
||||
|
||||
static std::vector<SocketMessage> parseSocketMessage(int socketFd, const std::string &delimiter) {
|
||||
char buffer[4096];
|
||||
std::string data;
|
||||
|
||||
ssize_t bytesRead = recv(socketFd, buffer, sizeof(buffer) - 1, 0);
|
||||
if (bytesRead > 0) {
|
||||
buffer[bytesRead] = '\0';
|
||||
data = std::string(buffer);
|
||||
} else if (bytesRead == 0) {
|
||||
spdlog::warn("Socket closed by peer");
|
||||
} else {
|
||||
spdlog::error("Error reading from socket");
|
||||
}
|
||||
|
||||
auto delimiterPos = data.find(delimiter);
|
||||
|
||||
if (delimiterPos == std::string::npos) {
|
||||
assert(false && "Delimiter not found in socket message");
|
||||
}
|
||||
|
||||
auto splitMessages = StringHelper::split(data, '\n');
|
||||
auto splitMessagesFinal = std::vector<SocketMessage>();
|
||||
for (auto splitMessage : splitMessages) {
|
||||
SocketMessage message;
|
||||
auto messageCommandVector = StringHelper::split(splitMessage, delimiter);
|
||||
|
||||
message.eventType = messageCommandVector[0];
|
||||
message.eventData = messageCommandVector.size() > 1 ? messageCommandVector[1] : "";
|
||||
splitMessagesFinal.push_back(message);
|
||||
}
|
||||
|
||||
return splitMessagesFinal;
|
||||
}
|
||||
};
|
||||
47
include/helpers/string.hpp
Normal file
47
include/helpers/string.hpp
Normal file
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
class StringHelper {
|
||||
public:
|
||||
static std::vector<std::string> split(const std::string &input, char delimiter) {
|
||||
std::vector<std::string> tokens;
|
||||
std::string token;
|
||||
for (char ch : input) {
|
||||
if (ch == delimiter) {
|
||||
if (!token.empty()) {
|
||||
tokens.push_back(token);
|
||||
token.clear();
|
||||
}
|
||||
} else {
|
||||
token += ch;
|
||||
}
|
||||
}
|
||||
if (!token.empty()) {
|
||||
tokens.push_back(token);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
static std::vector<std::string> split(const std::string &input, std::string delimiter) {
|
||||
std::vector<std::string> tokens;
|
||||
size_t start = 0;
|
||||
size_t end = input.find(delimiter);
|
||||
while (end != std::string::npos) {
|
||||
tokens.push_back(input.substr(start, end - start));
|
||||
start = end + delimiter.length();
|
||||
end = input.find(delimiter, start);
|
||||
}
|
||||
tokens.push_back(input.substr(start));
|
||||
return tokens;
|
||||
}
|
||||
|
||||
static std::string trimToSize(const std::string &input, size_t maxSize) {
|
||||
if (input.length() <= maxSize) {
|
||||
return input;
|
||||
}
|
||||
return input.substr(0, maxSize) + "...";
|
||||
}
|
||||
};
|
||||
17
include/helpers/system.hpp
Normal file
17
include/helpers/system.hpp
Normal file
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <fstream>
|
||||
|
||||
class SystemHelper {
|
||||
public:
|
||||
static std::string read_file_to_string(const std::string &filePath) {
|
||||
std::ifstream file(filePath);
|
||||
if (!file.is_open()) {
|
||||
throw std::runtime_error("Could not open file: " + filePath);
|
||||
}
|
||||
std::string content((std::istreambuf_iterator<char>(file)),
|
||||
std::istreambuf_iterator<char>());
|
||||
file.close();
|
||||
return content;
|
||||
}
|
||||
};
|
||||
@@ -1,39 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
class SystemHelper {
|
||||
public:
|
||||
static std::string get_command_output(const char *cmd) {
|
||||
std::array<char, 128> buffer;
|
||||
std::string result;
|
||||
std::unique_ptr<FILE, int (*)(FILE *)> pipe(popen(cmd, "r"), pclose);
|
||||
|
||||
if (!pipe) {
|
||||
throw std::runtime_error("popen() failed!");
|
||||
}
|
||||
|
||||
// Read the output a chunk at a time until the stream ends
|
||||
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
|
||||
result += buffer.data();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// Read an entire file into a string. Throws std::runtime_error on failure.
|
||||
static std::string read_file_to_string(const std::string &path) {
|
||||
std::ifstream in(path, std::ios::in | std::ios::binary);
|
||||
if (!in) {
|
||||
throw std::runtime_error("Failed to open file: " + path);
|
||||
}
|
||||
|
||||
std::ostringstream ss;
|
||||
ss << in.rdbuf();
|
||||
return ss.str();
|
||||
}
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#define ICON_HOME "\ue88a"
|
||||
47
include/services/dbus/messages.hpp
Normal file
47
include/services/dbus/messages.hpp
Normal file
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <sys/types.h>
|
||||
#include <vector>
|
||||
#include "gdkmm/pixbuf.h"
|
||||
#include "glibmm/variant.h"
|
||||
|
||||
|
||||
|
||||
struct MprisPlayer2Message {
|
||||
std::string title;
|
||||
std::vector<std::string> artist;
|
||||
std::string artwork_url;
|
||||
int64_t length_ms;
|
||||
|
||||
std::function<void()> play_pause;
|
||||
std::function<void()> next;
|
||||
std::function<void()> previous;
|
||||
};
|
||||
|
||||
enum NotificationUrgency {
|
||||
LOW = 0,
|
||||
NORMAL = 1,
|
||||
CRITICAL = 2
|
||||
};
|
||||
|
||||
struct NotifyMessage {
|
||||
std::string app_name;
|
||||
uint32_t replaces_id;
|
||||
std::string app_icon;
|
||||
std::string summary;
|
||||
std::string body;
|
||||
std::vector<std::string> actions;
|
||||
NotificationUrgency urgency = NORMAL;
|
||||
int32_t expire_timeout;
|
||||
// Callback to invoke when an action is triggered
|
||||
std::function<void(const std::string& action_id)> on_action;
|
||||
// Guard to prevent multiple action invocations across mirrors
|
||||
std::shared_ptr<bool> actionInvoked;
|
||||
// image data (if any) from dbus
|
||||
std::optional<Glib::RefPtr<Gdk::Pixbuf>> imageData;
|
||||
};
|
||||
57
include/services/dbus/mpris.hpp
Normal file
57
include/services/dbus/mpris.hpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <giomm.h>
|
||||
#include <sigc++/sigc++.h>
|
||||
#include <vector>
|
||||
#include "services/dbus/messages.hpp"
|
||||
|
||||
class MprisController {
|
||||
public:
|
||||
struct PlayerState {
|
||||
std::string title;
|
||||
std::vector<std::string> artist;
|
||||
std::string artwork_url;
|
||||
int64_t length_ms;
|
||||
};
|
||||
enum class PlaybackStatus {
|
||||
Playing,
|
||||
Paused,
|
||||
Stopped,
|
||||
};
|
||||
|
||||
static std::shared_ptr<MprisController> getInstance();
|
||||
|
||||
void toggle_play();
|
||||
void next_song();
|
||||
void previous_song();
|
||||
void emit_seeked(int64_t position_us);
|
||||
|
||||
sigc::signal<void(const MprisPlayer2Message &)> &signal_mpris_updated();
|
||||
sigc::signal<void(PlaybackStatus)> &signal_playback_status_changed();
|
||||
sigc::signal<void(int64_t)> &signal_playback_position_changed();
|
||||
|
||||
private:
|
||||
MprisController();
|
||||
std::map<std::string, PlaybackStatus> playbackStatusMap = {
|
||||
{"Playing", PlaybackStatus::Playing},
|
||||
{"Paused", PlaybackStatus::Paused},
|
||||
{"Stopped", PlaybackStatus::Stopped},
|
||||
};
|
||||
|
||||
PlaybackStatus currentPlaybackStatus = PlaybackStatus::Stopped;
|
||||
|
||||
Glib::RefPtr<Gio::DBus::Connection> m_connection;
|
||||
Glib::RefPtr<Gio::DBus::Proxy> m_proxy;
|
||||
|
||||
sigc::signal<void(const MprisPlayer2Message &)> mprisUpdatedSignal;
|
||||
sigc::signal<void(PlaybackStatus)> playbackStatusChangedSignal;
|
||||
sigc::signal<void(int64_t)> playbackPositionChangedSignal;
|
||||
|
||||
void on_bus_connected(const Glib::RefPtr<Gio::AsyncResult> &result);
|
||||
void signalNotification();
|
||||
|
||||
// Called when the song changes
|
||||
void on_properties_changed(const Gio::DBus::Proxy::MapChangedProperties &changed_properties,
|
||||
const std::vector<Glib::ustring> &invalidated_properties);
|
||||
};
|
||||
70
include/services/dbus/notification.hpp
Normal file
70
include/services/dbus/notification.hpp
Normal file
@@ -0,0 +1,70 @@
|
||||
#pragma once
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <giomm.h>
|
||||
#include <gtkmm.h>
|
||||
#include <sigc++/sigc++.h>
|
||||
|
||||
#include "giomm/dbusconnection.h"
|
||||
#include "giomm/dbusownname.h"
|
||||
#include "glib.h"
|
||||
|
||||
const Glib::ustring introspection_xml = R"(
|
||||
<node>
|
||||
<interface name="org.freedesktop.Notifications">
|
||||
<method name="GetCapabilities">
|
||||
<arg name="capabilities" type="as" direction="out"/>
|
||||
</method>
|
||||
<method name="Notify">
|
||||
<arg name="app_name" type="s" direction="in"/>
|
||||
<arg name="replaces_id" type="u" direction="in"/>
|
||||
<arg name="app_icon" type="s" direction="in"/>
|
||||
<arg name="summary" type="s" direction="in"/>
|
||||
<arg name="body" type="s" direction="in"/>
|
||||
<arg name="actions" type="as" direction="in"/>
|
||||
<arg name="hints" type="a{sv}" direction="in"/>
|
||||
<arg name="expire_timeout" type="i" direction="in"/>
|
||||
<arg name="id" type="u" direction="out"/>
|
||||
</method>
|
||||
<method name="CloseNotification">
|
||||
<arg name="id" type="u" direction="in"/>
|
||||
</method>
|
||||
<method name="GetServerInformation">
|
||||
<arg name="name" type="s" direction="out"/>
|
||||
<arg name="vendor" type="s" direction="out"/>
|
||||
<arg name="version" type="s" direction="out"/>
|
||||
<arg name="spec_version" type="s" direction="out"/>
|
||||
</method>
|
||||
</interface>
|
||||
</node>
|
||||
)";
|
||||
|
||||
class NotificationService {
|
||||
public:
|
||||
NotificationService() : notificationIdCounter(1) {
|
||||
Gio::DBus::own_name(
|
||||
Gio::DBus::BusType::SESSION,
|
||||
"org.freedesktop.Notifications",
|
||||
sigc::mem_fun(*this, &NotificationService::onBusAcquired),
|
||||
{}, // Name acquired slot (optional)
|
||||
{}, // Name lost slot (optional)
|
||||
Gio::DBus::BusNameOwnerFlags::REPLACE);
|
||||
}
|
||||
|
||||
void onBusAcquired(const Glib::RefPtr<Gio::DBus::Connection> &connection, const Glib::ustring &name);
|
||||
|
||||
private:
|
||||
guint notificationIdCounter;
|
||||
const Gio::DBus::InterfaceVTable &getMessageInterfaceVTable();
|
||||
void on_method_call(const Glib::RefPtr<Gio::DBus::Connection> &connection,
|
||||
const Glib::ustring &sender,
|
||||
const Glib::ustring &object_path,
|
||||
const Glib::ustring &interface_name,
|
||||
const Glib::ustring &method_name,
|
||||
const Glib::VariantContainerBase ¶meters,
|
||||
const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation);
|
||||
|
||||
void handle_notify(const Glib::VariantContainerBase ¶meters,
|
||||
const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation);
|
||||
void createNotificationPopup(const Glib::ustring &title, const Glib::ustring &message);
|
||||
};
|
||||
@@ -1,82 +1,115 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <glibmm.h>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <sigc++/sigc++.h>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
#include <vector>
|
||||
|
||||
#include "bar/bar.hpp"
|
||||
#include "components/workspaceIndicator.hpp"
|
||||
#include "helpers/socket.hpp"
|
||||
|
||||
#include "gtkmm/box.h"
|
||||
|
||||
#define NUM_WORKSPACES 7
|
||||
|
||||
class HyprlandService {
|
||||
inline static HyprlandService *instance = nullptr;
|
||||
|
||||
public:
|
||||
static constexpr int kWorkspaceSlotCount = 7;
|
||||
const char *kMonitorCommand = "hyprctl monitors -j";
|
||||
const char *kWorkspaceCommand = "hyprctl workspaces -j";
|
||||
const char *kClientsCommand = "hyprctl clients -j";
|
||||
|
||||
struct WindowState {
|
||||
int hyprId = -1;
|
||||
struct Client {
|
||||
std::string address;
|
||||
int workspaceId;
|
||||
std::string title;
|
||||
};
|
||||
|
||||
struct WorkspaceState {
|
||||
int hyprId = -1;
|
||||
int monitorId = -1;
|
||||
bool active = false;
|
||||
bool focused = false;
|
||||
std::vector<std::string> urgentWindows;
|
||||
struct WorkspaceData {
|
||||
int id;
|
||||
std::string monitorName;
|
||||
std::string label;
|
||||
|
||||
std::map<std::string, std::shared_ptr<Client>> clients;
|
||||
std::set<std::string> urgentClients;
|
||||
};
|
||||
|
||||
struct Workspace {
|
||||
std::shared_ptr<WorkspaceData> state;
|
||||
std::shared_ptr<WorkspaceIndicator> view;
|
||||
};
|
||||
|
||||
struct Monitor {
|
||||
std::map<int, WorkspaceState *> workspaceStates;
|
||||
int id;
|
||||
int activeWorkspaceId;
|
||||
bool focused;
|
||||
std::string name;
|
||||
int x = 0;
|
||||
int y = 0;
|
||||
int id = -1;
|
||||
int focusedWorkspaceId = -1;
|
||||
std::map<int, std::shared_ptr<Workspace>> monitorWorkspaces;
|
||||
std::shared_ptr<Bar> bar;
|
||||
};
|
||||
|
||||
void start();
|
||||
void on_hyprland_event(std::string event, std::string data);
|
||||
void printMonitor(const Monitor &mon) const;
|
||||
|
||||
sigc::signal<void(std::string, std::string)> socketEventSignal;
|
||||
sigc::signal<void()> workspaceStateChanged;
|
||||
sigc::signal<void()> monitorStateChanged;
|
||||
|
||||
Monitor *getMonitorById(int id);
|
||||
Monitor *getMonitorByIndex(std::size_t index);
|
||||
void switchToWorkspace(int workspaceId);
|
||||
|
||||
std::map<int, WorkspaceState *> getAllWorkspaces() const {
|
||||
return this->workspaces;
|
||||
}
|
||||
|
||||
static HyprlandService *getInstance() {
|
||||
if (HyprlandService::instance == nullptr) {
|
||||
HyprlandService::instance = new HyprlandService();
|
||||
if (!instance) {
|
||||
instance = new HyprlandService();
|
||||
}
|
||||
|
||||
return HyprlandService::instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
std::shared_ptr<Gtk::Box> getWorkspaceIndicatorsForMonitor(std::string monitorName);
|
||||
|
||||
void addBar(std::shared_ptr<Bar> bar, std::string monitorName);
|
||||
|
||||
private:
|
||||
enum SocketEventType {
|
||||
WORKSPACE_CHANGED,
|
||||
|
||||
ACTIVE_WINDOW,
|
||||
OPEN_WINDOW,
|
||||
CLOSE_WINDOW,
|
||||
MOVE_WINDOW,
|
||||
URGENT,
|
||||
|
||||
FOCUSED_MONITOR,
|
||||
MONITOR_REMOVED,
|
||||
};
|
||||
|
||||
std::map<std::string, SocketEventType> socketEventTypeMap = {
|
||||
{"workspace", WORKSPACE_CHANGED},
|
||||
{"activewindowv2", ACTIVE_WINDOW},
|
||||
{"openwindow", OPEN_WINDOW},
|
||||
{"closewindow", CLOSE_WINDOW},
|
||||
{"movewindowv2", MOVE_WINDOW},
|
||||
{"urgent", URGENT},
|
||||
{"focusedmon", FOCUSED_MONITOR},
|
||||
{"monitorremoved", MONITOR_REMOVED},
|
||||
};
|
||||
void onWorkspaceChanged(int workspaceId);
|
||||
void onFocusedMonitorChanged(std::string monitorData);
|
||||
void onOpenWindow(std::string windowData);
|
||||
void onCloseWindow(std::string windowData);
|
||||
void onMoveWindow(std::string windowData);
|
||||
void onUrgent(std::string windowAddress);
|
||||
void onActiveWindowChanged(std::string windowAddress);
|
||||
void onMonitorRemoved(std::string monitorName);
|
||||
// void onMonitorAdded(std::string monitorName);
|
||||
|
||||
HyprlandService();
|
||||
~HyprlandService();
|
||||
std::map<std::string, std::shared_ptr<Monitor>> monitors;
|
||||
std::map<int, std::shared_ptr<Workspace>> workspaces;
|
||||
std::map<std::string, std::shared_ptr<Client>> clients;
|
||||
|
||||
int fd = -1;
|
||||
std::map<int, Monitor> monitors;
|
||||
std::map<int, WorkspaceState *> workspaces;
|
||||
std::string socket_buffer;
|
||||
/// maybe refactor into reusable class
|
||||
std::string socketBuffer;
|
||||
int socketFd;
|
||||
///
|
||||
|
||||
std::string get_socket_path();
|
||||
bool on_socket_read(Glib::IOCondition condition);
|
||||
void parse_message(const std::string &line);
|
||||
void refresh_monitors();
|
||||
void refresh_workspaces();
|
||||
void onUrgentEvent(std::string windowAddress);
|
||||
void onActiveWindowEvent(std::string windowAddress);
|
||||
void bindHyprlandSocket();
|
||||
|
||||
void init();
|
||||
|
||||
void switchToWorkspace(int workspaceId);
|
||||
void refreshIndicator(std::shared_ptr<Workspace> workspace);
|
||||
|
||||
void handleSocketMessage(SocketHelper::SocketMessage message);
|
||||
};
|
||||
|
||||
36
include/services/notificationController.hpp
Normal file
36
include/services/notificationController.hpp
Normal file
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <sys/types.h>
|
||||
#include <vector>
|
||||
|
||||
#include "services/dbus/messages.hpp"
|
||||
#include "widgets/notification/baseNotification.hpp"
|
||||
|
||||
#include "gdkmm/monitor.h"
|
||||
|
||||
class NotificationController {
|
||||
static std::shared_ptr<NotificationController> instance;
|
||||
|
||||
public:
|
||||
static std::shared_ptr<NotificationController> getInstance() {
|
||||
if (!NotificationController::instance) {
|
||||
NotificationController::instance = std::shared_ptr<NotificationController>(new NotificationController());
|
||||
}
|
||||
return NotificationController::instance;
|
||||
}
|
||||
|
||||
void showSpotifyNotification(MprisPlayer2Message mpris);
|
||||
void showNotificationOnAllMonitors(NotifyMessage notify);
|
||||
|
||||
private:
|
||||
uint64_t globalNotificationId = 1;
|
||||
std::map<uint64_t, std::vector<std::shared_ptr<BaseNotification>>> activeNotifications;
|
||||
std::map<uint64_t, int> hoverCounts;
|
||||
NotificationController();
|
||||
std::vector<std::shared_ptr<Gdk::Monitor>> activeMonitors;
|
||||
void updateHoverState(uint64_t notificationId, bool isHovered);
|
||||
void closeNotification(uint64_t notificationId);
|
||||
};
|
||||
@@ -1,20 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <gio/gio.h>
|
||||
|
||||
class NotificationService {
|
||||
public:
|
||||
void intialize();
|
||||
|
||||
NotificationService() = default;
|
||||
~NotificationService();
|
||||
|
||||
guint32 allocateNotificationId(guint32 replacesId);
|
||||
GDBusConnection *getConnection() const { return connection; }
|
||||
|
||||
private:
|
||||
GDBusConnection *connection = nullptr;
|
||||
guint registrationId = 0;
|
||||
GDBusNodeInfo *nodeInfo = nullptr;
|
||||
guint32 nextNotificationId = 1;
|
||||
};
|
||||
20
include/services/textureCache.hpp
Normal file
20
include/services/textureCache.hpp
Normal file
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "gdkmm/texture.h"
|
||||
#include "glibmm/refptr.h"
|
||||
|
||||
class TextureCacheService {
|
||||
public:
|
||||
static TextureCacheService *getInstance();
|
||||
|
||||
Glib::RefPtr<Gdk::Texture> getTexture(const std::string &url);
|
||||
void pruneCache();
|
||||
|
||||
private:
|
||||
TextureCacheService() = default;
|
||||
|
||||
std::unordered_map<std::string, Glib::RefPtr<Gdk::Texture>> cache;
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "components/todoEntry.hpp"
|
||||
#include "services/todoAdapter.hpp"
|
||||
|
||||
class TodoService {
|
||||
public:
|
||||
TodoService(sigc::signal<void()> refreshSignal);
|
||||
~TodoService();
|
||||
|
||||
std::map<int, TodoEntry *> getTodos();
|
||||
void init();
|
||||
void removeTodo(int id);
|
||||
TodoEntry *addTodo(std::string text, bool emitSignal = true, bool persist = true);
|
||||
void updateTodo(int id, std::string text);
|
||||
|
||||
private:
|
||||
void load();
|
||||
|
||||
int nextId = 1;
|
||||
std::map<int, TodoEntry *> todos;
|
||||
sigc::signal<void()> refreshSignal;
|
||||
|
||||
std::unique_ptr<ITodoAdapter> adapter;
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct TodoRecord {
|
||||
int id;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
class ITodoAdapter {
|
||||
public:
|
||||
virtual ~ITodoAdapter() = default;
|
||||
|
||||
virtual bool init() = 0;
|
||||
virtual std::vector<TodoRecord> listTodos() = 0;
|
||||
|
||||
virtual int addTodo(const std::string &text) = 0;
|
||||
virtual bool removeTodo(int id) = 0;
|
||||
virtual bool updateTodo(int id, const std::string &text) = 0;
|
||||
};
|
||||
@@ -50,8 +50,11 @@ class TrayService {
|
||||
bool separator = false;
|
||||
std::vector<MenuNode> children;
|
||||
};
|
||||
std::optional<MenuNode> get_menu_layout(const std::string &id);
|
||||
bool activate_menu_item(const std::string &id, int itemId);
|
||||
using MenuLayoutCallback = sigc::slot<void(std::optional<MenuNode>)>;
|
||||
void request_menu_layout(const std::string &id, MenuLayoutCallback callback);
|
||||
bool activate_menu_item(const std::string &id, int itemId, int32_t x = -1,
|
||||
int32_t y = -1, uint32_t button = 1,
|
||||
uint32_t timestampMs = 0);
|
||||
|
||||
sigc::signal<void(const Item &)> &signal_item_added();
|
||||
sigc::signal<void(const std::string &)> &signal_item_removed();
|
||||
@@ -75,6 +78,11 @@ class TrayService {
|
||||
guint ownerWatchId = 0;
|
||||
Glib::RefPtr<Gio::MenuModel> menuModel;
|
||||
Glib::RefPtr<Gio::ActionGroup> menuActions;
|
||||
|
||||
guint refreshSourceId = 0;
|
||||
bool refreshInFlight = false;
|
||||
bool refreshQueued = false;
|
||||
bool addSignalPending = false;
|
||||
};
|
||||
|
||||
Glib::RefPtr<Gio::DBus::Connection> connection;
|
||||
@@ -124,7 +132,11 @@ class TrayService {
|
||||
void register_item(const Glib::ustring &sender, const std::string &service);
|
||||
void unregister_item(const std::string &id);
|
||||
|
||||
void refresh_item(TrackedItem &item);
|
||||
void schedule_refresh(const std::string &id);
|
||||
void begin_refresh(const std::string &id);
|
||||
static gboolean refresh_timeout_cb(gpointer user_data);
|
||||
static void on_refresh_finished_static(GObject *source, GAsyncResult *res,
|
||||
gpointer user_data);
|
||||
void emit_registered_items_changed();
|
||||
|
||||
Glib::Variant<std::vector<Glib::ustring>>
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "components/popover.hpp"
|
||||
#include "services/bluetooth.hpp"
|
||||
#include "widgets/bluetooth.hpp"
|
||||
#include "gtkmm/box.h"
|
||||
#include "widgets/controlCenter/mediaControl.hpp"
|
||||
|
||||
class ControlCenter : public Popover {
|
||||
public:
|
||||
@@ -11,7 +10,6 @@ class ControlCenter : public Popover {
|
||||
|
||||
private:
|
||||
Gtk::Box container;
|
||||
MediaControlWidget mediaControlWidget;
|
||||
|
||||
BluetoothWidget *bluetoothWidget = nullptr;
|
||||
BluetoothService *bluetoothService = BluetoothService::getInstance();
|
||||
};
|
||||
57
include/widgets/controlCenter/mediaControl.hpp
Normal file
57
include/widgets/controlCenter/mediaControl.hpp
Normal file
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
#include "gtkmm/box.h"
|
||||
#include "gtkmm/button.h"
|
||||
#include "gtkmm/label.h"
|
||||
#include "gtkmm/overlay.h"
|
||||
#include "gtkmm/picture.h"
|
||||
#include "gtkmm/scale.h"
|
||||
#include "gtkmm/scrolledwindow.h"
|
||||
|
||||
#include "services/dbus/mpris.hpp"
|
||||
|
||||
class MediaControlWidget : public Gtk::Box {
|
||||
public:
|
||||
MediaControlWidget();
|
||||
|
||||
private:
|
||||
std::shared_ptr<MprisController> mprisController = MprisController::getInstance();
|
||||
|
||||
int64_t currentPositionUs = 0;
|
||||
int64_t totalLengthUs = 0;
|
||||
sigc::connection seekTimerConnection;
|
||||
|
||||
void setCurrentPosition(int64_t position_us);
|
||||
void setTotalLength(int64_t length_us);
|
||||
void resetSeekTimer(int64_t start_position_us);
|
||||
bool onSeekTick();
|
||||
|
||||
Gtk::Box spotifyContainer;
|
||||
|
||||
// image as background, artist, title
|
||||
Gtk::Overlay topContainer;
|
||||
Gtk::Picture backgroundImage;
|
||||
Gtk::Box infoContainer;
|
||||
Gtk::Label artistLabel;
|
||||
Gtk::Label titleLabel;
|
||||
|
||||
//
|
||||
Gtk::Box seekBarContainer;
|
||||
Gtk::Label currentTimeLabel;
|
||||
Gtk::Scale seekBar;
|
||||
Gtk::Label totalTimeLabel;
|
||||
|
||||
// playback controls
|
||||
Gtk::Box bottomContainer;
|
||||
Gtk::Button previousButton;
|
||||
Gtk::Button playPauseButton;
|
||||
Gtk::Button nextButton;
|
||||
|
||||
Gtk::ScrolledWindow imageWrapper;
|
||||
|
||||
void onSpotifyMprisUpdated(const MprisPlayer2Message &message);
|
||||
|
||||
void onRunningStateChanged(MprisController::PlaybackStatus status);
|
||||
void onPlay();
|
||||
void onPause();
|
||||
void onStop();
|
||||
};
|
||||
45
include/widgets/notification/baseNotification.hpp
Normal file
45
include/widgets/notification/baseNotification.hpp
Normal file
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <csignal>
|
||||
#include <cstdint>
|
||||
#include <chrono>
|
||||
|
||||
#include <sigc++/connection.h>
|
||||
|
||||
#include "gdkmm/monitor.h"
|
||||
#include "gtkmm/window.h"
|
||||
|
||||
#define DEFAULT_NOTIFICATION_TIMEOUT 5000
|
||||
|
||||
|
||||
class BaseNotification : public Gtk::Window {
|
||||
public:
|
||||
BaseNotification( uint64_t notificationId, std::shared_ptr<Gdk::Monitor> monitor);
|
||||
|
||||
void pauseAutoClose();
|
||||
void resumeAutoClose();
|
||||
void startAutoClose(int timeoutMs);
|
||||
|
||||
sigc::signal<void(int)> signal_close;
|
||||
sigc::signal<void(bool)> signal_hover_changed;
|
||||
|
||||
virtual ~BaseNotification() = default;
|
||||
|
||||
uint64_t getNotificationId() const {
|
||||
return this->notificationId;
|
||||
}
|
||||
private:
|
||||
void ensure_notification_css_loaded();
|
||||
|
||||
void start_auto_close_timeout(int timeoutMs);
|
||||
void pause_auto_close();
|
||||
void resume_auto_close();
|
||||
|
||||
protected:
|
||||
uint64_t notificationId;
|
||||
|
||||
bool autoClosePaused = false;
|
||||
int autoCloseRemainingMs = 0;
|
||||
std::chrono::steady_clock::time_point autoCloseDeadline;
|
||||
sigc::connection autoCloseConnection;
|
||||
};
|
||||
13
include/widgets/notification/notificationWindow.hpp
Normal file
13
include/widgets/notification/notificationWindow.hpp
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include "services/dbus/messages.hpp"
|
||||
#include "widgets/notification/baseNotification.hpp"
|
||||
|
||||
class NotificationWindow : public BaseNotification {
|
||||
public:
|
||||
NotificationWindow(uint64_t notificationId, std::shared_ptr<Gdk::Monitor> monitor, NotifyMessage message);
|
||||
virtual ~NotificationWindow() = default;
|
||||
|
||||
};
|
||||
18
include/widgets/notification/spotifyNotification.hpp
Normal file
18
include/widgets/notification/spotifyNotification.hpp
Normal file
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
|
||||
#include "services/dbus/messages.hpp"
|
||||
#include "widgets/notification/baseNotification.hpp"
|
||||
|
||||
#include "gtkmm/centerbox.h"
|
||||
|
||||
class SpotifyNotification : public BaseNotification {
|
||||
public:
|
||||
SpotifyNotification(uint64_t notificationId, std::shared_ptr<Gdk::Monitor> monitor, MprisPlayer2Message message);
|
||||
virtual ~SpotifyNotification() = default;
|
||||
|
||||
private:
|
||||
std::unique_ptr<Gtk::CenterBox> createButtonBox(MprisPlayer2Message mpris);
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "components/popover.hpp"
|
||||
#include "services/todo.hpp"
|
||||
|
||||
class TodoPopover : public Popover {
|
||||
|
||||
public:
|
||||
TodoPopover(std::string icon, std::string title);
|
||||
|
||||
void update();
|
||||
|
||||
private:
|
||||
std::string name;
|
||||
TodoService *todoService = nullptr;
|
||||
Gtk::Box container;
|
||||
Gtk::Box inputArea;
|
||||
Gtk::Box *todoList = nullptr;
|
||||
};
|
||||
@@ -13,7 +13,9 @@
|
||||
#include <gtkmm/popovermenu.h>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "services/tray.hpp"
|
||||
#include "components/base/button.hpp"
|
||||
@@ -21,6 +23,7 @@
|
||||
class TrayIconWidget : public Button {
|
||||
public:
|
||||
TrayIconWidget(std::string id);
|
||||
~TrayIconWidget() override;
|
||||
|
||||
void update(const TrayService::Item &item);
|
||||
|
||||
@@ -31,25 +34,28 @@ class TrayIconWidget : public Button {
|
||||
Gtk::Picture picture;
|
||||
Gtk::Image image;
|
||||
Glib::RefPtr<Gtk::GestureClick> primaryGesture;
|
||||
Glib::RefPtr<Gtk::GestureClick> middleGesture;
|
||||
Glib::RefPtr<Gtk::GestureClick> secondaryGesture;
|
||||
Glib::RefPtr<Gtk::PopoverMenu> menuPopover;
|
||||
Glib::RefPtr<Gio::SimpleActionGroup> menuActions;
|
||||
Glib::RefPtr<Gio::MenuModel> menuModel;
|
||||
sigc::connection menuChangedConnection;
|
||||
bool menuPopupPending = false;
|
||||
bool menuRequestInFlight = false;
|
||||
bool hasRemoteMenu = false;
|
||||
std::shared_ptr<bool> aliveFlag;
|
||||
double pendingX = 0.0;
|
||||
double pendingY = 0.0;
|
||||
|
||||
void on_primary_released(int n_press, double x, double y);
|
||||
void on_middle_released(int n_press, double x, double y);
|
||||
void on_secondary_released(int n_press, double x, double y);
|
||||
bool ensure_menu();
|
||||
void on_menu_items_changed(guint position, guint removed, guint added);
|
||||
void try_popup();
|
||||
void on_menu_layout_ready(std::optional<TrayService::MenuNode> layout);
|
||||
void
|
||||
populate_menu_items(const std::vector<TrayService::MenuNode> &nodes,
|
||||
const Glib::RefPtr<Gio::Menu> &menu,
|
||||
const Glib::RefPtr<Gio::SimpleActionGroup> &actions);
|
||||
void on_menu_action(const Glib::VariantBase ¶meter, int itemId);
|
||||
bool try_get_pending_coords(int32_t &outX, int32_t &outY) const;
|
||||
};
|
||||
|
||||
class TrayWidget : public Gtk::Box {
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <gtkmm/box.h>
|
||||
#include <gtkmm/gestureclick.h>
|
||||
#include <gtkmm/label.h>
|
||||
#include <sigc++/connection.h>
|
||||
|
||||
#include "services/hyprland.hpp"
|
||||
#include "gtkmm/overlay.h"
|
||||
|
||||
class WorkspaceIndicator : public Gtk::Box {
|
||||
public:
|
||||
WorkspaceIndicator(int monitorId);
|
||||
~WorkspaceIndicator() override;
|
||||
|
||||
private:
|
||||
HyprlandService *service = HyprlandService::getInstance();
|
||||
int monitorId;
|
||||
sigc::connection workspaceConnection;
|
||||
sigc::connection monitorConnection;
|
||||
std::map<int, Gtk::Overlay *> workspaceIndicators;
|
||||
std::map<int, Glib::RefPtr<Gtk::GestureClick>> workspaceGestures;
|
||||
|
||||
void rebuild();
|
||||
void on_workspace_update();
|
||||
void on_monitor_update();
|
||||
void refreshLabel(Gtk::Overlay *overlay, const HyprlandService::WorkspaceState &state);
|
||||
};
|
||||
2
main.cpp
2
main.cpp
@@ -1,6 +1,6 @@
|
||||
#include "app.hpp"
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
int main()
|
||||
{
|
||||
App app;
|
||||
|
||||
|
||||
@@ -3,23 +3,27 @@
|
||||
all: unset;
|
||||
}
|
||||
|
||||
/* variable */
|
||||
:root {
|
||||
--icon-font-material: "Material Icons", sans-serif;
|
||||
--icon-font-awesome: "Font Awesome 7 Free", sans-serif;
|
||||
--text-font: "Hack Nerd Font Mono", sans-serif;
|
||||
--text-font-mono: "Hack Nerd Font Mono", monospace;
|
||||
}
|
||||
|
||||
window {
|
||||
background-color: #191919c6;
|
||||
color: #ffffff;
|
||||
padding-left: 4px;
|
||||
padding-right: 4px;
|
||||
padding-top: 2px;
|
||||
padding-bottom: 2px;
|
||||
font-size: 14px;
|
||||
font-family:
|
||||
"Hack Nerd Font Mono", "Font Awesome 7 Brands", "Font Awesome 7 Free",
|
||||
sans-serif;
|
||||
font-family: var(--text-font);
|
||||
}
|
||||
|
||||
popover {
|
||||
margin-top: 4px;
|
||||
font-family:
|
||||
"Hack Nerd Font Mono", "Material Icons", "Font Awesome 7 Free", sans-serif;
|
||||
font-family: var(--text-font);
|
||||
padding: 6px;
|
||||
border-radius: 8px;
|
||||
|
||||
@@ -29,6 +33,63 @@ popover {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.control-center-popover {
|
||||
padding: 12px;
|
||||
background-color: rgba(25, 25, 25, 0.95);
|
||||
}
|
||||
|
||||
.control-center-spotify-container {
|
||||
border: 1px solid rgba(80, 80, 80, 0.8);
|
||||
border-radius: 8px;
|
||||
background: rgba(30, 30, 30, 0.95);
|
||||
}
|
||||
|
||||
.control-center-spotify-artist-label {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
/* bold text shadow */
|
||||
text-shadow: 0 0 5px #000000aa;
|
||||
}
|
||||
|
||||
.control-center-spotify-title-label {
|
||||
font-size: 12px;
|
||||
color: #cccccc;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
/* bold text shadow */
|
||||
text-shadow: 0 0 5px #000000aa;
|
||||
}
|
||||
|
||||
.control-center-seek-bar {
|
||||
min-height: 6px;
|
||||
min-width: 120px;
|
||||
margin: 0 6px;
|
||||
}
|
||||
|
||||
.control-center-seek-bar trough {
|
||||
background-color: rgba(255, 255, 255, 0.18);
|
||||
border-radius: 999px;
|
||||
min-height: 6px;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.control-center-seek-bar highlight {
|
||||
background-color: rgba(255, 255, 255, 0.65);
|
||||
border-radius: 999px;
|
||||
}
|
||||
|
||||
.control-center-seek-bar slider {
|
||||
background-color: #ffffff;
|
||||
border-radius: 999px;
|
||||
min-width: 10px;
|
||||
min-height: 10px;
|
||||
}
|
||||
|
||||
tooltip {
|
||||
background-color: #222222;
|
||||
color: #ffffff;
|
||||
@@ -38,26 +99,28 @@ tooltip {
|
||||
}
|
||||
|
||||
button {
|
||||
font-family: "Material Icons", sans-serif;
|
||||
font-size: 20px;
|
||||
padding: 3px 6px;
|
||||
}
|
||||
|
||||
#spacer {
|
||||
font-weight: 900;
|
||||
padding: 0 5px;
|
||||
text-shadow: 0 0 5px #ffffffaa;
|
||||
}
|
||||
|
||||
.button {
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-family: "Material Icons", sans-serif;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
background-color: #111111;
|
||||
}
|
||||
|
||||
.flat-button {
|
||||
background-color: #333333;
|
||||
color: #ffffff;
|
||||
padding: 2px 4px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.workspace-pill {
|
||||
padding: 2px 5px;
|
||||
margin-right: 6px;
|
||||
@@ -74,8 +137,14 @@ button {
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.workspace-pill-active {
|
||||
.workspace-pill-alive {
|
||||
background-color: rgba(255, 255, 255, 0.153);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.workspace-pill-presenting {
|
||||
background-color: #666666;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.workspace-pill-focused {
|
||||
@@ -98,7 +167,6 @@ button {
|
||||
animation: workspace-updown 1.2s ease-in-out infinite;
|
||||
margin-left: -4px;
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.workspace-pill-seven {
|
||||
@@ -106,7 +174,6 @@ button {
|
||||
animation-delay: 0.6s;
|
||||
margin-right: -4px;
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@keyframes workspace-updown {
|
||||
|
||||
93
resources/notification.css
Normal file
93
resources/notification.css
Normal file
@@ -0,0 +1,93 @@
|
||||
:root {
|
||||
--icon-font-material: "Material Icons", sans-serif;
|
||||
--icon-font-awesome: "Font Awesome 7 Free", sans-serif;
|
||||
--text-font: "Hack Nerd Font Mono", sans-serif;
|
||||
--text-font-mono: "Hack Nerd Font Mono", monospace;
|
||||
|
||||
--color-notification-bg: rgba(30, 30, 30, 0.95);
|
||||
--color-notification-critical-bg: rgba(50, 20, 20, 0.95);
|
||||
--color-border: rgba(80, 80, 80, 0.8);
|
||||
}
|
||||
|
||||
.notification-popup {
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
background: var(--color-notification-bg);
|
||||
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.5);
|
||||
border: 1px solid var(--color-border);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.notification-critical {
|
||||
background: linear-gradient(145deg, #321010, #1e1e1e);
|
||||
border: 1px solid rgba(255, 75, 75, 0.5);
|
||||
border-left: 3px solid #ff4b4b;
|
||||
box-shadow:
|
||||
0 4px 30px rgba(0, 0, 0, 0.8),
|
||||
0 0 15px rgba(255, 75, 75, 0.2),
|
||||
inset 0 0 10px rgba(255, 75, 75, 0.1);
|
||||
|
||||
color: #ffffff;
|
||||
font-weight: 500;
|
||||
|
||||
}
|
||||
|
||||
.notification-normal {
|
||||
background: linear-gradient(90deg, #0c1f3a 0%, #1e1e1e 100%);
|
||||
border: 1px solid rgba(60, 160, 255, 0.3);
|
||||
border-left: 3px solid #3c9aff;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5),
|
||||
0 0 10px rgba(60, 160, 255, 0.1);
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.notification-low {
|
||||
background: linear-gradient(145deg, #2a2a2a, #1e1e1e);
|
||||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||||
border-left: 3px solid #888888;
|
||||
color: rgba(255, 255, 255, 0.95);
|
||||
/* white box shadow */
|
||||
box-shadow: 0 4px 20px rgba(255, 255, 255, 0.05);
|
||||
font-size: 13px;
|
||||
|
||||
}
|
||||
.notification-button-box {
|
||||
border-top: 1px solid var(--color-border);
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
.notification-button {
|
||||
background-color: #333333;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
color: #ffffff;
|
||||
padding: 4px 8px;
|
||||
margin-right: 6px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.notification-icon-button {
|
||||
font-family: var(--icon-font-material);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.notification-button:hover {
|
||||
background-color: #555555;
|
||||
}
|
||||
|
||||
.notification-app-icon {
|
||||
padding-right: 8px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.notification-app-name {
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
.notification-header {
|
||||
margin-bottom: 6px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
51
src/app.cpp
51
src/app.cpp
@@ -1,14 +1,24 @@
|
||||
#include "app.hpp"
|
||||
|
||||
#include <exception>
|
||||
#include <iostream>
|
||||
#include <sigc++/sigc++.h>
|
||||
#include <vector>
|
||||
#include "services/dbus/notification.hpp"
|
||||
#include "services/dbus/mpris.hpp"
|
||||
#include "services/notificationController.hpp"
|
||||
#include "services/textureCache.hpp"
|
||||
|
||||
App::App() {
|
||||
this->setupServices();
|
||||
this->notificationService.intialize();
|
||||
|
||||
this->app = Gtk::Application::create("org.example.mybar");
|
||||
this->setupServices();
|
||||
this->hyprlandService = HyprlandService::getInstance();
|
||||
this->notificationService = std::make_shared<NotificationService>();
|
||||
this->mprisController = MprisController::getInstance();
|
||||
|
||||
auto notificationController = NotificationController::getInstance();
|
||||
this->mprisController->signal_mpris_updated().connect(
|
||||
[notificationController](const MprisPlayer2Message &msg) {
|
||||
notificationController->showSpotifyNotification(msg);
|
||||
});
|
||||
|
||||
app->signal_activate().connect([&]() {
|
||||
auto display = Gdk::Display::get_default();
|
||||
@@ -16,23 +26,19 @@ App::App() {
|
||||
|
||||
for (guint i = 0; i < monitors->get_n_items(); ++i) {
|
||||
auto monitor = std::dynamic_pointer_cast<Gdk::Monitor>(
|
||||
monitors->get_object(i));
|
||||
monitors->get_object(i)
|
||||
);
|
||||
|
||||
if (monitor) {
|
||||
HyprlandService::Monitor *hyprlandMonitor = nullptr;
|
||||
|
||||
try {
|
||||
hyprlandMonitor =
|
||||
this->hyprlandService->getMonitorByIndex(i);
|
||||
} catch (const std::exception &ex) {
|
||||
std::cerr << "[App] Failed to fetch Hyprland monitor: "
|
||||
<< ex.what() << std::endl;
|
||||
continue;
|
||||
}
|
||||
|
||||
auto bar = new Bar(monitor->gobj(), hyprlandMonitor->id);
|
||||
auto bar = std::make_shared<Bar>(monitor->gobj());
|
||||
|
||||
bar->set_application(app);
|
||||
bar->show();
|
||||
|
||||
std::string monitorName = monitor->get_connector();
|
||||
bar->addLeftWidget(hyprlandService->getWorkspaceIndicatorsForMonitor(monitorName));
|
||||
hyprlandService->addBar(bar, monitorName);
|
||||
|
||||
bars.push_back(bar);
|
||||
}
|
||||
}
|
||||
@@ -40,20 +46,13 @@ App::App() {
|
||||
|
||||
|
||||
app->signal_shutdown().connect([&]() {
|
||||
for (auto bar : bars) {
|
||||
delete bar;
|
||||
}
|
||||
bars.clear();
|
||||
|
||||
this->trayService->stop();
|
||||
});
|
||||
}
|
||||
|
||||
void App::setupServices() {
|
||||
this->hyprlandService->socketEventSignal.connect(sigc::mem_fun(
|
||||
*this->hyprlandService, &HyprlandService::on_hyprland_event));
|
||||
TextureCacheService::getInstance()->pruneCache();
|
||||
|
||||
this->hyprlandService->start();
|
||||
this->trayService->start();
|
||||
}
|
||||
|
||||
|
||||
@@ -5,19 +5,16 @@
|
||||
#include <gtkmm/label.h>
|
||||
#include <gtkmm/window.h>
|
||||
|
||||
#include "helpers/systemHelper.hpp"
|
||||
#include "helpers/system.hpp"
|
||||
#include "widgets/date.hpp"
|
||||
#include "widgets/spacer.hpp"
|
||||
#include "widgets/todo.hpp"
|
||||
#include "widgets/volumeWidget.hpp"
|
||||
#include "widgets/workspaceIndicator.hpp"
|
||||
|
||||
#include "glibmm/main.h"
|
||||
#include "gtk/gtk.h"
|
||||
#include "sigc++/functors/mem_fun.h"
|
||||
|
||||
Bar::Bar(GdkMonitor *monitor, int monitorId)
|
||||
: monitorId(monitorId) {
|
||||
Bar::Bar(GdkMonitor *monitor) {
|
||||
set_name("bar-window");
|
||||
|
||||
gtk_layer_init_for_window(this->gobj());
|
||||
@@ -35,9 +32,8 @@ Bar::Bar(GdkMonitor *monitor, int monitorId)
|
||||
|
||||
set_child(main_box);
|
||||
|
||||
this->volumeWidget = Gtk::make_managed<VolumeWidget>();
|
||||
this->workspaceIndicator = Gtk::make_managed<WorkspaceIndicator>(monitorId);
|
||||
this->trayWidget = Gtk::make_managed<TrayWidget>();
|
||||
this->volumeWidget = std::make_shared<VolumeWidget>();
|
||||
this->trayWidget = std::make_shared<TrayWidget>();
|
||||
|
||||
load_css();
|
||||
setup_ui();
|
||||
@@ -60,14 +56,12 @@ void Bar::setup_ui() {
|
||||
}
|
||||
|
||||
void Bar::setup_left_box() {
|
||||
left_box.append(*workspaceIndicator);
|
||||
// left_box.append(*workspaceIndicator);
|
||||
}
|
||||
|
||||
void Bar::setup_center_box() {
|
||||
center_box.set_hexpand(false);
|
||||
|
||||
center_box.append(*(new TodoPopover("\uf23a", "To-Do")));
|
||||
center_box.append(*(new Spacer()));
|
||||
center_box.append(this->date);
|
||||
center_box.append(*(new Spacer()));
|
||||
center_box.append(this->clock);
|
||||
|
||||
@@ -2,18 +2,13 @@
|
||||
|
||||
#include "sigc++/functors/mem_fun.h"
|
||||
|
||||
|
||||
Button::Button(const std::string label)
|
||||
: Gtk::Button(label) {
|
||||
signal_clicked().connect(
|
||||
sigc::mem_fun(*this, &Button::on_clicked));
|
||||
Button::Button(const std::string label) : Gtk::Button(label) {
|
||||
signal_clicked().connect(sigc::mem_fun(*this, &Button::on_clicked));
|
||||
this->add_css_class("button");
|
||||
}
|
||||
|
||||
Button::Button(Gtk::Image &image)
|
||||
: Gtk::Button() {
|
||||
Button::Button(Gtk::Image &image) : Gtk::Button() {
|
||||
set_child(image);
|
||||
signal_clicked().connect(
|
||||
sigc::mem_fun(*this, &Button::on_clicked));
|
||||
signal_clicked().connect(sigc::mem_fun(*this, &Button::on_clicked));
|
||||
this->add_css_class("button");
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
#include "components/popover.hpp"
|
||||
|
||||
#include "gtkmm/label.h"
|
||||
#include "gtkmm/object.h"
|
||||
|
||||
Popover::Popover(const std::string icon, std::string name): Button(icon) {
|
||||
signal_clicked().connect(sigc::mem_fun(*this, &Popover::on_toggle_window));
|
||||
|
||||
set_name(name);
|
||||
|
||||
popover = new Gtk::Popover();
|
||||
popover->set_parent(*this);
|
||||
popover->set_autohide(true);
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
#include "components/todoEntry.hpp"
|
||||
|
||||
#include <gtkmm/label.h>
|
||||
#include <string>
|
||||
#include "components/base/button.hpp"
|
||||
|
||||
TodoEntry::TodoEntry(int id, std::string text, sigc::signal<void(int)> signal_dismissed, sigc::signal<void(int, std::string)> signal_edited)
|
||||
: Gtk::Box(Gtk::Orientation::HORIZONTAL) {
|
||||
this->id = id;
|
||||
this->text = text;
|
||||
this->signal_dismissed = signal_dismissed;
|
||||
this->signal_edited = signal_edited;
|
||||
|
||||
auto box = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL);
|
||||
box->set_hexpand(true);
|
||||
box->set_halign(Gtk::Align::START);
|
||||
box->set_valign(Gtk::Align::CENTER);
|
||||
box->set_name("todo-entry-box");
|
||||
box->add_css_class("todo-entry-box");
|
||||
append(*box);
|
||||
|
||||
auto label = Gtk::make_managed<Gtk::Label>(text);
|
||||
label->set_halign(Gtk::Align::START);
|
||||
label->set_valign(Gtk::Align::CENTER);
|
||||
box->append(*label);
|
||||
|
||||
auto buttonBox = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL);
|
||||
buttonBox->set_halign(Gtk::Align::END);
|
||||
buttonBox->set_valign(Gtk::Align::CENTER);
|
||||
append(*buttonBox);
|
||||
|
||||
auto dismissButton = Gtk::make_managed<Button>("\uf00d");
|
||||
dismissButton->set_valign(Gtk::Align::CENTER);
|
||||
dismissButton->set_tooltip_text("Dismiss");
|
||||
|
||||
dismissButton->signal_clicked().connect(sigc::mem_fun(*this, &TodoEntry::on_dismiss_clicked));
|
||||
|
||||
auto editButton = Gtk::make_managed<Button>("\uf044");
|
||||
editButton->set_valign(Gtk::Align::CENTER);
|
||||
|
||||
buttonBox->append(*editButton);
|
||||
buttonBox->append(*dismissButton);
|
||||
}
|
||||
|
||||
void TodoEntry::on_dismiss_clicked() {
|
||||
this->signal_dismissed.emit(this->id);
|
||||
}
|
||||
53
src/components/workspaceIndicator.cpp
Normal file
53
src/components/workspaceIndicator.cpp
Normal file
@@ -0,0 +1,53 @@
|
||||
#include "components/workspaceIndicator.hpp"
|
||||
|
||||
#include "gtkmm/gestureclick.h"
|
||||
#include "gtkmm/label.h"
|
||||
#include "gtkmm/overlay.h"
|
||||
|
||||
WorkspaceIndicator::WorkspaceIndicator(int id, std::string label, sigc::slot<void(int)> onClick)
|
||||
: Gtk::Box(Gtk::Orientation::HORIZONTAL) {
|
||||
|
||||
overlay = std::make_shared<Gtk::Overlay>();
|
||||
auto numLabel = Gtk::make_managed<Gtk::Label>(label);
|
||||
auto pillContainer = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL);
|
||||
|
||||
auto gesture = Gtk::GestureClick::create();
|
||||
gesture->set_button(GDK_BUTTON_PRIMARY);
|
||||
gesture->signal_released().connect([id, onClick](int, double, double) {
|
||||
onClick(
|
||||
id);
|
||||
});
|
||||
|
||||
overlay->add_controller(gesture);
|
||||
overlay->add_css_class("workspace-pill");
|
||||
|
||||
int sixSevenCheck = std::stoi(label);
|
||||
|
||||
if (sixSevenCheck == 6 || sixSevenCheck == 7) {
|
||||
auto indicator = Gtk::make_managed<Gtk::Label>(sixSevenCheck == 6 ? "🫱🏻" : "🫲🏻");
|
||||
indicator->add_css_class(sixSevenCheck == 6 ? "workspace-pill-six" : "workspace-pill-seven");
|
||||
indicator->set_valign(Gtk::Align::END);
|
||||
overlay->set_child(*indicator);
|
||||
overlay->add_overlay(*numLabel);
|
||||
pillContainer->append(*overlay);
|
||||
} else {
|
||||
overlay->set_child(*numLabel);
|
||||
pillContainer->append(*overlay);
|
||||
}
|
||||
|
||||
append(*pillContainer);
|
||||
}
|
||||
|
||||
void WorkspaceIndicator::setIndicatorState(InidicatorState state) {
|
||||
this->clearCssClass();
|
||||
this->currentState = state;
|
||||
auto cssClass = this->stateToCssClass[state];
|
||||
|
||||
this->overlay->add_css_class(cssClass);
|
||||
}
|
||||
|
||||
void WorkspaceIndicator::clearCssClass() {
|
||||
for (const auto &[_, cssClass] : stateToCssClass) {
|
||||
this->overlay->remove_css_class(cssClass);
|
||||
}
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
#include "services/bluetooth.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "glib.h"
|
||||
|
||||
BluetoothService::BluetoothService() {
|
||||
GError *error = nullptr;
|
||||
|
||||
this->adapter_proxy = g_dbus_proxy_new_for_bus_sync(
|
||||
G_BUS_TYPE_SYSTEM,
|
||||
G_DBUS_PROXY_FLAGS_NONE,
|
||||
nullptr,
|
||||
"org.bluez",
|
||||
"/org/bluez/hci0",
|
||||
"org.bluez.Adapter1",
|
||||
nullptr,
|
||||
&error);
|
||||
|
||||
if (error) {
|
||||
std::cerr << "Error creating Bluetooth adapter proxy: "
|
||||
<< error->message << std::endl;
|
||||
g_error_free(error);
|
||||
assert(false);
|
||||
}
|
||||
|
||||
this->powerState = this->getPowerState();
|
||||
this->isDiscovering = this->getIsDiscovering();
|
||||
|
||||
g_signal_connect(
|
||||
this->adapter_proxy,
|
||||
"g-properties-changed",
|
||||
G_CALLBACK(BluetoothService::onPropertyChangedStatic),
|
||||
this);
|
||||
}
|
||||
|
||||
bool BluetoothService::getPowerState() {
|
||||
GVariant *result = g_dbus_proxy_get_cached_property(
|
||||
this->adapter_proxy,
|
||||
"Powered");
|
||||
|
||||
if (!result) {
|
||||
std::cerr << "Error getting Powered property." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
gboolean powered;
|
||||
g_variant_get(result, "b", &powered);
|
||||
g_variant_unref(result);
|
||||
|
||||
return powered;
|
||||
}
|
||||
|
||||
bool BluetoothService::getIsDiscovering() {
|
||||
GVariant *result = g_dbus_proxy_get_cached_property(
|
||||
this->adapter_proxy,
|
||||
"Discovering");
|
||||
|
||||
if (!result) {
|
||||
std::cerr << "Error getting Discovering property." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
gboolean discovering;
|
||||
g_variant_get(result, "b", &discovering);
|
||||
g_variant_unref(result);
|
||||
|
||||
return discovering;
|
||||
}
|
||||
|
||||
void BluetoothService::togglePowerState() {
|
||||
GError *error = nullptr;
|
||||
bool state = !this->powerState;
|
||||
|
||||
GDBusConnection *connection = g_dbus_proxy_get_connection(this->adapter_proxy);
|
||||
GVariant *reply = g_dbus_connection_call_sync(
|
||||
connection,
|
||||
"org.bluez",
|
||||
"/org/bluez/hci0",
|
||||
"org.freedesktop.DBus.Properties",
|
||||
"Set",
|
||||
g_variant_new(
|
||||
"(ssv)",
|
||||
"org.bluez.Adapter1",
|
||||
"Powered",
|
||||
g_variant_new_boolean(state)),
|
||||
nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE,
|
||||
-1,
|
||||
nullptr,
|
||||
&error);
|
||||
|
||||
if (error) {
|
||||
std::cerr << "Error setting Powered property: "
|
||||
<< error->message << std::endl;
|
||||
g_error_free(error);
|
||||
}
|
||||
|
||||
if (reply) {
|
||||
g_variant_unref(reply);
|
||||
}
|
||||
|
||||
if (!error) {
|
||||
this->powerState = state;
|
||||
}
|
||||
}
|
||||
|
||||
void BluetoothService::toggleIsDiscovering() {
|
||||
bool newState = !this->isDiscovering;
|
||||
GError *error = nullptr;
|
||||
|
||||
const char *method = newState ? "StartDiscovery" : "StopDiscovery";
|
||||
GVariant *reply = g_dbus_proxy_call_sync(
|
||||
this->adapter_proxy,
|
||||
method,
|
||||
nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE,
|
||||
-1,
|
||||
nullptr,
|
||||
&error);
|
||||
|
||||
if (error) {
|
||||
std::cerr << "Error calling " << method << ": "
|
||||
<< error->message << std::endl;
|
||||
g_error_free(error);
|
||||
|
||||
if (reply) {
|
||||
g_variant_unref(reply);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this->isDiscovering = newState;
|
||||
|
||||
if (reply) {
|
||||
g_variant_unref(reply);
|
||||
}
|
||||
}
|
||||
|
||||
void BluetoothService::onPropertyChanged(GDBusProxy *proxy,
|
||||
GVariant *changed_properties,
|
||||
const gchar *const *invalidated_properties,
|
||||
gpointer user_data) {
|
||||
|
||||
gboolean is_powered = FALSE;
|
||||
gboolean is_discovering = FALSE;
|
||||
|
||||
if (g_variant_lookup(changed_properties, "Powered", "b", &is_powered)) {
|
||||
|
||||
if (!is_powered) {
|
||||
this->isDiscovering = is_discovering;
|
||||
isDiscoveringChangedSignal.emit(isDiscovering);
|
||||
}
|
||||
|
||||
this->powerState = is_powered;
|
||||
powerStateChangedSignal.emit(powerState);
|
||||
}
|
||||
|
||||
if (g_variant_lookup(changed_properties, "Discovering", "b", &is_discovering)) {
|
||||
this->isDiscovering = is_discovering;
|
||||
isDiscoveringChangedSignal.emit(isDiscovering);
|
||||
getDeviceObjectPaths();
|
||||
}
|
||||
}
|
||||
|
||||
void BluetoothService::onPropertyChangedStatic(GDBusProxy *proxy,
|
||||
GVariant *changed_properties,
|
||||
const gchar *const *invalidated_properties,
|
||||
gpointer user_data) {
|
||||
BluetoothService *service = static_cast<BluetoothService *>(user_data);
|
||||
|
||||
if (service) {
|
||||
service->onPropertyChanged(proxy, changed_properties, invalidated_properties, user_data);
|
||||
} else {
|
||||
std::cerr << "Error: BluetoothService instance is null in static callback." << std::endl;
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> BluetoothService::getDeviceObjectPaths() {
|
||||
std::vector<std::string> device_paths;
|
||||
|
||||
GError *error = nullptr;
|
||||
GDBusConnection *connection = g_dbus_proxy_get_connection(this->adapter_proxy);
|
||||
GVariant *reply = g_dbus_connection_call_sync(
|
||||
connection,
|
||||
"org.bluez",
|
||||
"/",
|
||||
"org.freedesktop.DBus.ObjectManager",
|
||||
"GetManagedObjects",
|
||||
nullptr,
|
||||
G_VARIANT_TYPE("(a{oa{sa{sv}}})"),
|
||||
G_DBUS_CALL_FLAGS_NONE,
|
||||
-1,
|
||||
nullptr,
|
||||
&error);
|
||||
|
||||
if (error) {
|
||||
std::cerr << "Error calling GetManagedObjects: " << error->message << std::endl;
|
||||
g_error_free(error);
|
||||
return device_paths;
|
||||
}
|
||||
|
||||
if (!reply) {
|
||||
return device_paths;
|
||||
}
|
||||
|
||||
GVariant *objects = g_variant_get_child_value(reply, 0);
|
||||
g_variant_unref(reply);
|
||||
|
||||
if (!objects) {
|
||||
return device_paths;
|
||||
}
|
||||
|
||||
GVariantIter iter;
|
||||
g_variant_iter_init(&iter, objects);
|
||||
|
||||
const gchar *object_path = nullptr;
|
||||
GVariant *interfaces = nullptr;
|
||||
while (g_variant_iter_next(&iter, "{&o@a{sa{sv}}}", &object_path, &interfaces)) {
|
||||
GVariant *device_props = nullptr;
|
||||
if (g_variant_lookup(interfaces, "org.bluez.Device1", "@a{sv}", &device_props)) {
|
||||
device_paths.emplace_back(object_path);
|
||||
g_variant_unref(device_props);
|
||||
}
|
||||
|
||||
g_variant_unref(interfaces);
|
||||
interfaces = nullptr;
|
||||
}
|
||||
|
||||
g_variant_unref(objects);
|
||||
return device_paths;
|
||||
}
|
||||
214
src/services/dbus/mpris.cpp
Normal file
214
src/services/dbus/mpris.cpp
Normal file
@@ -0,0 +1,214 @@
|
||||
#include "services/dbus/mpris.hpp"
|
||||
|
||||
#include <map>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "helpers/string.hpp"
|
||||
|
||||
#include "giomm/dbusconnection.h"
|
||||
#include "giomm/dbusproxy.h"
|
||||
|
||||
std::shared_ptr<MprisController> MprisController::getInstance() {
|
||||
static std::shared_ptr<MprisController> instance = std::shared_ptr<MprisController>(new MprisController());
|
||||
return instance;
|
||||
}
|
||||
|
||||
MprisController::MprisController() {
|
||||
Gio::DBus::Connection::get(
|
||||
Gio::DBus::BusType::SESSION,
|
||||
sigc::mem_fun(*this, &MprisController::on_bus_connected));
|
||||
}
|
||||
|
||||
sigc::signal<void(const MprisPlayer2Message &)> &MprisController::signal_mpris_updated() {
|
||||
return mprisUpdatedSignal;
|
||||
}
|
||||
|
||||
sigc::signal<void(MprisController::PlaybackStatus)> &MprisController::signal_playback_status_changed() {
|
||||
return playbackStatusChangedSignal;
|
||||
}
|
||||
|
||||
sigc::signal<void(int64_t)> &MprisController::signal_playback_position_changed() {
|
||||
return playbackPositionChangedSignal;
|
||||
}
|
||||
|
||||
void MprisController::on_bus_connected(const Glib::RefPtr<Gio::AsyncResult> &result) {
|
||||
if (!result) {
|
||||
spdlog::error("DBus Connection Error: null async result");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
m_connection = Gio::DBus::Connection::get_finish(result);
|
||||
|
||||
std::string player_bus_name = "org.mpris.MediaPlayer2.spotify";
|
||||
|
||||
m_proxy = Gio::DBus::Proxy::create_sync(
|
||||
m_connection,
|
||||
player_bus_name, // The Bus Name
|
||||
"/org/mpris/MediaPlayer2", // The Object Path
|
||||
"org.mpris.MediaPlayer2.Player" // The Interface
|
||||
);
|
||||
|
||||
if (m_proxy) {
|
||||
spdlog::info("Connected to: {}", player_bus_name);
|
||||
|
||||
signalNotification();
|
||||
|
||||
m_proxy->signal_properties_changed().connect(
|
||||
sigc::mem_fun(*this, &MprisController::on_properties_changed));
|
||||
}
|
||||
|
||||
} catch (const Glib::Error &ex) {
|
||||
spdlog::error("DBus Connection Error: {}", ex.what());
|
||||
}
|
||||
}
|
||||
|
||||
void MprisController::signalNotification() {
|
||||
if (!m_proxy) {
|
||||
return;
|
||||
}
|
||||
|
||||
Glib::VariantBase metadata_var;
|
||||
m_proxy->get_cached_property(metadata_var, "Metadata");
|
||||
|
||||
if (!metadata_var) {
|
||||
spdlog::info("No metadata available.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!metadata_var.is_of_type(Glib::VariantType("a{sv}"))) {
|
||||
spdlog::error("Unexpected metadata type.");
|
||||
return;
|
||||
}
|
||||
|
||||
using MetadataMap = std::map<Glib::ustring, Glib::VariantBase>;
|
||||
MetadataMap metadata_map;
|
||||
|
||||
Glib::Variant<MetadataMap> variant_dict =
|
||||
Glib::VariantBase::cast_dynamic<Glib::Variant<MetadataMap>>(metadata_var);
|
||||
|
||||
metadata_map = variant_dict.get();
|
||||
|
||||
std::string title, artwork_url;
|
||||
std::vector<std::string> artist;
|
||||
|
||||
if (metadata_map.count("xesam:title")) {
|
||||
const auto &title_base = metadata_map["xesam:title"];
|
||||
if (title_base.is_of_type(Glib::VariantType("s"))) {
|
||||
auto title_var = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(title_base);
|
||||
title = title_var.get();
|
||||
}
|
||||
}
|
||||
|
||||
if (metadata_map.count("xesam:artist")) {
|
||||
const auto &artist_var = metadata_map["xesam:artist"];
|
||||
|
||||
if (artist_var.is_of_type(Glib::VariantType("as"))) {
|
||||
auto artists = Glib::VariantBase::cast_dynamic<Glib::Variant<std::vector<Glib::ustring>>>(artist_var).get();
|
||||
if (!artists.empty()) {
|
||||
for (const auto &a : artists) {
|
||||
artist.push_back(a);
|
||||
}
|
||||
}
|
||||
} else if (artist_var.is_of_type(Glib::VariantType("s"))) {
|
||||
auto artist_str = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(artist_var);
|
||||
artist.push_back(artist_str.get());
|
||||
}
|
||||
}
|
||||
|
||||
if (metadata_map.count("mpris:artUrl")) {
|
||||
const auto &art_base = metadata_map["mpris:artUrl"];
|
||||
if (art_base.is_of_type(Glib::VariantType("s"))) {
|
||||
auto art_var = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(art_base);
|
||||
artwork_url = art_var.get();
|
||||
}
|
||||
}
|
||||
|
||||
int64_t length_us = 0;
|
||||
if (metadata_map.count("mpris:length")) {
|
||||
const auto &length_base = metadata_map["mpris:length"];
|
||||
if (length_base.is_of_type(Glib::VariantType("x"))) {
|
||||
auto length_var = Glib::VariantBase::cast_dynamic<Glib::Variant<gint64>>(length_base);
|
||||
length_us = static_cast<int64_t>(length_var.get());
|
||||
} else if (length_base.is_of_type(Glib::VariantType("t"))) {
|
||||
auto length_var = Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(length_base);
|
||||
length_us = static_cast<int64_t>(length_var.get());
|
||||
}
|
||||
}
|
||||
|
||||
MprisPlayer2Message mpris;
|
||||
mpris.title = StringHelper::trimToSize(title, 30);
|
||||
mpris.artist = artist;
|
||||
mpris.artwork_url = artwork_url;
|
||||
mpris.play_pause = [this]() { this->toggle_play(); };
|
||||
mpris.next = [this]() { this->next_song(); };
|
||||
mpris.previous = [this]() { this->previous_song(); };
|
||||
mpris.length_ms = length_us; // Convert microseconds to milliseconds
|
||||
mprisUpdatedSignal.emit(mpris);
|
||||
}
|
||||
|
||||
void MprisController::on_properties_changed(const Gio::DBus::Proxy::MapChangedProperties &changed_properties,
|
||||
const std::vector<Glib::ustring> &) {
|
||||
|
||||
if (changed_properties.find("Metadata") != changed_properties.end()) {
|
||||
signalNotification();
|
||||
}
|
||||
|
||||
if (changed_properties.find("PlaybackStatus") != changed_properties.end()) {
|
||||
auto status_var = changed_properties.at("PlaybackStatus");
|
||||
if (status_var.is_of_type(Glib::VariantType("s"))) {
|
||||
auto status = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(status_var).get();
|
||||
spdlog::info("Playback Status changed to: {}", status.raw());
|
||||
auto parsedStatusIt = playbackStatusMap.find(static_cast<std::string>(status));
|
||||
|
||||
if (parsedStatusIt != playbackStatusMap.end()) {
|
||||
currentPlaybackStatus = parsedStatusIt->second;
|
||||
playbackStatusChangedSignal.emit(currentPlaybackStatus);
|
||||
} else {
|
||||
spdlog::error("Unknown playback status: {}", status.raw());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (changed_properties.find("Position") != changed_properties.end()) {
|
||||
auto position_var = changed_properties.at("Position");
|
||||
if (position_var.is_of_type(Glib::VariantType("x"))) {
|
||||
auto position = Glib::VariantBase::cast_dynamic<Glib::Variant<gint64>>(position_var).get();
|
||||
spdlog::info("Position changed to: {}", position);
|
||||
playbackPositionChangedSignal.emit(static_cast<int64_t>(position));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MprisController::previous_song() {
|
||||
if (m_proxy) {
|
||||
m_proxy->call("Previous");
|
||||
}
|
||||
}
|
||||
|
||||
void MprisController::toggle_play() {
|
||||
if (m_proxy) {
|
||||
m_proxy->call("PlayPause");
|
||||
}
|
||||
}
|
||||
|
||||
void MprisController::next_song() {
|
||||
if (m_proxy) {
|
||||
m_proxy->call("Next");
|
||||
}
|
||||
}
|
||||
|
||||
void MprisController::emit_seeked(int64_t position_us) {
|
||||
if (!m_proxy) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Glib::VariantContainerBase params = Glib::VariantContainerBase::create_tuple(
|
||||
Glib::Variant<gint64>::create(position_us));
|
||||
|
||||
m_proxy->call("Seek", params);
|
||||
} catch (const Glib::Error &ex) {
|
||||
spdlog::error("Error seeking: {}", ex.what());
|
||||
}
|
||||
}
|
||||
172
src/services/dbus/notification.cpp
Normal file
172
src/services/dbus/notification.cpp
Normal file
@@ -0,0 +1,172 @@
|
||||
#include "services/dbus/notification.hpp"
|
||||
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "helpers/string.hpp"
|
||||
#include "services/notificationController.hpp"
|
||||
|
||||
#include "glib.h"
|
||||
#include "glibconfig.h"
|
||||
|
||||
void NotificationService::onBusAcquired(const Glib::RefPtr<Gio::DBus::Connection> &connection, const Glib::ustring &name) {
|
||||
spdlog::info("Acquired bus name: {}", name.raw());
|
||||
|
||||
auto introspection_data = Gio::DBus::NodeInfo::create_for_xml(introspection_xml);
|
||||
|
||||
// Register the object at the standard path
|
||||
connection->register_object(
|
||||
"/org/freedesktop/Notifications",
|
||||
introspection_data->lookup_interface("org.freedesktop.Notifications"),
|
||||
getMessageInterfaceVTable());
|
||||
}
|
||||
|
||||
const Gio::DBus::InterfaceVTable &NotificationService::getMessageInterfaceVTable() {
|
||||
static Gio::DBus::InterfaceVTable vtable(
|
||||
sigc::mem_fun(*this, &NotificationService::on_method_call));
|
||||
return vtable;
|
||||
}
|
||||
|
||||
void NotificationService::on_method_call(const Glib::RefPtr<Gio::DBus::Connection> &,
|
||||
const Glib::ustring &,
|
||||
const Glib::ustring &,
|
||||
const Glib::ustring &,
|
||||
const Glib::ustring &method_name,
|
||||
const Glib::VariantContainerBase ¶meters,
|
||||
const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation) {
|
||||
|
||||
if (method_name == "Notify") {
|
||||
handle_notify(parameters, invocation);
|
||||
} else if (method_name == "GetCapabilities") {
|
||||
auto caps = std::vector<Glib::ustring>{
|
||||
"body", "actions", "actions-icons", "persistence", "icon-static"
|
||||
};
|
||||
invocation->return_value(Glib::VariantContainerBase::create_tuple(
|
||||
Glib::Variant<std::vector<Glib::ustring>>::create(caps)));
|
||||
} else if (method_name == "GetServerInformation") {
|
||||
invocation->return_value(Glib::VariantContainerBase::create_tuple({Glib::Variant<Glib::ustring>::create("MyGtkmmNotifier"),
|
||||
Glib::Variant<Glib::ustring>::create("Custom"),
|
||||
Glib::Variant<Glib::ustring>::create("1.0"),
|
||||
Glib::Variant<Glib::ustring>::create("1.2")}));
|
||||
} else {
|
||||
// Handle other methods or return error
|
||||
invocation->return_value(Glib::VariantContainerBase());
|
||||
}
|
||||
}
|
||||
|
||||
void NotificationService::handle_notify(const Glib::VariantContainerBase ¶meters,
|
||||
const Glib::RefPtr<Gio::DBus::MethodInvocation> &invocation) {
|
||||
|
||||
Glib::VariantBase app_name_var, replaces_id_var, app_icon_var, summary_var, body_var, actions_var, hints_var, timeout_var;
|
||||
parameters.get_child(app_name_var, 0);
|
||||
parameters.get_child(replaces_id_var, 1);
|
||||
parameters.get_child(app_icon_var, 2);
|
||||
parameters.get_child(summary_var, 3);
|
||||
parameters.get_child(body_var, 4);
|
||||
parameters.get_child(actions_var, 5);
|
||||
parameters.get_child(hints_var, 6);
|
||||
parameters.get_child(timeout_var, 7);
|
||||
|
||||
Glib::ustring app_name = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(app_name_var).get();
|
||||
guint32 replaces_id = Glib::VariantBase::cast_dynamic<Glib::Variant<guint32>>(replaces_id_var).get();
|
||||
Glib::ustring app_icon = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(app_icon_var).get();
|
||||
Glib::ustring summary = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(summary_var).get();
|
||||
Glib::ustring body = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::ustring>>(body_var).get();
|
||||
std::vector<Glib::ustring> actions = Glib::VariantBase::cast_dynamic<Glib::Variant<std::vector<Glib::ustring>>>(actions_var).get();
|
||||
std::map<Glib::ustring, Glib::VariantBase> hints = Glib::VariantBase::cast_dynamic<Glib::Variant<std::map<Glib::ustring, Glib::VariantBase>>>(hints_var).get();
|
||||
gint32 expire_timeout = Glib::VariantBase::cast_dynamic<Glib::Variant<gint32>>(timeout_var).get();
|
||||
|
||||
spdlog::info("Notification Received: {} - {}", summary.raw(), body.raw());
|
||||
|
||||
NotifyMessage notify;
|
||||
notify.app_name = app_name;
|
||||
notify.replaces_id = replaces_id;
|
||||
notify.app_icon = app_icon;
|
||||
notify.summary = static_cast<std::string>(summary);
|
||||
notify.body = static_cast<std::string>(body);
|
||||
notify.actionInvoked = std::make_shared<bool>(false);
|
||||
|
||||
std::vector<std::string> actions_converted;
|
||||
actions_converted.reserve(actions.size());
|
||||
for (ulong i = 0; i < actions.size(); i += 2) {
|
||||
auto name = static_cast<std::string>(actions[i]);
|
||||
auto label = static_cast<std::string>(actions[i + 1]);
|
||||
|
||||
if (name == "default") {
|
||||
label = "Open";
|
||||
}
|
||||
|
||||
actions_converted.push_back(name);
|
||||
actions_converted.push_back(label);
|
||||
}
|
||||
notify.actions = actions_converted;
|
||||
|
||||
|
||||
for (const auto &[key, value] : hints) {
|
||||
if (key == "urgency") {
|
||||
if (value.is_of_type(Glib::VariantType("y"))) {
|
||||
auto urgency = Glib::VariantBase::cast_dynamic<Glib::Variant<guint8>>(value).get();
|
||||
notify.urgency = static_cast<NotificationUrgency>(urgency);
|
||||
}
|
||||
}
|
||||
|
||||
if (key == "image-data") {
|
||||
Glib::VariantBase image_value = value;
|
||||
if (image_value.is_of_type(Glib::VariantType("v"))) {
|
||||
try {
|
||||
image_value = Glib::VariantBase::cast_dynamic<Glib::Variant<Glib::VariantBase>>(image_value).get();
|
||||
} catch (const std::bad_cast &) {
|
||||
spdlog::warn("Failed to unwrap image-data variant");
|
||||
}
|
||||
}
|
||||
|
||||
if (image_value.is_of_type(Glib::VariantType("(iiibiiay)"))) {
|
||||
// This is a raw data image format which describes width, height, rowstride, has alpha,
|
||||
// bits per sample, channels and image data respectively.
|
||||
try {
|
||||
auto image_data_variant = Glib::VariantBase::cast_dynamic<
|
||||
Glib::Variant<std::tuple<gint32, gint32, gint32, bool, gint32, gint32, std::vector<guint8>>>>(image_value);
|
||||
auto [width, height, rowstride, has_alpha, bits_per_sample, channels, data] = image_data_variant.get();
|
||||
(void)channels;
|
||||
auto pixbuf = Gdk::Pixbuf::create_from_data(
|
||||
data.data(),
|
||||
Gdk::Colorspace::RGB,
|
||||
has_alpha,
|
||||
bits_per_sample,
|
||||
width,
|
||||
height,
|
||||
rowstride);
|
||||
notify.imageData = pixbuf;
|
||||
} catch (const std::bad_cast &e) {
|
||||
spdlog::warn("Failed to decode image-data hint: {}", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
notify.expire_timeout = expire_timeout;
|
||||
|
||||
if (app_name == "Thunderbird") {
|
||||
notify.expire_timeout = 10000; // 10 seconds for email notifications
|
||||
}
|
||||
|
||||
guint id = notificationIdCounter++;
|
||||
// Set up the callback to emit ActionInvoked on D-Bus
|
||||
Glib::RefPtr<Gio::DBus::Connection> dbus_conn = invocation->get_connection();
|
||||
notify.on_action = [dbus_conn, id](const std::string &action_id) {
|
||||
try {
|
||||
dbus_conn->emit_signal(
|
||||
"/org/freedesktop/Notifications",
|
||||
"org.freedesktop.Notifications",
|
||||
"ActionInvoked",
|
||||
"", // destination bus name (empty for broadcast)
|
||||
Glib::VariantContainerBase::create_tuple({Glib::Variant<guint>::create(id),
|
||||
Glib::Variant<Glib::ustring>::create(action_id)}));
|
||||
} catch (const std::exception &e) {
|
||||
spdlog::error("Failed to emit ActionInvoked: {}", e.what());
|
||||
}
|
||||
};
|
||||
NotificationController::getInstance()->showNotificationOnAllMonitors(notify);
|
||||
invocation->return_value(Glib::VariantContainerBase::create_tuple(
|
||||
Glib::Variant<guint>::create(id)));
|
||||
}
|
||||
@@ -1,317 +1,355 @@
|
||||
#include "services/hyprland.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <glib-unix.h>
|
||||
#include <glib.h>
|
||||
#include <memory>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "helpers/systemHelper.hpp"
|
||||
#include "helpers/hypr.hpp"
|
||||
#include "helpers/string.hpp"
|
||||
|
||||
HyprlandService::HyprlandService() = default;
|
||||
#include "gtkmm/box.h"
|
||||
|
||||
HyprlandService::~HyprlandService() {
|
||||
if (fd != -1) {
|
||||
close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
#include "spdlog/spdlog.h"
|
||||
|
||||
// free allocated workspace pointers
|
||||
for (auto &p : this->workspaces) {
|
||||
delete p.second;
|
||||
}
|
||||
this->workspaces.clear();
|
||||
this->monitors.clear();
|
||||
HyprlandService::HyprlandService() {
|
||||
init();
|
||||
this->bindHyprlandSocket();
|
||||
}
|
||||
|
||||
void HyprlandService::on_hyprland_event(std::string event, std::string data) {
|
||||
void HyprlandService::init() {
|
||||
auto monitorDataJson = HyprctlHelper::getMonitorData();
|
||||
auto onClick = sigc::mem_fun(*this, &HyprlandService::switchToWorkspace);
|
||||
|
||||
if (event == "urgent") {
|
||||
onUrgentEvent(data);
|
||||
for (const auto &item : monitorDataJson) {
|
||||
auto monitorPtr = std::make_shared<Monitor>();
|
||||
|
||||
std::string monitorName = item["name"].get<std::string>();
|
||||
int monitorId = item["id"].get<int>();
|
||||
|
||||
monitorPtr->id = monitorId;
|
||||
monitorPtr->name = monitorName;
|
||||
monitorPtr->activeWorkspaceId = item["activeWorkspace"]["id"].get<int>();
|
||||
monitorPtr->focused = item["focused"].get<bool>();
|
||||
this->monitors[monitorPtr->name] = monitorPtr;
|
||||
|
||||
for (int i = 1; i <= NUM_WORKSPACES; i++) {
|
||||
std::shared_ptr<WorkspaceData> state = std::make_shared<WorkspaceData>();
|
||||
int workspaceId = i + (NUM_WORKSPACES * monitorId);
|
||||
|
||||
state->id = workspaceId;
|
||||
state->monitorName = monitorName;
|
||||
auto view = std::make_shared<WorkspaceIndicator>(workspaceId, std::to_string(i), onClick);
|
||||
auto workSpace = std::make_shared<Workspace>();
|
||||
workSpace->state = state;
|
||||
workSpace->view = view;
|
||||
|
||||
monitorPtr->monitorWorkspaces[workspaceId] = workSpace;
|
||||
this->workspaces[workspaceId] = workSpace;
|
||||
}
|
||||
}
|
||||
|
||||
if (event == "activewindowv2") {
|
||||
onActiveWindowEvent(data);
|
||||
auto clientsDataJson = HyprctlHelper::getClientData();
|
||||
|
||||
for (const auto &client : clientsDataJson) {
|
||||
auto clientPtr = std::make_shared<Client>();
|
||||
clientPtr->address = client["address"].get<std::string>();
|
||||
clientPtr->workspaceId = client["workspace"]["id"].get<int>();
|
||||
clientPtr->title = client["title"].get<std::string>();
|
||||
this->clients[clientPtr->address] = clientPtr;
|
||||
|
||||
auto workspacePtr = workspaces[clientPtr->workspaceId];
|
||||
workspacePtr->state->clients[clientPtr->address] = clientPtr;
|
||||
|
||||
if (client.contains("urgent") && client["urgent"].get<bool>()) {
|
||||
workspacePtr->state->urgentClients.insert(clientPtr->address);
|
||||
}
|
||||
}
|
||||
|
||||
if (event == "workspace" || event == "movewindow") {
|
||||
refresh_workspaces();
|
||||
}
|
||||
auto workspaceDataJson = HyprctlHelper::getWorkspaceData();
|
||||
|
||||
if (event == "monitoradded" || event == "monitorremoved") {
|
||||
refresh_monitors();
|
||||
for (const auto &workspace : workspaceDataJson) {
|
||||
auto workspacePtr = workspaces[workspace["id"].get<int>()];
|
||||
auto state = workspacePtr->state;
|
||||
|
||||
state->id = workspace["id"].get<int>();
|
||||
state->monitorName = workspace["monitor"].get<std::string>();
|
||||
|
||||
refreshIndicator(workspacePtr);
|
||||
}
|
||||
}
|
||||
|
||||
void HyprlandService::start() {
|
||||
const std::string socket_path = get_socket_path();
|
||||
if (socket_path.empty()) {
|
||||
return;
|
||||
}
|
||||
void HyprlandService::bindHyprlandSocket() {
|
||||
std::string socketPath = HyprSocketHelper::getHyprlandSocketPath();
|
||||
|
||||
fd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (fd == -1) {
|
||||
std::cerr << "[Hyprland] Failed to create socket" << std::endl;
|
||||
socketFd = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
if (socketFd == -1) {
|
||||
spdlog::error("[Hyprland] Failed to create socket");
|
||||
return;
|
||||
}
|
||||
|
||||
struct sockaddr_un addr;
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sun_family = AF_UNIX;
|
||||
std::strncpy(addr.sun_path, socket_path.c_str(), sizeof(addr.sun_path) - 1);
|
||||
std::strncpy(addr.sun_path, socketPath.c_str(), sizeof(addr.sun_path) - 1);
|
||||
|
||||
if (connect(socketFd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) == -1) {
|
||||
spdlog::error("[Hyprland] Failed to connect to {}", socketPath);
|
||||
close(socketFd);
|
||||
socketFd = -1;
|
||||
|
||||
if (connect(fd, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) ==
|
||||
-1) {
|
||||
std::cerr << "[Hyprland] Failed to connect to " << socket_path
|
||||
<< std::endl;
|
||||
close(fd);
|
||||
fd = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
Glib::signal_io().connect(
|
||||
sigc::mem_fun(*this, &HyprlandService::on_socket_read), fd,
|
||||
Glib::IOCondition::IO_IN | Glib::IOCondition::IO_HUP |
|
||||
Glib::IOCondition::IO_ERR);
|
||||
auto socket_conditions = static_cast<GIOCondition>(G_IO_IN | G_IO_HUP | G_IO_ERR); // NOLINT(clang-analyzer-optin.core.EnumCastOutOfRange)
|
||||
GSource *source = g_unix_fd_source_new(socketFd, socket_conditions);
|
||||
|
||||
refresh_monitors();
|
||||
auto onSocketEvent = [](gint fd, GIOCondition, gpointer user_data) -> gboolean {
|
||||
HyprlandService *self = static_cast<HyprlandService *>(user_data);
|
||||
auto messages = SocketHelper::parseSocketMessage(fd, ">>");
|
||||
|
||||
for (const auto &message : messages) {
|
||||
self->handleSocketMessage(message);
|
||||
}
|
||||
|
||||
return G_SOURCE_CONTINUE;
|
||||
};
|
||||
|
||||
g_source_set_callback(source, reinterpret_cast<GSourceFunc>(reinterpret_cast<void *>(+onSocketEvent)), this, nullptr);
|
||||
g_source_attach(source, g_main_context_default());
|
||||
g_source_unref(source);
|
||||
}
|
||||
|
||||
bool HyprlandService::on_socket_read(Glib::IOCondition condition) {
|
||||
const auto error_mask = Glib::IOCondition::IO_HUP | Glib::IOCondition::IO_ERR;
|
||||
void HyprlandService::onWorkspaceChanged(int workspaceId) {
|
||||
auto newActive = workspaces[workspaceId];
|
||||
auto state = newActive->state;
|
||||
auto monitorPtr = monitors[state->monitorName];
|
||||
|
||||
if (static_cast<int>(condition & error_mask) != 0) {
|
||||
std::cerr << "[Hyprland] Socket disconnected." << std::endl;
|
||||
if (fd != -1) {
|
||||
close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
int oldActiveWorkspaceId = monitorPtr->activeWorkspaceId;
|
||||
auto oldActive = workspaces[oldActiveWorkspaceId];
|
||||
|
||||
char temp_buffer[4096];
|
||||
const ssize_t bytes_read = read(fd, temp_buffer, sizeof(temp_buffer));
|
||||
monitorPtr->activeWorkspaceId = workspaceId;
|
||||
|
||||
if (bytes_read <= 0) {
|
||||
// peer closed or error
|
||||
std::cerr << "[Hyprland] Socket read returned " << bytes_read << std::endl;
|
||||
if (fd != -1) {
|
||||
close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// append exactly bytes_read bytes (may contain embedded nulls)
|
||||
this->socket_buffer.append(temp_buffer, static_cast<size_t>(bytes_read));
|
||||
|
||||
size_t pos = 0;
|
||||
while ((pos = this->socket_buffer.find('\n')) != std::string::npos) {
|
||||
const std::string line = this->socket_buffer.substr(0, pos);
|
||||
parse_message(line);
|
||||
this->socket_buffer.erase(0, pos + 1);
|
||||
}
|
||||
|
||||
return true;
|
||||
refreshIndicator(newActive);
|
||||
refreshIndicator(oldActive);
|
||||
}
|
||||
|
||||
void HyprlandService::parse_message(const std::string &line) {
|
||||
const size_t split = line.find(">>");
|
||||
if (split != std::string::npos) {
|
||||
const std::string event_name = line.substr(0, split);
|
||||
const std::string event_data = line.substr(split + 2);
|
||||
void HyprlandService::onFocusedMonitorChanged(std::string monitorData) {
|
||||
std::string monitorName = StringHelper::split(monitorData, ',')[0];
|
||||
|
||||
socketEventSignal.emit(event_name, event_data);
|
||||
}
|
||||
}
|
||||
for (const auto &[_, monitorPtr] : monitors) {
|
||||
std::string itMonitorName = monitorPtr->name;
|
||||
|
||||
std::string HyprlandService::get_socket_path() {
|
||||
const char *sig = std::getenv("HYPRLAND_INSTANCE_SIGNATURE");
|
||||
const char *runtime = std::getenv("XDG_RUNTIME_DIR");
|
||||
if (itMonitorName == monitorName) {
|
||||
monitorPtr->focused = true;
|
||||
|
||||
if (!sig || !runtime) {
|
||||
std::cerr << "[Hyprland] Environment variables missing!" << std::endl;
|
||||
return "";
|
||||
}
|
||||
|
||||
return std::string(runtime) + "/hypr/" + sig + "/.socket2.sock";
|
||||
}
|
||||
|
||||
void HyprlandService::refresh_monitors() {
|
||||
// free any previously allocated WorkspaceState objects before rebuilding
|
||||
for (auto &p : this->workspaces) {
|
||||
delete p.second;
|
||||
}
|
||||
this->workspaces.clear();
|
||||
this->monitors.clear();
|
||||
|
||||
std::string output = SystemHelper::get_command_output(kMonitorCommand);
|
||||
auto monitorsJson = nlohmann::json::parse(output, nullptr, false);
|
||||
|
||||
for (const auto &monitorJson : monitorsJson) {
|
||||
Monitor monitor;
|
||||
monitor.id = monitorJson.value("id", -1);
|
||||
monitor.name = monitorJson.value("name", "");
|
||||
monitor.x = monitorJson.value("x", 0);
|
||||
monitor.y = monitorJson.value("y", 0);
|
||||
|
||||
monitor.focusedWorkspaceId = monitorJson["activeWorkspace"].value("id", -1);
|
||||
|
||||
if (monitor.id >= 0) {
|
||||
this->monitors[monitor.id] = monitor;
|
||||
}
|
||||
|
||||
for (int slot = 1; slot <= HyprlandService::kWorkspaceSlotCount; ++slot) {
|
||||
WorkspaceState wsState;
|
||||
wsState.focused = false;
|
||||
wsState.active = false;
|
||||
wsState.label = std::to_string(slot);
|
||||
wsState.monitorId = monitor.id;
|
||||
|
||||
int id = slot + monitor.id * HyprlandService::kWorkspaceSlotCount;
|
||||
wsState.hyprId = id;
|
||||
this->workspaces[id] = new WorkspaceState(wsState);
|
||||
if (monitor.id >= 0) {
|
||||
this->monitors[monitor.id].workspaceStates[slot] = this->workspaces[id];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this->refresh_workspaces();
|
||||
monitorStateChanged.emit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called every time when workspace changes have been detected.
|
||||
* Used to Update the internal state for the Workspaces,
|
||||
*/
|
||||
void HyprlandService::refresh_workspaces() {
|
||||
std::string output = SystemHelper::get_command_output(kWorkspaceCommand);
|
||||
auto workspacesJson = nlohmann::json::parse(output, nullptr, false);
|
||||
|
||||
for (auto &[id, ws] : this->workspaces) {
|
||||
ws->focused = false;
|
||||
ws->active = false;
|
||||
}
|
||||
|
||||
output = SystemHelper::get_command_output(kMonitorCommand);
|
||||
auto monitorsJson = nlohmann::json::parse(output, nullptr, false);
|
||||
|
||||
for (const auto &monitorJson : monitorsJson) {
|
||||
const int monitorId = monitorJson.value("id", -1);
|
||||
const int focusedWorkspaceId = monitorJson["activeWorkspace"].value("id", -1);
|
||||
|
||||
// write into the stored monitor (use reference)
|
||||
auto it = this->monitors.find(monitorId);
|
||||
if (it != this->monitors.end()) {
|
||||
it->second.focusedWorkspaceId = focusedWorkspaceId;
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &workspaceJson : workspacesJson) {
|
||||
const int workspaceId = workspaceJson.value("id", -1);
|
||||
auto workspaceStateIt = this->workspaces.find(workspaceId);
|
||||
if (workspaceStateIt == this->workspaces.end()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
WorkspaceState *workspaceState = workspaceStateIt->second;
|
||||
auto mit = this->monitors.find(workspaceState->monitorId);
|
||||
if (mit != this->monitors.end()) {
|
||||
workspaceState->focused = mit->second.focusedWorkspaceId == workspaceId;
|
||||
int activeWorkspaceId = monitorPtr->activeWorkspaceId;
|
||||
auto activeWorkspace = workspaces[activeWorkspaceId];
|
||||
refreshIndicator(activeWorkspace);
|
||||
} else {
|
||||
workspaceState->focused = false;
|
||||
monitorPtr->focused = false;
|
||||
|
||||
int activeWorkspaceId = monitorPtr->activeWorkspaceId;
|
||||
auto activeWorkspace = workspaces[activeWorkspaceId];
|
||||
refreshIndicator(activeWorkspace);
|
||||
}
|
||||
workspaceState->active = true;
|
||||
}
|
||||
}
|
||||
|
||||
void HyprlandService::onMonitorRemoved(std::string monitorName) {
|
||||
auto monitorPtr = this->monitors[monitorName];
|
||||
|
||||
for (const auto &[wsId, wsPtr] : monitorPtr->monitorWorkspaces) {
|
||||
this->workspaces.erase(wsId);
|
||||
}
|
||||
|
||||
workspaceStateChanged.emit();
|
||||
monitorPtr->monitorWorkspaces.clear();
|
||||
monitorPtr->bar->close();
|
||||
monitorPtr->bar = nullptr;
|
||||
|
||||
this->monitors.erase(monitorName);
|
||||
}
|
||||
|
||||
void HyprlandService::onMoveWindow(std::string windowData) {
|
||||
auto parts = StringHelper::split(windowData, ',');
|
||||
std::string addr = "0x" + parts[0];
|
||||
int newWorkspaceId = std::stoi(parts[1]);
|
||||
|
||||
if (this->clients.find(addr) == this->clients.end()) {
|
||||
spdlog::warn("[Hyprland] onMoveWindow: Client {} not found", addr);
|
||||
return;
|
||||
}
|
||||
|
||||
auto clientPtr = this->clients[addr];
|
||||
int oldWorkspaceId = clientPtr->workspaceId;
|
||||
|
||||
auto oldWorkspacePtr = workspaces[oldWorkspaceId];
|
||||
oldWorkspacePtr->state->clients.erase(addr);
|
||||
bool wasUrgent = oldWorkspacePtr->state->urgentClients.erase(addr) > 0;
|
||||
refreshIndicator(oldWorkspacePtr);
|
||||
|
||||
clientPtr->workspaceId = newWorkspaceId;
|
||||
|
||||
auto newWorkspacePtr = workspaces[newWorkspaceId];
|
||||
newWorkspacePtr->state->clients[addr] = clientPtr;
|
||||
if (wasUrgent) {
|
||||
newWorkspacePtr->state->urgentClients.insert(addr);
|
||||
}
|
||||
refreshIndicator(newWorkspacePtr);
|
||||
}
|
||||
|
||||
void HyprlandService::onOpenWindow(std::string windowData) {
|
||||
auto parts = StringHelper::split(windowData, ',');
|
||||
std::string addr = "0x" + parts[0];
|
||||
int workspaceId = std::stoi(parts[1]);
|
||||
std::string title = parts[2];
|
||||
|
||||
auto clientPtr = std::make_shared<Client>();
|
||||
clientPtr->address = addr;
|
||||
clientPtr->workspaceId = workspaceId;
|
||||
clientPtr->title = title;
|
||||
this->clients[clientPtr->address] = clientPtr;
|
||||
auto workspacePtr = workspaces[clientPtr->workspaceId];
|
||||
workspacePtr->state->clients[clientPtr->address] = clientPtr;
|
||||
|
||||
refreshIndicator(workspacePtr);
|
||||
}
|
||||
|
||||
void HyprlandService::onCloseWindow(std::string windowData) {
|
||||
auto parts = StringHelper::split(windowData, ',');
|
||||
std::string addr = "0x" + parts[0];
|
||||
|
||||
if (this->clients.find(addr) == this->clients.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto clientPtr = this->clients[addr];
|
||||
int workspaceId = clientPtr->workspaceId;
|
||||
|
||||
auto workspacePtr = workspaces[workspaceId];
|
||||
workspacePtr->state->clients.erase(addr);
|
||||
this->clients.erase(addr);
|
||||
|
||||
refreshIndicator(workspacePtr);
|
||||
}
|
||||
|
||||
void HyprlandService::handleSocketMessage(SocketHelper::SocketMessage message) {
|
||||
if (socketEventTypeMap.find(message.eventType) == socketEventTypeMap.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
SocketEventType eventType = socketEventTypeMap[message.eventType];
|
||||
std::string eventData = message.eventData;
|
||||
|
||||
switch (eventType) {
|
||||
case FOCUSED_MONITOR: {
|
||||
onFocusedMonitorChanged(eventData);
|
||||
break;
|
||||
}
|
||||
case WORKSPACE_CHANGED: {
|
||||
this->onWorkspaceChanged(std::stoi(eventData));
|
||||
break;
|
||||
}
|
||||
case OPEN_WINDOW: {
|
||||
this->onOpenWindow(eventData);
|
||||
break;
|
||||
}
|
||||
case CLOSE_WINDOW: {
|
||||
this->onCloseWindow(eventData);
|
||||
break;
|
||||
}
|
||||
case URGENT: {
|
||||
this->onUrgent(eventData);
|
||||
break;
|
||||
}
|
||||
case ACTIVE_WINDOW: {
|
||||
this->onActiveWindowChanged(eventData);
|
||||
break;
|
||||
}
|
||||
case MONITOR_REMOVED: {
|
||||
this->onMonitorRemoved(eventData);
|
||||
break;
|
||||
}
|
||||
case MOVE_WINDOW: {
|
||||
this->onMoveWindow(eventData);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
void HyprlandService::onUrgent(std::string windowAddress) {
|
||||
std::string addr = "0x" + windowAddress;
|
||||
if (this->clients.find(addr) == this->clients.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto clientPtr = this->clients[addr];
|
||||
int workspaceId = clientPtr->workspaceId;
|
||||
|
||||
auto workspacePtr = workspaces[workspaceId];
|
||||
workspacePtr->state->urgentClients.insert(addr);
|
||||
|
||||
refreshIndicator(workspacePtr);
|
||||
}
|
||||
|
||||
void HyprlandService::onActiveWindowChanged(std::string windowAddress) {
|
||||
std::string addr = "0x" + windowAddress;
|
||||
if (this->clients.find(addr) == this->clients.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto clientPtr = this->clients[addr];
|
||||
int workspaceId = clientPtr->workspaceId;
|
||||
|
||||
auto workspacePtr = workspaces[workspaceId];
|
||||
workspacePtr->state->urgentClients.erase(addr);
|
||||
|
||||
refreshIndicator(workspacePtr);
|
||||
}
|
||||
|
||||
std::shared_ptr<Gtk::Box> HyprlandService::getWorkspaceIndicatorsForMonitor(std::string monitorName) {
|
||||
auto box = std::make_shared<Gtk::Box>(Gtk::Orientation::HORIZONTAL);
|
||||
auto monitor = monitors[monitorName];
|
||||
|
||||
for (const auto &[wsId, wsPair] : monitor->monitorWorkspaces) {
|
||||
box->append((Gtk::Box &)*wsPair->view);
|
||||
}
|
||||
|
||||
return box;
|
||||
}
|
||||
|
||||
void HyprlandService::switchToWorkspace(int workspaceId) {
|
||||
std::string cmd =
|
||||
"hyprctl dispatch workspace " + std::to_string(workspaceId);
|
||||
HyprctlHelper::dispatchWorkspace(workspaceId);
|
||||
}
|
||||
|
||||
try {
|
||||
(void)SystemHelper::get_command_output(cmd.c_str());
|
||||
} catch (const std::exception &ex) {
|
||||
std::cerr << "[Hyprland] Failed to dispatch workspace command: "
|
||||
<< ex.what() << " cmd=" << cmd << std::endl;
|
||||
void HyprlandService::refreshIndicator(std::shared_ptr<Workspace> workspace) {
|
||||
auto view = workspace->view;
|
||||
|
||||
auto state = workspace->state;
|
||||
auto monitorsPtr = monitors[state->monitorName];
|
||||
|
||||
bool isUrgent = !state->urgentClients.empty();
|
||||
bool isEmpty = state->clients.empty();
|
||||
bool isPreseneting = state->id == monitorsPtr->activeWorkspaceId;
|
||||
bool isFocused = monitorsPtr->focused && isPreseneting;
|
||||
|
||||
if (isUrgent) {
|
||||
view->setIndicatorState(WorkspaceIndicator::URGENT);
|
||||
} else if (isFocused) {
|
||||
view->setIndicatorState(WorkspaceIndicator::FOCUSED);
|
||||
} else if (isPreseneting) {
|
||||
view->setIndicatorState(WorkspaceIndicator::PRESENTING);
|
||||
} else if (!isEmpty) {
|
||||
view->setIndicatorState(WorkspaceIndicator::ALIVE);
|
||||
} else {
|
||||
view->setIndicatorState(WorkspaceIndicator::EMPTY);
|
||||
}
|
||||
}
|
||||
|
||||
void HyprlandService::onUrgentEvent(std::string windowAddress) {
|
||||
std::string output = SystemHelper::get_command_output(kClientsCommand);
|
||||
auto clientsJson = nlohmann::json::parse(output, nullptr, false);
|
||||
|
||||
for (const auto &clientJson : clientsJson) {
|
||||
const std::string addr = clientJson.value("address", "");
|
||||
|
||||
if (addr == "0x" + windowAddress) {
|
||||
int workspaceId = clientJson["workspace"].value("id", -1);
|
||||
|
||||
auto it = this->workspaces.find(workspaceId);
|
||||
if (it != this->workspaces.end() && it->second) {
|
||||
|
||||
WorkspaceState *ws = it->second;
|
||||
auto uit = std::find(ws->urgentWindows.begin(), ws->urgentWindows.end(), windowAddress);
|
||||
if (uit == ws->urgentWindows.end()) {
|
||||
ws->urgentWindows.push_back(windowAddress);
|
||||
workspaceStateChanged.emit();
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void HyprlandService::onActiveWindowEvent(std::string windowAddress) {
|
||||
std::string output = SystemHelper::get_command_output(kClientsCommand);
|
||||
auto clientsJson = nlohmann::json::parse(output, nullptr, false);
|
||||
|
||||
for (const auto &clientJson : clientsJson) {
|
||||
const std::string addr = clientJson.value("address", "");
|
||||
|
||||
if (addr == "0x" + windowAddress) {
|
||||
int workspaceId = clientJson["workspace"]["id"];
|
||||
auto it = this->workspaces.find(workspaceId);
|
||||
if (it != this->workspaces.end() && it->second) {
|
||||
WorkspaceState *ws = it->second;
|
||||
auto uit = std::find(ws->urgentWindows.begin(), ws->urgentWindows.end(), windowAddress);
|
||||
if (uit != ws->urgentWindows.end()) {
|
||||
ws->urgentWindows.erase(uit);
|
||||
workspaceStateChanged.emit();
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HyprlandService::Monitor *HyprlandService::getMonitorById(int id) {
|
||||
auto it = monitors.find(id);
|
||||
if (it == monitors.end()) {
|
||||
throw std::runtime_error("Monitor with ID " + std::to_string(id) +
|
||||
" not found.");
|
||||
}
|
||||
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
HyprlandService::Monitor *HyprlandService::getMonitorByIndex(std::size_t index) {
|
||||
if (index >= monitors.size()) {
|
||||
throw std::runtime_error("Monitor index out of bounds: " + std::to_string(index));
|
||||
}
|
||||
|
||||
auto it = monitors.begin();
|
||||
std::advance(it, static_cast<long>(index));
|
||||
|
||||
return &it->second;
|
||||
void HyprlandService::addBar(std::shared_ptr<Bar> bar, std::string monitorName) {
|
||||
this->monitors[monitorName]->bar = bar;
|
||||
}
|
||||
139
src/services/notificationController.cpp
Normal file
139
src/services/notificationController.cpp
Normal file
@@ -0,0 +1,139 @@
|
||||
#include "services/notificationController.hpp"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "services/dbus/messages.hpp"
|
||||
#include "widgets/notification/baseNotification.hpp"
|
||||
#include "widgets/notification/notificationWindow.hpp"
|
||||
#include "widgets/notification/spotifyNotification.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "gdkmm/display.h"
|
||||
#include "sigc++/adaptors/bind.h"
|
||||
|
||||
std::shared_ptr<NotificationController> NotificationController::instance = nullptr;
|
||||
|
||||
NotificationController::NotificationController() {
|
||||
if (NotificationController::instance) {
|
||||
throw std::runtime_error("use getInstance()!");
|
||||
}
|
||||
|
||||
auto display = Gdk::Display::get_default();
|
||||
if (!display) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto monitors = display->get_monitors();
|
||||
if (!monitors) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (guint i = 0; i < monitors->get_n_items(); ++i) {
|
||||
auto monitor = std::dynamic_pointer_cast<Gdk::Monitor>(
|
||||
monitors->get_object(i));
|
||||
|
||||
this->activeMonitors.push_back(monitor);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void NotificationController::showNotificationOnAllMonitors(NotifyMessage notify) {
|
||||
uint64_t id = this->globalNotificationId++;
|
||||
std::vector<std::shared_ptr<BaseNotification>> notifications;
|
||||
|
||||
for (const auto &monitor : this->activeMonitors) {
|
||||
auto notification = std::make_shared<NotificationWindow>(id, monitor, notify);
|
||||
notifications.push_back(notification);
|
||||
|
||||
auto timeout = notify.expire_timeout;
|
||||
notification->show();
|
||||
// -1 means use default timeout, 0 means never expire
|
||||
if (timeout < 0) {
|
||||
timeout = DEFAULT_NOTIFICATION_TIMEOUT;
|
||||
}
|
||||
|
||||
notification->signal_close.connect([this, id = notification->getNotificationId()](int) {
|
||||
closeNotification(id);
|
||||
});
|
||||
|
||||
notification->signal_hover_changed.connect([this, id = notification->getNotificationId()](bool hovered) {
|
||||
updateHoverState(id, hovered);
|
||||
});
|
||||
|
||||
if (timeout == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
notification->startAutoClose(timeout);
|
||||
}
|
||||
|
||||
this->activeNotifications[id] = notifications;
|
||||
|
||||
}
|
||||
|
||||
|
||||
void NotificationController::showSpotifyNotification(MprisPlayer2Message mpris) {
|
||||
std::vector<std::shared_ptr<BaseNotification>> notifications;
|
||||
uint64_t id = this->globalNotificationId++;
|
||||
|
||||
|
||||
for (const auto &monitor : this->activeMonitors) {
|
||||
auto notification = std::make_shared<SpotifyNotification>(id, monitor, mpris);
|
||||
|
||||
notification->show();
|
||||
notifications.push_back(notification);
|
||||
|
||||
notification->signal_close.connect([this, id = notification->getNotificationId()](int) {
|
||||
closeNotification(id);
|
||||
});
|
||||
|
||||
notification->signal_hover_changed.connect([this, id = notification->getNotificationId()](bool hovered) {
|
||||
updateHoverState(id, hovered);
|
||||
});
|
||||
|
||||
|
||||
notification->startAutoClose(DEFAULT_NOTIFICATION_TIMEOUT);
|
||||
}
|
||||
|
||||
this->activeNotifications[id] = notifications;
|
||||
|
||||
}
|
||||
|
||||
void NotificationController::updateHoverState(uint64_t notificationId, bool isHovered) {
|
||||
if (this->activeNotifications.find(notificationId) == this->activeNotifications.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
int &count = this->hoverCounts[notificationId];
|
||||
if (isHovered) {
|
||||
count += 1;
|
||||
} else {
|
||||
count = std::max(0, count - 1);
|
||||
}
|
||||
|
||||
auto ¬ifications = this->activeNotifications[notificationId];
|
||||
if (count > 0) {
|
||||
for (const auto ¬ification : notifications) {
|
||||
notification->pauseAutoClose();
|
||||
}
|
||||
} else {
|
||||
for (const auto ¬ification : notifications) {
|
||||
notification->resumeAutoClose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void NotificationController::closeNotification(uint64_t notificationId) {
|
||||
if (this->activeNotifications.find(notificationId) == this->activeNotifications.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto notifications = this->activeNotifications[notificationId];
|
||||
for (const auto ¬ification : notifications) {
|
||||
notification->close();
|
||||
}
|
||||
|
||||
this->activeNotifications.erase(notificationId);
|
||||
this->hoverCounts.erase(notificationId);
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
#include "services/notifications.hpp"
|
||||
|
||||
#include <gio/gio.h>
|
||||
#include <iostream>
|
||||
|
||||
static constexpr const char *kNotificationsObjectPath = "/org/freedesktop/Notifications";
|
||||
static constexpr const char *kNotificationsInterface = "org.freedesktop.Notifications";
|
||||
|
||||
static const char *kNotificationsIntrospectionXml = R"XML(
|
||||
<node>
|
||||
<interface name="org.freedesktop.Notifications">
|
||||
<method name="Notify">
|
||||
<arg type="s" direction="in"/>
|
||||
<arg type="u" direction="in"/>
|
||||
<arg type="s" direction="in"/>
|
||||
<arg type="s" direction="in"/>
|
||||
<arg type="s" direction="in"/>
|
||||
<arg type="as" direction="in"/>
|
||||
<arg type="a{sv}" direction="in"/>
|
||||
<arg type="i" direction="in"/>
|
||||
<arg type="u" direction="out"/>
|
||||
</method>
|
||||
<method name="CloseNotification">
|
||||
<arg type="u" direction="in"/>
|
||||
</method>
|
||||
<method name="GetCapabilities">
|
||||
<arg type="as" direction="out"/>
|
||||
</method>
|
||||
<method name="GetServerInformation">
|
||||
<arg type="s" direction="out"/>
|
||||
<arg type="s" direction="out"/>
|
||||
<arg type="s" direction="out"/>
|
||||
<arg type="s" direction="out"/>
|
||||
</method>
|
||||
<signal name="NotificationClosed">
|
||||
<arg type="u"/>
|
||||
<arg type="u"/>
|
||||
</signal>
|
||||
<signal name="ActionInvoked">
|
||||
<arg type="u"/>
|
||||
<arg type="s"/>
|
||||
</signal>
|
||||
<signal name="ActivationToken">
|
||||
<arg type="u"/>
|
||||
<arg type="s"/>
|
||||
</signal>
|
||||
</interface>
|
||||
</node>)XML";
|
||||
|
||||
static void on_method_call(GDBusConnection * /*connection*/,
|
||||
const gchar * /*sender*/,
|
||||
const gchar * /*object_path*/,
|
||||
const gchar *interface_name,
|
||||
const gchar *method_name,
|
||||
GVariant *parameters,
|
||||
GDBusMethodInvocation *invocation,
|
||||
gpointer user_data) {
|
||||
auto *self = static_cast<NotificationService *>(user_data);
|
||||
|
||||
if (g_strcmp0(interface_name, kNotificationsInterface) != 0) {
|
||||
g_dbus_method_invocation_return_dbus_error(
|
||||
invocation,
|
||||
"org.freedesktop.DBus.Error.UnknownInterface",
|
||||
"Unknown interface");
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_strcmp0(method_name, "Notify") == 0) {
|
||||
const gchar *app_name = "";
|
||||
guint32 replaces_id = 0;
|
||||
const gchar *app_icon = "";
|
||||
const gchar *summary = "";
|
||||
const gchar *body = "";
|
||||
GVariant *actions = nullptr;
|
||||
GVariant *hints = nullptr;
|
||||
gint32 expire_timeout = -1;
|
||||
|
||||
g_variant_get(parameters, "(&su&s&s&s@as@a{sv}i)",
|
||||
&app_name,
|
||||
&replaces_id,
|
||||
&app_icon,
|
||||
&summary,
|
||||
&body,
|
||||
&actions,
|
||||
&hints,
|
||||
&expire_timeout);
|
||||
|
||||
std::cout << "--- Notification ---" << std::endl;
|
||||
std::cout << "App: " << (app_name ? app_name : "") << std::endl;
|
||||
std::cout << "Title: " << (summary ? summary : "") << std::endl;
|
||||
std::cout << "Body: " << (body ? body : "") << std::endl;
|
||||
|
||||
if (actions)
|
||||
g_variant_unref(actions);
|
||||
if (hints)
|
||||
g_variant_unref(hints);
|
||||
|
||||
guint32 id = self->allocateNotificationId(replaces_id);
|
||||
g_dbus_method_invocation_return_value(invocation, g_variant_new("(u)", id));
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_strcmp0(method_name, "GetCapabilities") == 0) {
|
||||
// Advertise common capabilities so clients don't disable notifications.
|
||||
// (Many apps probe this first and may skip Notify if it's empty.)
|
||||
const gchar *caps[] = {
|
||||
"body",
|
||||
"actions",
|
||||
"body-markup",
|
||||
"icon-static",
|
||||
"persistence",
|
||||
nullptr};
|
||||
GVariant *capsV = g_variant_new_strv(caps, -1);
|
||||
g_dbus_method_invocation_return_value(invocation, g_variant_new("(@as)", capsV));
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_strcmp0(method_name, "GetServerInformation") == 0) {
|
||||
g_dbus_method_invocation_return_value(
|
||||
invocation,
|
||||
g_variant_new("(ssss)", "bar", "bar", "0.1", "1.2"));
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_strcmp0(method_name, "CloseNotification") == 0) {
|
||||
guint32 id = 0;
|
||||
g_variant_get(parameters, "(u)", &id);
|
||||
|
||||
// reason: 3 = closed by call to CloseNotification
|
||||
if (self && self->getConnection()) {
|
||||
g_dbus_connection_emit_signal(
|
||||
self->getConnection(),
|
||||
nullptr,
|
||||
kNotificationsObjectPath,
|
||||
kNotificationsInterface,
|
||||
"NotificationClosed",
|
||||
g_variant_new("(uu)", id, 3u),
|
||||
nullptr);
|
||||
}
|
||||
|
||||
g_dbus_method_invocation_return_value(invocation, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
g_dbus_method_invocation_return_dbus_error(
|
||||
invocation,
|
||||
"org.freedesktop.DBus.Error.UnknownMethod",
|
||||
"Unknown method");
|
||||
}
|
||||
|
||||
guint32 NotificationService::allocateNotificationId(guint32 replacesId) {
|
||||
if (replacesId != 0)
|
||||
return replacesId;
|
||||
return this->nextNotificationId++;
|
||||
}
|
||||
|
||||
static const GDBusInterfaceVTable kVTable = {
|
||||
.method_call = on_method_call,
|
||||
.get_property = nullptr,
|
||||
.set_property = nullptr,
|
||||
};
|
||||
|
||||
NotificationService::~NotificationService() {
|
||||
if (this->connection) {
|
||||
// Best-effort release of the well-known name.
|
||||
{
|
||||
GError *error = nullptr;
|
||||
GVariant *releaseResult = g_dbus_connection_call_sync(
|
||||
this->connection,
|
||||
"org.freedesktop.DBus",
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"ReleaseName",
|
||||
g_variant_new("(s)", "org.freedesktop.Notifications"),
|
||||
G_VARIANT_TYPE("(u)"),
|
||||
G_DBUS_CALL_FLAGS_NONE,
|
||||
-1,
|
||||
nullptr,
|
||||
&error);
|
||||
if (releaseResult)
|
||||
g_variant_unref(releaseResult);
|
||||
if (error)
|
||||
g_error_free(error);
|
||||
}
|
||||
|
||||
if (this->registrationId != 0) {
|
||||
g_dbus_connection_unregister_object(this->connection, this->registrationId);
|
||||
this->registrationId = 0;
|
||||
}
|
||||
|
||||
g_object_unref(this->connection);
|
||||
this->connection = nullptr;
|
||||
}
|
||||
|
||||
if (this->nodeInfo) {
|
||||
g_dbus_node_info_unref(this->nodeInfo);
|
||||
this->nodeInfo = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void NotificationService::intialize() {
|
||||
GError *error = nullptr;
|
||||
|
||||
if (this->connection) {
|
||||
return;
|
||||
}
|
||||
|
||||
gchar *address = g_dbus_address_get_for_bus_sync(G_BUS_TYPE_SESSION, nullptr, &error);
|
||||
if (!address) {
|
||||
std::cerr << "Failed to get session bus address: " << (error ? error->message : "unknown error") << std::endl;
|
||||
if (error)
|
||||
g_error_free(error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
g_error_free(error);
|
||||
error = nullptr;
|
||||
}
|
||||
|
||||
this->connection = g_dbus_connection_new_for_address_sync(
|
||||
address,
|
||||
static_cast<GDBusConnectionFlags>(
|
||||
G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
|
||||
G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION),
|
||||
nullptr,
|
||||
nullptr,
|
||||
&error);
|
||||
g_free(address);
|
||||
|
||||
if (!this->connection) {
|
||||
std::cerr << "Failed to connect to session bus: " << (error ? error->message : "unknown error") << std::endl;
|
||||
if (error)
|
||||
g_error_free(error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
g_error_free(error);
|
||||
error = nullptr;
|
||||
}
|
||||
|
||||
this->nodeInfo = g_dbus_node_info_new_for_xml(kNotificationsIntrospectionXml, &error);
|
||||
if (!this->nodeInfo) {
|
||||
std::cerr << "Failed to create introspection data: " << (error ? error->message : "unknown error") << std::endl;
|
||||
if (error)
|
||||
g_error_free(error);
|
||||
return;
|
||||
}
|
||||
|
||||
GDBusInterfaceInfo *iface = g_dbus_node_info_lookup_interface(this->nodeInfo, kNotificationsInterface);
|
||||
if (!iface) {
|
||||
std::cerr << "Missing interface info for org.freedesktop.Notifications" << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
this->registrationId = g_dbus_connection_register_object(
|
||||
this->connection,
|
||||
kNotificationsObjectPath,
|
||||
iface,
|
||||
&kVTable,
|
||||
this,
|
||||
nullptr,
|
||||
&error);
|
||||
|
||||
if (this->registrationId == 0) {
|
||||
std::cerr << "Failed to register notifications object: " << (error ? error->message : "unknown error") << std::endl;
|
||||
if (error)
|
||||
g_error_free(error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Request the well-known name synchronously so we can detect conflicts.
|
||||
// Reply codes: 1=PRIMARY_OWNER, 2=IN_QUEUE, 3=EXISTS, 4=ALREADY_OWNER
|
||||
GVariant *requestResult = g_dbus_connection_call_sync(
|
||||
this->connection,
|
||||
"org.freedesktop.DBus",
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"RequestName",
|
||||
g_variant_new("(su)", "org.freedesktop.Notifications", 0u),
|
||||
G_VARIANT_TYPE("(u)"),
|
||||
G_DBUS_CALL_FLAGS_NONE,
|
||||
-1,
|
||||
nullptr,
|
||||
&error);
|
||||
|
||||
if (!requestResult) {
|
||||
std::cerr << "Failed to RequestName(org.freedesktop.Notifications): "
|
||||
<< (error ? error->message : "unknown error") << std::endl;
|
||||
if (error)
|
||||
g_error_free(error);
|
||||
return;
|
||||
}
|
||||
|
||||
guint32 reply = 0;
|
||||
g_variant_get(requestResult, "(u)", &reply);
|
||||
g_variant_unref(requestResult);
|
||||
|
||||
if (reply != 1u && reply != 4u) {
|
||||
std::cerr << "org.freedesktop.Notifications is already owned (RequestName reply=" << reply
|
||||
<< "). Stop your existing notification daemon (e.g. dunst/mako/swaync) or allow replacement." << std::endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <sqlite3.h>
|
||||
|
||||
#include "services/todoAdapter.hpp"
|
||||
|
||||
namespace {
|
||||
std::string getDbPath() {
|
||||
const char *homeDir = getenv("HOME");
|
||||
if (!homeDir) {
|
||||
return "todos.db";
|
||||
}
|
||||
|
||||
std::string path = std::string(homeDir) + "/.config/bar";
|
||||
if (!std::filesystem::exists(path)) {
|
||||
std::filesystem::create_directories(path);
|
||||
}
|
||||
|
||||
return path + "/todos.db";
|
||||
}
|
||||
|
||||
class SqliteTodoAdapter final : public ITodoAdapter {
|
||||
public:
|
||||
~SqliteTodoAdapter() override {
|
||||
if (db_) {
|
||||
sqlite3_close(db_);
|
||||
db_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool init() override {
|
||||
std::string dbPath = getDbPath();
|
||||
|
||||
int rc = sqlite3_open(dbPath.c_str(), &db_);
|
||||
if (rc != SQLITE_OK) {
|
||||
std::cerr << "Can't open database: " << sqlite3_errmsg(db_) << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *sql = "CREATE TABLE IF NOT EXISTS todos ("
|
||||
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
|
||||
"text TEXT NOT NULL);";
|
||||
char *zErrMsg = nullptr;
|
||||
rc = sqlite3_exec(db_, sql, nullptr, nullptr, &zErrMsg);
|
||||
if (rc != SQLITE_OK) {
|
||||
std::cerr << "SQL error (create table): " << (zErrMsg ? zErrMsg : "") << std::endl;
|
||||
sqlite3_free(zErrMsg);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<TodoRecord> listTodos() override {
|
||||
std::vector<TodoRecord> results;
|
||||
if (!db_) {
|
||||
return results;
|
||||
}
|
||||
|
||||
sqlite3_stmt *stmt = nullptr;
|
||||
const char *sql = "SELECT id, text FROM todos";
|
||||
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
|
||||
if (rc != SQLITE_OK) {
|
||||
std::cerr << "Failed to fetch data: " << sqlite3_errmsg(db_) << std::endl;
|
||||
return results;
|
||||
}
|
||||
|
||||
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
|
||||
int id = sqlite3_column_int(stmt, 0);
|
||||
const unsigned char *txt = sqlite3_column_text(stmt, 1);
|
||||
results.push_back({id, txt ? reinterpret_cast<const char *>(txt) : ""});
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return results;
|
||||
}
|
||||
|
||||
int addTodo(const std::string &text) override {
|
||||
if (!db_) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_stmt *stmt = nullptr;
|
||||
const char *sql = "INSERT INTO todos (text) VALUES (?1);";
|
||||
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
|
||||
if (rc != SQLITE_OK) {
|
||||
std::cerr << "SQL prepare error (insert): " << sqlite3_errmsg(db_) << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_bind_text(stmt, 1, text.c_str(), -1, SQLITE_TRANSIENT);
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE) {
|
||||
std::cerr << "SQL step error (insert): " << sqlite3_errmsg(db_) << std::endl;
|
||||
sqlite3_finalize(stmt);
|
||||
return -1;
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return static_cast<int>(sqlite3_last_insert_rowid(db_));
|
||||
}
|
||||
|
||||
bool removeTodo(int id) override {
|
||||
if (!db_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_stmt *stmt = nullptr;
|
||||
const char *sql = "DELETE FROM todos WHERE id = ?1;";
|
||||
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
|
||||
if (rc != SQLITE_OK) {
|
||||
std::cerr << "SQL prepare error (delete): " << sqlite3_errmsg(db_) << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_bind_int(stmt, 1, id);
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE) {
|
||||
std::cerr << "SQL step error (delete): " << sqlite3_errmsg(db_) << std::endl;
|
||||
sqlite3_finalize(stmt);
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool updateTodo(int id, const std::string &text) override {
|
||||
if (!db_) {
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_stmt *stmt = nullptr;
|
||||
const char *sql = "UPDATE todos SET text = ?1 WHERE id = ?2;";
|
||||
int rc = sqlite3_prepare_v2(db_, sql, -1, &stmt, nullptr);
|
||||
if (rc != SQLITE_OK) {
|
||||
std::cerr << "SQL prepare error (update): " << sqlite3_errmsg(db_) << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_bind_text(stmt, 1, text.c_str(), -1, SQLITE_TRANSIENT);
|
||||
sqlite3_bind_int(stmt, 2, id);
|
||||
rc = sqlite3_step(stmt);
|
||||
if (rc != SQLITE_DONE) {
|
||||
std::cerr << "SQL step error (update): " << sqlite3_errmsg(db_) << std::endl;
|
||||
sqlite3_finalize(stmt);
|
||||
return false;
|
||||
}
|
||||
|
||||
sqlite3_finalize(stmt);
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
sqlite3 *db_ = nullptr;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
// Factory kept local to this TU for now; TodoService uses it.
|
||||
std::unique_ptr<ITodoAdapter> makeSqliteTodoAdapter() {
|
||||
return std::make_unique<SqliteTodoAdapter>();
|
||||
}
|
||||
223
src/services/textureCache.cpp
Normal file
223
src/services/textureCache.cpp
Normal file
@@ -0,0 +1,223 @@
|
||||
#include "services/textureCache.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <curl/curl.h>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#include "giomm/file.h"
|
||||
#include "glibmm/bytes.h"
|
||||
|
||||
namespace {
|
||||
#define CACHE_SIZE 128
|
||||
#define CACHE_AGE 168
|
||||
|
||||
constexpr std::uint64_t kFnvOffsetBasis = 14695981039346656037ull;
|
||||
constexpr std::uint64_t kFnvPrime = 1099511628211ull;
|
||||
|
||||
std::string to_hex(std::uint64_t value) {
|
||||
std::ostringstream stream;
|
||||
stream << std::hex << std::setw(16) << std::setfill('0') << value;
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
std::string hash_url(const std::string &url) {
|
||||
std::uint64_t hash = kFnvOffsetBasis;
|
||||
for (unsigned char c : url) {
|
||||
hash ^= c;
|
||||
hash *= kFnvPrime;
|
||||
}
|
||||
return to_hex(hash);
|
||||
}
|
||||
|
||||
std::filesystem::path get_cache_dir() {
|
||||
const char *xdg_cache = std::getenv("XDG_CACHE_HOME");
|
||||
if (xdg_cache && *xdg_cache) {
|
||||
return std::filesystem::path(xdg_cache) / "bar";
|
||||
}
|
||||
|
||||
const char *home = std::getenv("HOME");
|
||||
if (home && *home) {
|
||||
return std::filesystem::path(home) / ".cache" / "bar";
|
||||
}
|
||||
|
||||
return std::filesystem::temp_directory_path() / "bar";
|
||||
}
|
||||
|
||||
std::filesystem::path get_cache_path_for_url(const std::string &url) {
|
||||
auto filename = hash_url(url);
|
||||
|
||||
auto last_slash = url.find_last_of('/');
|
||||
auto last_dot = url.find_last_of('.');
|
||||
if (last_dot != std::string::npos && (last_slash == std::string::npos || last_dot > last_slash)) {
|
||||
auto ext = url.substr(last_dot);
|
||||
if (ext.size() <= 10) {
|
||||
filename += ext;
|
||||
}
|
||||
}
|
||||
|
||||
return get_cache_dir() / filename;
|
||||
}
|
||||
|
||||
std::chrono::system_clock::time_point to_system_clock(std::filesystem::file_time_type time) {
|
||||
return std::chrono::time_point_cast<std::chrono::system_clock::duration>(
|
||||
time - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now()
|
||||
);
|
||||
}
|
||||
|
||||
size_t write_to_buffer(void *contents, size_t size, size_t nmemb, void *userp) {
|
||||
auto *buffer = static_cast<std::vector<unsigned char> *>(userp);
|
||||
auto total = size * nmemb;
|
||||
auto *bytes = static_cast<unsigned char *>(contents);
|
||||
buffer->insert(buffer->end(), bytes, bytes + total);
|
||||
return total;
|
||||
}
|
||||
|
||||
Glib::RefPtr<Gdk::Texture> load_texture_from_file(const std::filesystem::path &path) {
|
||||
if (!std::filesystem::exists(path)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
auto file = Gio::File::create_for_path(path.string());
|
||||
try {
|
||||
return Gdk::Texture::create_from_file(file);
|
||||
} catch (...) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Glib::RefPtr<Gdk::Texture> download_texture_from_url(const std::string &url, const std::filesystem::path &path) {
|
||||
if (url.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
CURL *curl = curl_easy_init();
|
||||
if (!curl) {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<unsigned char> buffer;
|
||||
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
|
||||
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_buffer);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
|
||||
curl_easy_setopt(curl, CURLOPT_USERAGENT, "bar/1.0");
|
||||
|
||||
auto res = curl_easy_perform(curl);
|
||||
curl_easy_cleanup(curl);
|
||||
|
||||
if (res != CURLE_OK || buffer.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::error_code error;
|
||||
std::filesystem::create_directories(path.parent_path(), error);
|
||||
|
||||
std::ofstream output(path, std::ios::binary | std::ios::trunc);
|
||||
if (output) {
|
||||
output.write(reinterpret_cast<const char *>(buffer.data()), static_cast<std::streamsize>(buffer.size()));
|
||||
}
|
||||
|
||||
auto bytes = Glib::Bytes::create(buffer.data(), buffer.size());
|
||||
return Gdk::Texture::create_from_bytes(bytes);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TextureCacheService *TextureCacheService::getInstance() {
|
||||
static TextureCacheService instance;
|
||||
return &instance;
|
||||
}
|
||||
|
||||
Glib::RefPtr<Gdk::Texture> TextureCacheService::getTexture(const std::string &url) {
|
||||
if (url.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
auto it = cache.find(url);
|
||||
if (it != cache.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
auto cache_path = get_cache_path_for_url(url);
|
||||
auto texture = load_texture_from_file(cache_path);
|
||||
if (!texture) {
|
||||
texture = download_texture_from_url(url, cache_path);
|
||||
}
|
||||
|
||||
if (texture) {
|
||||
cache.emplace(url, texture);
|
||||
std::error_code error;
|
||||
std::filesystem::last_write_time(cache_path, std::filesystem::file_time_type::clock::now(), error);
|
||||
}
|
||||
|
||||
return texture;
|
||||
}
|
||||
|
||||
void TextureCacheService::pruneCache() {
|
||||
std::error_code error;
|
||||
auto cache_dir = get_cache_dir();
|
||||
std::filesystem::create_directories(cache_dir, error);
|
||||
|
||||
std::vector<std::pair<std::filesystem::path, std::uintmax_t>> files;
|
||||
std::uintmax_t total_size = 0;
|
||||
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto max_age = std::chrono::hours(CACHE_AGE);
|
||||
|
||||
for (const auto &entry : std::filesystem::directory_iterator(cache_dir, error)) {
|
||||
if (error || !entry.is_regular_file()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
auto path = entry.path();
|
||||
auto last_write = entry.last_write_time(error);
|
||||
if (!error) {
|
||||
auto age = now - to_system_clock(last_write);
|
||||
if (age > max_age) {
|
||||
std::filesystem::remove(path, error);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
auto size = entry.file_size(error);
|
||||
if (!error) {
|
||||
total_size += size;
|
||||
files.emplace_back(path, size);
|
||||
}
|
||||
}
|
||||
|
||||
auto max_size = static_cast<std::uintmax_t>(CACHE_SIZE) * 1024ull * 1024ull;
|
||||
if (total_size <= max_size) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::sort(files.begin(), files.end(), [&](const auto &left, const auto &right) {
|
||||
std::error_code left_error;
|
||||
std::error_code right_error;
|
||||
auto left_time = std::filesystem::last_write_time(left.first, left_error);
|
||||
auto right_time = std::filesystem::last_write_time(right.first, right_error);
|
||||
if (left_error || right_error) {
|
||||
return left.first.string() < right.first.string();
|
||||
}
|
||||
return left_time < right_time;
|
||||
});
|
||||
|
||||
for (const auto &item : files) {
|
||||
if (total_size <= max_size) {
|
||||
break;
|
||||
}
|
||||
std::filesystem::remove(item.first, error);
|
||||
if (!error) {
|
||||
if (total_size >= item.second) {
|
||||
total_size -= item.second;
|
||||
} else {
|
||||
total_size = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
#include "services/todo.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <gtkmm/object.h>
|
||||
|
||||
#include "components/todoEntry.hpp"
|
||||
|
||||
std::unique_ptr<ITodoAdapter> makeSqliteTodoAdapter();
|
||||
|
||||
TodoService::TodoService(sigc::signal<void()> refreshSignal) {
|
||||
this->refreshSignal = refreshSignal;
|
||||
this->adapter = makeSqliteTodoAdapter();
|
||||
this->init();
|
||||
}
|
||||
|
||||
TodoService::~TodoService() {
|
||||
this->adapter.reset();
|
||||
}
|
||||
|
||||
std::map<int, TodoEntry *> TodoService::getTodos() {
|
||||
return this->todos;
|
||||
}
|
||||
|
||||
void TodoService::init() {
|
||||
if (!this->adapter) {
|
||||
std::cerr << "Todo adapter not set" << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this->adapter->init()) {
|
||||
std::cerr << "Todo adapter init failed" << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
this->load();
|
||||
}
|
||||
|
||||
void TodoService::removeTodo(int id) {
|
||||
if (todos.find(id) == todos.end()) {
|
||||
std::cerr << "Todo with id " << id << " not found!" << std::endl;
|
||||
assert(false);
|
||||
}
|
||||
|
||||
if (this->adapter) {
|
||||
this->adapter->removeTodo(id);
|
||||
}
|
||||
|
||||
todos.erase(id);
|
||||
this->refreshSignal.emit();
|
||||
}
|
||||
|
||||
TodoEntry *TodoService::addTodo(std::string text, bool emitSignal, bool persist) {
|
||||
int id = nextId;
|
||||
|
||||
if (persist) {
|
||||
if (!this->adapter) {
|
||||
return nullptr;
|
||||
}
|
||||
int newId = this->adapter->addTodo(text);
|
||||
if (newId < 0) {
|
||||
return nullptr;
|
||||
}
|
||||
id = newId;
|
||||
}
|
||||
|
||||
auto dismissSignal = sigc::signal<void(int)>();
|
||||
dismissSignal.connect(sigc::mem_fun(*this, &TodoService::removeTodo));
|
||||
|
||||
auto editSignal = sigc::signal<void(int, std::string)>();
|
||||
editSignal.connect(sigc::mem_fun(*this, &TodoService::updateTodo));
|
||||
|
||||
TodoEntry *todo = Gtk::make_managed<TodoEntry>(id, text, dismissSignal, editSignal);
|
||||
|
||||
todos[id] = todo;
|
||||
|
||||
if (id >= nextId) {
|
||||
nextId = id + 1;
|
||||
}
|
||||
|
||||
if (emitSignal) {
|
||||
this->refreshSignal.emit();
|
||||
}
|
||||
|
||||
return todo;
|
||||
}
|
||||
|
||||
void TodoService::updateTodo(int id, std::string text) {
|
||||
if (todos.find(id) == todos.end()) {
|
||||
std::cerr << "Todo with id " << id << " not found!" << std::endl;
|
||||
assert(false);
|
||||
}
|
||||
|
||||
if (this->adapter) {
|
||||
this->adapter->updateTodo(id, text);
|
||||
}
|
||||
|
||||
this->refreshSignal.emit();
|
||||
}
|
||||
|
||||
void TodoService::load() {
|
||||
if (!this->adapter) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto rows = this->adapter->listTodos();
|
||||
|
||||
int count = 0;
|
||||
|
||||
for (const auto &row : rows) {
|
||||
count++;
|
||||
int id = row.id;
|
||||
std::string text = row.text;
|
||||
|
||||
auto dismissSignal = sigc::signal<void(int)>();
|
||||
dismissSignal.connect(sigc::mem_fun(*this, &TodoService::removeTodo));
|
||||
|
||||
auto editSignal = sigc::signal<void(int, std::string)>();
|
||||
editSignal.connect(sigc::mem_fun(*this, &TodoService::updateTodo));
|
||||
|
||||
TodoEntry *todo = Gtk::make_managed<TodoEntry>(id, text, dismissSignal, editSignal);
|
||||
|
||||
todos[id] = todo;
|
||||
if (id >= nextId) {
|
||||
nextId = id + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
#include <giomm/dbusactiongroup.h>
|
||||
#include <giomm/dbusownname.h>
|
||||
#include <giomm/menumodel.h>
|
||||
#include <iostream>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <memory>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
@@ -21,6 +22,11 @@ constexpr const char *kItemInterface = "org.kde.StatusNotifierItem";
|
||||
constexpr const char *kDBusPropertiesIface = "org.freedesktop.DBus.Properties";
|
||||
constexpr const char *kDBusMenuInterface = "com.canonical.dbusmenu";
|
||||
|
||||
constexpr int kDBusTimeoutMs = 1500;
|
||||
constexpr int kDBusMenuTimeoutMs = 2000;
|
||||
constexpr int kRefreshDebounceMs = 50;
|
||||
constexpr int kAboutToShowTimeoutMs = 800;
|
||||
|
||||
const char *kWatcherIntrospection =
|
||||
R"(<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-Bus Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
|
||||
<node>
|
||||
@@ -105,53 +111,43 @@ void call_about_to_show(const Glib::RefPtr<Gio::DBus::Connection> &connection,
|
||||
return;
|
||||
}
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *result = g_dbus_connection_call_sync(
|
||||
connection->gobj(), busName.c_str(), menuPath.c_str(),
|
||||
kDBusMenuInterface, "AboutToShow", g_variant_new("(i)", id), nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
|
||||
if (result) {
|
||||
g_variant_unref(result);
|
||||
}
|
||||
if (error) {
|
||||
std::cerr << "[TrayService] AboutToShow failed for " << busName
|
||||
<< menuPath << " (" << id << "): " << error->message
|
||||
<< std::endl;
|
||||
g_error_free(error);
|
||||
}
|
||||
g_dbus_connection_call(connection->gobj(), busName.c_str(), menuPath.c_str(),
|
||||
kDBusMenuInterface, "AboutToShow",
|
||||
g_variant_new("(i)", id), nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE, kAboutToShowTimeoutMs,
|
||||
nullptr, nullptr, nullptr);
|
||||
}
|
||||
|
||||
GVariant *call_get_layout(const Glib::RefPtr<Gio::DBus::Connection> &connection,
|
||||
const std::string &busName,
|
||||
const std::string &menuPath) {
|
||||
if (!connection) {
|
||||
return nullptr;
|
||||
struct SimpleCallData {
|
||||
std::string debugLabel;
|
||||
bool ignoreUnknownMethod = false;
|
||||
};
|
||||
|
||||
void on_simple_call_finished(GObject *source, GAsyncResult *res,
|
||||
gpointer user_data) {
|
||||
std::unique_ptr<SimpleCallData> data(
|
||||
static_cast<SimpleCallData *>(user_data));
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *reply =
|
||||
g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error);
|
||||
|
||||
if (reply) {
|
||||
g_variant_unref(reply);
|
||||
}
|
||||
|
||||
GVariant *properties = create_property_list_variant();
|
||||
if (!properties) {
|
||||
return nullptr;
|
||||
if (!error) {
|
||||
return;
|
||||
}
|
||||
|
||||
GVariant *params = g_variant_new("(ii@as)", 0, -1, properties);
|
||||
g_variant_ref_sink(properties);
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *result = g_dbus_connection_call_sync(
|
||||
connection->gobj(), busName.c_str(), menuPath.c_str(),
|
||||
kDBusMenuInterface, "GetLayout", params, nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
|
||||
|
||||
g_variant_unref(properties);
|
||||
|
||||
if (error) {
|
||||
std::cerr << "[TrayService] GetLayout failed for " << busName
|
||||
<< menuPath << ": " << error->message << std::endl;
|
||||
g_error_free(error);
|
||||
return nullptr;
|
||||
const bool isUnknownMethod =
|
||||
(error->domain == G_DBUS_ERROR && error->code == G_DBUS_ERROR_UNKNOWN_METHOD);
|
||||
if (!(data && data->ignoreUnknownMethod && isUnknownMethod)) {
|
||||
spdlog::error("[TrayService] {} failed: {}",
|
||||
(data ? data->debugLabel : std::string("D-Bus call")),
|
||||
error->message);
|
||||
}
|
||||
|
||||
return result;
|
||||
g_error_free(error);
|
||||
}
|
||||
|
||||
void parse_menu_node(GVariant *tuple, TrayService::MenuNode &outNode) {
|
||||
@@ -292,8 +288,9 @@ void TrayService::start() {
|
||||
nodeInfo =
|
||||
Gio::DBus::NodeInfo::create_for_xml(kWatcherIntrospection);
|
||||
} catch (const Glib::Error &err) {
|
||||
std::cerr << "[TrayService] Failed to parse introspection data: "
|
||||
<< err.what() << std::endl;
|
||||
spdlog::error(
|
||||
"[TrayService] Failed to parse introspection data: {}",
|
||||
err.what());
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -308,6 +305,10 @@ void TrayService::start() {
|
||||
void TrayService::stop() {
|
||||
if (connection) {
|
||||
for (auto &pair : items) {
|
||||
if (pair.second->refreshSourceId != 0) {
|
||||
g_source_remove(pair.second->refreshSourceId);
|
||||
pair.second->refreshSourceId = 0;
|
||||
}
|
||||
if (pair.second->signalSubscriptionId != 0) {
|
||||
g_dbus_connection_signal_unsubscribe(
|
||||
connection->gobj(), pair.second->signalSubscriptionId);
|
||||
@@ -361,22 +362,14 @@ void TrayService::activate(const std::string &id, int32_t x, int32_t y) {
|
||||
return;
|
||||
}
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *result = g_dbus_connection_call_sync(
|
||||
auto data = new SimpleCallData();
|
||||
data->debugLabel = "Activate(" + id + ")";
|
||||
data->ignoreUnknownMethod = false;
|
||||
g_dbus_connection_call(
|
||||
connection->gobj(), it->second->publicData.busName.c_str(),
|
||||
it->second->publicData.objectPath.c_str(), kItemInterface, "Activate",
|
||||
g_variant_new("(ii)", x, y), nullptr, G_DBUS_CALL_FLAGS_NONE, -1,
|
||||
nullptr, &error);
|
||||
|
||||
if (result) {
|
||||
g_variant_unref(result);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
std::cerr << "[TrayService] Activate failed for " << id << ": "
|
||||
<< error->message << std::endl;
|
||||
g_error_free(error);
|
||||
}
|
||||
g_variant_new("(ii)", x, y), nullptr, G_DBUS_CALL_FLAGS_NONE,
|
||||
kDBusTimeoutMs, nullptr, &on_simple_call_finished, data);
|
||||
}
|
||||
|
||||
void TrayService::secondaryActivate(const std::string &id, int32_t x,
|
||||
@@ -386,22 +379,15 @@ void TrayService::secondaryActivate(const std::string &id, int32_t x,
|
||||
return;
|
||||
}
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *result = g_dbus_connection_call_sync(
|
||||
auto data = new SimpleCallData();
|
||||
data->debugLabel = "SecondaryActivate(" + id + ")";
|
||||
data->ignoreUnknownMethod = false;
|
||||
g_dbus_connection_call(
|
||||
connection->gobj(), it->second->publicData.busName.c_str(),
|
||||
it->second->publicData.objectPath.c_str(), kItemInterface,
|
||||
"SecondaryActivate", g_variant_new("(ii)", x, y), nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
|
||||
|
||||
if (result) {
|
||||
g_variant_unref(result);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
std::cerr << "[TrayService] SecondaryActivate failed for " << id << ": "
|
||||
<< error->message << std::endl;
|
||||
g_error_free(error);
|
||||
}
|
||||
G_DBUS_CALL_FLAGS_NONE, kDBusTimeoutMs, nullptr,
|
||||
&on_simple_call_finished, data);
|
||||
}
|
||||
|
||||
void TrayService::contextMenu(const std::string &id, int32_t x, int32_t y) {
|
||||
@@ -410,25 +396,15 @@ void TrayService::contextMenu(const std::string &id, int32_t x, int32_t y) {
|
||||
return;
|
||||
}
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *result = g_dbus_connection_call_sync(
|
||||
auto data = new SimpleCallData();
|
||||
data->debugLabel = "ContextMenu(" + id + ")";
|
||||
data->ignoreUnknownMethod = true;
|
||||
g_dbus_connection_call(
|
||||
connection->gobj(), it->second->publicData.busName.c_str(),
|
||||
it->second->publicData.objectPath.c_str(), kItemInterface,
|
||||
"ContextMenu", g_variant_new("(ii)", x, y), nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
|
||||
|
||||
if (result) {
|
||||
g_variant_unref(result);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
if (!(error->domain == G_DBUS_ERROR &&
|
||||
error->code == G_DBUS_ERROR_UNKNOWN_METHOD)) {
|
||||
std::cerr << "[TrayService] ContextMenu failed for " << id << ": "
|
||||
<< error->message << std::endl;
|
||||
}
|
||||
g_error_free(error);
|
||||
}
|
||||
G_DBUS_CALL_FLAGS_NONE, kDBusTimeoutMs, nullptr,
|
||||
&on_simple_call_finished, data);
|
||||
}
|
||||
|
||||
Glib::RefPtr<Gio::MenuModel>
|
||||
@@ -485,42 +461,110 @@ TrayService::get_menu_action_group(const std::string &id) {
|
||||
return item.menuActions;
|
||||
}
|
||||
|
||||
std::optional<TrayService::MenuNode>
|
||||
TrayService::get_menu_layout(const std::string &id) {
|
||||
struct MenuLayoutCallData {
|
||||
TrayService *self = nullptr;
|
||||
std::string id;
|
||||
std::string busName;
|
||||
std::string menuPath;
|
||||
TrayService::MenuLayoutCallback callback;
|
||||
};
|
||||
|
||||
void on_menu_layout_finished(GObject *source, GAsyncResult *res,
|
||||
gpointer user_data) {
|
||||
std::unique_ptr<MenuLayoutCallData> data(
|
||||
static_cast<MenuLayoutCallData *>(user_data));
|
||||
if (!data || !data->self) {
|
||||
return;
|
||||
}
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *reply =
|
||||
g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error);
|
||||
|
||||
if (error) {
|
||||
if (data->callback) {
|
||||
data->callback(std::nullopt);
|
||||
}
|
||||
g_error_free(error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!reply) {
|
||||
if (data->callback) {
|
||||
data->callback(std::nullopt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
GVariant *rootTuple = g_variant_get_child_value(reply, 1);
|
||||
g_variant_unref(reply);
|
||||
|
||||
if (!rootTuple) {
|
||||
if (data->callback) {
|
||||
data->callback(std::nullopt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
TrayService::MenuNode rootNode;
|
||||
parse_menu_node(rootTuple, rootNode);
|
||||
g_variant_unref(rootTuple);
|
||||
|
||||
if (data->callback) {
|
||||
data->callback(std::make_optional(std::move(rootNode)));
|
||||
}
|
||||
}
|
||||
|
||||
void TrayService::request_menu_layout(const std::string &id,
|
||||
MenuLayoutCallback callback) {
|
||||
auto it = items.find(id);
|
||||
if (it == items.end() || !connection) {
|
||||
return std::nullopt;
|
||||
if (callback) {
|
||||
callback(std::nullopt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
auto &item = *it->second;
|
||||
if (!item.publicData.menuAvailable || item.publicData.menuPath.empty()) {
|
||||
return std::nullopt;
|
||||
if (callback) {
|
||||
callback(std::nullopt);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
call_about_to_show(connection, item.publicData.busName,
|
||||
item.publicData.menuPath, 0);
|
||||
|
||||
GVariant *result = call_get_layout(connection, item.publicData.busName,
|
||||
item.publicData.menuPath);
|
||||
if (!result) {
|
||||
return std::nullopt;
|
||||
auto data = new MenuLayoutCallData();
|
||||
data->self = this;
|
||||
data->id = id;
|
||||
data->busName = item.publicData.busName;
|
||||
data->menuPath = item.publicData.menuPath;
|
||||
data->callback = std::move(callback);
|
||||
|
||||
GVariant *properties = create_property_list_variant();
|
||||
if (!properties) {
|
||||
if (data->callback) {
|
||||
data->callback(std::nullopt);
|
||||
}
|
||||
delete data;
|
||||
return;
|
||||
}
|
||||
|
||||
GVariant *rootTuple = g_variant_get_child_value(result, 1);
|
||||
g_variant_unref(result);
|
||||
// g_variant_new consumes the floating reference for '@as'.
|
||||
GVariant *params = g_variant_new("(ii@as)", 0, -1, properties);
|
||||
|
||||
if (!rootTuple) {
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
MenuNode rootNode;
|
||||
parse_menu_node(rootTuple, rootNode);
|
||||
g_variant_unref(rootTuple);
|
||||
|
||||
return rootNode;
|
||||
g_dbus_connection_call(connection->gobj(), data->busName.c_str(),
|
||||
data->menuPath.c_str(), kDBusMenuInterface,
|
||||
"GetLayout", params, nullptr,
|
||||
G_DBUS_CALL_FLAGS_NONE, kDBusMenuTimeoutMs, nullptr,
|
||||
&on_menu_layout_finished, data);
|
||||
}
|
||||
|
||||
bool TrayService::activate_menu_item(const std::string &id, int itemId) {
|
||||
bool TrayService::activate_menu_item(const std::string &id, int itemId,
|
||||
int32_t x, int32_t y, uint32_t button,
|
||||
uint32_t timestampMs) {
|
||||
auto it = items.find(id);
|
||||
if (it == items.end() || !connection) {
|
||||
return false;
|
||||
@@ -531,28 +575,44 @@ bool TrayService::activate_menu_item(const std::string &id, int itemId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GVariant *emptyData =
|
||||
g_variant_new_array(G_VARIANT_TYPE("{sv}"), nullptr, 0);
|
||||
GVariant *params = g_variant_new(
|
||||
"(isvu)", itemId, "clicked", g_variant_new_variant(emptyData),
|
||||
static_cast<guint32>(g_get_monotonic_time() / 1000));
|
||||
const guint32 nowMs = static_cast<guint32>(g_get_real_time() / 1000);
|
||||
const guint32 ts = timestampMs ? timestampMs : nowMs;
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *result = g_dbus_connection_call_sync(
|
||||
connection->gobj(), item.publicData.busName.c_str(),
|
||||
item.publicData.menuPath.c_str(), kDBusMenuInterface, "Event", params,
|
||||
nullptr, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
|
||||
spdlog::debug(
|
||||
"[TrayService] MenuEvent id={} item={} x={} y={} button={} tsMs={}",
|
||||
id, itemId, x, y, button, ts);
|
||||
|
||||
if (result) {
|
||||
g_variant_unref(result);
|
||||
// dbusmenu Event signature: (i s v u)
|
||||
// Some handlers (e.g., media players) look for both "timestamp" and
|
||||
// "time" keys; send both alongside coords/button when available.
|
||||
GVariantBuilder dict;
|
||||
g_variant_builder_init(&dict, G_VARIANT_TYPE("a{sv}"));
|
||||
g_variant_builder_add(&dict, "{sv}", "timestamp",
|
||||
g_variant_new_uint32(ts));
|
||||
g_variant_builder_add(&dict, "{sv}", "time", g_variant_new_uint32(ts));
|
||||
|
||||
if (x != -1 && y != -1) {
|
||||
g_variant_builder_add(&dict, "{sv}", "x", g_variant_new_int32(x));
|
||||
g_variant_builder_add(&dict, "{sv}", "y", g_variant_new_int32(y));
|
||||
}
|
||||
if (button > 0) {
|
||||
g_variant_builder_add(
|
||||
&dict, "{sv}", "button",
|
||||
g_variant_new_int32(static_cast<int32_t>(button)));
|
||||
}
|
||||
|
||||
if (error) {
|
||||
std::cerr << "[TrayService] Event failed for " << id << " (" << itemId
|
||||
<< "): " << error->message << std::endl;
|
||||
g_error_free(error);
|
||||
return false;
|
||||
}
|
||||
GVariant *payloadDict = g_variant_builder_end(&dict);
|
||||
GVariant *payload = g_variant_new_variant(payloadDict);
|
||||
GVariant *params = g_variant_new("(isvu)", itemId, "clicked",
|
||||
payload, ts);
|
||||
|
||||
auto data = new SimpleCallData();
|
||||
data->debugLabel = "MenuEvent(" + id + "," + std::to_string(itemId) + ")";
|
||||
g_dbus_connection_call(connection->gobj(), item.publicData.busName.c_str(),
|
||||
item.publicData.menuPath.c_str(), kDBusMenuInterface,
|
||||
"Event", params, nullptr, G_DBUS_CALL_FLAGS_NONE,
|
||||
kDBusMenuTimeoutMs, nullptr,
|
||||
&on_simple_call_finished, data);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -578,8 +638,7 @@ void TrayService::on_bus_acquired(
|
||||
|
||||
auto interface_info = nodeInfo->lookup_interface(kWatcherInterface);
|
||||
if (!interface_info) {
|
||||
std::cerr << "[TrayService] Missing interface info for watcher."
|
||||
<< std::endl;
|
||||
spdlog::error("[TrayService] Missing interface info for watcher.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -587,8 +646,9 @@ void TrayService::on_bus_acquired(
|
||||
registrationId = connection->register_object(kWatcherObjectPath,
|
||||
interface_info, vtable);
|
||||
} catch (const Glib::Error &err) {
|
||||
std::cerr << "[TrayService] Failed to register watcher object: "
|
||||
<< err.what() << std::endl;
|
||||
spdlog::error(
|
||||
"[TrayService] Failed to register watcher object: {}",
|
||||
err.what());
|
||||
registrationId = 0;
|
||||
return;
|
||||
}
|
||||
@@ -688,16 +748,15 @@ void TrayService::register_item(const Glib::ustring &sender,
|
||||
|
||||
ParsedService parsed = parse_service_identifier(sender, service);
|
||||
if (parsed.busName.empty() || parsed.objectPath.empty()) {
|
||||
std::cerr << "[TrayService] Invalid service registration: " << service
|
||||
<< std::endl;
|
||||
spdlog::warn("[TrayService] Invalid service registration: {}",
|
||||
service);
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string id = parsed.busName + parsed.objectPath;
|
||||
auto existing = items.find(id);
|
||||
if (existing != items.end()) {
|
||||
refresh_item(*existing->second);
|
||||
itemUpdatedSignal.emit(existing->second->publicData);
|
||||
schedule_refresh(id);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -706,7 +765,7 @@ void TrayService::register_item(const Glib::ustring &sender,
|
||||
item->publicData.busName = parsed.busName;
|
||||
item->publicData.objectPath = parsed.objectPath;
|
||||
|
||||
refresh_item(*item);
|
||||
item->addSignalPending = true;
|
||||
|
||||
item->signalSubscriptionId = g_dbus_connection_signal_subscribe(
|
||||
connection->gobj(), item->publicData.busName.c_str(), nullptr, nullptr,
|
||||
@@ -726,7 +785,7 @@ void TrayService::register_item(const Glib::ustring &sender,
|
||||
std::make_tuple(Glib::ustring(id)));
|
||||
emit_watcher_signal("StatusNotifierItemRegistered", params);
|
||||
|
||||
itemAddedSignal.emit(items.at(id)->publicData);
|
||||
schedule_refresh(id);
|
||||
}
|
||||
|
||||
void TrayService::unregister_item(const std::string &id) {
|
||||
@@ -735,6 +794,11 @@ void TrayService::unregister_item(const std::string &id) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (it->second->refreshSourceId != 0) {
|
||||
g_source_remove(it->second->refreshSourceId);
|
||||
it->second->refreshSourceId = 0;
|
||||
}
|
||||
|
||||
if (connection && it->second->signalSubscriptionId != 0) {
|
||||
g_dbus_connection_signal_unsubscribe(connection->gobj(),
|
||||
it->second->signalSubscriptionId);
|
||||
@@ -755,31 +819,59 @@ void TrayService::unregister_item(const std::string &id) {
|
||||
itemRemovedSignal.emit(id);
|
||||
}
|
||||
|
||||
void TrayService::refresh_item(TrackedItem &item) {
|
||||
if (!connection) {
|
||||
struct RefreshCallData {
|
||||
TrayService *self = nullptr;
|
||||
std::string id;
|
||||
std::string busName;
|
||||
std::string objectPath;
|
||||
};
|
||||
|
||||
void TrayService::on_refresh_finished_static(GObject *source, GAsyncResult *res,
|
||||
gpointer user_data) {
|
||||
std::unique_ptr<RefreshCallData> data(
|
||||
static_cast<RefreshCallData *>(user_data));
|
||||
if (!data || !data->self) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto it = data->self->items.find(data->id);
|
||||
if (it == data->self->items.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto &tracked = *it->second;
|
||||
|
||||
GError *error = nullptr;
|
||||
GVariant *reply = g_dbus_connection_call_sync(
|
||||
connection->gobj(), item.publicData.busName.c_str(),
|
||||
item.publicData.objectPath.c_str(), kDBusPropertiesIface, "GetAll",
|
||||
g_variant_new("(s)", kItemInterface), G_VARIANT_TYPE("(a{sv})"),
|
||||
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
|
||||
GVariant *reply =
|
||||
g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error);
|
||||
if (!reply) {
|
||||
if (error) {
|
||||
std::cerr << "[TrayService] Failed to query properties for "
|
||||
<< item.publicData.id << ": " << error->message
|
||||
<< std::endl;
|
||||
spdlog::error(
|
||||
"[TrayService] Failed to query properties for {}: {}",
|
||||
data->id, error->message);
|
||||
g_error_free(error);
|
||||
}
|
||||
|
||||
tracked.refreshInFlight = false;
|
||||
if (tracked.addSignalPending) {
|
||||
tracked.addSignalPending = false;
|
||||
data->self->itemAddedSignal.emit(tracked.publicData);
|
||||
}
|
||||
if (tracked.refreshQueued) {
|
||||
tracked.refreshQueued = false;
|
||||
data->self->schedule_refresh(data->id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
GVariant *dictVariant = g_variant_get_child_value(reply, 0);
|
||||
g_variant_unref(reply);
|
||||
|
||||
if (!dictVariant) {
|
||||
tracked.refreshInFlight = false;
|
||||
if (tracked.refreshQueued) {
|
||||
tracked.refreshQueued = false;
|
||||
data->self->schedule_refresh(data->id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -812,13 +904,8 @@ void TrayService::refresh_item(TrackedItem &item) {
|
||||
const gchar *str = g_variant_get_string(value, nullptr);
|
||||
status = str ? str : "";
|
||||
} else if (std::strcmp(key, "Menu") == 0) {
|
||||
if (g_variant_is_of_type(value, G_VARIANT_TYPE_OBJECT_PATH)) {
|
||||
const gchar *str = g_variant_get_string(value, nullptr);
|
||||
menuPath = str ? str : "";
|
||||
} else {
|
||||
const gchar *str = g_variant_get_string(value, nullptr);
|
||||
menuPath = str ? str : "";
|
||||
}
|
||||
const gchar *str = g_variant_get_string(value, nullptr);
|
||||
menuPath = str ? str : "";
|
||||
} else if (std::strcmp(key, "IconName") == 0) {
|
||||
const gchar *str = g_variant_get_string(value, nullptr);
|
||||
iconName = str ? str : "";
|
||||
@@ -826,39 +913,127 @@ void TrayService::refresh_item(TrackedItem &item) {
|
||||
const gchar *str = g_variant_get_string(value, nullptr);
|
||||
attentionIconName = str ? str : "";
|
||||
} else if (std::strcmp(key, "IconPixmap") == 0) {
|
||||
iconTexture = parse_icon_pixmap(value);
|
||||
iconTexture = TrayService::parse_icon_pixmap(value);
|
||||
} else if (std::strcmp(key, "AttentionIconPixmap") == 0) {
|
||||
attentionTexture = parse_icon_pixmap(value);
|
||||
attentionTexture = TrayService::parse_icon_pixmap(value);
|
||||
}
|
||||
|
||||
g_variant_unref(value);
|
||||
}
|
||||
|
||||
g_variant_unref(dictVariant);
|
||||
const bool menuPathChanged = (item.publicData.menuPath != menuPath);
|
||||
item.publicData.title = title;
|
||||
item.publicData.status = status;
|
||||
item.publicData.menuPath = menuPath;
|
||||
item.publicData.menuAvailable = !menuPath.empty();
|
||||
|
||||
if (menuPathChanged || !item.publicData.menuAvailable) {
|
||||
item.menuModel.reset();
|
||||
item.menuActions.reset();
|
||||
const bool menuPathChanged = (tracked.publicData.menuPath != menuPath);
|
||||
tracked.publicData.title = title;
|
||||
tracked.publicData.status = status;
|
||||
tracked.publicData.menuPath = menuPath;
|
||||
tracked.publicData.menuAvailable = !menuPath.empty();
|
||||
|
||||
if (menuPathChanged || !tracked.publicData.menuAvailable) {
|
||||
tracked.menuModel.reset();
|
||||
tracked.menuActions.reset();
|
||||
}
|
||||
item.publicData.iconName =
|
||||
|
||||
tracked.publicData.iconName =
|
||||
(status == "NeedsAttention" && !attentionIconName.empty())
|
||||
? attentionIconName
|
||||
: iconName;
|
||||
|
||||
if (status == "NeedsAttention" && attentionTexture) {
|
||||
item.publicData.iconPaintable = attentionTexture;
|
||||
tracked.publicData.iconPaintable = attentionTexture;
|
||||
} else {
|
||||
item.publicData.iconPaintable = iconTexture;
|
||||
tracked.publicData.iconPaintable = iconTexture;
|
||||
}
|
||||
|
||||
if (!item.publicData.iconPaintable && iconTexture) {
|
||||
item.publicData.iconPaintable = iconTexture;
|
||||
if (!tracked.publicData.iconPaintable && iconTexture) {
|
||||
tracked.publicData.iconPaintable = iconTexture;
|
||||
}
|
||||
|
||||
tracked.refreshInFlight = false;
|
||||
|
||||
if (tracked.addSignalPending) {
|
||||
tracked.addSignalPending = false;
|
||||
data->self->itemAddedSignal.emit(tracked.publicData);
|
||||
} else {
|
||||
data->self->itemUpdatedSignal.emit(tracked.publicData);
|
||||
}
|
||||
|
||||
if (tracked.refreshQueued) {
|
||||
tracked.refreshQueued = false;
|
||||
data->self->schedule_refresh(data->id);
|
||||
}
|
||||
}
|
||||
|
||||
struct RefreshTimeoutData {
|
||||
TrayService *self = nullptr;
|
||||
std::string id;
|
||||
};
|
||||
|
||||
gboolean TrayService::refresh_timeout_cb(gpointer user_data) {
|
||||
std::unique_ptr<RefreshTimeoutData> data(
|
||||
static_cast<RefreshTimeoutData *>(user_data));
|
||||
if (!data || !data->self) {
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
auto it = data->self->items.find(data->id);
|
||||
if (it == data->self->items.end()) {
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
it->second->refreshSourceId = 0;
|
||||
data->self->begin_refresh(data->id);
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
||||
void TrayService::schedule_refresh(const std::string &id) {
|
||||
auto it = items.find(id);
|
||||
if (it == items.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto &tracked = *it->second;
|
||||
if (tracked.refreshSourceId != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto *data = new RefreshTimeoutData();
|
||||
data->self = this;
|
||||
data->id = id;
|
||||
tracked.refreshSourceId =
|
||||
g_timeout_add(kRefreshDebounceMs, &TrayService::refresh_timeout_cb, data);
|
||||
}
|
||||
|
||||
void TrayService::begin_refresh(const std::string &id) {
|
||||
if (!connection) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto it = items.find(id);
|
||||
if (it == items.end()) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto &tracked = *it->second;
|
||||
if (tracked.refreshInFlight) {
|
||||
tracked.refreshQueued = true;
|
||||
return;
|
||||
}
|
||||
|
||||
tracked.refreshInFlight = true;
|
||||
|
||||
auto data = new RefreshCallData();
|
||||
data->self = this;
|
||||
data->id = id;
|
||||
data->busName = tracked.publicData.busName;
|
||||
data->objectPath = tracked.publicData.objectPath;
|
||||
|
||||
g_dbus_connection_call(connection->gobj(), data->busName.c_str(),
|
||||
data->objectPath.c_str(), kDBusPropertiesIface,
|
||||
"GetAll", g_variant_new("(s)", kItemInterface),
|
||||
G_VARIANT_TYPE("(a{sv})"), G_DBUS_CALL_FLAGS_NONE,
|
||||
kDBusTimeoutMs, nullptr,
|
||||
&TrayService::on_refresh_finished_static, data);
|
||||
}
|
||||
|
||||
void TrayService::emit_registered_items_changed() {
|
||||
@@ -956,12 +1131,10 @@ void TrayService::on_dbus_signal(const gchar *sender_name,
|
||||
std::strcmp(signal_name, "NewAttentionIcon") == 0 ||
|
||||
std::strcmp(signal_name, "NewToolTip") == 0 ||
|
||||
std::strcmp(signal_name, "NewMenu") == 0) {
|
||||
refresh_item(*it->second);
|
||||
itemUpdatedSignal.emit(it->second->publicData);
|
||||
schedule_refresh(it->first);
|
||||
}
|
||||
} else if (isPropertiesSignal) {
|
||||
refresh_item(*it->second);
|
||||
itemUpdatedSignal.emit(it->second->publicData);
|
||||
schedule_refresh(it->first);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1069,8 +1242,8 @@ Glib::RefPtr<Gdk::Paintable> TrayService::parse_icon_pixmap(GVariant *variant) {
|
||||
try {
|
||||
return Gdk::Texture::create_for_pixbuf(pixbuf);
|
||||
} catch (const Glib::Error &err) {
|
||||
std::cerr << "[TrayService] Failed to create texture: " << err.what()
|
||||
<< std::endl;
|
||||
spdlog::error("[TrayService] Failed to create texture: {}",
|
||||
err.what());
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
#include "widgets/bluetooth.hpp"
|
||||
#include "gtkmm/label.h"
|
||||
|
||||
|
||||
BluetoothWidget::BluetoothWidget() : Gtk::Box() {
|
||||
this->set_orientation(Gtk::Orientation::VERTICAL);
|
||||
this->add_css_class("bluetooth-popover-container");
|
||||
|
||||
this->statusArea.add_css_class("bluetooth-status-area");
|
||||
this->statusArea.set_hexpand(true);
|
||||
this->statusArea.set_halign(Gtk::Align::FILL);
|
||||
this->append(this->statusArea);
|
||||
|
||||
this->powerButton = Gtk::make_managed<Button>("\ue1a8");
|
||||
this->powerButton->set_tooltip_text("Turn Bluetooth Off");
|
||||
this->powerButton->signal_clicked().connect(sigc::mem_fun(*this, &BluetoothWidget::onPowerButtonClicked));
|
||||
this->powerButton->add_css_class("toggle-button");
|
||||
|
||||
this->scanButton = Gtk::make_managed<Button>("\ue1aa");
|
||||
this->scanButton->set_tooltip_text("Scan for Devices");
|
||||
this->scanButton->add_css_class("toggle-button");
|
||||
this->scanButton->signal_clicked().connect(sigc::mem_fun(*this, &BluetoothWidget::onScanButtonClicked));
|
||||
|
||||
this->statusArea.append(*this->powerButton);
|
||||
this->statusArea.append(*this->scanButton);
|
||||
}
|
||||
|
||||
void BluetoothWidget::onPowerButtonClicked() {
|
||||
onPowerStateButtonClickedSignal.emit();
|
||||
}
|
||||
|
||||
void BluetoothWidget::onScanButtonClicked() {
|
||||
onIsDiscoveringButtonClickedSignal.emit();
|
||||
}
|
||||
|
||||
void BluetoothWidget::toggleButton(Button *button, bool state) {
|
||||
if (state) {
|
||||
button->add_css_class("toggle-button-on");
|
||||
button->remove_css_class("toggle-button-off");
|
||||
} else {
|
||||
button->add_css_class("toggle-button-off");
|
||||
button->remove_css_class("toggle-button-on");
|
||||
}
|
||||
}
|
||||
|
||||
void BluetoothWidget::setPowerState(bool state) {
|
||||
this->isPowered = state;
|
||||
|
||||
this->scanButton->set_sensitive(state);
|
||||
|
||||
if (!state) {
|
||||
this->scanButton->add_css_class("toggle-button-disabled");
|
||||
// this->add_css_class("disabled-popover-icon");
|
||||
this->setIsDiscovering(false);
|
||||
} else {
|
||||
this->scanButton->remove_css_class("toggle-button-disabled");
|
||||
// this->remove_css_class("disabled-popover-icon");
|
||||
}
|
||||
|
||||
this->toggleButton(this->powerButton, state);
|
||||
}
|
||||
|
||||
void BluetoothWidget::setIsDiscovering(bool state) {
|
||||
this->isDiscovering = state;
|
||||
|
||||
this->toggleButton(this->scanButton, state);
|
||||
}
|
||||
|
||||
void BluetoothWidget::update() {
|
||||
setPowerState(isPowered);
|
||||
setIsDiscovering(isDiscovering);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
#include "widgets/controlCenter.hpp"
|
||||
|
||||
ControlCenter::ControlCenter(std::string icon, std::string name)
|
||||
: Popover(icon, name) {
|
||||
this->popover->set_size_request(200, -1);
|
||||
set_popover_child(this->container);
|
||||
|
||||
this->bluetoothWidget = Gtk::make_managed<BluetoothWidget>();
|
||||
this->container.append(*this->bluetoothWidget);
|
||||
|
||||
bluetoothService->powerStateChangedSignal.connect(
|
||||
sigc::mem_fun(*this->bluetoothWidget, &BluetoothWidget::setPowerState));
|
||||
|
||||
bluetoothWidget->onPowerStateButtonClickedSignal.connect(
|
||||
sigc::mem_fun(*this->bluetoothService, &BluetoothService::togglePowerState));
|
||||
|
||||
bluetoothWidget->setPowerState(bluetoothService->getPowerState());
|
||||
|
||||
bluetoothService->isDiscoveringChangedSignal.connect(
|
||||
sigc::mem_fun(*this->bluetoothWidget, &BluetoothWidget::setIsDiscovering));
|
||||
bluetoothWidget->onIsDiscoveringButtonClickedSignal.connect(
|
||||
sigc::mem_fun(*this->bluetoothService, &BluetoothService::toggleIsDiscovering));
|
||||
bluetoothWidget->setIsDiscovering(bluetoothService->getIsDiscovering());
|
||||
}
|
||||
20
src/widgets/controlCenter/controlCenter.cpp
Normal file
20
src/widgets/controlCenter/controlCenter.cpp
Normal file
@@ -0,0 +1,20 @@
|
||||
#include "widgets/controlCenter/controlCenter.hpp"
|
||||
|
||||
|
||||
ControlCenter::ControlCenter(std::string icon, std::string name)
|
||||
: Popover(icon, name) {
|
||||
this->popover->add_css_class("control-center-popover");
|
||||
this->container.set_orientation(Gtk::Orientation::VERTICAL);
|
||||
this->container.set_spacing(0);
|
||||
this->container.set_margin_top(0);
|
||||
this->container.set_margin_bottom(0);
|
||||
this->container.set_margin_start(0);
|
||||
this->container.set_margin_end(0);
|
||||
|
||||
set_popover_child(this->container);
|
||||
|
||||
|
||||
this->container.append(this->mediaControlWidget);
|
||||
|
||||
}
|
||||
|
||||
217
src/widgets/controlCenter/mediaControl.cpp
Normal file
217
src/widgets/controlCenter/mediaControl.cpp
Normal file
@@ -0,0 +1,217 @@
|
||||
#include "widgets/controlCenter/mediaControl.hpp"
|
||||
|
||||
#include "helpers/string.hpp"
|
||||
#include "services/textureCache.hpp"
|
||||
|
||||
MediaControlWidget::MediaControlWidget()
|
||||
: Gtk::Box(Gtk::Orientation::VERTICAL) {
|
||||
|
||||
this->set_orientation(Gtk::Orientation::VERTICAL);
|
||||
this->set_size_request(200, 240);
|
||||
this->set_hexpand(false);
|
||||
this->set_vexpand(false);
|
||||
this->add_css_class("control-center-spotify-container");
|
||||
|
||||
this->append(this->topContainer);
|
||||
this->append(this->seekBarContainer);
|
||||
this->append(this->bottomContainer);
|
||||
|
||||
this->backgroundImage.set_content_fit(Gtk::ContentFit::COVER);
|
||||
this->backgroundImage.set_can_shrink(true);
|
||||
|
||||
this->imageWrapper.set_policy(Gtk::PolicyType::NEVER, Gtk::PolicyType::NEVER);
|
||||
this->imageWrapper.set_child(this->backgroundImage);
|
||||
|
||||
this->topContainer.set_child(this->imageWrapper);
|
||||
|
||||
this->topContainer.set_size_request(200, 100);
|
||||
this->topContainer.set_vexpand(false);
|
||||
this->topContainer.set_hexpand(true);
|
||||
|
||||
this->infoContainer.set_orientation(Gtk::Orientation::VERTICAL);
|
||||
this->infoContainer.set_valign(Gtk::Align::END);
|
||||
this->infoContainer.set_halign(Gtk::Align::START);
|
||||
this->infoContainer.append(this->artistLabel);
|
||||
this->infoContainer.append(this->titleLabel);
|
||||
this->topContainer.add_overlay(this->infoContainer);
|
||||
|
||||
this->artistLabel.set_halign(Gtk::Align::START);
|
||||
this->titleLabel.set_halign(Gtk::Align::START);
|
||||
|
||||
this->seekBarContainer.set_orientation(Gtk::Orientation::HORIZONTAL);
|
||||
this->seekBarContainer.set_vexpand(false);
|
||||
this->seekBarContainer.set_hexpand(true);
|
||||
this->seekBarContainer.set_halign(Gtk::Align::CENTER);
|
||||
this->seekBarContainer.append(this->currentTimeLabel);
|
||||
this->seekBarContainer.append(this->seekBar);
|
||||
this->seekBarContainer.append(this->totalTimeLabel);
|
||||
|
||||
this->currentTimeLabel.set_text("0:00");
|
||||
this->currentTimeLabel.set_halign(Gtk::Align::START);
|
||||
this->totalTimeLabel.set_text("0:00");
|
||||
this->totalTimeLabel.set_halign(Gtk::Align::END);
|
||||
this->seekBar.set_range(0, 100);
|
||||
this->seekBar.set_value(0);
|
||||
this->seekBar.set_orientation(Gtk::Orientation::HORIZONTAL);
|
||||
this->seekBar.set_draw_value(false);
|
||||
this->seekBar.set_size_request(120, -1);
|
||||
this->seekBar.set_hexpand(true);
|
||||
this->seekBar.set_halign(Gtk::Align::CENTER);
|
||||
this->seekBar.add_css_class("control-center-seek-bar");
|
||||
|
||||
this->seekBar.signal_value_changed().connect([this]() {
|
||||
double fraction = this->seekBar.get_value() / 100.0;
|
||||
int64_t new_position_us =
|
||||
static_cast<int64_t>(fraction * static_cast<double>(this->totalLengthUs));
|
||||
this->mprisController->emit_seeked(new_position_us - this->currentPositionUs); // in us
|
||||
this->resetSeekTimer(new_position_us);
|
||||
});
|
||||
|
||||
this->bottomContainer.set_orientation(Gtk::Orientation::HORIZONTAL);
|
||||
this->bottomContainer.set_vexpand(false);
|
||||
this->bottomContainer.set_hexpand(false);
|
||||
this->bottomContainer.set_valign(Gtk::Align::START);
|
||||
this->bottomContainer.set_homogeneous(true);
|
||||
this->topContainer.set_vexpand(false);
|
||||
this->topContainer.set_hexpand(true);
|
||||
this->bottomContainer.append(this->previousButton);
|
||||
this->bottomContainer.append(this->playPauseButton);
|
||||
this->bottomContainer.append(this->nextButton);
|
||||
|
||||
this->previousButton.set_label("\u23EE"); // Previous track symbol
|
||||
this->previousButton.add_css_class("notification-button");
|
||||
this->previousButton.add_css_class("notification-icon-button");
|
||||
this->playPauseButton.set_label("\u23EF"); // Play/Pause symbol
|
||||
this->playPauseButton.add_css_class("notification-button");
|
||||
this->playPauseButton.add_css_class("notification-icon-button");
|
||||
this->nextButton.set_label("\u23ED"); // Next track symbol
|
||||
this->nextButton.add_css_class("notification-button");
|
||||
this->nextButton.add_css_class("notification-icon-button");
|
||||
|
||||
this->previousButton.signal_clicked().connect([this]() {
|
||||
this->mprisController->previous_song();
|
||||
});
|
||||
this->playPauseButton.signal_clicked().connect([this]() {
|
||||
this->mprisController->toggle_play();
|
||||
});
|
||||
this->nextButton.signal_clicked().connect([this]() {
|
||||
this->mprisController->next_song();
|
||||
});
|
||||
|
||||
this->mprisController->signal_mpris_updated().connect(
|
||||
sigc::mem_fun(*this, &MediaControlWidget::onSpotifyMprisUpdated));
|
||||
|
||||
this->mprisController->signal_playback_status_changed().connect(
|
||||
[this](MprisController::PlaybackStatus status) {
|
||||
this->onRunningStateChanged(status);
|
||||
});
|
||||
|
||||
this->mprisController->signal_playback_position_changed().connect(
|
||||
[this](int64_t position_us) {
|
||||
this->setCurrentPosition(position_us);
|
||||
});
|
||||
|
||||
this->artistLabel.set_text("Artist Name");
|
||||
this->artistLabel.add_css_class("control-center-spotify-artist-label");
|
||||
this->titleLabel.set_text("Song Title");
|
||||
this->titleLabel.add_css_class("control-center-spotify-title-label");
|
||||
|
||||
this->resetSeekTimer(0);
|
||||
}
|
||||
|
||||
void MediaControlWidget::onSpotifyMprisUpdated(const MprisPlayer2Message &message) {
|
||||
std::string artistText = "Unknown Artist";
|
||||
if (!message.artist.empty()) {
|
||||
artistText = StringHelper::trimToSize(message.artist[0], 30);
|
||||
}
|
||||
this->artistLabel.set_text(artistText);
|
||||
this->titleLabel.set_text(message.title);
|
||||
|
||||
if (auto texture = TextureCacheService::getInstance()->getTexture(message.artwork_url)) {
|
||||
this->backgroundImage.set_paintable(texture);
|
||||
}
|
||||
|
||||
this->setTotalLength(message.length_ms);
|
||||
this->setCurrentPosition(0);
|
||||
this->resetSeekTimer(0);
|
||||
}
|
||||
|
||||
void MediaControlWidget::setCurrentPosition(int64_t position_us) {
|
||||
this->currentPositionUs = position_us;
|
||||
int64_t seconds = (position_us / 1000000) % 60;
|
||||
int64_t minutes = (position_us / (1000000 * 60)) % 60;
|
||||
this->currentTimeLabel.set_text(
|
||||
std::to_string(minutes) + ":" + (seconds < 10 ? "0" : "") + std::to_string(seconds));
|
||||
if (totalLengthUs > 0) {
|
||||
double fraction = static_cast<double>(currentPositionUs) / static_cast<double>(totalLengthUs);
|
||||
this->seekBar.set_value(fraction * 100);
|
||||
}
|
||||
}
|
||||
|
||||
void MediaControlWidget::setTotalLength(int64_t length_us) {
|
||||
this->totalLengthUs = length_us;
|
||||
int64_t seconds = (length_us / 1000000) % 60;
|
||||
int64_t minutes = (length_us / (1000000 * 60)) % 60;
|
||||
this->totalTimeLabel.set_text(
|
||||
std::to_string(minutes) + ":" + (seconds < 10 ? "0" : "") + std::to_string(seconds));
|
||||
}
|
||||
|
||||
void MediaControlWidget::resetSeekTimer(int64_t start_position_us) {
|
||||
if (seekTimerConnection.connected()) {
|
||||
seekTimerConnection.disconnect();
|
||||
}
|
||||
|
||||
setCurrentPosition(start_position_us);
|
||||
|
||||
seekTimerConnection = Glib::signal_timeout().connect(
|
||||
sigc::mem_fun(*this, &MediaControlWidget::onSeekTick),
|
||||
1000);
|
||||
}
|
||||
|
||||
bool MediaControlWidget::onSeekTick() {
|
||||
if (totalLengthUs <= 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int64_t nextPosition = currentPositionUs + 1000000;
|
||||
if (nextPosition > totalLengthUs) {
|
||||
nextPosition = totalLengthUs;
|
||||
}
|
||||
setCurrentPosition(nextPosition);
|
||||
return true;
|
||||
}
|
||||
|
||||
void MediaControlWidget::onRunningStateChanged(MprisController::PlaybackStatus status) {
|
||||
switch (status) {
|
||||
case MprisController::PlaybackStatus::Playing:
|
||||
this->onPlay();
|
||||
break;
|
||||
case MprisController::PlaybackStatus::Paused:
|
||||
this->onPause();
|
||||
break;
|
||||
case MprisController::PlaybackStatus::Stopped:
|
||||
this->onStop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void MediaControlWidget::onPlay() {
|
||||
this->playPauseButton.set_label("\u23F8"); // Pause symbol
|
||||
// strart seek timer if not already running
|
||||
this->resetSeekTimer(currentPositionUs);
|
||||
}
|
||||
|
||||
void MediaControlWidget::onPause() {
|
||||
this->playPauseButton.set_label("\u23EF"); // Play symbol
|
||||
if (seekTimerConnection.connected()) {
|
||||
seekTimerConnection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
void MediaControlWidget::onStop() {
|
||||
this->playPauseButton.set_label("\u23EF"); // Play symbol
|
||||
if (seekTimerConnection.connected()) {
|
||||
seekTimerConnection.disconnect();
|
||||
}
|
||||
this->setCurrentPosition(0);
|
||||
}
|
||||
148
src/widgets/notification/baseNotification.cpp
Normal file
148
src/widgets/notification/baseNotification.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
#include "widgets/notification/baseNotification.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
#include "helpers/system.hpp"
|
||||
|
||||
#include "gdkmm/monitor.h"
|
||||
#include "glibmm/main.h"
|
||||
#include "glibmm/object.h"
|
||||
#include "gtk4-layer-shell.h"
|
||||
#include "gtkmm/button.h"
|
||||
#include "gtkmm/cssprovider.h"
|
||||
#include "gtkmm/eventcontrollermotion.h"
|
||||
#include "gtkmm/gestureclick.h"
|
||||
|
||||
BaseNotification::BaseNotification(uint64_t notificationId, std::shared_ptr<Gdk::Monitor> monitor) {
|
||||
ensure_notification_css_loaded();
|
||||
set_default_size(350, -1);
|
||||
gtk_layer_init_for_window(gobj());
|
||||
gtk_layer_set_monitor(gobj(), monitor->gobj());
|
||||
gtk_layer_set_layer(gobj(), GTK_LAYER_SHELL_LAYER_OVERLAY);
|
||||
gtk_layer_set_anchor(gobj(), GTK_LAYER_SHELL_EDGE_TOP, TRUE);
|
||||
gtk_layer_set_anchor(gobj(), GTK_LAYER_SHELL_EDGE_RIGHT, TRUE);
|
||||
gtk_layer_set_margin(gobj(), GTK_LAYER_SHELL_EDGE_TOP, 2);
|
||||
gtk_layer_set_margin(gobj(), GTK_LAYER_SHELL_EDGE_RIGHT, 2);
|
||||
add_css_class("notification-popup");
|
||||
|
||||
this->set_hexpand(false);
|
||||
this->set_vexpand(false);
|
||||
|
||||
this->notificationId = notificationId;
|
||||
|
||||
auto window_click = Gtk::GestureClick::create();
|
||||
window_click->set_button(GDK_BUTTON_PRIMARY);
|
||||
window_click->set_exclusive(false);
|
||||
window_click->signal_released().connect([this](int, double x, double y) {
|
||||
Gtk::Widget *picked = this->pick(x, y, Gtk::PickFlags::DEFAULT);
|
||||
for (auto *w = picked; w != nullptr; w = w->get_parent()) {
|
||||
if (dynamic_cast<Gtk::Button *>(w) != nullptr) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
this->signal_close.emit(this->notificationId);
|
||||
});
|
||||
add_controller(window_click);
|
||||
|
||||
auto window_motion = Gtk::EventControllerMotion::create();
|
||||
window_motion->signal_enter().connect([this](double, double) {
|
||||
signal_hover_changed.emit(true);
|
||||
pause_auto_close();
|
||||
});
|
||||
window_motion->signal_leave().connect([this]() {
|
||||
signal_hover_changed.emit(false);
|
||||
resume_auto_close();
|
||||
});
|
||||
add_controller(window_motion);
|
||||
}
|
||||
|
||||
void BaseNotification::pauseAutoClose() {
|
||||
pause_auto_close();
|
||||
}
|
||||
|
||||
void BaseNotification::resumeAutoClose() {
|
||||
resume_auto_close();
|
||||
}
|
||||
|
||||
void BaseNotification::startAutoClose(int timeoutMs) {
|
||||
if (timeoutMs <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
autoCloseRemainingMs = timeoutMs;
|
||||
autoClosePaused = false;
|
||||
start_auto_close_timeout(timeoutMs);
|
||||
}
|
||||
|
||||
void BaseNotification::start_auto_close_timeout(int timeoutMs) {
|
||||
if (autoCloseConnection.connected()) {
|
||||
autoCloseConnection.disconnect();
|
||||
}
|
||||
|
||||
autoCloseDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
autoCloseConnection = Glib::signal_timeout().connect([this]() {
|
||||
this->signal_close.emit(this->notificationId);
|
||||
return false; // Don't repeat
|
||||
},
|
||||
timeoutMs);
|
||||
}
|
||||
|
||||
void BaseNotification::pause_auto_close() {
|
||||
if (autoClosePaused || autoCloseRemainingMs <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (autoCloseConnection.connected()) {
|
||||
autoCloseConnection.disconnect();
|
||||
}
|
||||
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(autoCloseDeadline - now).count();
|
||||
autoCloseRemainingMs = static_cast<int>(std::max<int64_t>(0, remaining));
|
||||
autoClosePaused = true;
|
||||
}
|
||||
|
||||
void BaseNotification::resume_auto_close() {
|
||||
if (!autoClosePaused) {
|
||||
return;
|
||||
}
|
||||
|
||||
autoClosePaused = false;
|
||||
if (autoCloseRemainingMs <= 0) {
|
||||
this->signal_close.emit(this->notificationId);
|
||||
return;
|
||||
}
|
||||
|
||||
start_auto_close_timeout(autoCloseRemainingMs);
|
||||
}
|
||||
|
||||
|
||||
void BaseNotification::ensure_notification_css_loaded() {
|
||||
static bool loaded = false;
|
||||
if (loaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto css_provider = Gtk::CssProvider::create();
|
||||
|
||||
std::string css_path = "resources/notification.css";
|
||||
const char *home = std::getenv("HOME");
|
||||
if (home) {
|
||||
std::filesystem::path config_path =
|
||||
std::filesystem::path(home) / ".config/bar/notification.css";
|
||||
if (std::filesystem::exists(config_path)) {
|
||||
css_path = config_path.string();
|
||||
}
|
||||
}
|
||||
|
||||
const std::string css = SystemHelper::read_file_to_string(css_path);
|
||||
css_provider->load_from_data(css);
|
||||
|
||||
Gtk::StyleContext::add_provider_for_display(
|
||||
Gdk::Display::get_default(), css_provider,
|
||||
GTK_STYLE_PROVIDER_PRIORITY_USER + 2);
|
||||
|
||||
loaded = true;
|
||||
}
|
||||
104
src/widgets/notification/notificationWindow.cpp
Normal file
104
src/widgets/notification/notificationWindow.cpp
Normal file
@@ -0,0 +1,104 @@
|
||||
#include "widgets/notification/notificationWindow.hpp"
|
||||
#include <cstdint>
|
||||
#include <sys/types.h>
|
||||
#include "helpers/string.hpp"
|
||||
|
||||
#include "gtkmm/box.h"
|
||||
#include "gtkmm/button.h"
|
||||
#include "gtkmm/gestureclick.h"
|
||||
#include "gtkmm/image.h"
|
||||
#include "gtkmm/label.h"
|
||||
|
||||
NotificationWindow::NotificationWindow(uint64_t notificationId, std::shared_ptr<Gdk::Monitor> monitor, NotifyMessage notify) : BaseNotification(notificationId, monitor) {
|
||||
set_title(notify.summary);
|
||||
|
||||
|
||||
// Main vertical box
|
||||
auto vbox = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 8);
|
||||
vbox->set_halign(Gtk::Align::FILL);
|
||||
|
||||
switch (notify.urgency) {
|
||||
case NotificationUrgency::CRITICAL:
|
||||
add_css_class("notification-critical");
|
||||
break;
|
||||
case NotificationUrgency::NORMAL:
|
||||
add_css_class("notification-normal");
|
||||
break;
|
||||
case NotificationUrgency::LOW:
|
||||
add_css_class("notification-low");
|
||||
break;
|
||||
}
|
||||
|
||||
auto header_box = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL);
|
||||
header_box->set_halign(Gtk::Align::START);
|
||||
header_box->add_css_class("notification-header");
|
||||
header_box->set_hexpand(true);
|
||||
header_box->set_halign(Gtk::Align::FILL);
|
||||
|
||||
if (notify.imageData) {
|
||||
auto img = Gtk::make_managed<Gtk::Image>(*(notify.imageData));
|
||||
img->set_pixel_size(16);
|
||||
img->set_halign(Gtk::Align::START);
|
||||
img->set_valign(Gtk::Align::CENTER);
|
||||
img->add_css_class("notification-app-icon");
|
||||
header_box->append(*img);
|
||||
}
|
||||
|
||||
auto app_label = Gtk::make_managed<Gtk::Label>(StringHelper::trimToSize(notify.app_name, 24));
|
||||
app_label->set_halign(Gtk::Align::START);
|
||||
app_label->set_wrap(false);
|
||||
app_label->add_css_class("notification-app-name");
|
||||
header_box->append(*app_label);
|
||||
vbox->append(*header_box);
|
||||
|
||||
// Summary label
|
||||
auto summary_label = Gtk::make_managed<Gtk::Label>("<b>" + StringHelper::trimToSize(notify.summary, 20) + "</b>");
|
||||
summary_label->set_use_markup(true);
|
||||
summary_label->set_halign(Gtk::Align::START);
|
||||
summary_label->set_wrap(true);
|
||||
vbox->append(*summary_label);
|
||||
|
||||
auto body_label = Gtk::make_managed<Gtk::Label>(StringHelper::trimToSize(notify.body, 100));
|
||||
body_label->set_use_markup(true);
|
||||
body_label->set_halign(Gtk::Align::START);
|
||||
body_label->set_wrap(true);
|
||||
vbox->append(*body_label);
|
||||
|
||||
// If actions exist, add buttons
|
||||
if (!notify.actions.empty()) {
|
||||
auto actions_box = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL, 6);
|
||||
for (size_t i = 0; i + 1 < notify.actions.size(); i += 2) {
|
||||
std::string action_id = notify.actions[i];
|
||||
std::string action_label = notify.actions[i + 1];
|
||||
|
||||
auto btn = Gtk::make_managed<Gtk::Button>();
|
||||
btn->set_label(action_label);
|
||||
|
||||
btn->add_css_class("notification-button");
|
||||
|
||||
switch (notify.urgency) {
|
||||
case NotificationUrgency::CRITICAL:
|
||||
btn->add_css_class("notification-critical");
|
||||
break;
|
||||
case NotificationUrgency::NORMAL:
|
||||
btn->add_css_class("notification-normal");
|
||||
break;
|
||||
case NotificationUrgency::LOW:
|
||||
btn->add_css_class("notification-low");
|
||||
break;
|
||||
}
|
||||
|
||||
btn->signal_clicked().connect([this, action_id, cb = notify.on_action, guard = notify.actionInvoked]() {
|
||||
if (cb && guard && !*guard) {
|
||||
*guard = true;
|
||||
cb(action_id);
|
||||
this->signal_close.emit(this->notificationId);
|
||||
}
|
||||
});
|
||||
actions_box->append(*btn);
|
||||
}
|
||||
vbox->append(*actions_box);
|
||||
}
|
||||
|
||||
set_child(*vbox);
|
||||
}
|
||||
98
src/widgets/notification/spotifyNotification.cpp
Normal file
98
src/widgets/notification/spotifyNotification.cpp
Normal file
@@ -0,0 +1,98 @@
|
||||
#include "widgets/notification/spotifyNotification.hpp"
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "helpers/string.hpp"
|
||||
#include "services/textureCache.hpp"
|
||||
|
||||
#include "gtkmm/box.h"
|
||||
#include "gtkmm/button.h"
|
||||
#include "gtkmm/centerbox.h"
|
||||
#include "gtkmm/image.h"
|
||||
#include "gtkmm/label.h"
|
||||
|
||||
SpotifyNotification::SpotifyNotification(uint64_t notificationId, std::shared_ptr<Gdk::Monitor> monitor, MprisPlayer2Message mpris) : BaseNotification(notificationId, monitor) {
|
||||
auto container = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL, 10);
|
||||
container->set_hexpand(true);
|
||||
|
||||
if (auto texture = TextureCacheService::getInstance()->getTexture(mpris.artwork_url)) {
|
||||
auto img = Gtk::make_managed<Gtk::Image>(texture);
|
||||
img->set_pixel_size(64);
|
||||
container->append(*img);
|
||||
}
|
||||
|
||||
auto rightArea = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 5);
|
||||
rightArea->set_halign(Gtk::Align::FILL);
|
||||
rightArea->set_valign(Gtk::Align::CENTER);
|
||||
rightArea->set_hexpand(true);
|
||||
rightArea->set_size_request(220, -1);
|
||||
|
||||
auto title_label = Gtk::make_managed<Gtk::Label>("<b>" + mpris.title + "</b>");
|
||||
title_label->set_use_markup(true);
|
||||
title_label->set_hexpand(true);
|
||||
title_label->set_halign(Gtk::Align::CENTER);
|
||||
title_label->set_ellipsize(Pango::EllipsizeMode::END);
|
||||
|
||||
auto artistLabel = Gtk::make_managed<Gtk::Label>();
|
||||
artistLabel->set_text(StringHelper::trimToSize(mpris.artist[0], 30));
|
||||
artistLabel->set_hexpand(true);
|
||||
artistLabel->set_halign(Gtk::Align::CENTER);
|
||||
|
||||
auto buttonBox = createButtonBox(mpris);
|
||||
|
||||
rightArea->append(*artistLabel);
|
||||
rightArea->append(*title_label);
|
||||
rightArea->append(*buttonBox);
|
||||
|
||||
container->append(*rightArea);
|
||||
|
||||
set_child(*container);
|
||||
}
|
||||
|
||||
std::unique_ptr<Gtk::CenterBox> SpotifyNotification::createButtonBox(MprisPlayer2Message mpris) {
|
||||
auto buttonBox = std::make_unique<Gtk::CenterBox>();
|
||||
buttonBox->add_css_class("notification-button-box");
|
||||
buttonBox->set_hexpand(true);
|
||||
buttonBox->set_halign(Gtk::Align::CENTER);
|
||||
|
||||
auto backButton = Gtk::make_managed<Gtk::Button>("\ue045");
|
||||
backButton->add_css_class("notification-icon-button");
|
||||
backButton->add_css_class("notification-button");
|
||||
backButton->signal_clicked().connect([this, mpris]() {
|
||||
if (mpris.previous) {
|
||||
mpris.previous();
|
||||
this->signal_close.emit(this->notificationId);
|
||||
}
|
||||
});
|
||||
|
||||
auto playPauseButton = Gtk::make_managed<Gtk::Button>("\ue037");
|
||||
playPauseButton->add_css_class("notification-icon-button");
|
||||
playPauseButton->add_css_class("notification-button");
|
||||
playPauseButton->signal_clicked().connect([playPauseButton, mpris]() {
|
||||
if (mpris.play_pause) {
|
||||
mpris.play_pause();
|
||||
|
||||
static bool isPlaying = false;
|
||||
if (isPlaying) {
|
||||
playPauseButton->set_label("\ue037");
|
||||
} else {
|
||||
playPauseButton->set_label("\ue034");
|
||||
}
|
||||
isPlaying = !isPlaying;
|
||||
}
|
||||
});
|
||||
|
||||
auto nextButton = Gtk::make_managed<Gtk::Button>("\ue044");
|
||||
nextButton->add_css_class("notification-icon-button");
|
||||
nextButton->add_css_class("notification-button");
|
||||
nextButton->signal_clicked().connect([this, mpris]() {
|
||||
if (mpris.next) {
|
||||
mpris.next();
|
||||
this->signal_close.emit(this->notificationId);
|
||||
}
|
||||
});
|
||||
buttonBox->set_start_widget(*backButton);
|
||||
buttonBox->set_center_widget(*playPauseButton);
|
||||
buttonBox->set_end_widget(*nextButton);
|
||||
|
||||
return buttonBox;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
#include "widgets/todo.hpp"
|
||||
|
||||
#include <gtkmm/box.h>
|
||||
#include <gtkmm/entry.h>
|
||||
#include <string>
|
||||
|
||||
TodoPopover::TodoPopover(std::string icon, std::string title) : Popover(icon, title) {
|
||||
this->name = title;
|
||||
this->popover->set_size_request(300, -1);
|
||||
|
||||
container.set_orientation(Gtk::Orientation::VERTICAL);
|
||||
container.add_css_class("todo-popover-container");
|
||||
|
||||
auto entry = Gtk::make_managed<Gtk::Entry>();
|
||||
entry->set_placeholder_text("Enter your to-do item...");
|
||||
entry->add_css_class("todo-input");
|
||||
entry->set_hexpand(true);
|
||||
entry->set_halign(Gtk::Align::FILL);
|
||||
entry->set_valign(Gtk::Align::START);
|
||||
|
||||
inputArea.append(*entry);
|
||||
inputArea.add_css_class("todo-input-area");
|
||||
inputArea.set_hexpand(true);
|
||||
inputArea.set_halign(Gtk::Align::FILL);
|
||||
|
||||
entry->signal_activate().connect([this, entry]() {
|
||||
std::string text = entry->get_text();
|
||||
if (!text.empty()) {
|
||||
this->todoService->addTodo(text);
|
||||
|
||||
entry->set_text("");
|
||||
}
|
||||
});
|
||||
|
||||
container.append(inputArea);
|
||||
|
||||
this->todoList = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL);
|
||||
container.append(*todoList);
|
||||
todoList->add_css_class("todo-list");
|
||||
|
||||
auto signal = sigc::signal<void()>();
|
||||
this->todoService = new TodoService(signal);
|
||||
|
||||
signal.connect(sigc::mem_fun(*this, &TodoPopover::update));
|
||||
|
||||
this->set_popover_child(this->container);
|
||||
this->update();
|
||||
}
|
||||
|
||||
void TodoPopover::update() {
|
||||
auto todos = this->todoService->getTodos();
|
||||
|
||||
Gtk::Widget *child = todoList->get_first_child();
|
||||
|
||||
while (child) {
|
||||
Gtk::Widget *next = child->get_next_sibling();
|
||||
|
||||
bool found = false;
|
||||
for (auto &[id, todo] : todos) {
|
||||
if (child == todo) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
todoList->remove(*child);
|
||||
}
|
||||
|
||||
child = next;
|
||||
}
|
||||
|
||||
for (auto &[id, todo] : todos) {
|
||||
if (todo->get_parent() == nullptr) {
|
||||
todoList->append(*todo);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,189 @@
|
||||
#include <gdkmm/rectangle.h>
|
||||
#include <gio/gmenu.h>
|
||||
#include <gtk/gtk.h>
|
||||
#include <iostream>
|
||||
#include <cmath>
|
||||
#include <graphene.h>
|
||||
#include <utility>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include "components/base/button.hpp"
|
||||
|
||||
namespace {
|
||||
bool is_wayland_display(GtkWidget *widget) {
|
||||
if (!widget) {
|
||||
return true;
|
||||
}
|
||||
|
||||
GtkNative *native = gtk_widget_get_native(widget);
|
||||
if (!native) {
|
||||
return true;
|
||||
}
|
||||
|
||||
GdkSurface *surface = gtk_native_get_surface(native);
|
||||
if (!surface) {
|
||||
return true;
|
||||
}
|
||||
|
||||
GdkDisplay *display = gdk_surface_get_display(surface);
|
||||
if (!display) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const char *typeName = G_OBJECT_TYPE_NAME(display);
|
||||
if (!typeName) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return std::string(typeName).find("Wayland") != std::string::npos;
|
||||
}
|
||||
|
||||
bool try_get_monitor_geometry(GtkWidget *widget, GdkRectangle &outGeom) {
|
||||
if (!widget) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GtkNative *native = gtk_widget_get_native(widget);
|
||||
if (!native) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkSurface *surface = gtk_native_get_surface(native);
|
||||
if (!surface) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkDisplay *display = gdk_surface_get_display(surface);
|
||||
if (!display) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkMonitor *monitor = gdk_display_get_monitor_at_surface(display, surface);
|
||||
if (!monitor) {
|
||||
return false;
|
||||
}
|
||||
|
||||
gdk_monitor_get_geometry(monitor, &outGeom);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool try_get_global_click_coords(GtkWidget *widget, double x, double y,
|
||||
int32_t &outX, int32_t &outY) {
|
||||
if (!widget) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GtkNative *native = gtk_widget_get_native(widget);
|
||||
if (!native) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GtkWidget *nativeWidget = GTK_WIDGET(native);
|
||||
graphene_point_t src{static_cast<float>(x), static_cast<float>(y)};
|
||||
graphene_point_t dst{0.0f, 0.0f};
|
||||
if (!gtk_widget_compute_point(widget, nativeWidget, &src, &dst)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkRectangle geom;
|
||||
if (!try_get_monitor_geometry(widget, geom)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
outX = static_cast<int32_t>(geom.x + std::lround(dst.x));
|
||||
outY = static_cast<int32_t>(geom.y + std::lround(dst.y));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool try_get_global_pointer_coords(GtkWidget *widget, int32_t &outX,
|
||||
int32_t &outY) {
|
||||
if (!widget) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GtkNative *native = gtk_widget_get_native(widget);
|
||||
if (!native) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkSurface *surface = gtk_native_get_surface(native);
|
||||
if (!surface) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkDisplay *display = gdk_surface_get_display(surface);
|
||||
if (!display) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkSeat *seat = gdk_display_get_default_seat(display);
|
||||
if (!seat) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkDevice *pointer = gdk_seat_get_pointer(seat);
|
||||
if (!pointer) {
|
||||
return false;
|
||||
}
|
||||
|
||||
double sx = 0.0;
|
||||
double sy = 0.0;
|
||||
if (!gdk_surface_get_device_position(surface, pointer, &sx, &sy, nullptr)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GdkRectangle geom;
|
||||
if (!try_get_monitor_geometry(widget, geom)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
outX = static_cast<int32_t>(geom.x + std::lround(sx));
|
||||
outY = static_cast<int32_t>(geom.y + std::lround(sy));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool has_popup_surface(GtkWidget *widget) {
|
||||
if (!widget) {
|
||||
return false;
|
||||
}
|
||||
GtkRoot *root = gtk_widget_get_root(widget);
|
||||
if (!root) {
|
||||
return false;
|
||||
}
|
||||
GtkNative *native = gtk_widget_get_native(widget);
|
||||
if (!native) {
|
||||
return false;
|
||||
}
|
||||
GdkSurface *surface = gtk_native_get_surface(native);
|
||||
if (!surface) {
|
||||
return false;
|
||||
}
|
||||
return gdk_surface_get_mapped(surface);
|
||||
}
|
||||
|
||||
void log_menu_tree(const std::vector<TrayService::MenuNode> &nodes,
|
||||
int depth = 0) {
|
||||
const std::string indent(static_cast<std::size_t>(depth) * 2, ' ');
|
||||
for (const auto &node : nodes) {
|
||||
if (!node.visible) {
|
||||
continue;
|
||||
}
|
||||
spdlog::debug(
|
||||
"[TrayIconWidget] menu node id={} label='{}' enabled={} sep={} depth={}",
|
||||
node.id,
|
||||
node.label,
|
||||
node.enabled ? 1 : 0,
|
||||
node.separator ? 1 : 0,
|
||||
depth);
|
||||
if (!node.children.empty()) {
|
||||
log_menu_tree(node.children, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TrayIconWidget::TrayIconWidget( std::string id)
|
||||
: Button(id), id(std::move(id)),
|
||||
container(Gtk::Orientation::HORIZONTAL) {
|
||||
aliveFlag = std::make_shared<bool>(true);
|
||||
set_has_frame(false);
|
||||
set_focusable(false);
|
||||
set_valign(Gtk::Align::CENTER);
|
||||
@@ -40,6 +216,12 @@ TrayIconWidget::TrayIconWidget( std::string id)
|
||||
sigc::mem_fun(*this, &TrayIconWidget::on_primary_released));
|
||||
add_controller(primaryGesture);
|
||||
|
||||
middleGesture = Gtk::GestureClick::create();
|
||||
middleGesture->set_button(GDK_BUTTON_MIDDLE);
|
||||
middleGesture->signal_released().connect(
|
||||
sigc::mem_fun(*this, &TrayIconWidget::on_middle_released));
|
||||
add_controller(middleGesture);
|
||||
|
||||
secondaryGesture = Gtk::GestureClick::create();
|
||||
secondaryGesture->set_button(GDK_BUTTON_SECONDARY);
|
||||
secondaryGesture->signal_released().connect(
|
||||
@@ -47,19 +229,36 @@ TrayIconWidget::TrayIconWidget( std::string id)
|
||||
add_controller(secondaryGesture);
|
||||
}
|
||||
|
||||
TrayIconWidget::~TrayIconWidget() {
|
||||
if (aliveFlag) {
|
||||
*aliveFlag = false;
|
||||
}
|
||||
if (menuPopover) {
|
||||
menuPopover->popdown();
|
||||
menuPopover->remove_action_group("dbusmenu");
|
||||
menuPopover->set_menu_model({});
|
||||
if (menuPopover->get_parent()) {
|
||||
menuPopover->unparent();
|
||||
}
|
||||
menuPopover.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void TrayIconWidget::update(const TrayService::Item &item) {
|
||||
hasRemoteMenu = item.menuAvailable;
|
||||
menuPopupPending = false;
|
||||
menuRequestInFlight = false;
|
||||
|
||||
if (!item.menuAvailable) {
|
||||
menuModel.reset();
|
||||
menuActions.reset();
|
||||
menuPopupPending = false;
|
||||
if (menuChangedConnection.connected()) {
|
||||
menuChangedConnection.disconnect();
|
||||
}
|
||||
if (menuPopover) {
|
||||
menuPopover->insert_action_group("dbusmenu",
|
||||
Glib::RefPtr<Gio::ActionGroup>());
|
||||
menuPopover->insert_action_group(
|
||||
"dbusmenu", Glib::RefPtr<Gio::ActionGroup>());
|
||||
menuPopover->set_menu_model({});
|
||||
menuPopover->unparent();
|
||||
if (menuPopover->get_parent()) {
|
||||
menuPopover->unparent();
|
||||
}
|
||||
menuPopover.reset();
|
||||
}
|
||||
}
|
||||
@@ -89,52 +288,132 @@ void TrayIconWidget::update(const TrayService::Item &item) {
|
||||
}
|
||||
|
||||
void TrayIconWidget::on_primary_released(int /*n_press*/, double x, double y) {
|
||||
service.activate(id, -1, -1);
|
||||
int32_t sendX = static_cast<int32_t>(std::lround(x));
|
||||
int32_t sendY = static_cast<int32_t>(std::lround(y));
|
||||
|
||||
// Try the most accurate coordinates first; fall back to pointer and finally
|
||||
// to -1/-1 so apps (e.g. Spotify) see a valid activate event on both
|
||||
// Wayland and X11.
|
||||
if (!try_get_global_click_coords(GTK_WIDGET(gobj()), x, y, sendX, sendY)) {
|
||||
if (!try_get_global_pointer_coords(GTK_WIDGET(gobj()), sendX, sendY)) {
|
||||
sendX = -1;
|
||||
sendY = -1;
|
||||
}
|
||||
}
|
||||
|
||||
spdlog::debug("[TrayIconWidget] Activate primary id={} x={} y={}", id, sendX,
|
||||
sendY);
|
||||
service.activate(id, sendX, sendY);
|
||||
}
|
||||
|
||||
void TrayIconWidget::on_middle_released(int /*n_press*/, double x, double y) {
|
||||
// Map middle click to the StatusNotifier SecondaryActivate event; some
|
||||
// apps (e.g. media players) use this for alternate actions like toggling
|
||||
// visibility.
|
||||
int32_t sendX = static_cast<int32_t>(std::lround(x));
|
||||
int32_t sendY = static_cast<int32_t>(std::lround(y));
|
||||
if (!try_get_global_click_coords(GTK_WIDGET(gobj()), x, y, sendX, sendY)) {
|
||||
if (!try_get_global_pointer_coords(GTK_WIDGET(gobj()), sendX, sendY)) {
|
||||
sendX = -1;
|
||||
sendY = -1;
|
||||
}
|
||||
}
|
||||
|
||||
spdlog::debug(
|
||||
"[TrayIconWidget] SecondaryActivate (middle) id={} x={} y={}", id,
|
||||
sendX, sendY);
|
||||
service.secondaryActivate(id, sendX, sendY);
|
||||
}
|
||||
|
||||
void TrayIconWidget::on_secondary_released(int /*n_press*/, double x,
|
||||
double y) {
|
||||
service.contextMenu(id, -1, -1);
|
||||
|
||||
if (!ensure_menu()) {
|
||||
// If we are not attached to a toplevel (e.g., window hidden), fall back to
|
||||
// the item's own ContextMenu instead of trying to show a popover, which
|
||||
// would crash without a mapped surface.
|
||||
GtkWidget *selfWidget = GTK_WIDGET(gobj());
|
||||
if (!gtk_widget_get_mapped(selfWidget) || !has_popup_surface(selfWidget)) {
|
||||
spdlog::debug(
|
||||
"[TrayIconWidget] Secondary fallback ContextMenu (no surface) id={}",
|
||||
id);
|
||||
service.contextMenu(id, -1, -1);
|
||||
return;
|
||||
}
|
||||
|
||||
pendingX = x;
|
||||
pendingY = y;
|
||||
menuPopupPending = true;
|
||||
try_popup();
|
||||
pendingX = x;
|
||||
pendingY = y;
|
||||
|
||||
// Use dbusmenu popover when available and we have a mapped surface; else
|
||||
// fall back to the item's ContextMenu.
|
||||
if (hasRemoteMenu && has_popup_surface(selfWidget)) {
|
||||
spdlog::debug("[TrayIconWidget] Requesting dbusmenu for id={}", id);
|
||||
menuPopupPending = true;
|
||||
if (menuRequestInFlight) {
|
||||
return;
|
||||
}
|
||||
|
||||
menuRequestInFlight = true;
|
||||
auto weak = std::weak_ptr<bool>(aliveFlag);
|
||||
service.request_menu_layout(
|
||||
id, [weak, this](std::optional<TrayService::MenuNode> layout) {
|
||||
if (auto locked = weak.lock()) {
|
||||
if (*locked) {
|
||||
on_menu_layout_ready(std::move(layout));
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
int32_t sendX = static_cast<int32_t>(std::lround(x));
|
||||
int32_t sendY = static_cast<int32_t>(std::lround(y));
|
||||
if (!try_get_global_click_coords(GTK_WIDGET(gobj()), x, y, sendX, sendY)) {
|
||||
(void)try_get_global_pointer_coords(GTK_WIDGET(gobj()), sendX, sendY);
|
||||
}
|
||||
if (is_wayland_display(GTK_WIDGET(gobj()))) {
|
||||
spdlog::debug(
|
||||
"[TrayIconWidget] ContextMenu wayland id={} x=-1 y=-1", id);
|
||||
service.contextMenu(id, -1, -1);
|
||||
} else {
|
||||
spdlog::debug("[TrayIconWidget] ContextMenu id={} x={} y={}", id,
|
||||
sendX, sendY);
|
||||
service.contextMenu(id, sendX, sendY);
|
||||
}
|
||||
}
|
||||
|
||||
bool TrayIconWidget::ensure_menu() {
|
||||
auto layoutOpt = service.get_menu_layout(id);
|
||||
if (!layoutOpt) {
|
||||
void TrayIconWidget::on_menu_layout_ready(
|
||||
std::optional<TrayService::MenuNode> layoutOpt) {
|
||||
menuRequestInFlight = false;
|
||||
|
||||
if (!menuPopupPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
GtkWidget *selfWidget = GTK_WIDGET(gobj());
|
||||
|
||||
if (!has_popup_surface(selfWidget)) {
|
||||
menuPopupPending = false;
|
||||
menuModel.reset();
|
||||
menuActions.reset();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!layoutOpt) {
|
||||
menuPopupPending = false;
|
||||
if (menuChangedConnection.connected()) {
|
||||
menuChangedConnection.disconnect();
|
||||
}
|
||||
if (menuPopover) {
|
||||
remove_action_group("dbusmenu");
|
||||
menuPopover->set_menu_model({});
|
||||
menuPopover->unparent();
|
||||
menuPopover.reset();
|
||||
}
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
const auto &layout = *layoutOpt;
|
||||
|
||||
auto menu = Gio::Menu::create();
|
||||
auto actions = Gio::SimpleActionGroup::create();
|
||||
log_menu_tree(layout.children, 0);
|
||||
auto menu = Gio::Menu::create();
|
||||
auto actions = Gio::SimpleActionGroup::create();
|
||||
|
||||
populate_menu_items(layout.children, menu, actions);
|
||||
|
||||
const auto itemCount = menu->get_n_items();
|
||||
|
||||
if (itemCount == 0) {
|
||||
return false;
|
||||
if (menu->get_n_items() == 0) {
|
||||
menuModel.reset();
|
||||
menuActions.reset();
|
||||
menuPopupPending = false;
|
||||
return;
|
||||
}
|
||||
|
||||
menuModel = menu;
|
||||
@@ -145,7 +424,8 @@ bool TrayIconWidget::ensure_menu() {
|
||||
menuPopover =
|
||||
Glib::make_refptr_for_instance<Gtk::PopoverMenu>(rawPopover);
|
||||
if (!menuPopover) {
|
||||
return false;
|
||||
menuPopupPending = false;
|
||||
return;
|
||||
}
|
||||
|
||||
menuPopover->set_has_arrow(false);
|
||||
@@ -155,33 +435,17 @@ bool TrayIconWidget::ensure_menu() {
|
||||
|
||||
menuPopover->remove_action_group("dbusmenu");
|
||||
menuPopover->insert_action_group("dbusmenu", menuActions);
|
||||
|
||||
if (menuChangedConnection.connected()) {
|
||||
menuChangedConnection.disconnect();
|
||||
}
|
||||
menuChangedConnection = menuModel->signal_items_changed().connect(
|
||||
sigc::mem_fun(*this, &TrayIconWidget::on_menu_items_changed));
|
||||
|
||||
menuPopover->set_menu_model(menuModel);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void TrayIconWidget::on_menu_items_changed(guint /*position*/,
|
||||
guint /*removed*/, guint /*added*/) {
|
||||
if (!menuModel) {
|
||||
return;
|
||||
// Ensure popover is still parented to us and has a native/root before popup.
|
||||
if (!menuPopover->get_parent()) {
|
||||
menuPopover->set_parent(*this);
|
||||
}
|
||||
|
||||
try_popup();
|
||||
}
|
||||
|
||||
void TrayIconWidget::try_popup() {
|
||||
if (!menuPopupPending || !menuPopover || !menuModel) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (menuModel->get_n_items() == 0) {
|
||||
GtkWidget *popoverWidget = GTK_WIDGET(menuPopover->gobj());
|
||||
if (!popoverWidget || !gtk_widget_get_root(popoverWidget) ||
|
||||
!gtk_widget_get_native(popoverWidget) || !has_popup_surface(selfWidget)) {
|
||||
menuPopupPending = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -241,10 +505,47 @@ void TrayIconWidget::populate_menu_items(
|
||||
|
||||
void TrayIconWidget::on_menu_action(const Glib::VariantBase & /*parameter*/,
|
||||
int itemId) {
|
||||
service.activate_menu_item(id, itemId);
|
||||
// Pop down immediately so the popover doesn't outlive us if the item
|
||||
// removes itself synchronously (e.g., "Exit"), which would otherwise lead
|
||||
// to use-after-free.
|
||||
if (menuPopover) {
|
||||
menuPopover->popdown();
|
||||
// Also detach to avoid double-unparent if the item disappears during
|
||||
// the ensuing D-Bus call.
|
||||
if (menuPopover->get_parent()) {
|
||||
menuPopover->unparent();
|
||||
}
|
||||
}
|
||||
|
||||
int32_t sendX = -1;
|
||||
int32_t sendY = -1;
|
||||
(void)try_get_pending_coords(sendX, sendY);
|
||||
|
||||
spdlog::debug("[TrayIconWidget] Menu action id={} item={} x={} y={}",
|
||||
this->id, itemId, sendX, sendY);
|
||||
|
||||
const uint32_t nowMs = static_cast<uint32_t>(g_get_monotonic_time() / 1000);
|
||||
// Use button 1 for menu activation events; some dbusmenu handlers ignore
|
||||
// secondary-button payloads for activate.
|
||||
service.activate_menu_item(id, itemId, sendX, sendY, 1 /*button*/, nowMs);
|
||||
}
|
||||
|
||||
bool TrayIconWidget::try_get_pending_coords(int32_t &outX, int32_t &outY) const {
|
||||
outX = -1;
|
||||
outY = -1;
|
||||
int32_t sendX = static_cast<int32_t>(std::lround(pendingX));
|
||||
int32_t sendY = static_cast<int32_t>(std::lround(pendingY));
|
||||
if (!try_get_global_click_coords(GTK_WIDGET(gobj()), pendingX, pendingY,
|
||||
sendX, sendY)) {
|
||||
if (!try_get_global_pointer_coords(GTK_WIDGET(gobj()), sendX, sendY)) {
|
||||
sendX = -1;
|
||||
sendY = -1;
|
||||
}
|
||||
}
|
||||
|
||||
outX = sendX;
|
||||
outY = sendY;
|
||||
return (sendX != -1 || sendY != -1);
|
||||
}
|
||||
|
||||
TrayWidget::TrayWidget()
|
||||
@@ -307,7 +608,6 @@ void TrayWidget::on_item_removed(const std::string &id) {
|
||||
}
|
||||
|
||||
remove(*it->second);
|
||||
it->second->unparent();
|
||||
icons.erase(it);
|
||||
|
||||
if (icons.empty()) {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
#include "widgets/volumeWidget.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <spdlog/spdlog.h>
|
||||
#include <regex>
|
||||
#include <sigc++/functors/mem_fun.h>
|
||||
|
||||
#include "helpers/systemHelper.hpp"
|
||||
#include "helpers/command.hpp"
|
||||
|
||||
#include "giomm/applicationcommandline.h"
|
||||
|
||||
VolumeWidget::VolumeWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) {
|
||||
set_valign(Gtk::Align::CENTER);
|
||||
@@ -21,11 +23,10 @@ VolumeWidget::VolumeWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) {
|
||||
click->set_button(GDK_BUTTON_PRIMARY);
|
||||
click->signal_released().connect([this](int, double, double) {
|
||||
try {
|
||||
(void)SystemHelper::get_command_output(
|
||||
(void)CommandHelper::exec(
|
||||
"wpctl set-mute @DEFAULT_SINK@ toggle");
|
||||
} catch (const std::exception &ex) {
|
||||
std::cerr << "[VolumeWidget] failed to toggle mute: " << ex.what()
|
||||
<< std::endl;
|
||||
spdlog::error("[VolumeWidget] failed to toggle mute: {}", ex.what());
|
||||
}
|
||||
this->update();
|
||||
});
|
||||
@@ -44,8 +45,7 @@ VolumeWidget::~VolumeWidget() {
|
||||
|
||||
void VolumeWidget::update() {
|
||||
try {
|
||||
const std::string out =
|
||||
SystemHelper::get_command_output("wpctl get-volume @DEFAULT_SINK@");
|
||||
const std::string out = CommandHelper::exec("wpctl get-volume @DEFAULT_SINK@");
|
||||
|
||||
std::smatch m;
|
||||
std::regex r_percent(R"((\d+(?:\.\d+)?)%)");
|
||||
@@ -76,8 +76,7 @@ void VolumeWidget::update() {
|
||||
}
|
||||
}
|
||||
} catch (const std::exception &ex) {
|
||||
std::cerr << "[VolumeWidget] failed to read volume: " << ex.what()
|
||||
<< std::endl;
|
||||
spdlog::error("[VolumeWidget] failed to read volume: {}", ex.what());
|
||||
label.set_text("N/A");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
#include "widgets/workspaceIndicator.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <gdk/gdk.h>
|
||||
#include <gtkmm/gestureclick.h>
|
||||
#include <gtkmm/overlay.h>
|
||||
#include <gtkmm/widget.h>
|
||||
#include <sigc++/functors/mem_fun.h>
|
||||
|
||||
#include "services/hyprland.hpp"
|
||||
|
||||
#include "gtkmm/box.h"
|
||||
#include "gtkmm/label.h"
|
||||
|
||||
WorkspaceIndicator::WorkspaceIndicator(int monitorId)
|
||||
: Gtk::Box(Gtk::Orientation::HORIZONTAL),
|
||||
monitorId(monitorId) {
|
||||
set_margin_top(2);
|
||||
set_margin_bottom(2);
|
||||
|
||||
workspaceConnection = service->workspaceStateChanged.connect(
|
||||
sigc::mem_fun(*this, &WorkspaceIndicator::on_workspace_update));
|
||||
monitorConnection = service->monitorStateChanged.connect(
|
||||
sigc::mem_fun(*this, &WorkspaceIndicator::on_monitor_update));
|
||||
|
||||
for (int i = 1; i <= HyprlandService::kWorkspaceSlotCount; ++i) {
|
||||
auto overlay = Gtk::make_managed<Gtk::Overlay>();
|
||||
auto numLabel = Gtk::make_managed<Gtk::Label>(std::to_string(i));
|
||||
auto pillContainer = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL);
|
||||
|
||||
auto gesture = Gtk::GestureClick::create();
|
||||
gesture->set_button(GDK_BUTTON_PRIMARY);
|
||||
gesture->signal_released().connect([this, i](int, double, double) {
|
||||
this->service->switchToWorkspace(
|
||||
i + this->monitorId * HyprlandService::kWorkspaceSlotCount);
|
||||
});
|
||||
|
||||
workspaceGestures[i] = gesture;
|
||||
workspaceIndicators[i] = overlay;
|
||||
|
||||
overlay->add_controller(gesture);
|
||||
overlay->add_css_class("workspace-pill");
|
||||
|
||||
if (i == 6 || i == 7) {
|
||||
auto indicator = Gtk::make_managed<Gtk::Label>(i == 6 ? "🫱🏻" : "🫲🏻");
|
||||
indicator->add_css_class(i == 6 ? "workspace-pill-six" : "workspace-pill-seven");
|
||||
indicator->set_valign(Gtk::Align::END);
|
||||
overlay->set_child(*indicator);
|
||||
overlay->add_overlay(*numLabel);
|
||||
pillContainer->append(*overlay);
|
||||
} else {
|
||||
overlay->set_child(*numLabel);
|
||||
pillContainer->append(*overlay);
|
||||
}
|
||||
|
||||
append(*pillContainer);
|
||||
}
|
||||
|
||||
rebuild();
|
||||
}
|
||||
|
||||
WorkspaceIndicator::~WorkspaceIndicator() {
|
||||
if (workspaceConnection.connected()) {
|
||||
workspaceConnection.disconnect();
|
||||
}
|
||||
|
||||
if (monitorConnection.connected()) {
|
||||
monitorConnection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
void WorkspaceIndicator::on_workspace_update() {
|
||||
rebuild();
|
||||
}
|
||||
|
||||
void WorkspaceIndicator::on_monitor_update() {
|
||||
rebuild();
|
||||
}
|
||||
|
||||
void WorkspaceIndicator::refreshLabel(Gtk::Overlay *overlay, const HyprlandService::WorkspaceState &state) {
|
||||
overlay->remove_css_class("workspace-pill-active");
|
||||
overlay->remove_css_class("workspace-pill-focused");
|
||||
overlay->remove_css_class("workspace-pill-urgent");
|
||||
|
||||
// controller created once in constructor and reused
|
||||
if (state.urgentWindows.size() > 0) {
|
||||
overlay->add_css_class("workspace-pill-urgent");
|
||||
} else {
|
||||
if (state.focused) {
|
||||
overlay->add_css_class("workspace-pill-focused");
|
||||
} else if (state.active) {
|
||||
overlay->add_css_class("workspace-pill-active");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WorkspaceIndicator::rebuild() {
|
||||
HyprlandService::Monitor *mon = service->getMonitorById(this->monitorId);
|
||||
|
||||
for (auto [id, workspaceState] : mon->workspaceStates) {
|
||||
Gtk::Overlay *overlay = workspaceIndicators[id];
|
||||
this->refreshLabel(overlay, *workspaceState);
|
||||
}
|
||||
}
|
||||
24
tests/string_helper_tests.cpp
Normal file
24
tests/string_helper_tests.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include "helpers/string.hpp"
|
||||
|
||||
TEST_CASE("StringHelper::split by char", "[string]") {
|
||||
const auto tokens = StringHelper::split("a,b,,c", ',');
|
||||
REQUIRE(tokens.size() == 3);
|
||||
REQUIRE(tokens[0] == "a");
|
||||
REQUIRE(tokens[1] == "b");
|
||||
REQUIRE(tokens[2] == "c");
|
||||
}
|
||||
|
||||
TEST_CASE("StringHelper::split by string", "[string]") {
|
||||
const auto tokens = StringHelper::split("one::two::three", "::");
|
||||
REQUIRE(tokens.size() == 3);
|
||||
REQUIRE(tokens[0] == "one");
|
||||
REQUIRE(tokens[1] == "two");
|
||||
REQUIRE(tokens[2] == "three");
|
||||
}
|
||||
|
||||
TEST_CASE("StringHelper::trimToSize", "[string]") {
|
||||
REQUIRE(StringHelper::trimToSize("hello", 10) == "hello");
|
||||
REQUIRE(StringHelper::trimToSize("hello world", 5) == "hello...");
|
||||
}
|
||||
Reference in New Issue
Block a user