Compare commits

...

17 Commits

Author SHA1 Message Date
e3bb3fdf31 deine cousine 4. grades 2026-01-10 22:02:27 +01:00
0e613141da quick commit 2026-01-03 22:55:02 +01:00
ab7b3b3092 better working tray 2026-01-02 16:50:02 +01:00
2d5b492da8 deine mum 2025-12-30 21:55:11 +01:00
9b5db719cb refactor and shizz 2025-12-25 21:13:00 +01:00
a06c96f648 make bluetooth service singleton 2025-12-23 19:57:52 +01:00
8613024f8d nicer button interactivities 2025-12-22 02:32:18 +01:00
5a429a3b8b bar can now toggle bluetooth power and discovery 2025-12-22 01:41:01 +01:00
0101ea1ec0 add todos 2025-12-21 22:22:59 +01:00
22a1b7e369 add todo setup 2025-12-21 00:36:00 +01:00
36f8b6d8b2 small refactors 2025-12-20 21:05:57 +01:00
47f052f913 add popover component 2025-12-20 20:52:04 +01:00
3558fd3ebc get notifications from dbus 2025-12-20 18:53:19 +01:00
c245fa7277 deine cousine 2025-12-18 11:04:30 +01:00
9b0a036925 fix urgent window icons 2025-12-17 23:34:12 +01:00
11ccd55a52 fix workspace interactivity 2025-12-17 22:45:30 +01:00
a912cb9687 optimized the code, added some bugs :) 2025-12-17 16:12:15 +01:00
42 changed files with 3060 additions and 930 deletions

View File

@@ -1 +1,12 @@
IndentWidth: 4 IndentWidth: 4
ColumnLimit: 0
AlignConsecutiveAssignments: true
IncludeCategories:
- Regex: '^(<.+>)$'
Priority: 1
- Regex: '^"(.+\.hpp)"$'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeBlocks: Regroup

View File

