Working on porting to new ags version

This commit is contained in:
Thomas Avé 2025-07-09 16:09:53 +02:00
parent 586c1e5d87
commit eaba3a8978
7 changed files with 161 additions and 151 deletions

View File

@ -1,7 +1,9 @@
import { App, Astal, Gdk, Gtk, Widget } from "astal/gtk3"; import { Astal, Gdk } from "ags/gtk4";
import { GLib, Variable, bind } from "astal"; import app from "ags/gtk4/app"
import Gtk from "gi://Gtk?version=4.0"
import { createBinding, createState } from "ags"
import Tray from "gi://AstalTray"; import Tray from "gi://AstalTray";
import { execAsync } from "astal/process" import { execAsync } from "ags/process"
import Hyprland from "gi://AstalHyprland"; import Hyprland from "gi://AstalHyprland";
import { getIconName } from "./utils"; import { getIconName } from "./utils";
import Wp from "gi://AstalWp" import Wp from "gi://AstalWp"
@ -15,17 +17,17 @@ function SysTray(): JSX.Element {
const tray = Tray.get_default(); const tray = Tray.get_default();
return ( return (
<box> <box>
{bind(tray, "items").as((items) => {createBinding(tray, "items").as((items) =>
items.map((item) => { items.map((item) => {
if (item.iconThemePath) App.add_icons(item.iconThemePath); if (item.iconThemePath) app.add_icons(item.iconThemePath);
return ( return (
<menubutton <menubutton
className="systray" class="systray"
tooltipMarkup={bind(item, "tooltipMarkup")} tooltipMarkup={createBinding(item, "tooltipMarkup")}
usePopover={false} usePopover={false}
actionGroup={bind(item, "actionGroup").as(ag => ["dbusmenu", ag])} actionGroup={createBinding(item, "actionGroup").as(ag => ["dbusmenu", ag])}
menuModel={bind(item, "menuModel")}> menuModel={createBinding(item, "menuModel")}>
<icon gicon={bind(item, "gicon")} className="systray-item" /> {/* <icon gicon={createBinding(item, "gicon")} class="systray-item" /> */}
</menubutton> </menubutton>
); );
}), }),
@ -34,7 +36,7 @@ function SysTray(): JSX.Element {
); );
} }
function Left() : JSX.Element { function Left(): JSX.Element {
return ( return (
<box hexpand halign={Gtk.Align.START}> <box hexpand halign={Gtk.Align.START}>
<Clients /> <Clients />
@ -42,7 +44,7 @@ function Left() : JSX.Element {
); );
} }
function Center() : JSX.Element { function Center(): JSX.Element {
return ( return (
<box> <box>
<Workspaces /> <Workspaces />
@ -51,10 +53,10 @@ function Center() : JSX.Element {
} }
function Date({ format = "%Y-%m-%d" }): JSX.Element { function Date({ format = "%Y-%m-%d" }): JSX.Element {
const time = Variable<string>("").poll(60000, () => const time = createState<string>("").poll(60000, () =>
GLib.DateTime.new_now_local().format(format)!) GLib.DateTime.new_now_local().format(format)!)
return <button return <button
className="item" class="item"
onDestroy={() => time.drop()} onDestroy={() => time.drop()}
label={time()} label={time()}
onClicked={() => execAsync(['gnome-calendar'])} onClicked={() => execAsync(['gnome-calendar'])}
@ -62,62 +64,62 @@ function Date({ format = "%Y-%m-%d" }): JSX.Element {
} }
function Time({ format = "%H:%M:%S" }): JSX.Element { function Time({ format = "%H:%M:%S" }): JSX.Element {
const time = Variable<string>("").poll(1000, () => const time = createState<string>("").poll(1000, () =>
GLib.DateTime.new_now_local().format(format)!) GLib.DateTime.new_now_local().format(format)!)
return <label return <label
className="item blue" class="item blue"
onDestroy={() => time.drop()} onDestroy={() => time.drop()}
label={time()} label={time()}
/> />
} }
function Temp(): JSX.Element { function Temp(): JSX.Element {
let label = Variable<string>("N/A"); let label = createState<string>("N/A");
if (sensorsAvailable) { if (sensorsAvailable) {
label = Variable<string>("").poll(5000, 'sensors', out => { label = createState<string>("").poll(5000, 'sensors', out => {
const match = out.split('\n').find(line => line.includes('Tctl') || line.includes('Package'))?.match(/[0-9.]*°C/); const match = out.split('\n').find(line => line.includes('Tctl') || line.includes('Package'))?.match(/[0-9.]*°C/);
return match ? match[0] : "N/A"; return match ? match[0] : "N/A";
}) })
} }
return <label return <label
className="item blue" class="item blue"
onDestroy={() => label.drop()} onDestroy={() => label.drop()}
label={label()} label={label()}
/> />
} }
function Memory(): JSX.Element { function Memory(): JSX.Element {
const memory = Variable<string>("").poll(2000, "free", out => { const memory = createState<string>("").poll(2000, "free", out => {
const line = out.split('\n').find(line => line.includes('Mem:')); const line = out.split('\n').find(line => line.includes('Mem:'));
if (!line) return "N/A"; if (!line) return "N/A";
const split = line.split(/\s+/).map(Number); const split = line.split(/\s+/).map(Number);
return (split[2] / 1000000).toFixed(2) + "GB"; return (split[2] / 1000000).toFixed(2) + "GB";
}); });
return <label return <label
className="item blue" class="item blue"
onDestroy={() => memory.drop()} onDestroy={() => memory.drop()}
label={memory()} label={memory()}
/> />
} }
function ClockSpeed(): JSX.Element { function ClockSpeed(): JSX.Element {
const command = 'bash -c "cat /proc/cpuinfo | grep \\"MHz\\" | awk \'{print \\$4}\' | sort -n | tail -1 | awk \'{printf \\"%.2fGHz\\", \\$1/1000}\'"'; const command = 'bash -c "cat /proc/cpuinfo | grep \\"MHz\\" | awk \'{print \\$4}\' | sort -n | tail -1 | awk \'{printf \\"%.2fGHz\\", \\$1/1000}\'"';
const speed = Variable<string>("").poll(5000, command) const speed = createState<string>("").poll(5000, command)
return <label return <label
className="item" class="item"
onDestroy={() => speed.drop()} onDestroy={() => speed.drop()}
label={speed()} label={speed()}
/> />
} }
function CPU(): JSX.Element { function CPU(): JSX.Element {
const usage = Variable<string>("").poll(2000, "top -b -n 1", out => { const usage = createState<string>("").poll(2000, "top -b -n 1", out => {
const line = out.split("\n").find(line => line.includes('Cpu(s)')); const line = out.split("\n").find(line => line.includes('Cpu(s)'));
if (!line) return "N/A"; if (!line) return "N/A";
return line.split(/\s+/)[1].replace(',', '.').toString() + "%"; return line.split(/\s+/)[1].replace(',', '.').toString() + "%";
}); });
return <box className="item"> return <box class="item">
<icon icon="speedometer" css="margin-right: 0.7em;" /> {/* <icon icon="speedometer" css="margin-right: 0.7em;" /> */}
<label <label
onDestroy={() => usage.drop()} onDestroy={() => usage.drop()}
label={usage()} label={usage()}
@ -127,9 +129,9 @@ function CPU(): JSX.Element {
function Right() : JSX.Element { function Right(): JSX.Element {
return ( return (
<box className="right" hexpand halign={Gtk.Align.END} spacing={6}> <box class="right" hexpand halign={Gtk.Align.END} spacing={6}>
<Icons /> <Icons />
<Volume /> <Volume />
<CPU /> <CPU />
@ -142,29 +144,29 @@ function Right() : JSX.Element {
); );
} }
function BatteryIcon(): JSX.Element { // function BatteryIcon(): JSX.Element {
if (battery.get_state() == 0) return <box />; // if (battery.get_state() == 0) return <box />;
return <button className="battery-item" onClicked={() => execAsync(['gnome-power-statistics'])}> // return <button class="battery-item" onClicked={() => execAsync(['gnome-power-statistics'])}>
<box> // <box>
{ // {
bind(battery, "percentage").as((percentage) => { // createBinding(battery, "percentage").as((percentage) => {
const thresholds = [...Array(11).keys()].map( i => i * 10); // const thresholds = [...Array(11).keys()].map(i => i * 10);
const icon = thresholds.find(threshold => threshold >= percentage * 100) // const icon = thresholds.find(threshold => threshold >= percentage * 100)
const charging_name = battery.percentage >= 0.99 ? "charged" : "charging" // const charging_name = battery.percentage >= 0.99 ? "charged" : "charging"
return <icon // return <icon
icon={battery.charging? `battery-level-${icon}-${charging_name}-symbolic` : `battery-level-${icon}-symbolic`} // icon={battery.charging ? `battery-level-${icon}-${charging_name}-symbolic` : `battery-level-${icon}-symbolic`}
/> // />
}) // })
} // }
</box> // </box>
</button> // </button>
} // }
function Icons() { function Icons() {
return ( return (
<box className="item icon-group"> <box class="item icon-group">
<SysTray /> <SysTray />
<BatteryIcon /> {/* <BatteryIcon /> */}
</box> </box>
) )
} }
@ -173,30 +175,30 @@ function Volume(): JSX.Element {
if (!wirePlumber) return <box />; if (!wirePlumber) return <box />;
const audio = wirePlumber.audio; const audio = wirePlumber.audio;
const icon = bind(audio.default_speaker, "volume").as((volume) => { const icon = createBinding(audio.default_speaker, "volume").as((volume) => {
const vol = volume * 100 const vol = volume * 100
const icon = [ const icon = [
[101, 'overamplified'], [101, 'overamplified'],
[67, 'high'], [67, 'high'],
[34, 'medium'], [34, 'medium'],
[1, 'low'], [1, 'low'],
[0, 'muted'], [0, 'muted'],
].find(([threshold]) => Number(threshold) <= vol)?.[1] ].find(([threshold]) => Number(threshold) <= vol)?.[1]
return `audio-volume-${icon}-symbolic` return `audio-volume-${icon}-symbolic`
}); });
const css = bind(audio.default_speaker, "mute").as((mute) => { const css = createBinding(audio.default_speaker, "mute").as((mute) => {
return mute ? "margin-left:0;": "margin-left: 0.7em;" return mute ? "margin-left:0;" : "margin-left: 0.7em;"
}); });
return ( return (
<button className="item blue" onClicked={() => audio.default_speaker.mute = !audio.default_speaker.mute}> <button class="item blue" onClicked={() => audio.default_speaker.mute = !audio.default_speaker.mute}>
<box> <box>
<icon icon={icon} /> {/* <icon icon={icon} /> */}
{ {
bind(audio.default_speaker, "volume").as((volume) => <box> createBinding(audio.default_speaker, "volume").as((volume) => <box>
{ {
bind(audio.default_speaker, "mute").as((mute) => <box> createBinding(audio.default_speaker, "mute").as((mute) => <box>
{ {
<label label={mute? "": `${Math.floor(volume * 100)}%`} css={css} /> <label label={mute ? "" : `${Math.floor(volume * 100)}%`} css={css} />
} }
</box>) </box>)
} }
@ -208,23 +210,23 @@ function Volume(): JSX.Element {
} }
function Workspaces() : JSX.Element { function Workspaces(): JSX.Element {
const hyprland = Hyprland.get_default(); const hyprland = Hyprland.get_default();
return ( return (
<box className="workspaces"> <box class="workspaces">
{bind(hyprland, "workspaces").as((wss) => {createBinding(hyprland, "workspaces").as((wss) =>
<box> <box>
{bind(hyprland, "focusedMonitor").as((fm) => {createBinding(hyprland, "focusedMonitor").as((fm) =>
wss.sort((a, b) => a.id - b.id) wss.sort((a, b) => a.id - b.id)
.filter(ws => ws && ws.get_monitor() && ws.get_monitor().get_id() === fm.get_id()) .filter(ws => ws && ws.get_monitor() && ws.get_monitor().get_id() === fm.get_id())
.map((ws) => ( .map((ws) => (
<button <button
className={bind(hyprland, "focusedWorkspace").as((fw) => ws === fw ? "focused" : "",)} class={createBinding(hyprland, "focusedWorkspace").as((fw) => ws === fw ? "focused" : "",)}
onClicked={() => ws.focus()} onClicked={() => ws.focus()}
> >
{`${ws.id}`.slice(-1)} {`${ws.id}`.slice(-1)}
</button> </button>
)))} )))}
</box> </box>
)} )}
</box> </box>
@ -235,31 +237,31 @@ function shorten(title: string) {
return title.length > 40 ? title.slice(0, 20) + "..." : title return title.length > 40 ? title.slice(0, 20) + "..." : title
} }
function Clients() : JSX.Element { function Clients(): JSX.Element {
const hyprland = Hyprland.get_default(); const hyprland = Hyprland.get_default();
return ( return (
<box> <box>
{ {
bind(hyprland, "focusedWorkspace").as(fw => ( createBinding(hyprland, "focusedWorkspace").as(fw => (
<box className="clients"> <box class="clients">
{ {
bind(hyprland, "clients").as(cls => createBinding(hyprland, "clients").as(cls =>
cls cls
.sort((a, b) => a.pid - b.pid) .sort((a, b) => a.pid - b.pid)
.filter(cl => !cl.title.includes("rofi")) .filter(cl => !cl.title.includes("rofi"))
.filter(cl => fw && cl.get_workspace().get_id() === fw.get_id()) .filter(cl => fw && cl.get_workspace().get_id() === fw.get_id())
.map(cl => ( .map(cl => (
<box <box
className={bind(hyprland, "focusedClient").as(a => a && a.address === cl.address ? "focused" : "unfocused")} class={createBinding(hyprland, "focusedClient").as(a => a && a.address === cl.address ? "focused" : "unfocused")}
> >
<icon {/* <icon */}
icon={getIconName(cl)} {/* icon={getIconName(cl)} */}
className="app-icon" {/* class="app-icon" */}
/> {/* /> */}
<label label={bind(cl, 'title').as(title => shorten(title))} /> <label label={createBinding(cl, 'title').as(title => shorten(title))} />
</box> </box>
) )
) )
) )
} }
@ -271,23 +273,23 @@ function Clients() : JSX.Element {
); );
} }
export default function Bar(gdkmonitor: Gdk.Monitor, scaleFactor: number = 1): Widget.Window { export default function Bar(gdkmonitor: Gdk.Monitor, scaleFactor: number = 1): Gtk.Window {
return new Widget.Window({ return new Gtk.Window({
gdkmonitor, gdkmonitor,
css: "font-size: " + scaleFactor + "em;", css: "font-size: " + scaleFactor + "em;",
exclusivity: Astal.Exclusivity.EXCLUSIVE, exclusivity: Astal.Exclusivity.EXCLUSIVE,
anchor: Astal.WindowAnchor.TOP | Astal.WindowAnchor.LEFT | Astal.WindowAnchor.RIGHT, anchor: Astal.WindowAnchor.TOP | Astal.WindowAnchor.LEFT | Astal.WindowAnchor.RIGHT,
application: App, application: app,
className: "Bar", class: "Bar",
name: "top-bar", name: "top-bar",
setup: self => self.connect("destroy", () => { s: self => self.connect("destroy", () => {
print("Detroying bar"); print("Detroying bar");
App.remove_window(self); app.remove_window(self);
}), }),
child: <centerbox className="window-box"> child: <centerbox class="window-box">
<Left /> <Left />
<Center /> <Center />
<Right /> <Right />
</centerbox> </centerbox>
}) })
} }

View File

@ -1,8 +1,10 @@
import { App, Gdk, Widget } from "astal/gtk3" import app from "ags/gtk4/app"
import style from "./style.scss" import style from "./style.scss"
import Bar from "./Bar" import Bar from "./Bar"
import Hyprland from "gi://AstalHyprland"; import Hyprland from "gi://AstalHyprland";
import NotificationPopups from "./notifications/NotificationPopups" import NotificationPopups from "./notifications/NotificationPopups"
import Gtk from "gi://Gtk?version=4.0";
import { Gdk } from "ags/gtk4";
const hyprland = Hyprland.get_default(); const hyprland = Hyprland.get_default();
@ -22,21 +24,26 @@ function find_main_monitor(): Hyprland.Monitor {
} }
function register_windows(monitor: Hyprland.Monitor) { function register_windows(monitor: Hyprland.Monitor) {
let gtkMonitor = App.get_monitors()[0].get_display().get_monitor_at_point(monitor.get_x(), monitor.get_y()) let gtkMonitors = app.get_monitors()[0].get_display().get_monitors()
let scale = (monitor.get_width() >= 3000)? 1.2: 1 let gtkMonitor = gtkMonitors.get_item(0)
if (!gtkMonitor) {
console.error("No GTK monitor found for the Hyprland monitor:", monitor.get_name());
return;
}
let scale = (monitor.get_width() >= 3000) ? 1.2 : 1
Bar(gtkMonitor, scale) Bar(gtkMonitor, scale)
NotificationPopups(gtkMonitor) NotificationPopups(gtkMonitor)
} }
function switch_to_best_monitor() { function switch_to_best_monitor() {
let mainMonitor = find_main_monitor() let mainMonitor = find_main_monitor()
for (var wd of App.get_windows()) { for (var wd of app.get_windows()) {
wd.destroy(); wd.destroy();
} }
register_windows(mainMonitor); register_windows(mainMonitor);
} }
hyprland.connect("monitor-added", (_, monitor) => { hyprland.connect("monitor-added", (_, _monitor: Hyprland.Monitor) => {
switch_to_best_monitor() switch_to_best_monitor()
}) })
@ -44,7 +51,7 @@ hyprland.connect("monitor-removed", () => {
switch_to_best_monitor() switch_to_best_monitor()
}) })
App.start({ app.start({
css: style, css: style,
iconTheme: "Papirus", iconTheme: "Papirus",
main() { main() {

View File

@ -1,21 +1,21 @@
declare const SRC: string declare const SRC: string
declare module "inline:*" { declare module "inline:*" {
const content: string const content: string
export default content export default content
} }
declare module "*.scss" { declare module "*.scss" {
const content: string const content: string
export default content export default content
} }
declare module "*.blp" { declare module "*.blp" {
const content: string const content: string
export default content export default content
} }
declare module "*.css" { declare module "*.css" {
const content: string const content: string
export default content export default content
} }

View File

@ -1,7 +1,7 @@
import { GLib } from "astal" import { Gtk, Astal } from "ags/gtk4"
import { Gtk, Astal } from "astal/gtk3" import { EventBox } from "ags"
import { type EventBox } from "astal/gtk3/widget"
import Notifd from "gi://AstalNotifd" import Notifd from "gi://AstalNotifd"
import GLib from "gi://GLib"
const isIcon = (icon: string) => const isIcon = (icon: string) =>
!!Astal.Icon.lookup_icon(icon) !!Astal.Icon.lookup_icon(icon)
@ -35,24 +35,24 @@ export default function Notification(props: Props) {
const { START, CENTER, END } = Gtk.Align const { START, CENTER, END } = Gtk.Align
return <eventbox return <eventbox
className={`Notification ${urgency(n)}`} class={`Notification ${urgency(n)}`}
setup={setup} setup={setup}
onHoverLost={onHoverLost}> onHoverLost={onHoverLost}>
<box vertical> <box vertical>
<box className="header"> <box class="header">
{(n.appIcon || n.desktopEntry) && <icon {(n.appIcon || n.desktopEntry) && <icon
className="app-icon" class="app-icon"
visible={Boolean(n.appIcon || n.desktopEntry)} visible={Boolean(n.appIcon || n.desktopEntry)}
icon={n.appIcon || n.desktopEntry} icon={n.appIcon || n.desktopEntry}
/>} />}
<label <label
className="app-name" class="app-name"
halign={START} halign={START}
truncate truncate
label={n.appName || "Unknown"} label={n.appName || "Unknown"}
/> />
<label <label
className="time" class="time"
hexpand hexpand
halign={END} halign={END}
label={time(n.time)} label={time(n.time)}
@ -62,28 +62,28 @@ export default function Notification(props: Props) {
</button> </button>
</box> </box>
<Gtk.Separator visible /> <Gtk.Separator visible />
<box className="content"> <box class="content">
{n.image && fileExists(n.image) && <box {n.image && fileExists(n.image) && <box
valign={START} valign={START}
className="image" class="image"
css={`background-image: url('${n.image}')`} css={`background-image: url('${n.image}')`}
/>} />}
{n.image && isIcon(n.image) && <box {n.image && isIcon(n.image) && <box
expand={false} expand={false}
valign={START} valign={START}
className="icon-image"> class="icon-image">
<icon icon={n.image} expand halign={CENTER} valign={CENTER} /> <icon icon={n.image} expand halign={CENTER} valign={CENTER} />
</box>} </box>}
<box vertical> <box vertical>
<label <label
className="summary" class="summary"
halign={START} halign={START}
xalign={0} xalign={0}
label={n.summary} label={n.summary}
truncate truncate
/> />
{n.body && <label {n.body && <label
className="body" class="body"
wrap wrap
useMarkup useMarkup
halign={START} halign={START}
@ -93,7 +93,7 @@ export default function Notification(props: Props) {
/>} />}
</box> </box>
</box> </box>
{n.get_actions().length > 0 && <box className="actions"> {n.get_actions().length > 0 && <box class="actions">
{n.get_actions().map(({ label, id }) => ( {n.get_actions().map(({ label, id }) => (
<button <button
hexpand hexpand

View File

@ -1,8 +1,10 @@
import { Astal, Gtk, Gdk } from "astal/gtk3" import { Astal, Gtk, Gdk } from "ags/gtk4"
import Notifd from "gi://AstalNotifd" import Notifd from "gi://AstalNotifd"
import Notification from "./Notification" import Notification from "./Notification"
import { type Subscribable } from "astal/binding" import { type Subscribable } from "astal/binding"
import { GLib, Variable, bind, timeout } from "astal" import { timeout } from "ags/time"
import { createBinding, createState } from "ags"
import GLib from "gi://GLib"
// see comment below in constructor // see comment below in constructor
const TIMEOUT_DELAY = 5000 const TIMEOUT_DELAY = 5000
@ -16,7 +18,7 @@ class NotifiationMap implements Subscribable {
// it makes sense to use a Variable under the hood and use its // it makes sense to use a Variable under the hood and use its
// reactivity implementation instead of keeping track of subscribers ourselves // reactivity implementation instead of keeping track of subscribers ourselves
private var: Variable<Array<Gtk.Widget>> = Variable([]) private var: Array<Gtk.Widget> = createState([])
// notify subscribers to rerender when state changes // notify subscribers to rerender when state changes
private notifiy() { private notifiy() {
@ -99,7 +101,7 @@ export default function NotificationPopups(gdkmonitor: Gdk.Monitor) {
exclusivity={Astal.Exclusivity.EXCLUSIVE} exclusivity={Astal.Exclusivity.EXCLUSIVE}
anchor={TOP | RIGHT}> anchor={TOP | RIGHT}>
<box vertical> <box vertical>
{bind(notifs)} {createBinding(notifs)}
</box> </box>
</window> </window>
} }

View File

@ -0,0 +1,5 @@
{
"dependencies": {
"ags": "*"
}
}

View File

@ -1,22 +1,16 @@
{ {
"$schema": "https://json.schemastore.org/tsconfig", "$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true,
"strict": true, "strict": true,
"target": "ES2022",
"module": "ES2022", "module": "ES2022",
"target": "ES2020",
"lib": [
"ES2023"
],
"moduleResolution": "Bundler", "moduleResolution": "Bundler",
// "checkJs": true, // "checkJs": true,
// "allowJs": true, // "allowJs": true,
"jsx": "react-jsx", "jsx": "react-jsx",
"jsxImportSource": "/nix/store/1pd4fdq90f4vla3zghmfci9axsbvkd3w-astal-gjs/share/astal/gjs/gtk3", "jsxImportSource": "ags/gtk4"
"paths": {
"astal": [
"/nix/store/1pd4fdq90f4vla3zghmfci9axsbvkd3w-astal-gjs/share/astal/gjs"
],
"astal/*": [
"/nix/store/1pd4fdq90f4vla3zghmfci9axsbvkd3w-astal-gjs/share/astal/gjs/*"
]
},
} }
} }