Work on switching to new ags

This commit is contained in:
Thomas Avé 2024-11-24 12:56:22 +01:00
parent 3bbe1d6016
commit 6c26e0a8b0
15 changed files with 937 additions and 627 deletions

300
home/ags/files/Bar.tsx Normal file
View File

@ -0,0 +1,300 @@
import { App, Astal, Gdk, Gtk } from "astal/gtk3";
import { GLib, Variable, bind } from "astal";
import Tray from "gi://AstalTray";
import { execAsync } from "astal/process"
import Hyprland from "gi://AstalHyprland";
import { getIconName } from "./utils";
import Wp from "gi://AstalWp"
import Battery from "gi://AstalBattery"
const battery = Battery.get_default()
const sensorsAvailable = await execAsync(['sensors']).then(() => true).catch(() => false);
const wirePlumber = Wp.get_default();
function SysTray(): JSX.Element {
const tray = Tray.get_default();
return (
<box>
{bind(tray, "items").as((items) =>
items.map((item) => {
if (item.iconThemePath) App.add_icons(item.iconThemePath);
const menu = item.create_menu();
return (
<button
className="systray"
tooltipMarkup={bind(item, "tooltipMarkup")}
onDestroy={() => menu?.destroy()}
onClickRelease={(self) => {
menu?.popup_at_widget(
self,
Gdk.Gravity.SOUTH,
Gdk.Gravity.NORTH,
null,
);
}}>
<icon gIcon={bind(item, "gicon")} className="systray-item" />
</button>
);
}),
)}
</box>
);
}
function Left() : JSX.Element {
return (
<box hexpand halign={Gtk.Align.START}>
<Clients />
</box>
);
}
function Center() : JSX.Element {
return (
<box>
<Workspaces />
</box>
);
}
function Date({ format = "%Y-%m-%d" }): JSX.Element {
const time = Variable<string>("").poll(60000, () =>
GLib.DateTime.new_now_local().format(format)!)
return <button
className="item"
onDestroy={() => time.drop()}
label={time()}
onClicked={() => execAsync(['gnome-calendar'])}
/>
}
function Time({ format = "%H:%M:%S" }): JSX.Element {
const time = Variable<string>("").poll(1000, () =>
GLib.DateTime.new_now_local().format(format)!)
return <label
className="item blue"
onDestroy={() => time.drop()}
label={time()}
/>
}
function Temp(): JSX.Element {
if (sensorsAvailable) {
const temp = Variable<string>("").poll(5000, 'sensors', out => {
const match = out.split('\n').find(line => line.includes('Tctl') || line.includes('Package'))?.match(/[0-9.]*°C/);
return match ? match[0] : "N/A";
})
return <label
className="item blue"
onDestroy={() => temp.drop()}
label={temp()}
/>
}
return <box />
}
function Memory(): JSX.Element {
const memory = Variable<string>("").poll(2000, "free", out => {
const line = out.split('\n').find(line => line.includes('Mem:'));
if (!line) return "N/A";
const split = line.split(/\s+/).map(Number);
return ((split[2]-split[5]) / 1000000).toFixed(2) + "GB";
});
return <label
className="item blue"
onDestroy={() => memory.drop()}
label={memory()}
/>
}
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 speed = Variable<string>("").poll(5000, command)
return <label
className="item"
onDestroy={() => speed.drop()}
label={speed()}
/>
}
function CPU(): JSX.Element {
const usage = Variable<string>("").poll(2000, "top -b -n 1", out => {
const line = out.split("\n").find(line => line.includes('Cpu(s)'));
if (!line) return "N/A";
return line.split(/\s+/)[1].replace(',', '.').toString() + "%";
});
return <box className="item">
<icon icon="speedometer" css="margin-right: 0.7em;" />
<label
onDestroy={() => usage.drop()}
label={usage()}
/>
</box>
}
function Right() : JSX.Element {
return (
<box className="right" hexpand halign={Gtk.Align.END} spacing={6}>
<Icons />
<Volume />
<CPU />
<Memory />
<ClockSpeed />
<Temp />
<Date />
<Time />
</box>
);
}
function BatteryIcon(): JSX.Element {
const icon_name = bind(battery, "percentage").as((percentage) => {
const thresholds = [...Array(11).keys()].map( i => i * 10);
const icon = thresholds.find(threshold => threshold >= percentage * 100)
const charging_name = battery.percentage >= 0.99 ? "charged" : "charging"
return battery.charging? `battery-level-${icon}-${charging_name}-symbolic` : `battery-level-${icon}-symbolic`
});
return <box className="battery-item" tooltip_text={`Battery ${battery.percentage * 100}%`}>
<icon icon={icon_name} />
</box>
}
function Icons() {
return (
<box className="item icon-group">
<SysTray />
<BatteryIcon />
</box>
)
}
function Volume(): JSX.Element {
if (!wirePlumber) return <box />;
const audio = wirePlumber.audio;
const icon = bind(audio.default_speaker, "volume").as((volume) => {
const vol = volume * 100
const icon = [
[101, 'overamplified'],
[67, 'high'],
[34, 'medium'],
[1, 'low'],
[0, 'muted'],
].find(([threshold]) => Number(threshold) <= vol)?.[1]
return `audio-volume-${icon}-symbolic`
});
const css = bind(audio.default_speaker, "mute").as((mute) => {
return mute ? "margin-left:0;": "margin-left: 0.7em;"
});
return (
<button className="item blue" onClicked={() => audio.default_speaker.mute = !audio.default_speaker.mute}>
<box>
<icon icon={icon} />
{
bind(audio.default_speaker, "volume").as((volume) => <box>
{
bind(audio.default_speaker, "mute").as((mute) => <box>
{
<label label={mute? "": `${Math.floor(volume * 100)}%`} css={css} />
}
</box>)
}
</box>)
}
</box>
</button>
);
}
function Workspaces() : JSX.Element {
const hyprland = Hyprland.get_default();
return (
<box className="workspaces">
{bind(hyprland, "workspaces").as((wss) =>
wss
.sort((a, b) => a.id - b.id)
.filter(
(ws) =>
ws.get_monitor().get_id() ===
hyprland.get_focused_monitor().get_id(),
)
.map((ws) => (
<button
className={bind(hyprland, "focusedWorkspace").as((fw) =>
ws === fw ? "focused" : "",
)}
onClicked={() => ws.focus()}
>
{`${ws.id}`.slice(-1)}
</button>
)),
)}
</box>
);
}
function shorten(title: string) {
return title.length > 40 ? title.slice(0, 20) + "..." : title
}
function Clients() : JSX.Element {
const hyprland = Hyprland.get_default();
return (
<box>
{
bind(hyprland, "focusedWorkspace").as(fw => (
<box className="clients">
{
bind(hyprland, "clients").as(cls =>
cls
.sort((a, b) => a.pid - b.pid)
.filter(cl => !cl.title.includes("rofi"))
.filter(cl => cl.get_workspace().get_id() === fw.get_id())
.map(cl => (
<box
className={bind(hyprland, "focusedClient").as(a => a && a.address === cl.address ? "focused" : "unfocused")}
>
<icon
icon={getIconName(cl)}
className="app-icon"
/>
<label label={bind(cl, 'title').as(title => shorten(title))} />
</box>
)
)
)
}
</box>
)
)
}
</box>
);
}
export default function Bar(gdkmonitor: Gdk.Monitor) {
return (
<window
className="Bar"
gdkmonitor={gdkmonitor}
exclusivity={Astal.Exclusivity.EXCLUSIVE}
anchor={
Astal.WindowAnchor.TOP |
Astal.WindowAnchor.LEFT |
Astal.WindowAnchor.RIGHT
}
application={App}
>
<centerbox className="window-box" >
<Left />
<Center />
<Right />
</centerbox>
</window>
);
}