@@ -9,38 +9,42 @@ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
find_package(PkgConfig REQUIRED) find_package(PkgConfig REQUIRED)
# Some CMake versions may enable C++ modules and add compiler flags
# like `-fmodules-ts`. Older or certain `clang`/`clangd` builds may
# not accept this flag and will report "Unknown argument: '-fmodules-ts'".
# Strip that flag when using Clang to avoid diagnostics from clang/clangd.
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|AppleClang")
string(REPLACE "-fmodules-ts" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
string(REPLACE "-fmodules-ts" "" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
string(REPLACE "-fmodules-ts" "" CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
string(REPLACE "-fmodules-ts" "" CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL}")
string(REPLACE "-fmodules-ts" "" CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO}")
endif()
pkg_check_modules(GTKMM REQUIRED gtkmm-4.0) pkg_check_modules(GTKMM REQUIRED gtkmm-4.0)
pkg_check_modules(LAYERSHELL REQUIRED gtk4-layer-shell-0) pkg_check_modules(LAYERSHELL REQUIRED gtk4-layer-shell-0)
pkg_check_modules(WEBKIT REQUIRED webkitgtk-6.0) pkg_check_modules(WEBKIT REQUIRED webkitgtk-6.0)
pkg_check_modules(SQLITE3 REQUIRED sqlite3)
include_directories(${GTKMM_INCLUDE_DIRS} ${LAYERSHELL_INCLUDE_DIRS} ${WEBKIT_INCLUDE_DIRS}) 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}) link_directories(${GTKMM_LIBRARY_DIRS} ${LAYERSHELL_LIBRARY_DIRS} ${WEBKIT_LIBRARY_DIRS} ${SQLITE3_LIBRARY_DIRS})
add_library(bar_lib) add_library(bar_lib)
target_sources(bar_lib target_sources(bar_lib
PUBLIC PUBLIC
src/app.cpp src/app.cpp
src/bar/bar.cpp src/bar/bar.cpp
src/widgets/clock.cpp src/widgets/clock.cpp
src/widgets/date.cpp src/widgets/date.cpp
src/widgets/workspaceIndicator.cpp src/widgets/workspaceIndicator.cpp
src/widgets/volumeWidget.cpp src/widgets/volumeWidget.cpp
src/widgets/webWidget.cpp src/widgets/webWidget.cpp
src/widgets/battery.cpp
src/services/todo.cpp
src/services/sqliteTodoAdapter.cpp
src/services/hyprland.cpp src/services/hyprland.cpp
src/services/tray.cpp src/services/tray.cpp
src/services/notifications.cpp
src/services/bluetooth.cpp
src/widgets/tray.cpp src/widgets/tray.cpp
src/widgets/todo.cpp
src/widgets/bluetooth.cpp
src/widgets/controlCenter.cpp
src/components/popover.cpp
src/components/todoEntry.cpp
src/components/base/button.cpp
) )
include_directories(bar_lib PRIVATE include_directories(bar_lib PRIVATE
include include
@@ -48,7 +52,7 @@ include_directories(bar_lib PRIVATE
add_executable(bar main.cpp) add_executable(bar main.cpp)
target_link_libraries(bar bar_lib ${GTKMM_LIBRARIES} ${LAYERSHELL_LIBRARIES} ${WEBKIT_LIBRARIES}) target_link_libraries(bar bar_lib ${GTKMM_LIBRARIES} ${LAYERSHELL_LIBRARIES} ${WEBKIT_LIBRARIES} ${SQLITE3_LIBRARIES})
# Copy `resources/bar.css` into the build directory when it changes # Copy `resources/bar.css` into the build directory when it changes
set(RES_SRC "${CMAKE_CURRENT_SOURCE_DIR}/resources/bar.css") set(RES_SRC "${CMAKE_CURRENT_SOURCE_DIR}/resources/bar.css")

View File

@@ -3,10 +3,12 @@
#include <vector> #include <vector>
#include "bar/bar.hpp" #include "bar/bar.hpp"
#include "services/hyprland.hpp"
#include "services/notifications.hpp"
#include "services/tray.hpp"
#include "glibmm/refptr.h" #include "glibmm/refptr.h"
#include "gtkmm/application.h" #include "gtkmm/application.h"
#include "services/hyprland.hpp"
#include "services/tray.hpp"
class App { class App {
public: public:
@@ -17,8 +19,9 @@ class App {
private: private:
Glib::RefPtr<Gtk::Application> app; Glib::RefPtr<Gtk::Application> app;
std::vector<Bar *> bars; std::vector<Bar *> bars;
HyprlandService hyprlandService; HyprlandService *hyprlandService = HyprlandService::getInstance();
TrayService trayService; NotificationService notificationService;
TrayService *trayService = TrayService::getInstance();
void setupServices(); void setupServices();
}; };

View File

@@ -3,38 +3,42 @@
#include <gtk4-layer-shell/gtk4-layer-shell.h> #include <gtk4-layer-shell/gtk4-layer-shell.h>
#include <gtkmm.h> #include <gtkmm.h>
#include "services/hyprland.hpp" #include "icons.hpp"
#include "services/tray.hpp" #include "widgets/battery.hpp"
#include "widgets/clock.hpp" #include "widgets/clock.hpp"
#include "widgets/controlCenter.hpp"
#include "widgets/date.hpp" #include "widgets/date.hpp"
#include "widgets/tray.hpp" #include "widgets/tray.hpp"
#include "widgets/volumeWidget.hpp"
#include "widgets/webWidget.hpp" #include "widgets/webWidget.hpp"
#include "widgets/workspaceIndicator.hpp" #include "widgets/workspaceIndicator.hpp"
#include "icons.hpp"
class Bar : public Gtk::Window { class Bar : public Gtk::Window {
public: public:
Bar(GdkMonitor *monitor, HyprlandService &hyprlandService, Bar(GdkMonitor *monitor, int monitorId);
TrayService &trayService, int monitorId);
private:
int monitorId;
protected:
Gtk::CenterBox main_box{}; Gtk::CenterBox main_box{};
Gtk::Box left_box{Gtk::Orientation::HORIZONTAL}; Gtk::Box left_box{Gtk::Orientation::HORIZONTAL};
Gtk::Box center_box{Gtk::Orientation::HORIZONTAL}; Gtk::Box center_box{Gtk::Orientation::HORIZONTAL};
Gtk::Box right_box{Gtk::Orientation::HORIZONTAL}; Gtk::Box right_box{Gtk::Orientation::HORIZONTAL};
private:
Clock clock; Clock clock;
Date date; Date date;
WebWidget homeAssistant {ICON_HOME, "Home Assistant", WebWidget homeAssistant{ICON_HOME, "Home Assistant", "https://home.rivercry.com"};
"https://home.rivercry.com"}; ControlCenter controlCenter{"\ue8bb", "Control Center"};
TrayService &trayService;
HyprlandService &hyprlandService;
int monitorId;
WorkspaceIndicator *workspaceIndicator = nullptr; WorkspaceIndicator *workspaceIndicator = nullptr;
TrayWidget *trayWidget = nullptr; TrayWidget *trayWidget = nullptr;
class VolumeWidget *volumeWidget = nullptr; VolumeWidget *volumeWidget = nullptr;
BatteryWidget *batteryWidget = nullptr;
void setup_ui(); void setup_ui();
void setup_left_box();
void setup_center_box();
void setup_right_box();
void load_css(); void load_css();
}; };

View File

@@ -0,0 +1,18 @@
#pragma once
#include <gtkmm/button.h>
#include "gtkmm/image.h"
#include "sigc++/signal.h"
class Button : public Gtk::Button {
public:
Button(const std::string label);
Button(Gtk::Image &image);
sigc::signal<void()> onClickedSignal;
private:
void on_clicked() {
onClickedSignal.emit();
}
};

View File

@@ -0,0 +1,19 @@
#pragma once
#include <gtkmm/button.h>
#include <gtkmm/popover.h>
#include <string>
#include "components/base/button.hpp"
class Popover : public Button {
public:
Popover(const std::string icon, std::string name);
~Popover() override;
protected:
void on_toggle_window();
Gtk::Popover *popover = nullptr;
void set_popover_child(Gtk::Widget &child) {
gtk_popover_set_child(popover->gobj(), child.gobj());
}
};

View File

@@ -0,0 +1,21 @@
#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();
};

View File

@@ -1,7 +1,7 @@
#pragma once #pragma once
class IUpdatable { class IUpdatable {
public: public:
virtual ~IUpdatable() = default; virtual ~IUpdatable() = default;
virtual bool onUpdate() = 0; virtual bool onUpdate() = 0;
}; };

View File

@@ -0,0 +1,49 @@
#pragma once
#include <gio/gio.h>
#include <gtk/gtk.h>
#include <string>
#include <vector>
#include "sigc++/signal.h"
class BluetoothService {
inline static BluetoothService *instance = nullptr;
public:
sigc::signal<void(bool)> powerStateChangedSignal;
sigc::signal<void(bool)> isDiscoveringChangedSignal;
bool getPowerState();
bool getIsDiscovering();
void togglePowerState();
void toggleIsDiscovering();
static BluetoothService *getInstance() {
if (BluetoothService::instance == nullptr) {
BluetoothService::instance = new BluetoothService();
}
return BluetoothService::instance;
}
private:
BluetoothService();
GDBusProxy *adapter_proxy = nullptr;
std::vector<std::string> getDeviceObjectPaths();
bool powerState = false;
bool isDiscovering = false;
void onPropertyChanged(GDBusProxy *proxy,
GVariant *changed_properties,
const gchar *const *invalidated_properties,
gpointer user_data);
static void onPropertyChangedStatic(GDBusProxy *proxy,
GVariant *changed_properties,
const gchar *const *invalidated_properties,
gpointer user_data);
};

View File

@@ -2,26 +2,36 @@
#include <cstddef> #include <cstddef>
#include <glibmm.h> #include <glibmm.h>
#include <iostream>
#include <map> #include <map>
#include <sigc++/sigc++.h> #include <sigc++/sigc++.h>
#include <string> #include <string>
#include <sys/stat.h>
#include <vector>
class HyprlandService { class HyprlandService {
inline static HyprlandService *instance = nullptr;
public: public:
static constexpr int kWorkspaceSlotCount = 5; 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 WorkspaceState { struct WorkspaceState {
int id = -1;
int hyprId = -1; int hyprId = -1;
int monitorId = -1;
bool active = false; bool active = false;
bool focused = false; bool focused = false;
bool urgent = false; std::vector<std::string> urgentWindows;
std::string label; std::string label;
}; };
struct Monitor { struct Monitor {
std::map<int, WorkspaceState> workspaceStates; std::map<int, WorkspaceState *> workspaceStates;
std::string name; std::string name;
int x = 0; int x = 0;
int y = 0; int y = 0;
@@ -29,74 +39,44 @@ class HyprlandService {
int focusedWorkspaceId = -1; int focusedWorkspaceId = -1;
}; };
HyprlandService();
~HyprlandService();
void start(); void start();
void on_hyprland_event(std::string event, std::string data); void on_hyprland_event(std::string event, std::string data);
void printMonitor(const Monitor &mon) const; void printMonitor(const Monitor &mon) const;
sigc::signal<void(std::string, std::string)> socketEventSignal; sigc::signal<void(std::string, std::string)> socketEventSignal;
sigc::signal<void(int)> workspaceStateChanged; sigc::signal<void()> workspaceStateChanged;
sigc::signal<void()> monitorStateChanged; sigc::signal<void()> monitorStateChanged;
Monitor *getMonitorById(int id); Monitor *getMonitorById(int id);
const Monitor *getMonitorById(int id) const;
Monitor *getMonitorByIndex(std::size_t index); Monitor *getMonitorByIndex(std::size_t index);
const Monitor *getMonitorByIndex(std::size_t index) const;
// Switch to a workspace slot on a given monitor. If the workspace has an
// associated Hyprland workspace id (hyprId >= 0) that id will be used.
// Otherwise the slot and monitor name will be used to request creation
// / activation via `hyprctl`.
void switchToWorkspace(int workspaceId); void switchToWorkspace(int workspaceId);
private: std::map<int, WorkspaceState *> getAllWorkspaces() const {
int fd = -1; return this->workspaces;
std::string buffer; }
std::map<int, Monitor> monitors;
static HyprlandService *getInstance() {
if (HyprlandService::instance == nullptr) {
HyprlandService::instance = new HyprlandService();
}
return HyprlandService::instance;
}
private:
HyprlandService();
~HyprlandService();
int fd = -1;
std::map<int, Monitor> monitors;
std::map<int, WorkspaceState *> workspaces;
std::string socket_buffer;
std::string get_socket_path();
bool on_socket_read(Glib::IOCondition condition); bool on_socket_read(Glib::IOCondition condition);
void parse_message(const std::string &line); void parse_message(const std::string &line);
std::string get_socket_path();
void refresh_monitors(); void refresh_monitors();
void refresh_workspaces(); void refresh_workspaces();
void handle_urgent_window(std::string windowAddress); void onUrgentEvent(std::string windowAddress);
void onActiveWindowEvent(std::string windowAddress);
}; };
inline void HyprlandService::printMonitor(const Monitor &mon) const {
std::cout << "=== Monitor Info ===\n";
std::cout << "Name: " << mon.name << " (ID: " << mon.id << ")\n";
std::cout << "Position: (" << mon.x << ", " << mon.y << ")\n";
std::cout << "Focused Workspace ID: " << mon.focusedWorkspaceId << "\n";
std::cout << "Workspaces:\n";
if (mon.workspaceStates.empty()) {
std::cout << " (None)\n";
} else {
for (int slot = 1; slot <= HyprlandService::kWorkspaceSlotCount;
++slot) {
const auto it = mon.workspaceStates.find(slot);
if (it == mon.workspaceStates.end()) {
std::cout << " - [Slot: " << slot << " | HyprID: n/a]"
<< " Label: <none> | Active: No | Focused: No | "
"Urgent: No\n";
continue;
}
const WorkspaceState &ws = it->second;
std::cout << " - [Slot: " << ws.id << " | HyprID: "
<< (ws.hyprId >= 0 ? std::to_string(ws.hyprId)
: std::string("n/a"))
<< "] "
<< "Label: " << (ws.label.empty() ? "<none>" : ws.label)
<< " | "
<< "Active: " << (ws.active ? "Yes" : "No") << " | "
<< "Focused: " << (ws.focused ? "Yes" : "No") << " | "
<< "Urgent: " << (ws.urgent ? "Yes" : "No") << "\n";
}
}
std::cout << "====================\n";
}

View File

@@ -0,0 +1,20 @@
#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;
};

28
include/services/todo.hpp Normal file
View File

@@ -0,0 +1,28 @@
#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;
};

View File

@@ -0,0 +1,21 @@
#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;
};

View File

@@ -1,22 +1,22 @@
#pragma once #pragma once
#include <gdkmm/memorytexture.h> #include <gdkmm/memorytexture.h>
#include <gio/gio.h>
#include <giomm/actiongroup.h> #include <giomm/actiongroup.h>
#include <giomm/dbusconnection.h> #include <giomm/dbusconnection.h>
#include <giomm/init.h> #include <giomm/init.h>
#include <giomm/menumodel.h> #include <giomm/menumodel.h>
#include <glibmm/bytes.h> #include <glibmm/bytes.h>
#include <glibmm/refptr.h> #include <glibmm/refptr.h>
#include <sigc++/sigc++.h>
#include <gio/gio.h>
#include <map> #include <map>
#include <memory> #include <memory>
#include <optional> #include <optional>
#include <sigc++/sigc++.h>
#include <string> #include <string>
#include <vector> #include <vector>
class TrayService { class TrayService {
inline static TrayService *instance = nullptr;
public: public:
struct Item { struct Item {
std::string id; std::string id;
@@ -30,9 +30,6 @@ class TrayService {
Glib::RefPtr<Gdk::Paintable> iconPaintable; Glib::RefPtr<Gdk::Paintable> iconPaintable;
}; };
TrayService();
~TrayService();
void start(); void start();
void stop(); void stop();
@@ -45,7 +42,6 @@ class TrayService {
Glib::RefPtr<Gio::MenuModel> get_menu_model(const std::string &id); Glib::RefPtr<Gio::MenuModel> get_menu_model(const std::string &id);
Glib::RefPtr<Gio::ActionGroup> get_menu_action_group(const std::string &id); Glib::RefPtr<Gio::ActionGroup> get_menu_action_group(const std::string &id);
void debug_dump_menu_layout(const std::string &id);
struct MenuNode { struct MenuNode {
int id = 0; int id = 0;
std::string label; std::string label;
@@ -54,20 +50,39 @@ class TrayService {
bool separator = false; bool separator = false;
std::vector<MenuNode> children; std::vector<MenuNode> children;
}; };
std::optional<MenuNode> get_menu_layout(const std::string &id); using MenuLayoutCallback = sigc::slot<void(std::optional<MenuNode>)>;
bool activate_menu_item(const std::string &id, int itemId); 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 Item &)> &signal_item_added();
sigc::signal<void(const std::string &)> &signal_item_removed(); sigc::signal<void(const std::string &)> &signal_item_removed();
sigc::signal<void(const Item &)> &signal_item_updated(); sigc::signal<void(const Item &)> &signal_item_updated();
static TrayService *getInstance() {
if (TrayService::instance == nullptr) {
TrayService::instance = new TrayService();
}
return TrayService::instance;
}
private: private:
TrayService();
~TrayService();
struct TrackedItem { struct TrackedItem {
Item publicData; Item publicData;
guint signalSubscriptionId = 0; guint signalSubscriptionId = 0;
guint ownerWatchId = 0; guint ownerWatchId = 0;
Glib::RefPtr<Gio::MenuModel> menuModel; Glib::RefPtr<Gio::MenuModel> menuModel;
Glib::RefPtr<Gio::ActionGroup> menuActions; Glib::RefPtr<Gio::ActionGroup> menuActions;
guint refreshSourceId = 0;
bool refreshInFlight = false;
bool refreshQueued = false;
bool addSignalPending = false;
}; };
Glib::RefPtr<Gio::DBus::Connection> connection; Glib::RefPtr<Gio::DBus::Connection> connection;
@@ -117,7 +132,11 @@ class TrayService {
void register_item(const Glib::ustring &sender, const std::string &service); void register_item(const Glib::ustring &sender, const std::string &service);
void unregister_item(const std::string &id); 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(); void emit_registered_items_changed();
Glib::Variant<std::vector<Glib::ustring>> Glib::Variant<std::vector<Glib::ustring>>

View File

@@ -0,0 +1,26 @@
#pragma once
#include <filesystem>
#include <gtkmm/box.h>
#include <gtkmm/label.h>
#include <sigc++/connection.h>
class BatteryWidget : public Gtk::Box {
public:
BatteryWidget();
~BatteryWidget();
private:
Gtk::Label iconLabel;
Gtk::Label label;
sigc::connection timeoutConn;
std::filesystem::path batteryPath;
std::string currentStateClass;
void update();
bool on_timeout();
void find_battery_path();
void set_state_class(const std::string &stateClass);
std::string build_icon(int capacity, bool hasBattery, bool charging, bool full) const;
std::string build_text(int capacity, const std::string &status, bool hasBattery, bool charging, bool full) const;
};

View File

@@ -0,0 +1,68 @@
#pragma once
#include <gtkmm/box.h>
#include <gtkmm/button.h>
#include <gtkmm/label.h>
#include "components/base/button.hpp"
class BluetoothEntry : Gtk::Box {
public:
BluetoothEntry(std::string name, std::string address) {
this->set_orientation(Gtk::Orientation::VERTICAL);
this->add_css_class("bluetooth-entry-box");
auto nameLabel = Gtk::make_managed<Gtk::Label>(name);
nameLabel->set_halign(Gtk::Align::START);
nameLabel->add_css_class("bluetooth-entry-name");
this->append(*nameLabel);
auto addressLabel = Gtk::make_managed<Gtk::Label>(address);
addressLabel->set_halign(Gtk::Align::START);
addressLabel->add_css_class("bluetooth-entry-address");
this->append(*addressLabel);
this->add_css_class("bluetooth-entry");
auto connectButton = Gtk::make_managed<Button>("Connect");
connectButton->set_halign(Gtk::Align::END);
connectButton->set_tooltip_text("Connect to Device");
connectButton->onClickedSignal.connect([this, address]() {
this->connect_clicked.emit(address);
});
this->append(*connectButton);
}
sigc::signal<void(std::string)> connect_clicked;
};
class BluetoothWidget : public Gtk::Box {
public:
BluetoothWidget();
void setPowerState(bool state);
void setIsDiscovering(bool state);
sigc::signal<void()> onPowerStateButtonClickedSignal;
sigc::signal<void()> onIsDiscoveringButtonClickedSignal;
void update();
private:
bool isPowered = false;
bool isDiscovering = false;
Gtk::Box statusArea;
std::map<std::string, BluetoothEntry *> deviceEntries;
Gtk::Box devicesArea;
Button *scanButton = nullptr;
Button *powerButton = nullptr;
void onPowerButtonClicked();
void onScanButtonClicked();
void toggleButton(Button *button, bool state);
};

View File

@@ -0,0 +1,17 @@
#pragma once
#include "components/popover.hpp"
#include "services/bluetooth.hpp"
#include "widgets/bluetooth.hpp"
#include "gtkmm/box.h"
class ControlCenter : public Popover {
public:
ControlCenter(std::string icon, std::string name);
private:
Gtk::Box container;
BluetoothWidget *bluetoothWidget = nullptr;
BluetoothService *bluetoothService = BluetoothService::getInstance();
};

21
include/widgets/todo.hpp Normal file
View File

@@ -0,0 +1,21 @@
#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;
};

View File

@@ -11,54 +11,60 @@
#include <gtkmm/image.h> #include <gtkmm/image.h>
#include <gtkmm/picture.h> #include <gtkmm/picture.h>
#include <gtkmm/popovermenu.h> #include <gtkmm/popovermenu.h>
#include <map> #include <map>
#include <memory> #include <memory>
#include <optional>
#include <string> #include <string>
#include <vector>
#include "services/tray.hpp" #include "services/tray.hpp"
#include "components/base/button.hpp"
class TrayIconWidget : public Gtk::Button { class TrayIconWidget : public Button {
public: public:
TrayIconWidget(TrayService &service, std::string id); TrayIconWidget(std::string id);
~TrayIconWidget() override;
void update(const TrayService::Item &item); void update(const TrayService::Item &item);
private: private:
TrayService &service; TrayService &service = *TrayService::getInstance();
std::string id; std::string id;
Gtk::Box container; Gtk::Box container;
Gtk::Picture picture; Gtk::Picture picture;
Gtk::Image image; Gtk::Image image;
Glib::RefPtr<Gtk::GestureClick> primaryGesture; Glib::RefPtr<Gtk::GestureClick> primaryGesture;
Glib::RefPtr<Gtk::GestureClick> middleGesture;
Glib::RefPtr<Gtk::GestureClick> secondaryGesture; Glib::RefPtr<Gtk::GestureClick> secondaryGesture;
Glib::RefPtr<Gtk::PopoverMenu> menuPopover; Glib::RefPtr<Gtk::PopoverMenu> menuPopover;
Glib::RefPtr<Gio::SimpleActionGroup> menuActions; Glib::RefPtr<Gio::SimpleActionGroup> menuActions;
Glib::RefPtr<Gio::MenuModel> menuModel; Glib::RefPtr<Gio::MenuModel> menuModel;
sigc::connection menuChangedConnection;
bool menuPopupPending = false; bool menuPopupPending = false;
bool menuRequestInFlight = false;
bool hasRemoteMenu = false;
std::shared_ptr<bool> aliveFlag;
double pendingX = 0.0; double pendingX = 0.0;
double pendingY = 0.0; double pendingY = 0.0;
void on_primary_released(int n_press, double x, double y); 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); void on_secondary_released(int n_press, double x, double y);
bool ensure_menu(); void on_menu_layout_ready(std::optional<TrayService::MenuNode> layout);
void on_menu_items_changed(guint position, guint removed, guint added);
void try_popup();
void void
populate_menu_items(const std::vector<TrayService::MenuNode> &nodes, populate_menu_items(const std::vector<TrayService::MenuNode> &nodes,
const Glib::RefPtr<Gio::Menu> &menu, const Glib::RefPtr<Gio::Menu> &menu,
const Glib::RefPtr<Gio::SimpleActionGroup> &actions); const Glib::RefPtr<Gio::SimpleActionGroup> &actions);
void on_menu_action(const Glib::VariantBase &parameter, int itemId); void on_menu_action(const Glib::VariantBase &parameter, int itemId);
bool try_get_pending_coords(int32_t &outX, int32_t &outY) const;
}; };
class TrayWidget : public Gtk::Box { class TrayWidget : public Gtk::Box {
public: public:
explicit TrayWidget(TrayService &service); explicit TrayWidget();
~TrayWidget() override; ~TrayWidget() override;
private: private:
TrayService &service; TrayService *service = TrayService::getInstance();
std::map<std::string, std::unique_ptr<TrayIconWidget>> icons; std::map<std::string, std::unique_ptr<TrayIconWidget>> icons;
sigc::connection addConnection; sigc::connection addConnection;

View File

@@ -3,12 +3,9 @@
#include <gtkmm/button.h> #include <gtkmm/button.h>
#include <gtkmm/popover.h> #include <gtkmm/popover.h>
class WebWidget : public Gtk::Button { #include "components/popover.hpp"
public:
WebWidget(std::string icon, std::string title, std::string url);
~WebWidget() override;
private: class WebWidget : public Popover {
void on_toggle_window(); public:
Gtk::Popover* popover = nullptr; WebWidget(std::string icon, std::string title, std::string url);
}; };

View File

@@ -1,24 +1,28 @@
#pragma once #pragma once
#include <gtkmm/box.h> #include <gtkmm/box.h>
#include <gtkmm/gestureclick.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <sigc++/connection.h> #include <sigc++/connection.h>
#include "services/hyprland.hpp" #include "services/hyprland.hpp"
#include "gtkmm/overlay.h"
class WorkspaceIndicator : public Gtk::Box { class WorkspaceIndicator : public Gtk::Box {
public: public:
WorkspaceIndicator(HyprlandService &service, int monitorId); WorkspaceIndicator(int monitorId);
~WorkspaceIndicator() override; ~WorkspaceIndicator() override;
private: private:
HyprlandService &service; HyprlandService *service = HyprlandService::getInstance();
int monitorId; int monitorId;
sigc::connection workspaceConnection; sigc::connection workspaceConnection;
sigc::connection monitorConnection; sigc::connection monitorConnection;
std::map<int, Gtk::Overlay *> workspaceIndicators;
std::map<int, Glib::RefPtr<Gtk::GestureClick>> workspaceGestures;
void rebuild(); void rebuild();
void on_workspace_update(int monitorId); void on_workspace_update();
void on_monitor_update(); void on_monitor_update();
void clear_children(); void refreshLabel(Gtk::Overlay *overlay, const HyprlandService::WorkspaceState &state);
}; };

View File

@@ -1,91 +1,228 @@
/** biome-ignore-all lint/correctness/noUnknownTypeSelector: gtk css has more valid identifiers */
* { * {
all: unset; all: unset;
} }
window { window {
background-color: rgba(30, 30, 30, 0.8); background-color: #191919c6;
color: #ffffff; color: #ffffff;
font-family: "IBMPlexSans-Regular", sans-serif; padding-left: 4px;
padding-right: 4px;
padding-top: 2px;
padding-bottom: 2px;
font-size: 14px; font-size: 14px;
padding: 2px 7px; font-family:
"Hack Nerd Font Mono", "Font Awesome 7 Brands", "Font Awesome 7 Free",
sans-serif;
} }
#clock-label { popover {
font-weight: bold; margin-top: 4px;
font-family: monospace; font-family:
"Hack Nerd Font Mono", "Material Icons", "Font Awesome 7 Free", sans-serif;
padding: 6px;
border-radius: 8px;
background: rgba(25, 25, 25, 0.8);
box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
border: 1px solid rgba(57, 57, 57, 0.71);
font-size: 14px;
}
tooltip {
background-color: #222222;
color: #ffffff;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
}
button {
font-family: "Material Icons", sans-serif;
font-size: 20px;
}
#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;
} }
.workspace-pill { .workspace-pill {
padding: 2px 5px; padding: 2px 5px;
margin-right: 6px; margin-right: 6px;
border-radius: 5px; border-radius: 5px;
text-shadow: 0 0 2px #646464;
transition:
background-color 0.2s,
color 0.2s,
box-shadow 0.2s;
}
.workspace-pill:hover {
background-color: rgba(255, 255, 255, 0.1);
color: #ffffff;
}
.workspace-pill-active {
background-color: #666666;
} }
.workspace-pill-focused { .workspace-pill-focused {
background-color: #ffffff; background-color: #ffffff;
color: #1e1e1e; color: #1e1e1e;
font-weight: bold; box-shadow: 0 0 6px rgba(255, 255, 255, 0.8);
border-bottom: #89b4fa 2px;
} }
.workspace-pill-active { .workspace-pill-focused:hover {
background-color: rgba(255, 255, 255, 0.2); box-shadow: none;
} }
.workspace-pill-urgent { .workspace-pill-urgent {
background-color: #ff5555; background-color: #ff5555;
color: #fff; color: #fff;
animation: workspace-blink 1s linear infinite;
} }
.workspace-pill:last-child { .workspace-pill-six {
margin-right: 0; animation: workspace-updown 1.2s ease-in-out infinite;
margin-left: -4px;
margin-top: 4px;
font-size: 12px;
} }
.workspace-pill:hover { .workspace-pill-seven {
background-color: rgba(255, 255, 255, 0.1); animation: workspace-updown 1.2s ease-in-out infinite;
animation-delay: 0.6s;
margin-right: -4px;
margin-top: 4px;
font-size: 12px;
} }
.minimized { @keyframes workspace-updown {
background-color: rgba(50, 50, 50, 0.5); 0% {
transform: translateY(4px);
}
50% {
transform: translateY(0px);
}
100% {
transform: translateY(4px);
}
} }
.restored { @keyframes workspace-blink {
background-color: transparent; 0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
} }
button { .battery-widget {
padding: 2px 5px; padding: 2px 6px;
margin: 0 2px; border-radius: 6px;
border-radius: 3px; background-color: rgba(255, 255, 255, 0.04);
background-color: transparent;
color: #ffffff;
border: none;
} }
button:hover { .battery-widget-icon {
background-color: #111111; min-width: 7ch;
text-align: center;
font-weight: 700;
letter-spacing: 0.08ch;
} }
#spacer { .battery-widget-text {
color: rgba(255, 255, 255, 0.3); font-weight: 500;
padding: 0 5px;
} }
popover { .battery-widget-normal {
background-color: rgb(30, 30, 30); background-color: rgba(120, 120, 120, 0.18);
color: #ffffff;
font-family: "IBMPlexSans-Regular", sans-serif;
} }
tooltip { .battery-widget-full {
background-color: rgba(50, 50, 50, 0.9); background-color: rgba(76, 129, 76, 0.24);
color: #ffffff;
font-family: "IBMPlexSans-Regular", sans-serif;
padding: 5px 10px;
} }
.icon-label { .battery-widget-full .battery-widget-icon {
font-family: "Material Icons, Hack Nerd Font Mono"; color: #bdf5bd;
font-size: 19px; }
.battery-widget-charging {
background-color: rgba(76, 129, 76, 0.28);
}
.battery-widget-charging .battery-widget-icon {
color: #9df19d;
animation: battery-charge-glow 1.4s ease-in-out infinite;
}
.battery-widget-low {
background-color: rgba(148, 61, 61, 0.28);
}
.battery-widget-low .battery-widget-icon {
color: #ff8585;
animation: battery-low-blink 1s steps(2, start) infinite;
}
.battery-widget-external {
background-color: rgba(100, 100, 100, 0.18);
}
.battery-widget-external .battery-widget-icon {
color: #d7d7d7;
}
@keyframes battery-charge-glow {
0% {
opacity: 0.7;
transform: translateX(0);
}
50% {
opacity: 1;
transform: translateX(1px);
}
100% {
opacity: 0.7;
transform: translateX(0);
}
}
@keyframes battery-low-blink {
0% {
opacity: 1;
}
49% {
opacity: 1;
}
50% {
opacity: 0.4;
}
100% {
opacity: 0.4;
}
} }

View File

@@ -6,6 +6,7 @@
App::App() { App::App() {
this->setupServices(); this->setupServices();
this->notificationService.intialize();
this->app = Gtk::Application::create("org.example.mybar"); this->app = Gtk::Application::create("org.example.mybar");
@@ -21,15 +22,14 @@ App::App() {
try { try {
hyprlandMonitor = hyprlandMonitor =
this->hyprlandService.getMonitorByIndex(i); this->hyprlandService->getMonitorByIndex(i);
} catch (const std::exception &ex) { } catch (const std::exception &ex) {
std::cerr << "[App] Failed to fetch Hyprland monitor: " std::cerr << "[App] Failed to fetch Hyprland monitor: "
<< ex.what() << std::endl; << ex.what() << std::endl;
continue; continue;
} }
auto bar = new Bar(monitor->gobj(), this->hyprlandService, auto bar = new Bar(monitor->gobj(), hyprlandMonitor->id);
this->trayService, hyprlandMonitor->id);
bar->set_application(app); bar->set_application(app);
bar->show(); bar->show();
@@ -38,22 +38,23 @@ App::App() {
} }
}); });
app->signal_shutdown().connect([&]() { app->signal_shutdown().connect([&]() {
for (auto bar : bars) { for (auto bar : bars) {
delete bar; delete bar;
} }
bars.clear(); bars.clear();
this->trayService.stop(); this->trayService->stop();
}); });
} }
void App::setupServices() { void App::setupServices() {
this->hyprlandService.socketEventSignal.connect(sigc::mem_fun( this->hyprlandService->socketEventSignal.connect(sigc::mem_fun(
this->hyprlandService, &HyprlandService::on_hyprland_event)); *this->hyprlandService, &HyprlandService::on_hyprland_event));
this->hyprlandService.start(); this->hyprlandService->start();
this->trayService.start(); this->trayService->start();
} }
int App::run() { return this->app->run(); } int App::run() { return this->app->run(); }

View File

@@ -1,24 +1,23 @@
#include "bar/bar.hpp" #include "bar/bar.hpp"
#include "gtk/gtk.h"
#include "widgets/date.hpp"
#include "widgets/spacer.hpp"
#include "widgets/volumeWidget.hpp"
#include "widgets/workspaceIndicator.hpp"
#include "helpers/systemHelper.hpp"
#include <filesystem> #include <filesystem>
#include <gtkmm/enums.h> #include <gtkmm/enums.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <gtkmm/window.h> #include <gtkmm/window.h>
#include "helpers/systemHelper.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 "glibmm/main.h"
#include "gtk/gtk.h"
#include "sigc++/functors/mem_fun.h" #include "sigc++/functors/mem_fun.h"
Bar::Bar(GdkMonitor *monitor, HyprlandService &hyprlandService, Bar::Bar(GdkMonitor *monitor, int monitorId)
TrayService &trayService, int monitorId) : monitorId(monitorId) {
: hyprlandService(hyprlandService), trayService(trayService),
monitorId(monitorId) {
set_name("bar-window"); set_name("bar-window");
gtk_layer_init_for_window(this->gobj()); gtk_layer_init_for_window(this->gobj());
@@ -30,79 +29,74 @@ Bar::Bar(GdkMonitor *monitor, HyprlandService &hyprlandService,
gtk_layer_set_anchor(this->gobj(), GTK_LAYER_SHELL_EDGE_TOP, true); gtk_layer_set_anchor(this->gobj(), GTK_LAYER_SHELL_EDGE_TOP, true);
gtk_layer_set_anchor(this->gobj(), GTK_LAYER_SHELL_EDGE_LEFT, true); gtk_layer_set_anchor(this->gobj(), GTK_LAYER_SHELL_EDGE_LEFT, true);
gtk_layer_set_anchor(this->gobj(), GTK_LAYER_SHELL_EDGE_RIGHT, true); gtk_layer_set_anchor(this->gobj(), GTK_LAYER_SHELL_EDGE_RIGHT, true);
gtk_layer_set_layer(this->gobj(), GTK_LAYER_SHELL_LAYER_TOP);
gtk_layer_auto_exclusive_zone_enable(this->gobj()); gtk_layer_auto_exclusive_zone_enable(this->gobj());
set_child(main_box); set_child(main_box);
this->volumeWidget = Gtk::make_managed<VolumeWidget>(); this->volumeWidget = Gtk::make_managed<VolumeWidget>();
this->workspaceIndicator = Gtk::make_managed<WorkspaceIndicator>(monitorId);
this->trayWidget = Gtk::make_managed<TrayWidget>();
this->batteryWidget = Gtk::make_managed<BatteryWidget>();
load_css(); load_css();
setup_ui(); setup_ui();
clock.onUpdate(); clock.onUpdate();
Glib::signal_timeout().connect(sigc::mem_fun(clock, &Clock::onUpdate),
1000);
date.onUpdate(); date.onUpdate();
Glib::signal_timeout().connect(sigc::mem_fun(date, &Date::onUpdate), Glib::signal_timeout().connect(sigc::mem_fun(clock, &Clock::onUpdate), 1000);
1000); Glib::signal_timeout().connect(sigc::mem_fun(date, &Date::onUpdate), 1000);
} }
void Bar::setup_ui() { void Bar::setup_ui() {
main_box.set_hexpand(true);
main_box.set_start_widget(left_box); main_box.set_start_widget(left_box);
main_box.set_center_widget(center_box); main_box.set_center_widget(center_box);
main_box.set_end_widget(right_box); main_box.set_end_widget(right_box);
main_box.set_valign(Gtk::Align::CENTER);
left_box.set_valign(Gtk::Align::CENTER); setup_left_box();
setup_center_box();
setup_right_box();
}
// Don't expand the center box — keep it centered by alignment void Bar::setup_left_box() {
center_box.set_hexpand(false);
center_box.set_valign(Gtk::Align::CENTER);
center_box.set_halign(Gtk::Align::CENTER);
right_box.set_valign(Gtk::Align::CENTER);
workspaceIndicator =
Gtk::make_managed<WorkspaceIndicator>(hyprlandService, monitorId);
left_box.append(*workspaceIndicator); left_box.append(*workspaceIndicator);
}
clock.set_name("clock-label"); 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(this->date);
center_box.append(*(new Spacer())); center_box.append(*(new Spacer()));
center_box.append(this->clock); center_box.append(this->clock);
center_box.append(*(new Spacer())); center_box.append(*(new Spacer()));
center_box.append(*this->volumeWidget); center_box.append(*this->volumeWidget);
}
void Bar::setup_right_box() {
trayWidget = Gtk::make_managed<TrayWidget>(trayService); right_box.append(*this->trayWidget);
right_box.append(*trayWidget); right_box.append(*this->batteryWidget);
right_box.append(homeAssistant); right_box.append(this->homeAssistant);
right_box.append(this->controlCenter);
} }
void Bar::load_css() { void Bar::load_css() {
auto css_provider = Gtk::CssProvider::create(); auto css_provider = Gtk::CssProvider::create();
std::string css_path = "resources/bar.css"; std::string css_path = "resources/bar.css";
const char* home = std::getenv("HOME"); const char *home = std::getenv("HOME");
if (home) { if (home) {
std::filesystem::path config_path = std::filesystem::path(home) / ".config/bar/bar.css"; std::filesystem::path config_path =
std::filesystem::path(home) / ".config/bar/bar.css";
if (std::filesystem::exists(config_path)) { if (std::filesystem::exists(config_path)) {
css_path = config_path.string(); css_path = config_path.string();
} }
} }
const std::string css = const std::string css = SystemHelper::read_file_to_string(css_path);
SystemHelper::read_file_to_string(css_path);
css_provider->load_from_data(css); css_provider->load_from_data(css);
Gtk::StyleContext::add_provider_for_display( Gtk::StyleContext::add_provider_for_display(

View File

@@ -0,0 +1,19 @@
#include "components/base/button.hpp"
#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));
this->add_css_class("button");
}
Button::Button(Gtk::Image &image)
: Gtk::Button() {
set_child(image);
signal_clicked().connect(
sigc::mem_fun(*this, &Button::on_clicked));
this->add_css_class("button");
}

View File

@@ -0,0 +1,24 @@
#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));
popover = new Gtk::Popover();
popover->set_parent(*this);
popover->set_autohide(true);
}
Popover::~Popover() {
delete popover;
}
void Popover::on_toggle_window() {
if (popover->get_visible()) {
popover->popdown();
} else {
popover->popup();
}
}

View File

@@ -0,0 +1,47 @@
#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);
}

237
src/services/bluetooth.cpp Normal file
View File

@@ -0,0 +1,237 @@
#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;
}