13
home/ags/files/app.ts Normal file
View File

@ -0,0 +1,13 @@
import { App } from "astal/gtk3"
import style from "./style.scss"
import Bar from "./Bar"
import NotificationPopups from "./notifications/NotificationPopups"
App.start({
css: style,
iconTheme: "Papirus",
main() {
App.get_monitors().map(Bar)
App.get_monitors().map(NotificationPopups)
},
})

View File

@ -1,274 +0,0 @@
const hyprland = await Service.import("hyprland")
const audio = await Service.import("audio")
const systemtray = await Service.import("systemtray")
import { getIconName } from "./utils.js"
import { NotificationPopups } from "./notificationPopups.js"
const battery = await Service.import('battery')
const powerProfiles = await Service.import('powerprofiles')
const batteryIndicator = Widget.Box({
visible: battery.available,
children: battery.available? [
Widget.Icon().hook(battery, self => {
const thresholds = [...Array(11).keys()].map( i => i * 10);
const icon = thresholds.find(threshold => threshold >= battery.percent)
const charging_name = battery.percent >= 99 ? "charged" : "charging"
self.icon = battery.charging? `battery-level-${icon}-${charging_name}-symbolic` : `battery-level-${icon}-symbolic`
self.tooltip_text = `Battery ${battery.percent}%`
self.class_name = "battery-item";
}),
]: []
})
const sensorsAvailable = await Utils.execAsync(['sensors']).then(() => true).catch(() => false)
const volumeIndicator = Widget.Button({
on_clicked: () => audio.speaker.is_muted = !audio.speaker.is_muted,
class_name: "item blue",
child: Widget.Box({
children: [
Widget.Icon().hook(audio.speaker, self => {
const vol = audio.speaker.volume * 100
const icon = [
[101, 'overamplified'],
[67, 'high'],
[34, 'medium'],
[1, 'low'],
[0, 'muted'],
].find(([threshold]) => threshold <= vol)?.[1]
self.icon = `audio-volume-${icon}-symbolic`
self.tooltip_text = `Volume ${Math.floor(vol)}%`
}),
Widget.Label().hook(audio.speaker, self => {
const label = `${Math.floor(audio.speaker.volume * 100)}%`
self.label = audio.speaker.is_muted ? "" : label
self.css = audio.speaker.is_muted ? "margin-left:0;": "margin-left: 0.7em;"
})
]}),
});
let monitor = 0
for (const mon in hyprland.monitors) {
if (hyprland.monitors[mon]["width"] > hyprland.monitors[monitor]["width"]) {
monitor = mon
}
}
function Clients() {
const activeId = hyprland.active.client.bind("address")
const clients = hyprland.bind("clients").as(cl =>
cl.filter(a => !a.title.includes("rofi")).map(({ address, title, workspace }) =>
{
const short_title = title.length > 40 ? title.slice(0, 20) + "..." : title
return Widget.Box({
attribute: workspace.id,
class_name: activeId.as(i => `${i === address ? "focused" : ""}`),
children: [
Widget.Icon({
vexpand: false,
size: 16,
className: "app-icon",
icon: getIconName(hyprland.clients.find(c => c.address === address))
}),
Widget.Label(`${short_title}`)
],
})
})
)
return Widget.Box({
class_name: "clients",
children: clients,
setup: self => self.hook(hyprland, () => self.children.forEach(box => {
box.visible = hyprland.active.workspace.id === box.attribute
})),
})
}
function Workspaces() {
const activeId = hyprland.active.workspace.bind("id")
const workspaces = hyprland.bind("workspaces").as(ws => {
ws.sort((a, b) => a.id - b.id)
return ws.map(({ id, monitorID }) =>
Widget.Button({
attribute: monitorID,
label: `${id}`.slice(-1),
onClicked: () => hyprland.messageAsync(`dispatch workspace ${id}`),
class_name: activeId.as(i => `${i === id ? "focused" : ""}`),
})
)
})
return Widget.Box({
children: workspaces,
class_name: "workspaces",
setup: self => self.hook(hyprland, () => self.children.forEach(btn => {
btn.visible = hyprland.active.monitor.id === btn.attribute
})),
})
}
function SysTray() {
const items = systemtray.bind("items")
.as(items => items.map(item => {
return Widget.Button({
child: Widget.Icon({
icon: item.bind("icon"),
class_name: "systray-item",
}),
on_primary_click: (_, event) => item.activate(event),
on_secondary_click: (_, event) => item.openMenu(event),
tooltip_markup: item.bind("tooltip_markup"),
class_name: "systray",
})}
))
return Widget.Box({
children: items,
})
}
function Left() {
return Widget.Box({
spacing: 8,
children: [
Clients(),
],
})
}
function Center() {
return Widget.Box({
spacing: 8,
children: [
Workspaces(),
],
})
}
function Icons() {
return Widget.Box({
spacing: 0,
class_name: "item icon-group",
children: [
SysTray(),
batteryIndicator,
],
})
}
function Right() {
return Widget.Box({
hpack: "end",
spacing: 8,
class_name: "right",
children: [
Icons(),
volumeIndicator,
Widget.Box({
class_name: "item",
children: [
Widget.Icon({
vexpand: false,
size: 16,
icon: "speedometer",
css: "margin-right: 0.7em;",
}),
Widget.Label({
label: Variable("", {
poll: [2000, 'top -b -n 1', out => out.split('\n')
.find(line => line.includes('Cpu(s)'))
.split(/\s+/)[1]
.replace(',', '.').toString() + "%"],
}).bind()
})
]}),
Widget.Label({
class_name: "item blue",
label: Variable("", {
poll: [2000, 'free', out => (out.split('\n')
.find(line => line.includes('Mem:'))
.split(/\s+/)[2] / 1000000).toFixed(2) + "GB"],
}).bind(),
}),
Widget.Button({
class_name: "item",
child: Widget.Box({
children: [
Widget.Icon({
vexpand: false,
size: 16,
icon: powerProfiles.bind('active_profile').as(profile => `power-profile-${profile}-symbolic`),
css: "margin-right: 0.7em;",
}),
Widget.Label({
label: Variable("", { poll: [5000, 'bash -c "cat /proc/cpuinfo | grep \\"MHz\\" | awk \'{print \\$4}\' | sort -n | tail -1 | awk \'{printf \\"%.2fGHz\\", \\$1/1000}\'"'] }).bind(),
}),
]
}),
on_clicked: () => {
let next = false
for (const profile of powerProfiles.profiles) {
if (next) {
powerProfiles.active_profile = profile["Profile"]
return
} else if (profile["Profile"] === powerProfiles.active_profile) {
next = true
}
}
powerProfiles.active_profile = powerProfiles.profiles[0]["Profile"]
},
}),
Widget.Label({
class_name: "item blue",
label: sensorsAvailable ? Variable("", {
poll: [5000, 'sensors', out => {
const match = out.split('\n').find(line => line.includes('Tctl') || line.includes('Package'))?.match(/[0-9.]*°C/);
return match ? match[0] : "N/A";
}],
}).bind() : "N/A",
}),
Widget.Button({
class_name: "item",
child: Widget.Label({
label: Variable("", { poll: [1000, 'date "+%Y-%m-%d"'] }).bind(),
}),
on_clicked: () => Utils.execAsync(['gnome-calendar']),
}),
Widget.Label({
class_name: "item blue",
label: Variable("", { poll: [1000, 'date "+%H:%M:%S"'] }).bind(),
})
],
})
}
function Bar(monitor = 0) {
return Widget.Window({
name: `ags-bar-${monitor}`, // name has to be unique
class_name: "bar",
monitor,
anchor: ["top", "left", "right"],
exclusivity: "exclusive",
css: "font-size: " + (hyprland.monitors[monitor]["width"] > 2600? "1.2em;": "1em;"),
child: Widget.CenterBox({
class_name: "window-box",
start_widget: Left(),
center_widget: Center(),
end_widget: Right(),
}),
})
}
print(JSON.stringify(monitor))
App.config({
style: "./style.css",
iconTheme: "Papirus",
windows: [
Bar(monitor),
NotificationPopups(),
],
})
export { }

21
home/ags/files/env.d.ts vendored Normal file
View File

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

View File

@ -1,140 +0,0 @@
const notifications = await Service.import("notifications")
notifications.popupTimeout = 3000
notifications.forceTimeout = true
/** @param {import('resource:///com/github/Aylur/ags/service/notifications.js').Notification} n */
function NotificationIcon({ app_entry, app_icon, image }) {
if (image) {
return Widget.Box({
css: `background-image: url("${image}");`
+ "background-size: contain;"
+ "background-repeat: no-repeat;"
+ "background-position: center;",
})
}
let icon = "dialog-information-symbolic"
if (Utils.lookUpIcon(app_icon))
icon = app_icon
if (app_entry && Utils.lookUpIcon(app_entry))
icon = app_entry
return Widget.Box({
child: Widget.Icon(icon),
})
}
/** @param {import('resource:///com/github/Aylur/ags/service/notifications.js').Notification} n */
function Notification(n) {
const icon = Widget.Box({
vpack: "start",
class_name: "icon",
child: NotificationIcon(n),
})
const title = Widget.Label({
class_name: "title",
xalign: 0,
justification: "left",
hexpand: true,
max_width_chars: 24,
truncate: "end",
wrap: true,
label: n.summary,
use_markup: true,
})
const body = Widget.Label({
class_name: "body",
hexpand: true,
use_markup: true,
xalign: 0,
justification: "left",
label: n.body,
wrap: true,
})
const actions = Widget.Box({
class_name: "actions",
children: n.actions.map(({ id, label }) => Widget.Button({
class_name: "action-button",
on_clicked: () => {
n.invoke(id)
n.dismiss()
},
hexpand: true,
child: Widget.Label(label),
})),
})
return Widget.EventBox(
{
attribute: { id: n.id },
on_primary_click: n.dismiss,
},
Widget.Box(
{
class_name: `notification ${n.urgency}`,
vertical: true,
},
Widget.Box([
icon,
Widget.Box(
{ vertical: true },
title,
body,
),
]),
actions,
),
)
}
export function NotificationPopups(monitor = 0) {
const list = Widget.Box({
vertical: true,
children: notifications.popups.map(Notification),
})
function onNotified(_, /** @type {number} */ id) {
const n = notifications.getNotification(id)
if (n) {
list.children = [Notification(n), ...list.children]
// Schedule a timeout to dismiss the notification
setTimeout(() => {
const n = notifications.getNotification(id)
if (n) { // if the notification is still there
n.dismiss()
}
}, notifications.popupTimeout)
}
}
function onDismissed(_, /** @type {number} */ id) {
list.children.find(n => n.attribute.id === id)?.destroy()
}
list.hook(notifications, onNotified, "notified")
.hook(notifications, onDismissed, "dismissed")
return Widget.Window({
monitor,
name: `notifications${monitor}`,
class_name: "notification-popups",
anchor: ["top", "right"],
child: Widget.Box({
css: "min-width: 2px; min-height: 2px;",
class_name: "notifications",
vertical: true,
child: list,
/** this is a simple one liner that could be used instead of
hooking into the 'notified' and 'dismissed' signals.
but its not very optimized becuase it will recreate
the whole list everytime a notification is added or dismissed */
// children: notifications.bind('popups')
// .as(popups => popups.map(Notification))
}),
})
}