View File

@@ -1,29 +1,20 @@
#include "services/hyprland.hpp" #include "services/hyprland.hpp"
#include <algorithm>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <iostream>
#include <iterator> #include <iterator>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <stdexcept> #include <stdexcept>
#include <string> #include <string>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/un.h> #include <sys/un.h>
#include <unordered_set>
#include <unistd.h> #include <unistd.h>
#include <iostream>
#include "helpers/systemHelper.hpp" #include "helpers/systemHelper.hpp"
namespace {
const char *kMonitorCommand = "hyprctl monitors -j";
const char *kWorkspaceCommand = "hyprctl workspaces -j";
const char *kClientsCommand = "hyprctl clients -j";
bool is_workspace_event(const std::string &event) {
return event.find("workspace") != std::string::npos;
}
} // namespace
HyprlandService::HyprlandService() = default; HyprlandService::HyprlandService() = default;
HyprlandService::~HyprlandService() { HyprlandService::~HyprlandService() {
@@ -31,18 +22,32 @@ HyprlandService::~HyprlandService() {
close(fd); close(fd);
fd = -1; fd = -1;
} }
// free allocated workspace pointers
for (auto &p : this->workspaces) {
delete p.second;
}
this->workspaces.clear();
this->monitors.clear();
} }
void HyprlandService::on_hyprland_event(std::string event, std::string data) { void HyprlandService::on_hyprland_event(std::string event, std::string data) {
if (event == "urgent") { if (event == "urgent") {
handle_urgent_window(data); onUrgentEvent(data);
} }
if (is_workspace_event(event) || event == "focusedmon" || if (event == "activewindowv2") {
event == "monitoradded" || event == "monitorremoved") { onActiveWindowEvent(data);
refresh_monitors(); }
if (event == "workspace" || event == "movewindow") {
refresh_workspaces(); refresh_workspaces();
} }
if (event == "monitoradded" || event == "monitorremoved") {
refresh_monitors();
}
} }
void HyprlandService::start() { void HyprlandService::start() {
@@ -71,42 +76,47 @@ void HyprlandService::start() {
return; return;
} }
std::cout << "[Hyprland] Connected to event socket." << std::endl;
Glib::signal_io().connect( Glib::signal_io().connect(
sigc::mem_fun(*this, &HyprlandService::on_socket_read), fd, sigc::mem_fun(*this, &HyprlandService::on_socket_read), fd,
Glib::IOCondition::IO_IN | Glib::IOCondition::IO_HUP | Glib::IOCondition::IO_IN | Glib::IOCondition::IO_HUP |
Glib::IOCondition::IO_ERR); Glib::IOCondition::IO_ERR);
refresh_monitors(); refresh_monitors();
refresh_workspaces();
} }
bool HyprlandService::on_socket_read(Glib::IOCondition condition) { bool HyprlandService::on_socket_read(Glib::IOCondition condition) {
const auto error_mask = const auto error_mask = Glib::IOCondition::IO_HUP | Glib::IOCondition::IO_ERR;
Glib::IOCondition::IO_HUP | Glib::IOCondition::IO_ERR;
if (static_cast<int>(condition & error_mask) != 0) { if (static_cast<int>(condition & error_mask) != 0) {
std::cerr << "[Hyprland] Socket disconnected." << std::endl; std::cerr << "[Hyprland] Socket disconnected." << std::endl;
if (fd != -1) {
close(fd); close(fd);
fd = -1; fd = -1;
}
return false; return false;
} }
char buffer[4096]; char temp_buffer[4096];
const ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1); const ssize_t bytes_read = read(fd, temp_buffer, sizeof(temp_buffer));
if (bytes_read > 0) { if (bytes_read <= 0) {
buffer[bytes_read] = '\0'; // peer closed or error
this->buffer.append(buffer); 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; size_t pos = 0;
while ((pos = this->socket_buffer.find('\n')) != std::string::npos) {
while ((pos = this->buffer.find('\n')) != std::string::npos) { const std::string line = this->socket_buffer.substr(0, pos);
const std::string line = this->buffer.substr(0, pos);
parse_message(line); parse_message(line);
this->buffer.erase(0, pos + 1); this->socket_buffer.erase(0, pos + 1);
}
} }
return true; return true;
@@ -135,177 +145,121 @@ std::string HyprlandService::get_socket_path() {
} }
void HyprlandService::refresh_monitors() { void HyprlandService::refresh_monitors() {
std::string output; // free any previously allocated WorkspaceState objects before rebuilding
for (auto &p : this->workspaces) {
try { delete p.second;
output = SystemHelper::get_command_output(kMonitorCommand);
} catch (const std::exception &ex) {
std::cerr << "[Hyprland] Failed to query monitors: " << ex.what()
<< std::endl;
return;
} }
this->workspaces.clear();
this->monitors.clear();
std::string output = SystemHelper::get_command_output(kMonitorCommand);
auto monitorsJson = nlohmann::json::parse(output, nullptr, false); auto monitorsJson = nlohmann::json::parse(output, nullptr, false);
if (!monitorsJson.is_array()) {
std::cerr << "[Hyprland] Unexpected monitor payload" << std::endl;
return;
}
std::map<int, Monitor> updated;
for (const auto &monitorJson : monitorsJson) { for (const auto &monitorJson : monitorsJson) {
if (!monitorJson.is_object()) {
continue;
}
Monitor monitor; Monitor monitor;
monitor.id = monitorJson.value("id", -1); monitor.id = monitorJson.value("id", -1);
monitor.name = monitorJson.value("name", ""); monitor.name = monitorJson.value("name", "");
monitor.x = monitorJson.value("x", 0); monitor.x = monitorJson.value("x", 0);
monitor.y = monitorJson.value("y", 0); monitor.y = monitorJson.value("y", 0);
if (monitorJson.contains("activeWorkspace") && monitor.focusedWorkspaceId = monitorJson["activeWorkspace"].value("id", -1);
monitorJson["activeWorkspace"].is_object()) {
monitor.focusedWorkspaceId =
monitorJson["activeWorkspace"].value("id", -1);
}
if (monitor.id >= 0) { if (monitor.id >= 0) {
updated.emplace(monitor.id, std::move(monitor)); 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];
}
} }
} }
monitors.swap(updated); this->refresh_workspaces();
monitorStateChanged.emit(); monitorStateChanged.emit();
} }
/**
* Called every time when workspace changes have been detected.
* Used to Update the internal state for the Workspaces,
*/
void HyprlandService::refresh_workspaces() { void HyprlandService::refresh_workspaces() {
if (monitors.empty()) { std::string output = SystemHelper::get_command_output(kWorkspaceCommand);
return;
}
std::string output;
try {
output = SystemHelper::get_command_output(kWorkspaceCommand);
} catch (const std::exception &ex) {
std::cerr << "[Hyprland] Failed to query workspaces: " << ex.what()
<< std::endl;
return;
}
auto workspacesJson = nlohmann::json::parse(output, nullptr, false); auto workspacesJson = nlohmann::json::parse(output, nullptr, false);
if (!workspacesJson.is_array()) {
std::cerr << "[Hyprland] Unexpected workspace payload" << std::endl; for (auto &[id, ws] : this->workspaces) {
return; ws->focused = false;
ws->active = false;
} }
for (auto &pair : monitors) { output = SystemHelper::get_command_output(kMonitorCommand);
auto &monitor = pair.second; auto monitorsJson = nlohmann::json::parse(output, nullptr, false);
monitor.workspaceStates.clear();
int focusedSlot = -1; for (const auto &monitorJson : monitorsJson) {
if (monitor.focusedWorkspaceId > 0) { const int monitorId = monitorJson.value("id", -1);
focusedSlot = ((monitor.focusedWorkspaceId - 1) % const int focusedWorkspaceId = monitorJson["activeWorkspace"].value("id", -1);
HyprlandService::kWorkspaceSlotCount) +
1; // write into the stored monitor (use reference)
auto it = this->monitors.find(monitorId);
if (it != this->monitors.end()) {
it->second.focusedWorkspaceId = focusedWorkspaceId;
}
} }
for (int slot = 1; slot <= HyprlandService::kWorkspaceSlotCount; std::string clientsOutput = SystemHelper::get_command_output(kClientsCommand);
++slot) { auto clientsJson = nlohmann::json::parse(clientsOutput, nullptr, false);
WorkspaceState state; std::unordered_set<std::string> liveClientAddresses;
state.id = slot; for (const auto &clientJson : clientsJson) {
state.hyprId = -1; const std::string addr = clientJson.value("address", "");
state.label = std::to_string(slot); if (addr.empty()) {
state.active = (slot == focusedSlot); continue;
state.focused = state.focused; }
state.urgent = false;
monitor.workspaceStates.emplace(slot, state); if (addr.rfind("0x", 0) == 0) {
liveClientAddresses.insert(addr.substr(2));
} else {
liveClientAddresses.insert(addr);
} }
} }
for (const auto &workspaceJson : workspacesJson) { for (const auto &workspaceJson : workspacesJson) {
if (!workspaceJson.is_object()) {
continue;
}
const int monitorId = workspaceJson.value("monitorID", -1);
const int workspaceId = workspaceJson.value("id", -1); const int workspaceId = workspaceJson.value("id", -1);
auto workspaceStateIt = this->workspaces.find(workspaceId);
auto monitorIt = monitors.find(monitorId); if (workspaceStateIt == this->workspaces.end()) {
if (monitorIt == monitors.end() || workspaceId < 0) {
continue; continue;
} }
auto &monitor = monitorIt->second; WorkspaceState *workspaceState = workspaceStateIt->second;
const int slot = auto mit = this->monitors.find(workspaceState->monitorId);
((workspaceId - 1) % HyprlandService::kWorkspaceSlotCount) + 1; if (mit != this->monitors.end()) {
auto &workspaceState = monitor.workspaceStates[slot]; workspaceState->focused = mit->second.focusedWorkspaceId == workspaceId;
workspaceState.id = slot;
workspaceState.hyprId = workspaceId;
workspaceState.focused = (monitor.focusedWorkspaceId == workspaceId);
workspaceState.active =
workspaceState.focused || workspaceJson.value("windows", 0) > 0;
workspaceState.urgent = false;
std::string labelCandidate;
if (workspaceJson.contains("name") &&
workspaceJson["name"].is_string()) {
labelCandidate = workspaceJson["name"].get<std::string>();
}
if (labelCandidate.empty() ||
labelCandidate == std::to_string(workspaceId)) {
workspaceState.label = std::to_string(slot);
} else { } else {
workspaceState.label = labelCandidate; workspaceState->focused = false;
}
workspaceState->active = true;
} }
if (workspaceJson.contains("urgent") && // drop urgent flags for windows no longer reported by hyprctl clients
workspaceJson["urgent"].is_boolean()) { for (auto &[id, ws] : this->workspaces) {
workspaceState.urgent = workspaceJson["urgent"].get<bool>(); auto &urgent = ws->urgentWindows;
} else if (workspaceJson.contains("hasurgent") && auto newEnd = std::remove_if(urgent.begin(), urgent.end(), [&](const std::string &addr) {
workspaceJson["hasurgent"].is_boolean()) { return liveClientAddresses.find(addr) == liveClientAddresses.end();
workspaceState.urgent = workspaceJson["hasurgent"].get<bool>(); });
if (newEnd != urgent.end()) {
urgent.erase(newEnd, urgent.end());
} }
} }
for (const auto &pair : monitors) { workspaceStateChanged.emit();
workspaceStateChanged.emit(pair.first);
}
}
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;
}
const HyprlandService::Monitor *HyprlandService::getMonitorById(int id) const {
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::switchToWorkspace(int workspaceId) { void HyprlandService::switchToWorkspace(int workspaceId) {
@@ -320,68 +274,73 @@ void HyprlandService::switchToWorkspace(int workspaceId) {
} }
} }
const HyprlandService::Monitor * void HyprlandService::onUrgentEvent(std::string windowAddress) {
HyprlandService::getMonitorByIndex(std::size_t index) const { 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()) { if (index >= monitors.size()) {
throw std::runtime_error("Monitor index out of bounds: " + throw std::runtime_error("Monitor index out of bounds: " + std::to_string(index));
std::to_string(index));
} }
auto it = monitors.begin(); auto it = monitors.begin();
std::advance(it, static_cast<long>(index)); std::advance(it, static_cast<long>(index));
return &it->second; return &it->second;
} }
void HyprlandService::handle_urgent_window(std::string windowAddress) {
std::string output;
try {
output = SystemHelper::get_command_output(kClientsCommand);
} catch (const std::exception &ex) {
std::cerr << "[Hyprland] Failed to query clients: " << ex.what()
<< std::endl;
return;
}
auto clientsJson = nlohmann::json::parse(output, nullptr, false);
if (!clientsJson.is_array()) {
return;
}
int workspaceId = -1;
for (const auto &client : clientsJson) {
if (!client.is_object())
continue;
std::string addr = client.value("address", "");
if (addr == "0x" + windowAddress) {
if (client.contains("workspace") &&
client["workspace"].is_object()) {
workspaceId = client["workspace"].value("id", -1);
}
break;
}
}
if (workspaceId == -1) {
return;
}
for (auto &pair : monitors) {
auto &monitor = pair.second;
bool changed = false;
for (auto &wsPair : monitor.workspaceStates) {
if (wsPair.second.hyprId == workspaceId) {
if (!wsPair.second.urgent) {
wsPair.second.urgent = true;
changed = true;
}
}
}
if (changed) {
workspaceStateChanged.emit(monitor.id);
}
}
}

View File

@@ -0,0 +1,305 @@
#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;
}
}

View File

@@ -0,0 +1,164 @@
#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>();
}

128
src/services/todo.cpp Normal file
View File

@@ -0,0 +1,128 @@
#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;
}
}
}

View File

@@ -1,5 +1,7 @@
#include "services/tray.hpp" #include "services/tray.hpp"
#include <algorithm>
#include <cstring>
#include <gdkmm/pixbuf.h> #include <gdkmm/pixbuf.h>
#include <gdkmm/texture.h> #include <gdkmm/texture.h>
#include <gio/gdbusmenumodel.h> #include <gio/gdbusmenumodel.h>
@@ -7,10 +9,8 @@
#include <giomm/dbusactiongroup.h> #include <giomm/dbusactiongroup.h>
#include <giomm/dbusownname.h> #include <giomm/dbusownname.h>
#include <giomm/menumodel.h> #include <giomm/menumodel.h>
#include <algorithm>
#include <cstring>
#include <iostream> #include <iostream>
#include <memory>
#include <tuple> #include <tuple>
#include <vector> #include <vector>
@@ -22,6 +22,11 @@ constexpr const char *kItemInterface = "org.kde.StatusNotifierItem";
constexpr const char *kDBusPropertiesIface = "org.freedesktop.DBus.Properties"; constexpr const char *kDBusPropertiesIface = "org.freedesktop.DBus.Properties";
constexpr const char *kDBusMenuInterface = "com.canonical.dbusmenu"; 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 = 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"> R"(<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-Bus Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node> <node>
@@ -106,53 +111,43 @@ void call_about_to_show(const Glib::RefPtr<Gio::DBus::Connection> &connection,
return; return;
} }
GError *error = nullptr; g_dbus_connection_call(connection->gobj(), busName.c_str(), menuPath.c_str(),
GVariant *result = g_dbus_connection_call_sync( kDBusMenuInterface, "AboutToShow",
connection->gobj(), busName.c_str(), menuPath.c_str(), g_variant_new("(i)", id), nullptr,
kDBusMenuInterface, "AboutToShow", g_variant_new("(i)", id), nullptr, G_DBUS_CALL_FLAGS_NONE, kAboutToShowTimeoutMs,
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error); nullptr, nullptr, nullptr);
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);
}
} }
GVariant *call_get_layout(const Glib::RefPtr<Gio::DBus::Connection> &connection, struct SimpleCallData {
const std::string &busName, std::string debugLabel;
const std::string &menuPath) { bool ignoreUnknownMethod = false;
if (!connection) { };
return nullptr;
}
GVariant *properties = create_property_list_variant(); void on_simple_call_finished(GObject *source, GAsyncResult *res,
if (!properties) { gpointer user_data) {
return nullptr; std::unique_ptr<SimpleCallData> data(
} static_cast<SimpleCallData *>(user_data));
GVariant *params = g_variant_new("(ii@as)", 0, -1, properties);
g_variant_ref_sink(properties);
GError *error = nullptr; GError *error = nullptr;
GVariant *result = g_dbus_connection_call_sync( GVariant *reply =
connection->gobj(), busName.c_str(), menuPath.c_str(), g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error);
kDBusMenuInterface, "GetLayout", params, nullptr,
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
g_variant_unref(properties); if (reply) {
g_variant_unref(reply);
if (error) {
std::cerr << "[TrayService] GetLayout failed for " << busName
<< menuPath << ": " << error->message << std::endl;
g_error_free(error);
return nullptr;
} }
return result; if (!error) {
return;
}
const bool isUnknownMethod =
(error->domain == G_DBUS_ERROR && error->code == G_DBUS_ERROR_UNKNOWN_METHOD);
if (!(data && data->ignoreUnknownMethod && isUnknownMethod)) {
std::cerr << "[TrayService] "
<< (data ? data->debugLabel : std::string("D-Bus call"))
<< " failed: " << error->message << std::endl;
}
g_error_free(error);
} }
void parse_menu_node(GVariant *tuple, TrayService::MenuNode &outNode) { void parse_menu_node(GVariant *tuple, TrayService::MenuNode &outNode) {
@@ -309,6 +304,10 @@ void TrayService::start() {
void TrayService::stop() { void TrayService::stop() {
if (connection) { if (connection) {
for (auto &pair : items) { for (auto &pair : items) {
if (pair.second->refreshSourceId != 0) {
g_source_remove(pair.second->refreshSourceId);
pair.second->refreshSourceId = 0;
}
if (pair.second->signalSubscriptionId != 0) { if (pair.second->signalSubscriptionId != 0) {
g_dbus_connection_signal_unsubscribe( g_dbus_connection_signal_unsubscribe(
connection->gobj(), pair.second->signalSubscriptionId); connection->gobj(), pair.second->signalSubscriptionId);
@@ -362,22 +361,14 @@ void TrayService::activate(const std::string &id, int32_t x, int32_t y) {
return; return;
} }
GError *error = nullptr; auto data = new SimpleCallData();
GVariant *result = g_dbus_connection_call_sync( data->debugLabel = "Activate(" + id + ")";
data->ignoreUnknownMethod = false;
g_dbus_connection_call(
connection->gobj(), it->second->publicData.busName.c_str(), connection->gobj(), it->second->publicData.busName.c_str(),
it->second->publicData.objectPath.c_str(), kItemInterface, "Activate", it->second->publicData.objectPath.c_str(), kItemInterface, "Activate",
g_variant_new("(ii)", x, y), nullptr, G_DBUS_CALL_FLAGS_NONE, -1, g_variant_new("(ii)", x, y), nullptr, G_DBUS_CALL_FLAGS_NONE,
nullptr, &error); kDBusTimeoutMs, nullptr, &on_simple_call_finished, data);
if (result) {
g_variant_unref(result);
}
if (error) {
std::cerr << "[TrayService] Activate failed for " << id << ": "
<< error->message << std::endl;
g_error_free(error);
}
} }
void TrayService::secondaryActivate(const std::string &id, int32_t x, void TrayService::secondaryActivate(const std::string &id, int32_t x,
@@ -387,22 +378,15 @@ void TrayService::secondaryActivate(const std::string &id, int32_t x,
return; return;
} }
GError *error = nullptr; auto data = new SimpleCallData();
GVariant *result = g_dbus_connection_call_sync( data->debugLabel = "SecondaryActivate(" + id + ")";
data->ignoreUnknownMethod = false;
g_dbus_connection_call(
connection->gobj(), it->second->publicData.busName.c_str(), connection->gobj(), it->second->publicData.busName.c_str(),
it->second->publicData.objectPath.c_str(), kItemInterface, it->second->publicData.objectPath.c_str(), kItemInterface,
"SecondaryActivate", g_variant_new("(ii)", x, y), nullptr, "SecondaryActivate", g_variant_new("(ii)", x, y), nullptr,
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error); G_DBUS_CALL_FLAGS_NONE, kDBusTimeoutMs, nullptr,
&on_simple_call_finished, data);
if (result) {
g_variant_unref(result);
}
if (error) {
std::cerr << "[TrayService] SecondaryActivate failed for " << id << ": "
<< error->message << std::endl;
g_error_free(error);
}
} }
void TrayService::contextMenu(const std::string &id, int32_t x, int32_t y) { void TrayService::contextMenu(const std::string &id, int32_t x, int32_t y) {
@@ -411,25 +395,15 @@ void TrayService::contextMenu(const std::string &id, int32_t x, int32_t y) {
return; return;
} }
GError *error = nullptr; auto data = new SimpleCallData();
GVariant *result = g_dbus_connection_call_sync( data->debugLabel = "ContextMenu(" + id + ")";
data->ignoreUnknownMethod = true;
g_dbus_connection_call(
connection->gobj(), it->second->publicData.busName.c_str(), connection->gobj(), it->second->publicData.busName.c_str(),
it->second->publicData.objectPath.c_str(), kItemInterface, it->second->publicData.objectPath.c_str(), kItemInterface,
"ContextMenu", g_variant_new("(ii)", x, y), nullptr, "ContextMenu", g_variant_new("(ii)", x, y), nullptr,
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error); G_DBUS_CALL_FLAGS_NONE, kDBusTimeoutMs, nullptr,
&on_simple_call_finished, data);
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);
}
} }
Glib::RefPtr<Gio::MenuModel> Glib::RefPtr<Gio::MenuModel>
@@ -486,70 +460,110 @@ TrayService::get_menu_action_group(const std::string &id) {
return item.menuActions; return item.menuActions;
} }
void TrayService::debug_dump_menu_layout(const std::string &id) { struct MenuLayoutCallData {
auto it = items.find(id); TrayService *self = nullptr;
if (it == items.end() || !connection) { 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; return;
} }
const auto &item = *it->second; GError *error = nullptr;
if (!item.publicData.menuAvailable || item.publicData.menuPath.empty()) { 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; return;
} }
GVariant *result = call_get_layout(connection, item.publicData.busName, if (!reply) {
item.publicData.menuPath); if (data->callback) {
data->callback(std::nullopt);
if (!result) { }
return; return;
} }
gchar *printed = g_variant_print(result, TRUE); GVariant *rootTuple = g_variant_get_child_value(reply, 1);
if (printed) { g_variant_unref(reply);
std::cout << "[TrayService] GetLayout for " << id << ":\n"
<< printed << std::endl; if (!rootTuple) {
g_free(printed); if (data->callback) {
data->callback(std::nullopt);
}
return;
} }
g_variant_unref(result); TrayService::MenuNode rootNode;
parse_menu_node(rootTuple, rootNode);
g_variant_unref(rootTuple);
if (data->callback) {
data->callback(std::make_optional(std::move(rootNode)));
}
} }
std::optional<TrayService::MenuNode> void TrayService::request_menu_layout(const std::string &id,
TrayService::get_menu_layout(const std::string &id) { MenuLayoutCallback callback) {
auto it = items.find(id); auto it = items.find(id);
if (it == items.end() || !connection) { if (it == items.end() || !connection) {
return std::nullopt; if (callback) {
callback(std::nullopt);
}
return;
} }
auto &item = *it->second; auto &item = *it->second;
if (!item.publicData.menuAvailable || item.publicData.menuPath.empty()) { 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, call_about_to_show(connection, item.publicData.busName,
item.publicData.menuPath, 0); item.publicData.menuPath, 0);
GVariant *result = call_get_layout(connection, item.publicData.busName, auto data = new MenuLayoutCallData();
item.publicData.menuPath); data->self = this;
if (!result) { data->id = id;
return std::nullopt; 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_new consumes the floating reference for '@as'.
g_variant_unref(result); GVariant *params = g_variant_new("(ii@as)", 0, -1, properties);
if (!rootTuple) { g_dbus_connection_call(connection->gobj(), data->busName.c_str(),
return std::nullopt; data->menuPath.c_str(), kDBusMenuInterface,
} "GetLayout", params, nullptr,
G_DBUS_CALL_FLAGS_NONE, kDBusMenuTimeoutMs, nullptr,
MenuNode rootNode; &on_menu_layout_finished, data);
parse_menu_node(rootTuple, rootNode);
g_variant_unref(rootTuple);
return rootNode;
} }
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); auto it = items.find(id);
if (it == items.end() || !connection) { if (it == items.end() || !connection) {
return false; return false;
@@ -560,28 +574,44 @@ bool TrayService::activate_menu_item(const std::string &id, int itemId) {
return false; return false;
} }
GVariant *emptyData = const guint32 nowMs = static_cast<guint32>(g_get_real_time() / 1000);
g_variant_new_array(G_VARIANT_TYPE("{sv}"), nullptr, 0); const guint32 ts = timestampMs ? timestampMs : nowMs;
GVariant *params = g_variant_new(
"(isvu)", itemId, "clicked", g_variant_new_variant(emptyData),
static_cast<guint32>(g_get_monotonic_time() / 1000));
GError *error = nullptr; std::cerr << "[TrayService] MenuEvent id=" << id << " item=" << itemId
GVariant *result = g_dbus_connection_call_sync( << " x=" << x << " y=" << y << " button=" << button
connection->gobj(), item.publicData.busName.c_str(), << " tsMs=" << ts << std::endl;
item.publicData.menuPath.c_str(), kDBusMenuInterface, "Event", params,
nullptr, G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
if (result) { // dbusmenu Event signature: (i s v u)
g_variant_unref(result); // 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) { GVariant *payloadDict = g_variant_builder_end(&dict);
std::cerr << "[TrayService] Event failed for " << id << " (" << itemId GVariant *payload = g_variant_new_variant(payloadDict);
<< "): " << error->message << std::endl; GVariant *params = g_variant_new("(isvu)", itemId, "clicked",
g_error_free(error); payload, ts);
return false;
} 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; return true;
} }
@@ -725,8 +755,7 @@ void TrayService::register_item(const Glib::ustring &sender,
const std::string id = parsed.busName + parsed.objectPath; const std::string id = parsed.busName + parsed.objectPath;
auto existing = items.find(id); auto existing = items.find(id);
if (existing != items.end()) { if (existing != items.end()) {
refresh_item(*existing->second); schedule_refresh(id);
itemUpdatedSignal.emit(existing->second->publicData);
return; return;
} }
@@ -735,7 +764,7 @@ void TrayService::register_item(const Glib::ustring &sender,
item->publicData.busName = parsed.busName; item->publicData.busName = parsed.busName;
item->publicData.objectPath = parsed.objectPath; item->publicData.objectPath = parsed.objectPath;
refresh_item(*item); item->addSignalPending = true;
item->signalSubscriptionId = g_dbus_connection_signal_subscribe( item->signalSubscriptionId = g_dbus_connection_signal_subscribe(
connection->gobj(), item->publicData.busName.c_str(), nullptr, nullptr, connection->gobj(), item->publicData.busName.c_str(), nullptr, nullptr,
@@ -755,7 +784,7 @@ void TrayService::register_item(const Glib::ustring &sender,
std::make_tuple(Glib::ustring(id))); std::make_tuple(Glib::ustring(id)));
emit_watcher_signal("StatusNotifierItemRegistered", params); emit_watcher_signal("StatusNotifierItemRegistered", params);
itemAddedSignal.emit(items.at(id)->publicData); schedule_refresh(id);
} }
void TrayService::unregister_item(const std::string &id) { void TrayService::unregister_item(const std::string &id) {
@@ -764,6 +793,11 @@ void TrayService::unregister_item(const std::string &id) {
return; return;
} }
if (it->second->refreshSourceId != 0) {
g_source_remove(it->second->refreshSourceId);
it->second->refreshSourceId = 0;
}
if (connection && it->second->signalSubscriptionId != 0) { if (connection && it->second->signalSubscriptionId != 0) {
g_dbus_connection_signal_unsubscribe(connection->gobj(), g_dbus_connection_signal_unsubscribe(connection->gobj(),
it->second->signalSubscriptionId); it->second->signalSubscriptionId);
@@ -784,31 +818,58 @@ void TrayService::unregister_item(const std::string &id) {
itemRemovedSignal.emit(id); itemRemovedSignal.emit(id);
} }
void TrayService::refresh_item(TrackedItem &item) { struct RefreshCallData {
if (!connection) { 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; return;
} }
auto it = data->self->items.find(data->id);
if (it == data->self->items.end()) {
return;
}
auto &tracked = *it->second;
GError *error = nullptr; GError *error = nullptr;
GVariant *reply = g_dbus_connection_call_sync( GVariant *reply =
connection->gobj(), item.publicData.busName.c_str(), g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), res, &error);
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);
if (!reply) { if (!reply) {
if (error) { if (error) {
std::cerr << "[TrayService] Failed to query properties for " std::cerr << "[TrayService] Failed to query properties for "
<< item.publicData.id << ": " << error->message << data->id << ": " << error->message << std::endl;
<< std::endl;
g_error_free(error); 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; return;
} }
GVariant *dictVariant = g_variant_get_child_value(reply, 0); GVariant *dictVariant = g_variant_get_child_value(reply, 0);
g_variant_unref(reply); g_variant_unref(reply);
if (!dictVariant) { if (!dictVariant) {
tracked.refreshInFlight = false;
if (tracked.refreshQueued) {
tracked.refreshQueued = false;
data->self->schedule_refresh(data->id);
}
return; return;
} }
@@ -841,13 +902,8 @@ void TrayService::refresh_item(TrackedItem &item) {
const gchar *str = g_variant_get_string(value, nullptr); const gchar *str = g_variant_get_string(value, nullptr);
status = str ? str : ""; status = str ? str : "";
} else if (std::strcmp(key, "Menu") == 0) { } 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); const gchar *str = g_variant_get_string(value, nullptr);
menuPath = str ? str : ""; menuPath = str ? str : "";
} else {
const gchar *str = g_variant_get_string(value, nullptr);
menuPath = str ? str : "";
}
} else if (std::strcmp(key, "IconName") == 0) { } else if (std::strcmp(key, "IconName") == 0) {
const gchar *str = g_variant_get_string(value, nullptr); const gchar *str = g_variant_get_string(value, nullptr);
iconName = str ? str : ""; iconName = str ? str : "";
@@ -855,39 +911,127 @@ void TrayService::refresh_item(TrackedItem &item) {
const gchar *str = g_variant_get_string(value, nullptr); const gchar *str = g_variant_get_string(value, nullptr);
attentionIconName = str ? str : ""; attentionIconName = str ? str : "";
} else if (std::strcmp(key, "IconPixmap") == 0) { } 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) { } 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(value);
} }
g_variant_unref(dictVariant); 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) { const bool menuPathChanged = (tracked.publicData.menuPath != menuPath);
item.menuModel.reset(); tracked.publicData.title = title;
item.menuActions.reset(); 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()) (status == "NeedsAttention" && !attentionIconName.empty())
? attentionIconName ? attentionIconName
: iconName; : iconName;
if (status == "NeedsAttention" && attentionTexture) { if (status == "NeedsAttention" && attentionTexture) {
item.publicData.iconPaintable = attentionTexture; tracked.publicData.iconPaintable = attentionTexture;
} else { } else {
item.publicData.iconPaintable = iconTexture; tracked.publicData.iconPaintable = iconTexture;
} }
if (!item.publicData.iconPaintable && iconTexture) { if (!tracked.publicData.iconPaintable && iconTexture) {
item.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() { void TrayService::emit_registered_items_changed() {
@@ -985,12 +1129,10 @@ void TrayService::on_dbus_signal(const gchar *sender_name,
std::strcmp(signal_name, "NewAttentionIcon") == 0 || std::strcmp(signal_name, "NewAttentionIcon") == 0 ||
std::strcmp(signal_name, "NewToolTip") == 0 || std::strcmp(signal_name, "NewToolTip") == 0 ||
std::strcmp(signal_name, "NewMenu") == 0) { std::strcmp(signal_name, "NewMenu") == 0) {
refresh_item(*it->second); schedule_refresh(it->first);
itemUpdatedSignal.emit(it->second->publicData);
} }
} else if (isPropertiesSignal) { } else if (isPropertiesSignal) {
refresh_item(*it->second); schedule_refresh(it->first);
itemUpdatedSignal.emit(it->second->publicData);
} }
} }