View File

@ -0,0 +1,125 @@
@use "sass:string";
@function gtkalpha($c, $a) {
@return string.unquote("alpha(#{$c},#{$a})");
}
// https://gitlab.gnome.org/GNOME/gtk/-/blob/gtk-3-24/gtk/theme/Adwaita/_colors-public.scss
$fg-color: #{"@theme_fg_color"};
$bg-color: #1f2430;
$error: red;
window.NotificationPopups {
all: unset;
}
eventbox.Notification {
&:first-child>box {
margin-top: 1rem;
}
&:last-child>box {
margin-bottom: 1rem;
}
// eventboxes can not take margins so we style its inner box instead
>box {
min-width: 400px;
border-radius: 13px;
background-color: #1f2430;
margin: .5rem 1rem .5rem 1rem;
box-shadow: 2px 3px 8px 0 gtkalpha(black, .4);
border: 1pt solid gtkalpha($fg-color, .03);
}
&.critical>box {
border: 1pt solid gtkalpha($error, .4);
.header {
.app-name {
color: gtkalpha($error, .8);
}
.app-icon {
color: gtkalpha($error, .6);
}
}
}
.header {
padding: .5rem;
color: gtkalpha($fg-color, 0.5);
.app-icon {
margin: 0 .4rem;
}
.app-name {
margin-right: .3rem;
font-weight: bold;
&:first-child {
margin-left: .4rem;
}
}
.time {
margin: 0 .4rem;
}
button {
padding: .2rem;
min-width: 0;
min-height: 0;
}
}
separator {
margin: 0 .4rem;
background-color: gtkalpha($fg-color, .1);
}
.content {
margin: 1rem;
margin-top: .5rem;
.summary {
font-size: 1.2em;
color: $fg-color;
}
.body {
color: gtkalpha($fg-color, 0.8);
}
.image {
border: 1px solid gtkalpha($fg-color, .02);
margin-right: .5rem;
border-radius: 9px;
min-width: 100px;
min-height: 100px;
background-size: cover;
background-position: center;
}
}
.actions {
margin: 1rem;
margin-top: 0;
button {
margin: 0 .3rem;
&:first-child {
margin-left: 0;
}
&:last-child {
margin-right: 0;
}
}
}
}