219
src/widgets/battery.cpp Normal file
View File

@@ -0,0 +1,219 @@
#include "widgets/battery.hpp"
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <string>
#include <glibmm/main.h>
#include <sigc++/functors/mem_fun.h>
namespace {
std::string trim(const std::string &value) {
const auto start = value.find_first_not_of(" \t\n\r");
if (start == std::string::npos) {
return "";
}
const auto end = value.find_last_not_of(" \t\n\r");
return value.substr(start, end - start + 1);
}
}
BatteryWidget::BatteryWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) {
set_valign(Gtk::Align::CENTER);
set_halign(Gtk::Align::CENTER);
set_spacing(6);
add_css_class("battery-widget");
iconLabel.set_halign(Gtk::Align::CENTER);
iconLabel.set_valign(Gtk::Align::CENTER);
iconLabel.set_width_chars(7);
iconLabel.set_text("[ ]");
iconLabel.add_css_class("battery-widget-icon");
append(iconLabel);
label.set_halign(Gtk::Align::CENTER);
label.set_valign(Gtk::Align::CENTER);
label.set_width_chars(5);
label.set_text("--%");
label.add_css_class("battery-widget-text");
append(label);
update();
timeoutConn = Glib::signal_timeout().connect(
sigc::mem_fun(*this, &BatteryWidget::on_timeout), 100);
}
BatteryWidget::~BatteryWidget() {
if (timeoutConn.connected()) {
timeoutConn.disconnect();
}
}
void BatteryWidget::find_battery_path() {
constexpr auto base = "/sys/class/power_supply";
batteryPath.clear();
if (!std::filesystem::exists(base)) {
return;
}
for (const auto &entry : std::filesystem::directory_iterator(base)) {
if (!entry.is_directory()) {
continue;
}
std::ifstream typeFile(entry.path() / "type");
if (!typeFile) {
continue;
}
std::string type;
std::getline(typeFile, type);
type = trim(type);
std::transform(type.begin(), type.end(), type.begin(), [](unsigned char ch) {
return static_cast<char>(std::toupper(ch));
});
if (type == "BATTERY") {
batteryPath = entry.path();
break;
}
}
}
void BatteryWidget::update() {
try {
if (batteryPath.empty() || !std::filesystem::exists(batteryPath)) {
find_battery_path();
}
const bool hasBattery = !batteryPath.empty();
int capacity = -1;
std::string status;
if (hasBattery) {
std::ifstream capacityFile(batteryPath / "capacity");
if (capacityFile) {
capacityFile >> capacity;
}
std::ifstream statusFile(batteryPath / "status");
if (statusFile) {
std::getline(statusFile, status);
}
}
status = trim(status);
const bool charging = status == "Charging";
const bool full = hasBattery && (status == "Full" || (capacity >= 95));
const bool low = (capacity >= 0 && capacity < 20 && !charging);
std::string stateClass;
if (!hasBattery) {
stateClass = "battery-widget-external";
} else if (charging) {
stateClass = "battery-widget-charging";
} else if (low) {
stateClass = "battery-widget-low";
} else if (full) {
stateClass = "battery-widget-full";
} else {
stateClass = "battery-widget-normal";
}
set_state_class(stateClass);
iconLabel.set_text(build_icon(capacity, hasBattery, charging, full));
label.set_text(build_text(capacity, status, hasBattery, charging, full));
} catch (...) {
set_state_class("battery-widget-normal");
iconLabel.set_text("[???]");
label.set_text("??%");
}
}
bool BatteryWidget::on_timeout() {
update();
return true;
}
void BatteryWidget::set_state_class(const std::string &stateClass) {
if (currentStateClass == stateClass) {
return;
}
if (!currentStateClass.empty()) {
remove_css_class(currentStateClass);
}
currentStateClass = stateClass;
if (!currentStateClass.empty()) {
add_css_class(currentStateClass);
}
}
std::string BatteryWidget::build_icon(int capacity, bool hasBattery, bool charging, bool full) const {
if (!hasBattery) {
return "<AC>";
}
static constexpr int segments = 5;
const int clampedCapacity = std::clamp(capacity, 0, 100);
int filledSegments = (clampedCapacity * segments + 99) / 100;
if (full) {
filledSegments = segments;
}
std::string icon = "[";
for (int i = 0; i < segments; ++i) {
icon += (i < filledSegments) ? '=' : ' ';
}
icon += ']';
if (charging) {
icon += '>';
} else if (clampedCapacity <= 5) {
icon += '!';
} else {
icon += ' ';
}
return icon;
}
std::string BatteryWidget::build_text(int capacity, const std::string &status, bool hasBattery, bool charging, bool full) const {
if (!hasBattery) {
return "AC";
}
if (capacity >= 0) {
std::string text;
if (full && capacity >= 99) {
text = "100%";
} else {
text = std::to_string(std::clamp(capacity, 0, 100)) + "%";
}
if (charging && capacity < 100) {
text.insert(text.begin(), '+');
}
return text;
}
if (!status.empty()) {
return status;
}
return "?%";
}