View File

@ -0,0 +1,107 @@
import { GLib } from "astal"
import { Gtk, Astal } from "astal/gtk3"
import { type EventBox } from "astal/gtk3/widget"
import Notifd from "gi://AstalNotifd"
const isIcon = (icon: string) =>
!!Astal.Icon.lookup_icon(icon)
const fileExists = (path: string) =>
GLib.file_test(path, GLib.FileTest.EXISTS)
const time = (time: number, format = "%H:%M") => GLib.DateTime
.new_from_unix_local(time)
.format(format)!
const urgency = (n: Notifd.Notification) => {
const { LOW, NORMAL, CRITICAL } = Notifd.Urgency
// match operator when?
switch (n.urgency) {
case LOW: return "low"
case CRITICAL: return "critical"
case NORMAL:
default: return "normal"
}
}
type Props = {
setup(self: EventBox): void
onHoverLost(self: EventBox): void
notification: Notifd.Notification
}
export default function Notification(props: Props) {
const { notification: n, onHoverLost, setup } = props
const { START, CENTER, END } = Gtk.Align
return <eventbox
className={`Notification ${urgency(n)}`}
setup={setup}
onHoverLost={onHoverLost}>
<box vertical>
<box className="header">
{(n.appIcon || n.desktopEntry) && <icon
className="app-icon"
visible={Boolean(n.appIcon || n.desktopEntry)}
icon={n.appIcon || n.desktopEntry}
/>}
<label
className="app-name"
halign={START}
truncate
label={n.appName || "Unknown"}
/>
<label
className="time"
hexpand
halign={END}
label={time(n.time)}
/>
<button onClicked={() => n.dismiss()}>
<icon icon="window-close-symbolic" />
</button>
</box>
<Gtk.Separator visible />
<box className="content">
{n.image && fileExists(n.image) && <box
valign={START}
className="image"
css={`background-image: url('${n.image}')`}
/>}
{n.image && isIcon(n.image) && <box
expand={false}
valign={START}
className="icon-image">
<icon icon={n.image} expand halign={CENTER} valign={CENTER} />
</box>}
<box vertical>
<label
className="summary"
halign={START}
xalign={0}
label={n.summary}
truncate
/>
{n.body && <label
className="body"
wrap
useMarkup
halign={START}
xalign={0}
justifyFill
label={n.body}
/>}
</box>
</box>
{n.get_actions().length > 0 && <box className="actions">
{n.get_actions().map(({ label, id }) => (
<button
hexpand
onClicked={() => n.invoke(id)}>
<label label={label} halign={CENTER} hexpand />
</button>
))}
</box>}
</box>
</eventbox>
}

View File

@ -0,0 +1,105 @@
import { Astal, Gtk, Gdk } from "astal/gtk3"
import Notifd from "gi://AstalNotifd"
import Notification from "./Notification"
import { type Subscribable } from "astal/binding"
import { GLib, Variable, bind, timeout } from "astal"
// see comment below in constructor
const TIMEOUT_DELAY = 5000
// The purpose if this class is to replace Variable<Array<Widget>>
// with a Map<number, Widget> type in order to track notification widgets
// by their id, while making it conviniently bindable as an array
class NotifiationMap implements Subscribable {
// the underlying map to keep track of id widget pairs
private map: Map<number, Gtk.Widget> = new Map()
// it makes sense to use a Variable under the hood and use its
// reactivity implementation instead of keeping track of subscribers ourselves
private var: Variable<Array<Gtk.Widget>> = Variable([])
// notify subscribers to rerender when state changes
private notifiy() {
this.var.set([...this.map.values()].reverse())
}
private constructor() {
const notifd = Notifd.get_default()
/**
* uncomment this if you want to
* ignore timeout by senders and enforce our own timeout
* note that if the notification has any actions
* they might not work, since the sender already treats them as resolved
*/
// notifd.ignoreTimeout = true
notifd.connect("notified", (_, id) => {
this.set(id, Notification({
notification: notifd.get_notification(id)!,
// once hovering over the notification is done
// destroy the widget without calling notification.dismiss()
// so that it acts as a "popup" and we can still display it
// in a notification center like widget
// but clicking on the close button will close it
onHoverLost: () => this.delete(id),
// notifd by default does not close notifications
// until user input or the timeout specified by sender
// which we set to ignore above
setup: () => timeout(TIMEOUT_DELAY, () => {
/**
* uncomment this if you want to "hide" the notifications
* after TIMEOUT_DELAY
*/
this.delete(id)
})
}))
})
// notifications can be closed by the outside before
// any user input, which have to be handled too
notifd.connect("resolved", (_, id) => {
this.delete(id)
})
}
private set(key: number, value: Gtk.Widget) {
// in case of replacecment destroy previous widget
this.map.get(key)?.destroy()
this.map.set(key, value)
this.notifiy()
}
private delete(key: number) {
this.map.get(key)?.destroy()
this.map.delete(key)
this.notifiy()
}
// needed by the Subscribable interface
get() {
return this.var.get()
}
// needed by the Subscribable interface
subscribe(callback: (list: Array<Gtk.Widget>) => void) {
return this.var.subscribe(callback)
}
}
export default function NotificationPopups(gdkmonitor: Gdk.Monitor) {
const { TOP, RIGHT } = Astal.WindowAnchor
const notifs = new NotifiationMap()
return <window
className="NotificationPopups"
gdkmonitor={gdkmonitor}
exclusivity={Astal.Exclusivity.EXCLUSIVE}
anchor={TOP | RIGHT}>
<box vertical>
{bind(notifs)}
</box>
</window>
}