72
src/widgets/bluetooth.cpp Normal file
View File

@@ -0,0 +1,72 @@
#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);
}

View File

@@ -0,0 +1,24 @@
#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());
}

78
src/widgets/todo.cpp Normal file
View File

@@ -0,0 +1,78 @@
#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);
}
}
}

View File

@@ -3,16 +3,192 @@
#include <gdkmm/rectangle.h> #include <gdkmm/rectangle.h>
#include <gio/gmenu.h> #include <gio/gmenu.h>
#include <gtk/gtk.h> #include <gtk/gtk.h>
#include <iostream> #include <cmath>
#include <graphene.h>
#include <utility> #include <utility>
#include <iostream>
#include "components/base/button.hpp"
TrayIconWidget::TrayIconWidget(TrayService &service, std::string id) namespace {
: service(service), id(std::move(id)), 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;
}
std::cerr << "[TrayIconWidget] menu node id=" << node.id
<< " label='" << node.label << "' enabled="
<< (node.enabled ? "1" : "0") << " sep="
<< (node.separator ? "1" : "0") << " depth=" << depth
<< std::endl;
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) { container(Gtk::Orientation::HORIZONTAL) {
aliveFlag = std::make_shared<bool>(true);
set_has_frame(false); set_has_frame(false);
set_focusable(false); set_focusable(false);
set_valign(Gtk::Align::CENTER); set_valign(Gtk::Align::CENTER);
set_halign(Gtk::Align::CENTER); set_halign(Gtk::Align::CENTER);
add_css_class("tray-icon");
picture.set_halign(Gtk::Align::CENTER); picture.set_halign(Gtk::Align::CENTER);
picture.set_valign(Gtk::Align::CENTER); picture.set_valign(Gtk::Align::CENTER);
@@ -38,6 +214,12 @@ TrayIconWidget::TrayIconWidget(TrayService &service, std::string id)
sigc::mem_fun(*this, &TrayIconWidget::on_primary_released)); sigc::mem_fun(*this, &TrayIconWidget::on_primary_released));
add_controller(primaryGesture); 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 = Gtk::GestureClick::create();
secondaryGesture->set_button(GDK_BUTTON_SECONDARY); secondaryGesture->set_button(GDK_BUTTON_SECONDARY);
secondaryGesture->signal_released().connect( secondaryGesture->signal_released().connect(
@@ -45,19 +227,36 @@ TrayIconWidget::TrayIconWidget(TrayService &service, std::string id)
add_controller(secondaryGesture); 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) { void TrayIconWidget::update(const TrayService::Item &item) {
hasRemoteMenu = item.menuAvailable;
menuPopupPending = false;
menuRequestInFlight = false;
if (!item.menuAvailable) { if (!item.menuAvailable) {
menuModel.reset(); menuModel.reset();
menuActions.reset(); menuActions.reset();
menuPopupPending = false;
if (menuChangedConnection.connected()) {
menuChangedConnection.disconnect();
}
if (menuPopover) { if (menuPopover) {
menuPopover->insert_action_group("dbusmenu", menuPopover->insert_action_group(
Glib::RefPtr<Gio::ActionGroup>()); "dbusmenu", Glib::RefPtr<Gio::ActionGroup>());
menuPopover->set_menu_model({}); menuPopover->set_menu_model({});
if (menuPopover->get_parent()) {
menuPopover->unparent(); menuPopover->unparent();
}
menuPopover.reset(); menuPopover.reset();
} }
} }
@@ -87,54 +286,131 @@ void TrayIconWidget::update(const TrayService::Item &item) {
} }
void TrayIconWidget::on_primary_released(int /*n_press*/, double x, double y) { 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;
}
}
std::cerr << "[TrayIconWidget] Activate primary id=" << id << " x="
<< sendX << " y=" << sendY << std::endl;
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;
}
}
std::cerr << "[TrayIconWidget] SecondaryActivate (middle) id=" << id
<< " x=" << sendX << " y=" << sendY << std::endl;
service.secondaryActivate(id, sendX, sendY);
} }
void TrayIconWidget::on_secondary_released(int /*n_press*/, double x, void TrayIconWidget::on_secondary_released(int /*n_press*/, double x,
double y) { double y) {
// 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)) {
std::cerr << "[TrayIconWidget] Secondary fallback ContextMenu (no surface) id="
<< id << std::endl;
service.contextMenu(id, -1, -1); service.contextMenu(id, -1, -1);
if (!ensure_menu()) {
return; return;
} }
pendingX = x; pendingX = x;
pendingY = y; 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)) {
std::cerr << "[TrayIconWidget] Requesting dbusmenu for id=" << id
<< std::endl;
menuPopupPending = true; menuPopupPending = true;
try_popup(); 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()))) {
std::cerr << "[TrayIconWidget] ContextMenu wayland id=" << id
<< " x=-1 y=-1" << std::endl;
service.contextMenu(id, -1, -1);
} else {
std::cerr << "[TrayIconWidget] ContextMenu id=" << id << " x=" << sendX
<< " y=" << sendY << std::endl;
service.contextMenu(id, sendX, sendY);
}
} }
bool TrayIconWidget::ensure_menu() { void TrayIconWidget::on_menu_layout_ready(
auto layoutOpt = service.get_menu_layout(id); std::optional<TrayService::MenuNode> layoutOpt) {
if (!layoutOpt) { menuRequestInFlight = false;
if (!menuPopupPending) {
return;
}
GtkWidget *selfWidget = GTK_WIDGET(gobj());
if (!has_popup_surface(selfWidget)) {
menuPopupPending = false;
menuModel.reset(); menuModel.reset();
menuActions.reset(); menuActions.reset();
return;
}
if (!layoutOpt) {
menuPopupPending = false; menuPopupPending = false;
if (menuChangedConnection.connected()) { return;
menuChangedConnection.disconnect();
}
if (menuPopover) {
remove_action_group("dbusmenu");
menuPopover->set_menu_model({});
menuPopover->unparent();
menuPopover.reset();
}
return false;
} }
const auto &layout = *layoutOpt; const auto &layout = *layoutOpt;
log_menu_tree(layout.children, 0);
auto menu = Gio::Menu::create(); auto menu = Gio::Menu::create();
auto actions = Gio::SimpleActionGroup::create(); auto actions = Gio::SimpleActionGroup::create();
populate_menu_items(layout.children, menu, actions); populate_menu_items(layout.children, menu, actions);
const auto itemCount = menu->get_n_items(); if (menu->get_n_items() == 0) {
std::cout << "[TrayIconWidget] menu update for " << id menuModel.reset();
<< ", items: " << itemCount << std::endl; menuActions.reset();
if (itemCount == 0) { menuPopupPending = false;
service.debug_dump_menu_layout(id); return;
return false;
} }
menuModel = menu; menuModel = menu;
@@ -145,7 +421,8 @@ bool TrayIconWidget::ensure_menu() {
menuPopover = menuPopover =
Glib::make_refptr_for_instance<Gtk::PopoverMenu>(rawPopover); Glib::make_refptr_for_instance<Gtk::PopoverMenu>(rawPopover);
if (!menuPopover) { if (!menuPopover) {
return false; menuPopupPending = false;
return;
} }
menuPopover->set_has_arrow(false); menuPopover->set_has_arrow(false);
@@ -155,36 +432,17 @@ bool TrayIconWidget::ensure_menu() {
menuPopover->remove_action_group("dbusmenu"); menuPopover->remove_action_group("dbusmenu");
menuPopover->insert_action_group("dbusmenu", menuActions); 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); menuPopover->set_menu_model(menuModel);
return true; // Ensure popover is still parented to us and has a native/root before popup.
} if (!menuPopover->get_parent()) {
menuPopover->set_parent(*this);
void TrayIconWidget::on_menu_items_changed(guint /*position*/,
guint /*removed*/, guint /*added*/) {
if (!menuModel) {
return;
} }
const auto count = menuModel->get_n_items(); GtkWidget *popoverWidget = GTK_WIDGET(menuPopover->gobj());
std::cout << "[TrayIconWidget] items changed for " << id << ": " << count if (!popoverWidget || !gtk_widget_get_root(popoverWidget) ||
<< " entries" << std::endl; !gtk_widget_get_native(popoverWidget) || !has_popup_surface(selfWidget)) {
try_popup(); menuPopupPending = false;
}
void TrayIconWidget::try_popup() {
if (!menuPopupPending || !menuPopover || !menuModel) {
return;
}
if (menuModel->get_n_items() == 0) {
return; return;
} }
@@ -244,23 +502,61 @@ void TrayIconWidget::populate_menu_items(
void TrayIconWidget::on_menu_action(const Glib::VariantBase & /*parameter*/, void TrayIconWidget::on_menu_action(const Glib::VariantBase & /*parameter*/,
int itemId) { 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) { if (menuPopover) {
menuPopover->popdown(); 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);
std::cerr << "[TrayIconWidget] Menu action id=" << this->id
<< " item=" << itemId << " x=" << sendX << " y=" << sendY
<< std::endl;
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);
} }
TrayWidget::TrayWidget(TrayService &service) bool TrayIconWidget::try_get_pending_coords(int32_t &outX, int32_t &outY) const {
: Gtk::Box(Gtk::Orientation::HORIZONTAL), service(service) { 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()
: Gtk::Box(Gtk::Orientation::HORIZONTAL) {
set_valign(Gtk::Align::CENTER); set_valign(Gtk::Align::CENTER);
set_halign(Gtk::Align::CENTER); set_halign(Gtk::Align::CENTER);
set_visible(false); set_visible(false);
addConnection = service.signal_item_added().connect( addConnection = service->signal_item_added().connect(
sigc::mem_fun(*this, &TrayWidget::on_item_added)); sigc::mem_fun(*this, &TrayWidget::on_item_added));
removeConnection = service.signal_item_removed().connect( removeConnection = service->signal_item_removed().connect(
sigc::mem_fun(*this, &TrayWidget::on_item_removed)); sigc::mem_fun(*this, &TrayWidget::on_item_removed));
updateConnection = service.signal_item_updated().connect( updateConnection = service->signal_item_updated().connect(
sigc::mem_fun(*this, &TrayWidget::on_item_updated)); sigc::mem_fun(*this, &TrayWidget::on_item_updated));
rebuild_existing(); rebuild_existing();
@@ -279,7 +575,7 @@ TrayWidget::~TrayWidget() {
} }
void TrayWidget::rebuild_existing() { void TrayWidget::rebuild_existing() {
auto items = service.snapshotItems(); auto items = service->snapshotItems();
for (const auto &item : items) { for (const auto &item : items) {
on_item_added(item); on_item_added(item);
} }
@@ -294,7 +590,7 @@ void TrayWidget::on_item_added(const TrayService::Item &item) {
return; return;
} }
auto icon = std::make_unique<TrayIconWidget>(service, item.id); auto icon = std::make_unique<TrayIconWidget>(item.id);
icon->update(item); icon->update(item);
auto *raw = icon.get(); auto *raw = icon.get();
append(*raw); append(*raw);
@@ -310,7 +606,6 @@ void TrayWidget::on_item_removed(const std::string &id) {
} }
remove(*it->second); remove(*it->second);
it->second->unparent();
icons.erase(it); icons.erase(it);
if (icons.empty()) { if (icons.empty()) {

View File

@@ -1,12 +1,12 @@
#include "widgets/volumeWidget.hpp" #include "widgets/volumeWidget.hpp"
#include "helpers/systemHelper.hpp"
#include <cmath> #include <cmath>
#include <iostream> #include <iostream>
#include <regex> #include <regex>
#include <sigc++/functors/mem_fun.h> #include <sigc++/functors/mem_fun.h>
#include "helpers/systemHelper.hpp"
VolumeWidget::VolumeWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) { VolumeWidget::VolumeWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) {
set_valign(Gtk::Align::CENTER); set_valign(Gtk::Align::CENTER);
set_halign(Gtk::Align::CENTER); set_halign(Gtk::Align::CENTER);
@@ -17,15 +17,10 @@ VolumeWidget::VolumeWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) {
append(label); append(label);
// Click toggles mute using wpctl
click = Gtk::GestureClick::create(); click = Gtk::GestureClick::create();
click->set_button(GDK_BUTTON_PRIMARY); click->set_button(GDK_BUTTON_PRIMARY);
// signal_released provides (int, double, double) — use lambda to ignore click->signal_released().connect([this](int, double, double) {
// args
click->signal_released().connect([this](int /*n_press*/, double /*x*/,
double /*y*/) {
try { try {
// Toggle mute then refresh
(void)SystemHelper::get_command_output( (void)SystemHelper::get_command_output(
"wpctl set-mute @DEFAULT_SINK@ toggle"); "wpctl set-mute @DEFAULT_SINK@ toggle");
} catch (const std::exception &ex) { } catch (const std::exception &ex) {
@@ -34,19 +29,17 @@ VolumeWidget::VolumeWidget() : Gtk::Box(Gtk::Orientation::HORIZONTAL) {
} }
this->update(); this->update();
}); });
add_controller(click);
// Initial read add_controller(click);
update(); update();
// Start polling every 1 second to keep the display up to date this->timeoutConn = Glib::signal_timeout().connect(
timeoutConn = Glib::signal_timeout().connect(
sigc::mem_fun(*this, &VolumeWidget::on_timeout), 100); sigc::mem_fun(*this, &VolumeWidget::on_timeout), 100);
} }
VolumeWidget::~VolumeWidget() { VolumeWidget::~VolumeWidget() {
if (timeoutConn.connected()) if (this->timeoutConn.connected())
timeoutConn.disconnect(); this->timeoutConn.disconnect();
} }
void VolumeWidget::update() { void VolumeWidget::update() {
@@ -54,7 +47,6 @@ void VolumeWidget::update() {
const std::string out = const std::string out =
SystemHelper::get_command_output("wpctl get-volume @DEFAULT_SINK@"); SystemHelper::get_command_output("wpctl get-volume @DEFAULT_SINK@");
// Attempt to parse a number (percentage or fraction)
std::smatch m; std::smatch m;
std::regex r_percent(R"((\d+(?:\.\d+)?)%)"); std::regex r_percent(R"((\d+(?:\.\d+)?)%)");
std::regex r_number(R"((\d+(?:\.\d+)?))"); std::regex r_number(R"((\d+(?:\.\d+)?))");
@@ -65,7 +57,6 @@ void VolumeWidget::update() {
if (std::regex_search(text, m, r_percent)) { if (std::regex_search(text, m, r_percent)) {
percent = static_cast<int>(std::round(std::stod(m[1].str()))); percent = static_cast<int>(std::round(std::stod(m[1].str())));
} else if (std::regex_search(text, m, r_number)) { } else if (std::regex_search(text, m, r_number)) {
// If number looks like 0.8 treat as fraction
const double v = std::stod(m[1].str()); const double v = std::stod(m[1].str());
if (v <= 1.0) if (v <= 1.0)
percent = static_cast<int>(std::round(v * 100.0)); percent = static_cast<int>(std::round(v * 100.0));
@@ -76,7 +67,6 @@ void VolumeWidget::update() {
if (percent >= 0) { if (percent >= 0) {
label.set_text(std::to_string(percent) + "%"); label.set_text(std::to_string(percent) + "%");
} else { } else {
// Fallback to raw output (trimmed)
auto pos = text.find_first_not_of(" \t\n\r"); auto pos = text.find_first_not_of(" \t\n\r");
if (pos != std::string::npos) { if (pos != std::string::npos) {
auto end = text.find_last_not_of(" \t\n\r"); auto end = text.find_last_not_of(" \t\n\r");
@@ -94,5 +84,6 @@ void VolumeWidget::update() {
bool VolumeWidget::on_timeout() { bool VolumeWidget::on_timeout() {
update(); update();
return true; // keep timeout active return true; // keep timeout active
} }

View File

@@ -1,25 +1,9 @@
#include "widgets/webWidget.hpp" #include "widgets/webWidget.hpp"
#include <gtkmm/box.h>
#include <gtkmm/label.h> #include <gtkmm/label.h>
#include <webkit/webkit.h> #include <webkit/webkit.h>
WebWidget::WebWidget(std::string icon, std::string title, std::string url) { WebWidget::WebWidget(std::string icon, std::string name, std::string url) : Popover(icon, name) {
auto label = Gtk::make_managed<Gtk::Label>(icon);
label->add_css_class("icon-label");
set_child(*label);
signal_clicked().connect(
sigc::mem_fun(*this, &WebWidget::on_toggle_window));
popover = new Gtk::Popover();
popover->set_parent(*this);
popover->set_autohide(true);
popover->signal_closed().connect([this]() {
this->add_css_class("minimized");
this->remove_css_class("restored");
});
auto webview = webkit_web_view_new(); auto webview = webkit_web_view_new();
gtk_widget_set_hexpand(webview, true); gtk_widget_set_hexpand(webview, true);
gtk_widget_set_vexpand(webview, true); gtk_widget_set_vexpand(webview, true);
@@ -31,19 +15,5 @@ WebWidget::WebWidget(std::string icon, std::string title, std::string url) {
webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url.c_str()); webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url.c_str());
gtk_popover_set_child(popover->gobj(), webview); this->set_popover_child(*Glib::wrap(webview));
}
WebWidget::~WebWidget() {
delete popover;
}
void WebWidget::on_toggle_window() {
if (popover->get_visible()) {
popover->popdown();
} else {
popover->popup();
this->remove_css_class("minimized");
this->add_css_class("restored");
}
} }

View File

@@ -1,22 +1,61 @@
#include "widgets/workspaceIndicator.hpp" #include "widgets/workspaceIndicator.hpp"
#include <exception> #include <cassert>
#include <gdk/gdk.h> #include <gdk/gdk.h>
#include <gtkmm/gestureclick.h> #include <gtkmm/gestureclick.h>
#include <gtkmm/overlay.h>
#include <gtkmm/widget.h> #include <gtkmm/widget.h>
#include <sigc++/functors/mem_fun.h> #include <sigc++/functors/mem_fun.h>
WorkspaceIndicator::WorkspaceIndicator(HyprlandService &service, int monitorId) #include "services/hyprland.hpp"
: Gtk::Box(Gtk::Orientation::HORIZONTAL), service(service),
#include "gtkmm/box.h"
#include "gtkmm/label.h"
WorkspaceIndicator::WorkspaceIndicator(int monitorId)
: Gtk::Box(Gtk::Orientation::HORIZONTAL),
monitorId(monitorId) { monitorId(monitorId) {
set_margin_top(2); set_margin_top(2);
set_margin_bottom(2); set_margin_bottom(2);
workspaceConnection = service.workspaceStateChanged.connect( workspaceConnection = service->workspaceStateChanged.connect(
sigc::mem_fun(*this, &WorkspaceIndicator::on_workspace_update)); sigc::mem_fun(*this, &WorkspaceIndicator::on_workspace_update));
monitorConnection = service.monitorStateChanged.connect( monitorConnection = service->monitorStateChanged.connect(
sigc::mem_fun(*this, &WorkspaceIndicator::on_monitor_update)); 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(); rebuild();
} }
@@ -30,77 +69,36 @@ WorkspaceIndicator::~WorkspaceIndicator() {
} }
} }
void WorkspaceIndicator::on_workspace_update(int monitorId) { void WorkspaceIndicator::on_workspace_update() {
if (this->monitorId != monitorId && monitorId != -1) {
return;
}
rebuild(); rebuild();
} }
void WorkspaceIndicator::on_monitor_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() { void WorkspaceIndicator::rebuild() {
clear_children(); HyprlandService::Monitor *mon = service->getMonitorById(this->monitorId);
HyprlandService::Monitor *monitor = nullptr; for (auto [id, workspaceState] : mon->workspaceStates) {
try { Gtk::Overlay *overlay = workspaceIndicators[id];
monitor = service.getMonitorById(monitorId); this->refreshLabel(overlay, *workspaceState);
} catch (const std::exception &) {
return;
}
if (monitor == nullptr) {
return;
}
for (int workspaceId = 1;
workspaceId <= HyprlandService::kWorkspaceSlotCount; ++workspaceId) {
const HyprlandService::WorkspaceState *state = nullptr;
auto it = monitor->workspaceStates.find(workspaceId);
if (it != monitor->workspaceStates.end()) {
state = &it->second;
}
const std::string display = (state && !state->label.empty())
? state->label
: std::to_string(workspaceId);
auto label = Gtk::make_managed<Gtk::Label>(display);
label->add_css_class("workspace-pill");
auto gesture = Gtk::GestureClick::create();
gesture->set_button(GDK_BUTTON_PRIMARY);
gesture->signal_released().connect(
[this, workspaceId](int /*n_press*/, double /*x*/, double /*y*/) {
int realWorkspaceId = workspaceId + 5 * (monitorId);
service.switchToWorkspace(realWorkspaceId);
});
label->add_controller(gesture);
if (state != nullptr) {
if (state->urgent != true) {
if (state->focused) {
label->add_css_class("workspace-pill-focused");
} else if (state->active) {
label->add_css_class("workspace-pill-active");
}
} else {
label->add_css_class("workspace-pill-urgent");
}
}
append(*label);
}
}
void WorkspaceIndicator::clear_children() {
Gtk::Widget *child = get_first_child();
while (child != nullptr) {
Gtk::Widget *next = child->get_next_sibling();
remove(*child);
child = next;
} }
} }

View File

@@ -1,10 +0,0 @@
#include <giomm/menumodel.h>
#include <gio/gio.h>
#include <gio/gdbusmenumodel.h>
int main(){
GDBusMenuModel *dbusModel = g_dbus_menu_model_get_for_bus_sync(G_BUS_TYPE_SESSION, G_DBUS_MENU_MODEL_FLAGS_NONE, "org.freedesktop.Notifications", "/Menu", nullptr, nullptr);
if(!dbusModel) return 0;
Glib::RefPtr<Gio::MenuModel> model = Glib::wrap(G_MENU_MODEL(dbusModel));
return model ? 0 : 1;
}