View File

@ -1,136 +0,0 @@
window.bar {
background-color: rgba(0, 0, 0, 0.2);
font-family: "Noto Sans", "FontAwesome";
}
.systray-item {
margin-left: 0.3em;
margin-right: 0.3em;
}
.window-box {
margin-bottom: 0.3em;
margin-top: 0.2em;
}
.clients box {
margin-right: 0.3em;
}
.battery-item {
padding-left: 0.6em;
padding-right: 0.6em;
border-radius: 0.3em;
background: #1f2430;
}
.battery-item:hover {
background: #023269;
}
.item, .clients box {
background: #1f2430;
padding-left: 0.7em;
padding-right: 0.7em;
border-radius: 0.3em;
}
.app-icon {
margin-right: 0.6em;
}
.icon-group {
padding-left: 0.3em;
padding-right: 0.3em;
}
button {
background: #1f2430;
border:none;
padding: 0.2em;
border-radius: 0.3em;
}
.focused, .clients box.focused {
background: #023269;
}
button:hover {
background: #023269;
}
button.blue:hover {
background: #1f2430;
}
.workspaces button {
padding-left: 0.4em;
padding-right: 0.4em;
margin-left: 0.2em;
margin-right: 0.2em;
}
.notification {
color: yellow;
}
.blue {
background: #023269;
}
/* Notifications */
window.notification-popups box.notifications {
padding: .5em;
}
.icon {
min-width: 68px;
min-height: 68px;
margin-right: 1em;
}
.icon image {
font-size: 58px;
/* to center the icon */
margin: 5px;
color: @theme_fg_color;
}
.icon box {
min-width: 68px;
min-height: 68px;
border-radius: 7px;
}
.notification {
min-width: 350px;
border-radius: 11px;
padding: 1em;
margin: .5em;
background-color: #1f2430;
}
.notification.critical {
border: 1px solid lightcoral;
}
.title {
color: @theme_fg_color;
font-size: 1.4em;
}
.body {
color: @theme_unfocused_fg_color;
}
.actions .action-button {
margin: 0 .4em;
margin-top: .8em;
}
.actions .action-button:first-child {
margin-left: 0;
}
.actions .action-button:last-child {
margin-right: 0;
}

79
home/ags/files/style.scss Normal file
View File

@ -0,0 +1,79 @@
@use "./notifications/Notification.scss";
$theme_fg_color: "@theme_fg_color";
$theme_bg_color: "@theme_bg_color";
window.Bar {
background-color: rgba(0, 0, 0, 0.2);
font-family: "Noto Sans", "FontAwesome";
font-weight: 500;
.systray-item {
margin-left: 0.3em;
margin-right: 0.3em;
}
.window-box {
margin-bottom: 0.3em;
margin-top: 0.2em;
}
.clients box {
margin-right: 0.3em;
}
.battery-item {
padding-left: 0.6em;
padding-right: 0.6em;
border-radius: 0.3em;
background: #1f2430;
}
.battery-item:hover {
background: #023269;
}
.item, .clients box {
background: #1f2430;
padding-left: 0.7em;
padding-right: 0.7em;
border-radius: 0.3em;
}
.app-icon {
margin-right: 0.6em;
}
.icon-group {
padding-left: 0.3em;
padding-right: 0.3em;
}
button {
background: #1f2430;
border:none;
padding: 0.2em;
border-radius: 0.3em;
}
.focused, .clients box.focused {
background: #023269;
}
button:hover {
background: #023269;
}
button.blue:hover {
background: #1f2430;
}
.workspaces button {
padding-left: 0.4em;
padding-right: 0.4em;
margin-left: 0.2em;
margin-right: 0.2em;
}
.blue {
background: #023269;
}
}

View File

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

View File

@ -1,77 +0,0 @@
import { Applications } from "resource:///com/github/Aylur/ags/service/applications.js";
import GLib from "gi://GLib?version=2.0";
const app_icons = new Applications().list.reduce(
(acc, app) => {
if (app.icon_name) {
acc.classOrNames[app.wm_class ?? app.name] = app.icon_name;
acc.executables[app.executable] = app.icon_name;
}
return acc;
},
{ classOrNames: {}, executables: {} },
);
function fileExists(path) {
return GLib.file_test(path, GLib.FileTest.EXISTS);
}
export function getIconName(client) {
if (!client) {
return "";
}
let icon = app_icons.classOrNames[client.class];
if (!icon) {
// TODO cache?
const filePath = `${App.configDir}/assets/${client.class}.png`;
if (fileExists(filePath)) {
icon = filePath;
app_icons.classOrNames[client.class] = icon;
}
}
if (!icon) {
// TODO cache?
const filePath = `${App.configDir}/assets/${client.class}.svg`;
if (fileExists(filePath)) {
icon = filePath;
app_icons.classOrNames[client.class] = icon;
}
}
if (!icon) {
const binaryName = Utils.exec(`ps -p ${client.pid} -o comm=`);
icon = app_icons.executables[binaryName];
if (!icon) {
let key = Object.keys(app_icons.executables).find((key) => key.startsWith(binaryName));
if (key) {
icon = app_icons.executables[key];
}
}
if (icon) {
app_icons[client.class] = icon;
}
}
if (!icon) {
const icon_key = Object.keys(app_icons.classOrNames).find(
(key) =>
key.includes(client.title) ||
key.includes(client.initialTitle) ||
key.includes(client.initialClass) ||
key.includes(client.class),
);
if (icon_key) {
icon = app_icons.classOrNames[icon_key];
app_icons.classOrNames[client.class] = icon;
}
}
if (!icon) {
app_icons.classOrNames[client.class] = "";
}
return icon;
}

40
home/ags/files/utils.ts Normal file
View File

@ -0,0 +1,40 @@
import Apps from "gi://AstalApps"
import AstalHyprland from "gi://AstalHyprland";
const app_icons = new Apps.Apps().list.reduce(
(acc, app) => {
if (app.icon_name) {
acc.classOrNames[app.wm_class ?? app.name] = app.icon_name;
acc.executables[app.executable] = app.icon_name;
}
return acc;
},
{ classOrNames: {}, executables: {} },
);
export function getIconName(client: AstalHyprland.Client) {
if (!client) {
return "";
}
let icon = app_icons.classOrNames[client.class];
if (!icon) {
const icon_key = Object.keys(app_icons.classOrNames).find(
(key) =>
key.includes(client.title) ||
key.includes(client.initialTitle) ||
key.includes(client.initialClass) ||
key.includes(client.class),
);
if (icon_key) {
icon = app_icons.classOrNames[icon_key];
app_icons.classOrNames[client.class] = icon;
}
}
if (!icon) {
app_icons.classOrNames[client.class] = "";
}
return icon;
}

70
home/ags/flake.lock Normal file
View File

@ -0,0 +1,70 @@
{
"nodes": {
"ags": {
"inputs": {
"astal": "astal",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1732307740,
"narHash": "sha256-ZDsYdZOtg5qkK/wfLLB83B3SI+fE32S+/6Ey0ggHODM=",
"owner": "aylur",
"repo": "ags",
"rev": "81159966eb8b39b66c3efc133982fd76920c9605",
"type": "github"
},
"original": {
"owner": "aylur",
"repo": "ags",
"type": "github"
}
},
"astal": {
"inputs": {
"nixpkgs": [
"ags",
"nixpkgs"
]
},
"locked": {
"lastModified": 1731952585,
"narHash": "sha256-Sh1E7sJd8JJM3PCU1ZOei/QWz97OLCENIi2rTRoaniw=",
"owner": "aylur",
"repo": "astal",
"rev": "664c7a4ddfcf48c6e8accd3c33bb94424b0e8609",
"type": "github"
},
"original": {
"owner": "aylur",
"repo": "astal",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1732014248,
"narHash": "sha256-y/MEyuJ5oBWrWAic/14LaIr/u5E0wRVzyYsouYY3W6w=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "23e89b7da85c3640bbc2173fe04f4bd114342367",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"ags": "ags",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

55
home/ags/flake.nix Normal file
View File

@ -0,0 +1,55 @@
{
description = "AGS Config";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
ags = {
url = "github:aylur/ags";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = {
nixpkgs,
ags,
}: let
system = "x86_64-linux";
pkgs = nixpkgs.legacyPackages.${system};
extraPackages = with ags.packages.${pkgs.system}; [
pkgs.gtksourceview
pkgs.webkitgtk
pkgs.accountsservice
battery
hyprland
tray
powerprofiles
wireplumber
mpris
network
apps
notifd
];
in {
packages.${system} = {
default = ags.lib.bundle {
inherit pkgs;
src = ./files;
name = "ags-bar";
entry = "app.ts";
extraPackages = extraPackages;
};
};
devShells.${system} = {
default = pkgs.mkShell {
buildInputs = [
# ags.packages.${system}.agsFull
(ags.packages.${system}.default.override {
extraPackages = extraPackages;
})
];
};
};
};
}