Compare commits

..
10 Commits
Author SHA1 Message Date
mxandClaude Opus 5.5 c716a20e04 Use Lua dispatches and options for Hyprland 0.57
Hyprland 0.57 removed hyprctl keyword and name-style dispatches, and
hyprglass 1.1 dropped its layer namespace options. Move workspace, window,
logout, glass and Game Mode calls to hl.dsp and hyprctl eval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:39:45 +01:00
mxandClaude Opus 5.5 bfbfc8961e Add a manual Game Mode Control Center tile
Turns off animations, blur, shadows and HyprGlass, switches to the
performance power profile and turns on Do Not Disturb, each optional in
Settings > Power. The helper journals the values it changes per Hyprland
session and restores them exactly, also after a shell crash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:13:48 +02:00
mxandClaude Opus 5.5 9e1ac4efe7 Add Clipboard and Emoji pills beside the launcher bar
Round glass pills to the right of the search bar switch the launcher to
Clipboard History or the Emoji picker and back, naming themselves in the
empty bar on hover. The launcher runtime test now runs without a second
notification server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:13:48 +02:00
mxandClaude Opus 5.5 7f1189606c Place Control Center tiles freely and host plugin widgets as tiles
Tiles keep the cell they are dropped in, so gaps stay where they are
left; moving or resizing onto other tiles pushes those straight down.
Enabled plugins with a Noctalia controlCenterWidget entry point are
offered as tiles in edit mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:02:18 +02:00
mxandClaude Opus 5.5 72a21c9363 List app playback streams for per-app volume and drop device lists
Quickshell marks playback streams as sinks, so the mixer showed
recording streams instead of players. Right-clicking Sound now shows
only the app sliders; Microphone no longer extends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 21:40:57 +02:00
mxandClaude Opus 5.5 11bdc4c751 Lay the Control Center out as a resizable, editable grid
Modules are tiles on a 4-column grid, each 1x1 to 4x4 and adapting its
layout to its size. Edit Controls in the panel reorders by dragging,
resizes from a corner handle, removes with a badge and adds from a tray.
Connectivity splits into Wi-Fi, Bluetooth and Network tiles and Audio
into Sound and Microphone; right-clicking Sound extends it with output
devices and a volume slider per app. Adds a Caffeine tile. Config
version 2 migrates existing layouts in place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:52:14 +02:00
mxandClaude Opus 5.5 0dcf37346c Add a Caffeine inhibitor, app stream volumes and vertical bar sliders
CaffeineService holds a systemd-inhibit idle/sleep lock while active.
AudioService lists app playback streams and tracks their volume only
while a view holds a Demand on it. GlassBarSlider fills from the bottom
when vertical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:52:14 +02:00
mxandClaude Opus 5.5 d6a6cf69f4 Style in-window tooltips as glass instead of the stock Basic look
Dock items, the launcher mode button and the settings hints used the attached
ToolTip, which only gets the Basic style. GlassToolTip wraps ToolTip with a
GlassPanel background, theme text and a Theme.duration fade, matching the
bar's tooltip popout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:50:24 +02:00
mxandClaude Opus 5.5 b3076a4cde Add an Emoji Picker as a launcher mode with a searchable grid
The launcher gains an emoji mode like Clipboard History: >emoji switches in
place without closing or animating, and glassmxrph emoji toggles it. Emoji
show as a grid instead of named rows; the selected or hovered emoji's name is
the section label. Search requires every term and ranks name matches before
keyword matches; Enter copies with wl-copy.

assets/emoji.tsv comes from Unicode 17 emoji-test.txt without skin-tone
variants, with keywords from the rofi emopicker list (scripts/emoji-data).
The test driver caps snapshot results, since IPC replies have a size limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:47:14 +02:00
mxandClaude Opus 5.5 29dd64572a Open the Control Center from the bar clock
Drop the dashboard's now-unused Open from clock toggle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:10:51 +02:00
68 changed files with 5190 additions and 449 deletions

No files matched your search

+17 -3
View File
@@ -161,6 +161,8 @@ Schema 3 preserves existing pins/settings and adds dock defaults.
Run `./scripts/glassmxrph launcher` to toggle the running shell's launcher.
Search applications, use Up/Down and Enter, or type `>` for Settings commands such
as `>dock`, `>appearance`, `>wallpaper` and `>media`. Escape/outside click closes.
The two round pills beside the search bar switch to Clipboard History and the Emoji
picker (click again to go back); `>clipboard` and `>emoji` do the same.
Other future destinations remain explicitly labelled until their phases are implemented. All destinations are also in Settings' page selector.
Recent-file indexing is deferred.
@@ -175,9 +177,21 @@ without replacing your saved layout. Cava is optional and off by default.
## Control Center
Click the right-hand system pill or run `./scripts/glassmxrph controlcenter`.
Control Center opens at the active monitor's upper-right, with configurable modules
for connectivity, audio/microphone, brightness, Night Light, DND, power profiles,
shared media and power actions. Settings → Control Center enables/reorders modules.
Control Center opens at the active monitor's upper-right. Its modules sit on a
4-column grid: Wi-Fi, Bluetooth, network throughput, sound, microphone, display
brightness, Night Light, DND, Caffeine (keeps the system awake via `systemd-inhibit`),
power profile, Now Playing, power actions and system metrics, with Notifications
below. Each tile can be any size from 1×1 to 4×4 and adapts its layout to it.
Tiles sit wherever you put them, gaps included. **Edit Controls** at the bottom
of the panel lets you drag tiles to any cell, resize them from the corner handle
(tiles in the way are pushed down), remove them with the badge and add others.
Plugins with a Noctalia `controlCenterWidget` entry point appear there as tiles too.
Right-click Sound to extend it with a volume slider per app (the players
EasyEffects processes); right-click a toggle to open its settings.
**Game Mode** (tile) turns off animations, blur, shadows and HyprGlass, switches to
the performance power profile and turns on Do Not Disturb until you switch it off;
Settings → Power chooses which. Changed values are journalled and restored exactly,
also after a shell crash. `glassmxrph`'s IPC target `gamemode` toggles it.
Logout, reboot and shutdown require explicit confirmation.
NetworkManager, BlueZ and PipeWire use native Quickshell models. Other controls reuse
+21
View File
@@ -114,6 +114,18 @@ failures do not cause restart loops. Song artwork never changes the global accen
## Phase 7 system controls
`ControlCenter` is an active-monitor overlay with a registry-driven module layout.
Modules are `CCModule` tiles placed freely on a 4-column grid
(`controlcenter/GridLogic.js`): each entry in `controlCenter.modules` may store its
cell (`x` 0–3, `y`) and size (`w`/`h` 1–4, else the `ControlRegistry` default).
Tiles without a cell take the first free spot; moving or resizing one in the
panel's edit mode pushes overlapped tiles straight down and saves every cell, so
gaps persist. Enabled plugins with a Noctalia `controlCenterWidget` entry point
add `plugin:<id>` tiles hosted by `modules/Plugin.qml`. Tiles adapt their layout to their size. A tile can extend below
its cells (`extraHeight`: the Sound mixer, power confirmation) and the grid moves
the tiles underneath down. Config version 2 split the old Connectivity and Audio
cards into Wi-Fi/Bluetooth/Network and Output/Input. `CaffeineService` holds a
`systemd-inhibit` idle/sleep lock while on; `AudioService.streams` lists app
playback streams, tracked only while a mixer holds a `Demand`.
`ShellState` coordinates its visibility with existing shell popups. `AudioService`,
`NetworkService` and `BluetoothService` adapt native Quickshell event-driven models.
`SystemService` serializes one-shot JSON provider jobs for visible display/DND/power
@@ -155,3 +167,12 @@ and snaps the height instead of animating it. `ClipboardService` reads the user'
history through `helpers/clipboard.py` only when the launcher opens, and keeps the last list cached.
The helper never stores entries (the user's `wl-paste --watch cliphist store` does), decodes
thumbnails for the newest images into the cache, and detaches `wl-copy` when copying.
## Emoji Picker
The Emoji Picker is another launcher mode: `>emoji` switches in place like `>clipboard`, and
`glassmxrph emoji` toggles it directly. Results show as a grid of glyphs with the selected (or
hovered) emoji's name as the section label. `EmojiService` reads `assets/emoji.tsv` the first time
the mode opens; search requires every term and lists name matches before keyword matches. Enter
copies with `wl-copy`. `scripts/emoji-data` regenerates the table from Unicode's `emoji-test.txt`
(skin-tone variants omitted) plus an optional keyword list. `tests/emoji_runtime.py` covers it.
File diff suppressed because it is too large. Load diff
+3 -4
View File
@@ -21,11 +21,10 @@ GlassPill {
color: Theme.text
font.pixelSize: 13
}
// Clicking the clock opens the dashboard (Settings → Dashboard).
// Clicking the clock toggles the Control Center.
MouseArea {
anchors.fill: parent
enabled: ConfigService.ready && ConfigService.data.dashboard.enabled && ConfigService.data.dashboard.openFromClock
cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
onClicked: ShellState.toggleDashboard("")
cursorShape: Qt.PointingHandCursor
onClicked: ShellState.toggleControlCenter()
}
}
+1 -1
View File
@@ -199,7 +199,7 @@ GlassPill {
anchors.fill: parent
hoverEnabled: root.pacman
cursorShape: Qt.PointingHandCursor
onClicked: Hyprland.dispatch("workspace " + (slot.index + 1))
onClicked: Hyprland.dispatch("hl.dsp.focus({ workspace = '" + (slot.index + 1) + "' })")
}
}
}
@@ -26,6 +26,6 @@ Singleton {
return s ? s.devicePixelRatio : 1;
}
function switchToWorkspace(workspace) {
Hyprland.dispatch("workspace " + (workspace && workspace.id !== undefined ? workspace.id : workspace));
Hyprland.dispatch("hl.dsp.focus({ workspace = '" + (workspace && workspace.id !== undefined ? workspace.id : workspace) + "' })");
}
}
+28 -17
View File
@@ -3,30 +3,40 @@ import QtQuick.Controls
import "../theme"
// Thick pill slider with an icon inside the track (macOS Control Center style).
// Vertical sliders fill from the bottom with the icon at the foot.
Slider {
id: root
property string glyph
property string fallback
implicitWidth: 220
implicitHeight: 28
implicitWidth: vertical ? 28 : 220
implicitHeight: vertical ? 220 : 28
padding: 0
background: Rectangle {
x: root.leftPadding
y: root.topPadding + root.availableHeight / 2 - height / 2
y: root.topPadding + (root.vertical ? 0 : root.availableHeight / 2 - height / 2)
width: root.availableWidth
height: root.availableHeight
radius: height / 2
radius: Math.min(width, height) / 2
color: Theme.surfaceVariant
border.width: root.activeFocus ? 1 : 0
border.color: Theme.accent
Rectangle {
readonly property real knob: parent.height
width: Math.max(knob, knob + root.visualPosition * (parent.width - knob))
height: parent.height
radius: height / 2
readonly property real knob: root.vertical ? parent.width : parent.height
readonly property real length: Math.max(knob, knob + root.position * ((root.vertical ? parent.height : parent.width) - knob))
y: root.vertical ? parent.height - height : 0
width: root.vertical ? parent.width : length
height: root.vertical ? length : parent.height
radius: knob / 2
color: root.enabled ? Qt.alpha(Theme.text, 0.92) : Qt.alpha(Theme.text, 0.35)
Behavior on width {
enabled: !root.pressed
enabled: !root.pressed && !root.vertical
NumberAnimation {
duration: Theme.duration / 2
easing.type: Easing.OutCubic
}
}
Behavior on height {
enabled: !root.pressed && root.vertical
NumberAnimation {
duration: Theme.duration / 2
easing.type: Easing.OutCubic
@@ -34,20 +44,21 @@ Slider {
}
}
Text {
anchors.left: parent.left
anchors.leftMargin: (parent.height - width) / 2
anchors.verticalCenter: parent.verticalCenter
readonly property real knob: root.vertical ? parent.width : parent.height
x: root.vertical ? (parent.width - width) / 2 : (knob - width) / 2
y: root.vertical ? parent.height - knob / 2 - height / 2 : (parent.height - height) / 2
text: Icons.available && root.glyph ? root.glyph : root.fallback
font.family: Icons.available && root.glyph ? Icons.family : ""
font.pixelSize: Math.round(parent.height * 0.5)
font.pixelSize: Math.round(knob * 0.5)
color: Theme.surface
}
}
handle: Rectangle {
x: root.leftPadding + root.visualPosition * (root.availableWidth - width)
y: root.topPadding + root.availableHeight / 2 - height / 2
width: root.availableHeight
height: root.availableHeight
readonly property real knob: root.vertical ? root.availableWidth : root.availableHeight
x: root.leftPadding + (root.vertical ? 0 : root.visualPosition * (root.availableWidth - width))
y: root.topPadding + (root.vertical ? root.visualPosition * (root.availableHeight - height) : root.availableHeight / 2 - height / 2)
width: knob
height: knob
radius: width / 2
color: root.enabled ? Theme.text : Qt.alpha(Theme.text, 0.5)
border.width: 1
+41
View File
@@ -0,0 +1,41 @@
import QtQuick
import QtQuick.Controls
import "../theme"
// In-window hover hint styled like the bar's tooltip popout. Declare it as a
// child of the hovered item instead of using the attached ToolTip, which only
// gets the stock Basic style.
ToolTip {
id: root
padding: 7
leftPadding: 12
rightPadding: 12
y: -implicitHeight - 6
font.pixelSize: 12
contentItem: Text {
text: root.text
font: root.font
color: Theme.text
wrapMode: Text.Wrap
}
background: GlassPanel {
surfaceOpacity: Theme.panelOpacity
radius: Math.min(Theme.radius, height / 2)
}
enter: Transition {
NumberAnimation {
property: "opacity"
from: 0
to: 1
duration: Theme.duration / 2
}
}
exit: Transition {
NumberAnimation {
property: "opacity"
from: 1
to: 0
duration: Theme.duration / 2
}
}
}
+51 -22
View File
@@ -150,47 +150,76 @@
"history": []
},
"controlCenter": {
"version": 1,
"version": 2,
"width": 400,
"modules": [
{
"id": "connectivity",
"enabled": true
},
{
"id": "audio",
"enabled": true
},
{
"id": "brightness",
"enabled": true
},
{
"id": "nightLight",
"enabled": true
},
{
"id": "dnd",
"enabled": true
},
{
"id": "profiles",
"id": "wifi",
"enabled": true
},
{
"id": "media",
"enabled": true
},
{
"id": "bluetooth",
"enabled": true
},
{
"id": "dnd",
"enabled": true
},
{
"id": "nightLight",
"enabled": true
},
{
"id": "caffeine",
"enabled": true
},
{
"id": "profiles",
"enabled": true
},
{
"id": "gameMode",
"enabled": true
},
{
"id": "output",
"enabled": true
},
{
"id": "input",
"enabled": true
},
{
"id": "brightness",
"enabled": true
},
{
"id": "power",
"enabled": true
},
{
"id": "network",
"enabled": false
},
{
"id": "metrics",
"enabled": false
},
{
"id": "notifications",
"enabled": true
}
]
},
"gameMode": {
"effects": true,
"doNotDisturb": true,
"performance": true
},
"launcher": {
"recentFiles": false,
"width": 680,
+109
View File
@@ -0,0 +1,109 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import Quickshell.Widgets
import "../components"
import "../services"
import "../theme"
// Extension of the Sound tile: a volume slider per app playback stream (the
// players EasyEffects processes). The app icon mutes it.
ColumnLayout {
id: root
spacing: 2
Demand {
service: AudioService
counter: "streamConsumers"
}
Text {
visible: AudioService.streams.length === 0
text: "No apps are playing audio"
color: Theme.textSecondary
font.pixelSize: 11
Layout.leftMargin: 6
Layout.topMargin: 2
}
Repeater {
model: AudioService.streams
RowLayout {
id: stream
required property var modelData
readonly property bool muted: !!modelData.audio && modelData.audio.muted
readonly property string icon: AudioService.streamIcon(modelData)
objectName: "appVolume-" + AudioService.streamName(modelData)
Layout.fillWidth: true
Layout.preferredHeight: 30
spacing: 8
// The app icon doubles as its mute button.
Item {
implicitWidth: 22
implicitHeight: 22
opacity: stream.muted ? 0.4 : 1
Accessible.role: Accessible.Button
Accessible.name: (stream.muted ? "Unmute " : "Mute ") + AudioService.streamName(stream.modelData)
IconImage {
anchors.fill: parent
visible: stream.icon !== ""
source: stream.icon
asynchronous: true
}
GlassIcon {
anchors.fill: parent
visible: stream.icon === ""
size: 22
glyphSize: 11
fallback: AudioService.streamName(stream.modelData).charAt(0).toUpperCase()
}
Text {
visible: stream.muted
anchors.right: parent.right
anchors.bottom: parent.bottom
anchors.margins: -3
text: Icons.available ? "󰖁" : "×"
font.family: Icons.available ? Icons.family : ""
font.pixelSize: 11
color: Theme.text
}
MouseArea {
objectName: "appMute-" + AudioService.streamName(stream.modelData)
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: AudioService.streamMute(stream.modelData)
}
}
ColumnLayout {
Layout.fillWidth: true
spacing: 2
Text {
text: AudioService.streamName(stream.modelData)
color: Theme.text
font.pixelSize: 11
elide: Text.ElideRight
Layout.fillWidth: true
}
GlassBarSlider {
id: level
objectName: "appSlider-" + AudioService.streamName(stream.modelData)
Layout.fillWidth: true
Layout.preferredHeight: 10
from: 0
to: 1
stepSize: 0.01
enabled: !!stream.modelData.audio
value: stream.modelData.audio ? stream.modelData.audio.volume : 0
onMoved: AudioService.streamVolume(stream.modelData, value)
onPressedChanged: if (!pressed)
value = Qt.binding(() => stream.modelData.audio ? stream.modelData.audio.volume : 0)
Accessible.name: AudioService.streamName(stream.modelData) + " volume"
}
}
Text {
text: stream.modelData.audio ? Math.round(stream.modelData.audio.volume * 100) + "%" : "—"
color: Theme.textSecondary
font.pixelSize: 11
horizontalAlignment: Text.AlignRight
Layout.preferredWidth: 32
}
}
}
}
+52
View File
@@ -0,0 +1,52 @@
pragma ComponentBehavior: Bound
import QtQuick
import "../theme"
// Control Center grid tile. Modules fill their cells and adapt to `cols` ×
// `rows` (1–4 each). A module can extend below its cells (`extraHeight`, e.g.
// per-app volume); the grid moves the tiles underneath down to make room.
// Outside the grid (Settings pages) it is a 4×1 tile that grows the same way.
Item {
id: root
default property alias content: body.data
// Config id of this tile; the grid sets it (plugin tiles need it).
property string moduleId
property int cols: 4
property int rows: 1
// Height of the cells, without the extension; the grid sets it.
property real baseHeight: rows * 68 + (rows - 1) * 10
// Height wanted below the cells while extended; 0 when not.
property real extraHeight: 0
property bool expanded: false
// 1×1 toggles draw as a circle centred in their cell.
property bool round: false
property bool hovered: false
property color color: hovered ? Theme.hover : Theme.fill
readonly property bool compact: cols === 1 && rows === 1
readonly property bool wide: cols >= 2
readonly property bool tall: rows >= 2
readonly property bool circle: round && compact && extraHeight <= 0
readonly property alias background: bg
implicitWidth: 360
implicitHeight: baseHeight + (extraHeight > 0 ? extraHeight + 10 : 0)
Rectangle {
id: bg
readonly property real d: Math.min(root.width, root.baseHeight)
x: root.circle ? (root.width - d) / 2 : 0
width: root.circle ? d : root.width
height: root.circle ? d : root.height
radius: root.circle ? d / 2 : Math.min(30, root.baseHeight / 2, root.width / 2)
color: root.color
border.width: 1
border.color: Theme.hairline
Behavior on color {
ColorAnimation {
duration: Theme.duration / 2
}
}
}
Item {
id: body
anchors.fill: parent
}
}
+217
View File
@@ -0,0 +1,217 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "../components"
import "../theme"
// Level tile (volume, microphone, brightness). One row is a title over a
// slider; 1 wide and taller is a vertical slider; 1×1 is a round button that
// shows the level, toggles mute and scrolls to adjust. An `extension` (e.g.
// the per-app mixer) fills spare rows of wide tall tiles, and right click
// extends the tile down to show it at other sizes.
CCModule {
id: root
property string title
property string glyph
property string fallback
property string mutedGlyph: glyph
property real value: 0
property real from: 0
property real to: 1
property real stepSize: 0.01
property bool muted: false
property bool muteable: false
property string sliderName
property string muteName
property string notice
property Component extension: null
readonly property alias slider: horizontal
readonly property bool inline: !!extension && wide && tall
// Whether `value` is real; it can be while the slider is briefly disabled.
property bool known: enabled
readonly property string percent: known ? Math.round((value - from) / Math.max(1e-9, to - from) * 100) + "%" : "—"
// Live changes while dragging, and the final value on release.
signal moved(real value)
signal committed(real value)
signal muteClicked
round: true
hovered: area.containsMouse
extraHeight: expanded && outer.item ? outer.implicitHeight + 24 : 0
function nudge(steps) {
const next = Math.max(from, Math.min(to, value + steps * (to - from) / 20));
moved(next);
committed(next);
}
component Level: GlassBarSlider {
from: root.from
to: root.to
stepSize: root.stepSize
value: root.value
enabled: root.enabled
// The mute button carries the icon when there is one.
glyph: root.muteable ? "" : root.glyph
fallback: root.muteable ? "" : root.fallback
onMoved: root.moved(value)
// Dragging writes `value`; follow the source again once released.
onPressedChanged: if (!pressed) {
root.committed(value);
value = Qt.binding(() => root.value);
}
Keys.onReleased: event => {
if (event.key === Qt.Key_Left || event.key === Qt.Key_Right || event.key === Qt.Key_Up || event.key === Qt.Key_Down)
root.committed(value);
}
Accessible.name: root.title
}
component Mute: CCToggle {
visible: root.muteable
size: 26
glyph: root.muted ? root.mutedGlyph : root.glyph
fallback: root.muted ? "×" : root.fallback
checked: root.muted
enabled: root.enabled
onClicked: root.muteClicked()
Accessible.name: "Mute " + root.title
}
MouseArea {
id: area
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: mouse => {
if (mouse.button === Qt.RightButton && root.extension && !root.inline)
root.expanded = !root.expanded;
else if (mouse.button === Qt.LeftButton && root.compact && root.muteable)
root.muteClicked();
}
onWheel: wheel => {
if (root.enabled)
root.nudge(wheel.angleDelta.y > 0 ? 1 : wheel.angleDelta.y < 0 ? -1 : 0);
}
}
GlassToolTip {
visible: root.compact && area.containsMouse
delay: 500
text: root.title + " · " + root.percent
}
// 1×1: icon and level in a circle.
Column {
visible: root.compact
x: (root.width - width) / 2
y: (root.baseHeight - height) / 2
spacing: 1
Text {
anchors.horizontalCenter: parent.horizontalCenter
text: Icons.available && root.glyph ? (root.muted ? root.mutedGlyph : root.glyph) : root.fallback
font.family: Icons.available && root.glyph ? Icons.family : ""
font.pixelSize: Math.round(root.background.width * 0.3)
color: root.muted ? Theme.textSecondary : Theme.text
}
Text {
anchors.horizontalCenter: parent.horizontalCenter
text: root.percent
color: Theme.textSecondary
font.pixelSize: 10
font.weight: Font.DemiBold
}
}
// One column: a vertical slider with mute above it.
ColumnLayout {
visible: !root.wide && root.tall
anchors.fill: parent
anchors.topMargin: 12
anchors.bottomMargin: 12 + root.height - root.baseHeight
spacing: 8
Mute {
Layout.alignment: Qt.AlignHCenter
}
Text {
visible: !root.muteable
text: root.percent
color: Theme.textSecondary
font.pixelSize: 10
font.weight: Font.DemiBold
Layout.alignment: Qt.AlignHCenter
}
Level {
orientation: Qt.Vertical
Layout.alignment: Qt.AlignHCenter
Layout.fillHeight: true
Layout.preferredWidth: Math.min(40, root.width - 34)
}
}
// Wide: title and level over the slider, then the extension in spare rows.
ColumnLayout {
id: wideLayout
visible: root.wide
x: 14
y: root.tall ? 12 : (root.baseHeight - implicitHeight) / 2
width: root.width - 28
spacing: 6
RowLayout {
Layout.fillWidth: true
Text {
text: root.title
color: Theme.text
font.pixelSize: 13
font.weight: Font.DemiBold
elide: Text.ElideRight
Layout.fillWidth: true
}
Text {
text: root.notice || root.percent
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
Layout.maximumWidth: root.width * 0.6
}
}
RowLayout {
Layout.fillWidth: true
spacing: 8
Mute {
objectName: root.muteName
}
Level {
id: horizontal
objectName: root.sliderName
Layout.fillWidth: true
Layout.preferredHeight: root.tall ? 30 : 26
}
}
}
Flickable {
visible: root.inline
x: 14
y: wideLayout.y + wideLayout.height + 10
width: root.width - 28
height: root.baseHeight - y - 10
clip: true
contentHeight: inner.implicitHeight
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar {
policy: ScrollBar.AsNeeded
}
Loader {
id: inner
width: parent.width
active: root.inline
sourceComponent: root.extension
}
}
// Extended below the cells.
Loader {
id: outer
x: 14
y: root.baseHeight + 6
width: root.width - 28
active: root.expanded && !root.inline
sourceComponent: root.extension
}
}
+117 -27
View File
@@ -1,60 +1,150 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import "../components"
import "../core"
import "../theme"
// Small Control Center tile: round toggle, title and state; the whole tile toggles.
ControlCard {
// Toggle tile: icon, title and state. 1×1 is a round toggle, one row is a pill
// with labels beside the icon, taller tiles stack them. Left click toggles;
// right click opens the matching Settings page.
CCModule {
id: root
property string title
property string glyph
property string fallback
property string detail
property string page
property bool checked: false
// 1×1 shows the icon; modules with their own compact face turn it off.
property bool compactGlyph: true
signal clicked
padding: 10
heading: false
signal secondaryClicked
round: true
hovered: area.containsMouse && enabled
opacity: enabled ? 1 : 0.55
color: area.containsMouse && enabled ? Theme.hover : Theme.fill
color: compact && checked ? Theme.accent : hovered ? Theme.hover : Theme.fill
Accessible.role: Accessible.CheckBox
Accessible.name: title
Accessible.checked: checked
onSecondaryClicked: if (page)
ShellState.openSettings(page)
component Labels: ColumnLayout {
property int align: Text.AlignLeft
property int lines: 1
spacing: 1
Text {
text: root.title
color: Theme.text
font.pixelSize: root.wide && root.tall ? 14 : 12
font.weight: Font.DemiBold
elide: Text.ElideRight
horizontalAlignment: parent.align
Layout.fillWidth: true
}
Text {
text: root.detail
visible: text !== ""
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
wrapMode: parent.lines > 1 ? Text.Wrap : Text.NoWrap
maximumLineCount: parent.lines
horizontalAlignment: parent.align
Layout.fillWidth: true
}
}
MouseArea {
id: area
parent: root
z: -1
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton
cursorShape: Qt.PointingHandCursor
onClicked: root.clicked()
onClicked: mouse => mouse.button === Qt.RightButton ? root.secondaryClicked() : root.clicked()
}
GlassToolTip {
visible: root.compact && area.containsMouse
delay: 500
text: root.title + (root.detail ? " · " + root.detail : "")
}
// 1×1: the circle itself is the toggle.
Text {
visible: root.compact && root.compactGlyph
x: root.background.x + (root.background.width - width) / 2
y: root.background.y + (root.background.height - height) / 2
text: Icons.available && root.glyph ? root.glyph : root.fallback
font.family: Icons.available && root.glyph ? Icons.family : ""
font.pixelSize: Math.round(root.background.width * 0.34)
font.weight: Font.DemiBold
color: root.checked ? Theme.accentText : Theme.text
scale: area.pressed ? 0.92 : 1
Behavior on scale {
NumberAnimation {
duration: Theme.duration / 2
}
}
}
// One row: icon beside the labels.
RowLayout {
Layout.fillWidth: true
visible: root.wide && !root.tall
anchors.fill: parent
anchors.leftMargin: (root.baseHeight - toggleRow.size) / 2
anchors.rightMargin: 14
spacing: 10
CCToggle {
id: toggleRow
size: Math.min(38, root.baseHeight - 20)
glyph: root.glyph
fallback: root.fallback
checked: root.checked
enabled: root.enabled
onClicked: root.clicked()
}
ColumnLayout {
Labels {
Layout.fillWidth: true
spacing: 0
Text {
text: root.title
color: Theme.text
font.pixelSize: 12
font.weight: Font.DemiBold
elide: Text.ElideRight
Layout.fillWidth: true
}
Text {
text: root.detail
visible: text !== ""
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
Layout.fillWidth: true
}
}
}
// One column: icon above centred labels.
ColumnLayout {
visible: !root.wide && root.tall
anchors.centerIn: parent
width: parent.width - 16
spacing: 8
CCToggle {
size: Math.min(44, root.width - 24)
Layout.alignment: Qt.AlignHCenter
glyph: root.glyph
fallback: root.fallback
checked: root.checked
enabled: root.enabled
onClicked: root.clicked()
}
Labels {
align: Text.AlignHCenter
lines: Math.max(1, root.rows - 1)
Layout.fillWidth: true
}
}
// Large: icon top left, labels along the bottom.
CCToggle {
visible: root.wide && root.tall
x: 14
y: 14
size: 44
glyph: root.glyph
fallback: root.fallback
checked: root.checked
enabled: root.enabled
onClicked: root.clicked()
}
Labels {
visible: root.wide && root.tall
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
anchors.margins: 14
lines: root.rows - 1
}
}
+532 -87
View File
@@ -9,6 +9,7 @@ import "../components"
import "../services"
import "../core"
import "../theme"
import "GridLogic.js" as Grid
// macOS-style Control Center. The layer surface is sized to the panel so
// compositor glass (HyprGlass) shapes its edges to the panel, not the screen.
@@ -45,44 +46,111 @@ PanelWindow {
Component.onCompleted: ShellState.controlCenterWindow = root
Component.onDestruction: ShellState.controlCenterWindow = null
// Connectivity and the small tiles share one block (connectivity left, tiles
// stacked right), placed where the first of them appears; other modules
// span the full width in their configured order.
readonly property var smallTiles: ["dnd", "nightLight", "profiles"]
readonly property var blocks: {
if (!ConfigService.ready)
return [];
const ids = ConfigService.data.controlCenter.modules.filter(m => m.enabled && !!ControlRegistry.entry(m.id)).map(m => m.id);
const grouped = ids.filter(id => id === "connectivity" || smallTiles.includes(id));
const result = [];
let placed = false;
for (const id of ids) {
if (!grouped.includes(id)) {
result.push({
kind: "full",
ids: [id]
// Modules sit freely on a 4-column grid at their saved cell, so gaps stay
// where they are left; tiles without a position take the first free spot.
// Notifications is a section under it. Edit mode moves tiles by dragging and
// resizes them from the corner handle (tiles in the way are pushed down),
// removes them with the badge and adds them from a tray.
readonly property int gap: 10
readonly property int cellHeight: 68
readonly property real gridWidth: panel.targetWidth - 28
readonly property real cellWidth: (gridWidth - 3 * gap) / Grid.COLS
readonly property var entries: ConfigService.ready ? ConfigService.data.controlCenter.modules : []
readonly property var tiles: entries.filter(m => m.enabled && !!ControlRegistry.entry(m.id) && !ControlRegistry.entry(m.id).section)
readonly property bool notifications: entries.some(m => m.id === "notifications" && m.enabled)
readonly property var addable: ControlRegistry.ids.filter(id => !entries.some(m => m.id === id && m.enabled))
property bool editing: false
// Live edit preview while a tile is dragged or resized.
property var preview: null
property string dragId: ""
property point dragPoint
property point grabOffset
property string resizeId: ""
// Tile id -> pixels a tile extends below its cells.
property var extras: ({})
readonly property var savedPlan: Grid.layout(tiles.map(m => {
const size = ControlRegistry.size(m);
return {
id: m.id,
w: size.w,
h: size.h,
x: m.x,
y: m.y
};
}))
readonly property var plan: preview || savedPlan
// Edit mode shows one empty row below the tiles to drop into.
readonly property int shownRows: plan.rows + (editing ? 1 : 0)
readonly property var geometry: Grid.geometry(plan, cellWidth, cellHeight, gap, editing ? {} : extras)
function setExtra(id, value) {
if ((extras[id] || 0) === value)
return;
const next = Object.assign({}, extras);
next[id] = value;
extras = next;
}
// Writes every tile's cell (and changed sizes) back, so nothing repacks
// and gaps stay.
function save(plan, patch) {
ConfigService.setValue("controlCenter.modules", entries.map(m => {
const i = plan.items.find(t => t.id === m.id);
let next = Object.assign({}, m);
if (i) {
const def = ControlRegistry.size({
id: m.id
});
} else if (!placed) {
placed = true;
const tiles = grouped.filter(g => g !== "connectivity");
if (!grouped.includes("connectivity"))
result.push({
kind: "grid",
ids: tiles
});
else if (tiles.length === 0)
result.push({
kind: "full",
ids: ["connectivity"]
});
else
result.push({
kind: "split",
ids: tiles
});
next.x = i.col;
next.y = i.row;
if (m.w !== undefined || m.h !== undefined || i.w !== def.w || i.h !== def.h) {
next.w = i.w;
next.h = i.h;
}
}
if (patch && patch[m.id])
next = patch[m.id](next);
return next;
}));
}
function setEnabled(id, on) {
if (!on) {
// The rest keep their cells; the removed tile forgets its own.
save(savedPlan, {
[id]: m => {
const next = Object.assign({}, m, {
enabled: false
});
delete next.x;
delete next.y;
return next;
}
});
return;
}
const e = ControlRegistry.entry(id);
const known = entries.find(m => m.id === id);
const size = ControlRegistry.size(known || {
id: id
});
const spot = e && !e.section ? Grid.freeSpot(savedPlan, size.w, size.h) : null;
const added = Object.assign({}, known || {
id: id
}, {
enabled: true
}, spot ? {
x: spot.col,
y: spot.row
} : {});
ConfigService.setValue("controlCenter.modules", known ? entries.map(m => m.id === id ? added : m) : entries.concat([added]));
}
function reset() {
ConfigService.setValue("controlCenter.modules", ConfigService.defaults.controlCenter.modules);
}
Connections {
target: ShellState
function onControlCenterOpenChanged() {
if (!ShellState.controlCenterOpen)
root.editing = false;
}
return result;
}
component ModuleSlot: Loader {
@@ -92,6 +160,62 @@ PanelWindow {
active: ShellState.controlCenterOpen
source: moduleId ? ControlRegistry.entry(moduleId).source : ""
}
component Badge: Rectangle {
id: badge
property string glyph
signal clicked
width: 22
height: 22
radius: 11
color: badgeArea.containsMouse ? Theme.accent : Theme.surface
border.width: 1
border.color: Qt.alpha(Theme.text, 0.35)
Accessible.role: Accessible.Button
Text {
anchors.centerIn: parent
text: badge.glyph
color: badgeArea.containsMouse ? Theme.accentText : Theme.text
font.pixelSize: 15
font.weight: Font.DemiBold
}
MouseArea {
id: badgeArea
anchors.fill: parent
anchors.margins: -3
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: badge.clicked()
}
}
component Pill: Rectangle {
id: pill
property string text
property bool strong: false
signal clicked
implicitWidth: pillLabel.implicitWidth + 28
implicitHeight: 30
radius: 15
color: strong ? (pillArea.containsMouse ? Theme.accentHover : Theme.accent) : pillArea.containsMouse ? Theme.hover : Theme.fill
border.width: strong ? 0 : 1
border.color: Theme.hairline
Accessible.role: Accessible.Button
Accessible.name: text
Text {
id: pillLabel
anchors.centerIn: parent
text: pill.text
color: pill.strong ? Theme.accentText : Theme.text
font.pixelSize: 12
font.weight: Font.Medium
}
MouseArea {
id: pillArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: pill.clicked()
}
}
component HeaderButton: Rectangle {
id: headerButton
property string glyph
@@ -152,6 +276,8 @@ PanelWindow {
Keys.onEscapePressed: {
if (PowerService.pending)
PowerService.cancel();
else if (root.editing)
root.editing = false;
else
ShellState.controlCenterOpen = false;
}
@@ -179,13 +305,14 @@ PanelWindow {
Layout.leftMargin: 4
spacing: 2
Text {
text: "Control Center"
text: root.editing ? "Edit Controls" : "Control Center"
color: Theme.text
font.pixelSize: 14
font.weight: Font.DemiBold
Layout.fillWidth: true
}
HeaderButton {
visible: root.editing
glyph: "󰒓"
fallback: "⚙"
onClicked: ShellState.openSettings("controlcenter")
@@ -198,61 +325,310 @@ PanelWindow {
Accessible.name: "Close Control Center"
}
}
Repeater {
model: root.blocks
Item {
id: block
required property var modelData
Layout.fillWidth: true
implicitHeight: block.modelData.kind === "full" ? full.implicitHeight : block.modelData.kind === "split" ? split.implicitHeight : grid.implicitHeight
ModuleSlot {
id: full
visible: block.modelData.kind === "full"
width: parent.width
moduleId: block.modelData.kind === "full" ? block.modelData.ids[0] : ""
active: visible && ShellState.controlCenterOpen
Item {
id: grid
objectName: "controlGrid"
Layout.fillWidth: true
implicitHeight: root.geometry.height + (root.editing ? root.cellHeight + root.gap : 0)
visible: root.tiles.length > 0 || root.editing
Behavior on implicitHeight {
enabled: panel.settled && !root.dragId
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
RowLayout {
id: split
visible: block.modelData.kind === "split"
width: parent.width
spacing: 10
ModuleSlot {
moduleId: "connectivity"
active: split.visible && ShellState.controlCenterOpen
Layout.fillHeight: true
}
// Edit mode: faint cells show the grid, and where a dragged tile lands.
Repeater {
// Only the empty cells: tiles are translucent.
model: root.editing ? Array.from({
length: Grid.COLS * root.shownRows
}, (_, i) => i).filter(i => !root.plan.items.some(t => i % Grid.COLS >= t.col && i % Grid.COLS < t.col + t.w && Math.floor(i / Grid.COLS) >= t.row && Math.floor(i / Grid.COLS) < t.row + t.h)) : []
Rectangle {
required property int modelData
x: (modelData % Grid.COLS) * (root.cellWidth + root.gap)
y: Math.floor(modelData / Grid.COLS) * (root.cellHeight + root.gap)
width: root.cellWidth
height: root.cellHeight
radius: 16
color: Qt.alpha(Theme.text, 0.03)
border.width: 1
border.color: Qt.alpha(Theme.text, 0.07)
}
}
Rectangle {
readonly property var target: root.dragId ? root.geometry.tiles[root.dragId] : null
visible: !!target
x: target ? target.x : 0
y: target ? target.y : 0
width: target ? target.w : 0
height: target ? target.h : 0
radius: Math.min(30, height / 2, width / 2)
color: Qt.alpha(Theme.accent, 0.12)
border.width: 2
border.color: Qt.alpha(Theme.accent, 0.6)
}
Repeater {
// Keyed by id so moving or resizing keeps each module alive.
model: ScriptModel {
values: root.tiles.map(m => m.id)
}
Item {
id: slot
required property string modelData
readonly property var cell: root.plan.items.find(i => i.id === modelData) || null
readonly property var rect: root.geometry.tiles[modelData] || null
readonly property bool dragging: root.dragId === modelData
readonly property real extra: loader.item ? loader.item.extraHeight : 0
objectName: "controlTile-" + modelData
visible: !!rect
x: dragging ? root.dragPoint.x - root.grabOffset.x : rect ? rect.x : 0
y: dragging ? root.dragPoint.y - root.grabOffset.y : rect ? rect.y : 0
width: rect ? rect.w : 0
height: rect ? rect.h : 0
z: dragging ? 10 : 0
scale: dragging ? 1.04 : 1
onExtraChanged: root.setExtra(modelData, extra)
Behavior on x {
enabled: panel.settled && !slot.dragging
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
ColumnLayout {
Layout.fillWidth: true
Layout.preferredWidth: 1
Layout.alignment: Qt.AlignTop
spacing: 10
Repeater {
model: block.modelData.kind === "split" ? block.modelData.ids : []
ModuleSlot {
required property string modelData
moduleId: modelData
Behavior on y {
enabled: panel.settled && !slot.dragging
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
Behavior on width {
enabled: panel.settled
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
Behavior on height {
enabled: panel.settled
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
Behavior on scale {
NumberAnimation {
duration: Theme.duration / 2
}
}
Loader {
id: loader
anchors.fill: parent
active: ShellState.controlCenterOpen
source: ControlRegistry.entry(slot.modelData).source
// Edit mode shows every tile at rest.
opacity: root.editing ? 0.85 : 1
}
Binding {
target: loader.item
when: !!loader.item
property: "moduleId"
value: slot.modelData
}
Binding {
target: loader.item
when: !!loader.item && !!slot.cell
property: "cols"
value: slot.cell ? slot.cell.w : 1
}
Binding {
target: loader.item
when: !!loader.item && !!slot.cell
property: "rows"
value: slot.cell ? slot.cell.h : 1
}
Binding {
target: loader.item
when: !!loader.item && !!slot.cell
property: "baseHeight"
value: slot.cell ? slot.cell.h * root.cellHeight + (slot.cell.h - 1) * root.gap : 0
}
// One extended tile at a time, none while editing.
Connections {
target: loader.item
function onExpandedChanged() {
if (!loader.item.expanded)
return;
for (let i = 0; i < grid.children.length; ++i) {
const other = grid.children[i];
if (other !== slot && other.collapse)
other.collapse();
}
}
}
function collapse() {
if (loader.item && loader.item.expanded)
loader.item.expanded = false;
}
Connections {
target: root
function onEditingChanged() {
if (root.editing)
slot.collapse();
}
}
// The tile's drawn shape: a 1×1 circle is smaller than its cell.
readonly property var shape: loader.item ? loader.item.background : null
readonly property bool circle: !!loader.item && loader.item.circle
// Edit mode: this layer takes the clicks, so pressing drags.
Rectangle {
visible: root.editing
x: slot.shape ? slot.shape.x : 0
y: slot.shape ? slot.shape.y : 0
width: slot.shape ? slot.shape.width : parent.width
height: slot.shape ? slot.shape.height : parent.height
radius: slot.shape ? slot.shape.radius : 12
color: move.containsMouse || slot.dragging ? Qt.alpha(Theme.text, 0.06) : Theme.transparent
border.width: slot.dragging || root.resizeId === slot.modelData ? 2 : 1
border.color: slot.dragging || root.resizeId === slot.modelData ? Theme.accent : Qt.alpha(Theme.text, 0.3)
}
MouseArea {
id: move
objectName: "controlMove-" + slot.modelData
visible: root.editing
anchors.fill: parent
hoverEnabled: true
preventStealing: true
cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor
property var lastCell: null
onPressed: mouse => {
const p = mapToItem(grid, mouse.x, mouse.y);
root.grabOffset = Qt.point(p.x - slot.x, p.y - slot.y);
root.dragPoint = p;
lastCell = null;
}
onPositionChanged: mouse => {
if (!pressed)
return;
const p = mapToItem(grid, mouse.x, mouse.y);
if (!root.dragId) {
if (Math.hypot(p.x - root.dragPoint.x, p.y - root.dragPoint.y) < 6)
return;
root.dragId = slot.modelData;
}
root.dragPoint = p;
// The cell nearest the tile's top-left corner, at most one row below the rest.
const c = Grid.cellAt(p.x - root.grabOffset.x, p.y - root.grabOffset.y, root.cellWidth, root.cellHeight, root.gap);
c.row = Math.min(c.row, root.savedPlan.rows);
if (lastCell && c.col === lastCell.col && c.row === lastCell.row)
return;
lastCell = c;
// Always from the saved layout, so tiles pushed aside come back.
root.preview = Grid.moveTo(root.savedPlan, slot.modelData, c);
}
onReleased: {
const plan = root.preview;
root.dragId = "";
root.preview = null;
if (plan)
root.save(plan);
}
onCanceled: {
root.dragId = "";
root.preview = null;
}
}
Badge {
objectName: "controlRemove-" + slot.modelData
visible: root.editing && !slot.dragging
// On the shape's top-left curve, inside the scroll clip.
x: slot.circle && slot.shape ? slot.shape.x + slot.shape.width * 0.146 - width / 2 : 0
y: slot.circle && slot.shape ? slot.shape.y + slot.shape.height * 0.146 - height / 2 : 0
glyph: "−"
onClicked: root.setEnabled(slot.modelData, false)
Accessible.name: "Remove " + ControlRegistry.entry(slot.modelData).title
}
// Size while resizing.
Rectangle {
visible: root.resizeId === slot.modelData
anchors.centerIn: parent
implicitWidth: sizeLabel.implicitWidth + 16
implicitHeight: 22
radius: 11
color: Theme.accent
Text {
id: sizeLabel
anchors.centerIn: parent
text: slot.cell ? slot.cell.w + "×" + slot.cell.h : ""
color: Theme.accentText
font.pixelSize: 11
font.weight: Font.DemiBold
}
}
Rectangle {
id: handle
visible: root.editing && !slot.dragging
x: slot.circle && slot.shape ? slot.shape.x + slot.shape.width * 0.854 - width / 2 : parent.width - width - 2
y: slot.circle && slot.shape ? slot.shape.y + slot.shape.height * 0.854 - height / 2 : parent.height - height - 2
width: 14
height: 14
radius: 7
color: Theme.text
border.width: 2
border.color: Theme.accent
MouseArea {
objectName: "controlResize-" + slot.modelData
anchors.fill: parent
anchors.margins: -5
preventStealing: true
cursorShape: Qt.SizeFDiagCursor
property point start
property var startSize
onPressed: mouse => {
start = mapToItem(grid, mouse.x, mouse.y);
startSize = {
w: slot.cell.w,
h: slot.cell.h
};
root.resizeId = slot.modelData;
}
onPositionChanged: mouse => {
if (!pressed)
return;
const p = mapToItem(grid, mouse.x, mouse.y);
const next = Grid.resize(startSize, p.x - start.x, p.y - start.y, root.cellWidth, root.cellHeight, root.gap);
if (next.w !== slot.cell.w || next.h !== slot.cell.h)
root.preview = Grid.moveTo(root.savedPlan, slot.modelData, next);
}
onReleased: {
const plan = root.preview;
root.resizeId = "";
root.preview = null;
if (plan)
root.save(plan);
}
onCanceled: {
root.resizeId = "";
root.preview = null;
}
}
}
}
GridLayout {
id: grid
visible: block.modelData.kind === "grid"
width: parent.width
columns: 2
columnSpacing: 10
rowSpacing: 10
Repeater {
model: block.modelData.kind === "grid" ? block.modelData.ids : []
ModuleSlot {
required property string modelData
moduleId: modelData
}
}
}
}
}
Text {
visible: root.tiles.length === 0 && !root.editing
text: "No controls. Use Edit Controls to add some."
color: Theme.textSecondary
font.pixelSize: 12
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.Wrap
Layout.fillWidth: true
Layout.topMargin: 8
Layout.bottomMargin: 8
}
Text {
visible: SystemService.acting
text: "Updating system controls…"
@@ -270,10 +646,79 @@ PanelWindow {
Layout.fillWidth: true
Layout.leftMargin: 4
}
GlassButton {
visible: root.blocks.length === 0
text: "Add modules"
onClicked: ShellState.openSettings("controlcenter")
ModuleSlot {
moduleId: "notifications"
visible: root.notifications && !root.editing
active: visible && ShellState.controlCenterOpen
}
// Edit mode stands the Notifications section in as a bar.
Item {
visible: root.notifications && root.editing
Layout.fillWidth: true
implicitHeight: 44
Rectangle {
anchors.fill: parent
radius: 22
color: Theme.fill
border.width: 1
border.color: Qt.alpha(Theme.text, 0.3)
Text {
anchors.centerIn: parent
text: "Notifications"
color: Theme.textSecondary
font.pixelSize: 12
font.weight: Font.DemiBold
}
}
Badge {
objectName: "controlRemove-notifications"
glyph: "−"
onClicked: root.setEnabled("notifications", false)
Accessible.name: "Remove Notifications"
}
}
ColumnLayout {
visible: root.editing && root.addable.length > 0
Layout.fillWidth: true
Layout.topMargin: 4
spacing: 8
Text {
text: "Add Controls"
color: Theme.textSecondary
font.pixelSize: 12
font.weight: Font.DemiBold
Layout.leftMargin: 4
}
Flow {
Layout.fillWidth: true
spacing: 8
Repeater {
model: root.editing ? root.addable : []
Pill {
required property string modelData
objectName: "controlAdd-" + modelData
text: "+ " + (Icons.available ? ControlRegistry.entry(modelData).glyph + " " : "") + ControlRegistry.entry(modelData).title
onClicked: root.setEnabled(modelData, true)
}
}
}
}
RowLayout {
Layout.alignment: Qt.AlignHCenter
Layout.topMargin: 2
spacing: 8
Pill {
objectName: "controlReset"
visible: root.editing
text: "Reset"
onClicked: root.reset()
}
Pill {
objectName: "controlEdit"
text: root.editing ? "Done" : "Edit Controls"
strong: root.editing
onClicked: root.editing = !root.editing
}
}
}
}
+107 -10
View File
@@ -1,47 +1,144 @@
pragma Singleton
import QtQuick
import Quickshell
import "../services"
// Control Center modules. Grid tiles have a default size in cells (w × h,
// each 1–4) that the user can change in edit mode; Notifications is a section
// under the grid instead. Enabled plugins with a Control Center widget add
// "plugin:<id>" tiles.
Singleton {
readonly property var ids: Object.keys(modules).concat(PluginService.controlModules)
function entry(id) {
if (String(id).startsWith("plugin:")) {
const plugin = String(id).slice("plugin:".length);
return PluginService.controlModules.includes(id) ? {
title: PluginService.title(plugin),
glyph: "󰏗",
w: 1,
h: 1,
plugin: plugin,
source: Qt.resolvedUrl("modules/Plugin.qml")
} : null;
}
return Object.prototype.hasOwnProperty.call(modules, id) ? modules[id] : null;
}
// Configured size, else the module's default.
function size(module) {
if (!module)
return {
w: 1,
h: 1
};
const e = entry(module.id);
return {
w: module.w || (e ? e.w : 1),
h: module.h || (e ? e.h : 1)
};
}
readonly property var modules: ({
metrics: {title:"System Metrics", source:Qt.resolvedUrl("modules/Metrics.qml")},
connectivity: {
title: "Connectivity",
source: Qt.resolvedUrl("modules/Connectivity.qml")
wifi: {
title: "Wi-Fi",
glyph: "󰖩",
w: 2,
h: 1,
source: Qt.resolvedUrl("modules/Wifi.qml")
},
audio: {
title: "Audio",
source: Qt.resolvedUrl("modules/Audio.qml")
bluetooth: {
title: "Bluetooth",
glyph: "󰂯",
w: 1,
h: 1,
source: Qt.resolvedUrl("modules/Bluetooth.qml")
},
network: {
title: "Network",
glyph: "󰛳",
w: 2,
h: 1,
source: Qt.resolvedUrl("modules/Network.qml")
},
output: {
title: "Sound",
glyph: "󰕾",
w: 4,
h: 1,
source: Qt.resolvedUrl("modules/Output.qml")
},
input: {
title: "Microphone",
glyph: "󰍬",
w: 4,
h: 1,
source: Qt.resolvedUrl("modules/Input.qml")
},
brightness: {
title: "Brightness",
title: "Display",
glyph: "󰃠",
w: 4,
h: 1,
source: Qt.resolvedUrl("modules/Brightness.qml")
},
nightLight: {
title: "Night Light",
glyph: "󰖔",
w: 1,
h: 1,
source: Qt.resolvedUrl("modules/NightLight.qml")
},
dnd: {
title: "Do Not Disturb",
glyph: "󰽥",
w: 1,
h: 1,
source: Qt.resolvedUrl("modules/Dnd.qml")
},
caffeine: {
title: "Caffeine",
glyph: "󰅶",
w: 1,
h: 1,
source: Qt.resolvedUrl("modules/Caffeine.qml")
},
gameMode: {
title: "Game Mode",
glyph: "󰊴",
w: 2,
h: 1,
source: Qt.resolvedUrl("modules/GameMode.qml")
},
profiles: {
title: "Power profile",
glyph: "󰾅",
w: 2,
h: 1,
source: Qt.resolvedUrl("modules/Profiles.qml")
},
media: {
title: "Media",
source: Qt.resolvedUrl("modules/Media.qml")
title: "Now Playing",
glyph: "󰝚",
w: 2,
h: 2,
source: Qt.resolvedUrl("modules/NowPlaying.qml")
},
power: {
title: "Power",
glyph: "󰐥",
w: 4,
h: 1,
source: Qt.resolvedUrl("modules/Power.qml")
},
metrics: {
title: "System Metrics",
glyph: "󰍛",
w: 4,
h: 1,
source: Qt.resolvedUrl("modules/Metrics.qml")
},
notifications: {
title: "Notifications",
glyph: "󰂚",
section: true,
source: Qt.resolvedUrl("modules/Notifications.qml")
}
})
+137
View File
@@ -0,0 +1,137 @@
// Pure helpers for the Control Center grid: free placement, moving with
// push-down, resizing and pixel geometry.
// Tiles are {id, w, h, x?, y?}: a size in cells and an optional position
// (column x, row y). The grid is `cols` wide and grows down.
var COLS = 4;
var MAX = 4;
function clampSize(n) {
n = Math.round(Number(n));
return Number.isFinite(n) ? Math.max(1, Math.min(MAX, n)) : 1;
}
function overlaps(a, b) {
return a.col < b.col + b.w && b.col < a.col + a.w && a.row < b.row + b.h && b.row < a.row + a.h;
}
function rowsOf(items) {
return items.reduce((n, i) => Math.max(n, i.row + i.h), 0);
}
// Places tiles. Positioned tiles keep their spot (an earlier one wins; a later
// one it overlaps moves straight down to the first free row). Tiles without a
// position then take the first free spot in reading order. Gaps stay as set.
function layout(tiles, cols) {
cols = cols || COLS;
const placed = [];
const free = t => !placed.some(p => overlaps(p, t));
const sized = t => {
const w = Math.min(cols, clampSize(t.w)), h = clampSize(t.h);
return {id: t.id, col: 0, row: 0, w: w, h: h};
};
for (const t of tiles) {
if (!Number.isInteger(t.x) || !Number.isInteger(t.y))
continue;
const item = sized(t);
item.col = Math.max(0, Math.min(cols - item.w, t.x));
item.row = Math.max(0, t.y);
while (!free(item))
item.row++;
placed.push(item);
}
for (const t of tiles) {
if (Number.isInteger(t.x) && Number.isInteger(t.y))
continue;
const item = sized(t);
let done = false;
for (let r = 0; !done; r++)
for (let c = 0; c + item.w <= cols && !done; c++) {
item.col = c;
item.row = r;
done = free(item);
}
placed.push(item);
}
// Back in list order.
const items = tiles.map(t => placed.find(p => p.id === t.id));
return {items: items, rows: rowsOf(items)};
}
// First free spot for a new tile, in reading order.
function freeSpot(plan, w, h, cols) {
return layout(plan.items.map(i => ({id: i.id, x: i.col, y: i.row, w: i.w, h: i.h})).concat([{id: "\u0000new", w: w, h: h}]), cols).items.slice(-1)[0];
}
// Moves and/or resizes one tile. Tiles it lands on are pushed straight down
// below it, cascading; nothing moves up, so gaps elsewhere are kept.
function moveTo(plan, id, target, cols) {
cols = cols || COLS;
const items = plan.items.map(i => Object.assign({}, i));
const moved = items.find(i => i.id === id);
if (!moved)
return {items: items, rows: rowsOf(items)};
moved.w = Math.min(cols, clampSize(target.w !== undefined ? target.w : moved.w));
moved.h = clampSize(target.h !== undefined ? target.h : moved.h);
moved.col = Math.max(0, Math.min(cols - moved.w, Math.round(target.col !== undefined ? target.col : moved.col)));
moved.row = Math.max(0, Math.round(target.row !== undefined ? target.row : moved.row));
const queue = [moved];
while (queue.length) {
const a = queue.shift();
for (const b of items) {
if (b === a || !overlaps(a, b))
continue;
if (b === moved) {
// A pushed tile never displaces the moved one: it goes below it.
a.row = moved.row + moved.h;
queue.push(a);
break;
}
b.row = a.row + a.h;
queue.push(b);
}
}
return {items: items, rows: rowsOf(items)};
}
// Cell for a tile whose top-left corner is at pixel (x, y).
function cellAt(x, y, cellW, cellH, gap) {
return {col: Math.round(x / (cellW + gap)), row: Math.round(y / (cellH + gap))};
}
// Cells for a tile resized by a pixel delta from its start size.
function resize(start, dx, dy, cellW, cellH, gap) {
return {
w: clampSize(start.w + dx / (cellW + gap)),
h: clampSize(start.h + dy / (cellH + gap))
};
}
// Pixel geometry. `extras` maps tile id -> extra height below it (an expanded
// tile); everything starting at or below that tile's bottom row moves down.
function geometry(plan, cellW, cellH, gap, extras) {
extras = extras || {};
const boundary = {};
for (const i of plan.items) {
const e = extras[i.id] || 0;
if (e > 0)
boundary[i.row + i.h] = Math.max(boundary[i.row + i.h] || 0, e + gap);
}
function shift(row) {
let s = 0;
for (const b in boundary)
if (row >= Number(b))
s += boundary[b];
return s;
}
const out = {};
for (const i of plan.items)
out[i.id] = {
x: i.col * (cellW + gap),
y: i.row * (cellH + gap) + shift(i.row),
w: i.w * cellW + (i.w - 1) * gap,
h: i.h * cellH + (i.h - 1) * gap + ((extras[i.id] || 0) > 0 ? extras[i.id] + gap : 0)
};
const height = plan.rows ? plan.rows * (cellH + gap) - gap + shift(plan.rows) : 0;
return {tiles: out, height: height};
}
@@ -0,0 +1,16 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
CCTile {
objectName: "bluetoothToggle"
title: "Bluetooth"
detail: !BluetoothService.adapter ? "No adapter" : !BluetoothService.canToggle ? "Hardware blocked" : BluetoothService.summary
page: "bluetooth"
glyph: BluetoothService.enabled ? "󰂯" : "󰂲"
fallback: "B"
checked: BluetoothService.enabled
enabled: BluetoothService.canToggle
onClicked: BluetoothService.toggle()
}
+15 -35
View File
@@ -1,44 +1,24 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import ".."
import "../../components"
import "../../services"
import "../../theme"
ControlCard {
id: root
// Display brightness; providers apply it on release.
CCSlider {
readonly property var info: SystemService.state.brightness || ({
available: false
})
objectName: "brightnessTile"
title: "Display"
GlassBarSlider {
objectName: "brightnessSlider"
Layout.fillWidth: true
glyph: "󰃠"
fallback: "☀"
from: 1
to: 100
stepSize: 1
value: root.info.value || 1
enabled: !!root.info.available && !SystemService.acting
onPressedChanged: if (!pressed && enabled) {
SystemService.action("brightness", value, false);
value = Qt.binding(() => root.info.value || 1);
}
Keys.onReleased: event => {
if (event.key === Qt.Key_Left || event.key === Qt.Key_Right) {
SystemService.action("brightness", value, false);
value = Qt.binding(() => root.info.value || 1);
}
}
Accessible.name: "Display brightness"
}
Text {
visible: !root.info.available
text: root.info.notice || "No brightness provider"
color: Theme.textSecondary
font.pixelSize: 11
wrapMode: Text.Wrap
Layout.fillWidth: true
}
glyph: "󰃠"
fallback: "☀"
sliderName: "brightnessSlider"
from: 1
to: 100
stepSize: 1
value: info.value || 1
enabled: !!info.available && !SystemService.acting
known: !!info.available
notice: info.available ? "" : info.notice || "No brightness provider"
onCommitted: value => SystemService.action("brightness", value, false)
}
@@ -0,0 +1,15 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
// Keeps the screen on and the system awake until turned off.
CCTile {
objectName: "caffeineToggle"
title: "Caffeine"
detail: CaffeineService.active ? "Staying awake" : "Off"
glyph: CaffeineService.active ? "󰅶" : "󰛊"
fallback: "☕"
checked: CaffeineService.active
onClicked: CaffeineService.toggle()
}
@@ -1,97 +0,0 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import ".."
import "../../services"
import "../../core"
import "../../theme"
// Wi-Fi, Bluetooth and live throughput; labels open the matching Settings page.
ControlCard {
id: root
// Tile metrics, so rows line up with the small tiles beside this card: when
// the block stretches it, the gaps grow and each row meets a tile's toggle.
readonly property int rowHeight: 34
padding: 10
implicitHeight: 3 * rowHeight + 2 * 10 + 2 * padding
spacing: Math.max(10, (root.height - 2 * root.padding - 3 * root.rowHeight) / 2)
Demand {
service: MetricsService
}
component Entry: RowLayout {
id: entry
property alias toggle: toggle
property string title
property string detail
property string page
Layout.fillWidth: true
Layout.preferredHeight: toggle.size
spacing: 10
CCToggle {
id: toggle
}
Item {
Layout.fillWidth: true
implicitHeight: labels.implicitHeight
ColumnLayout {
id: labels
anchors.left: parent.left
anchors.right: parent.right
spacing: 0
Text {
text: entry.title
color: Theme.text
font.pixelSize: 12
font.weight: Font.DemiBold
elide: Text.ElideRight
Layout.fillWidth: true
}
Text {
text: entry.detail
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
Layout.fillWidth: true
}
}
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: ShellState.openSettings(entry.page)
}
}
}
Entry {
title: "Wi-Fi"
detail: !NetworkService.available ? "No Wi-Fi adapter" : !NetworkService.backend.wifiHardwareEnabled ? "Hardware blocked" : NetworkService.enabled ? NetworkService.summary : "Off"
page: "network"
toggle.objectName: "wifiToggle"
toggle.glyph: NetworkService.enabled ? "󰖩" : "󰖪"
toggle.fallback: "W"
toggle.checked: NetworkService.available && NetworkService.enabled
toggle.enabled: NetworkService.available && NetworkService.backend.wifiHardwareEnabled
toggle.onClicked: NetworkService.toggle()
toggle.Accessible.name: "Wi-Fi"
}
Entry {
title: "Bluetooth"
detail: !BluetoothService.adapter ? "No adapter" : !BluetoothService.canToggle ? "Hardware blocked" : BluetoothService.summary
page: "bluetooth"
toggle.objectName: "bluetoothToggle"
toggle.glyph: BluetoothService.enabled ? "󰂯" : "󰂲"
toggle.fallback: "B"
toggle.checked: BluetoothService.enabled
toggle.enabled: BluetoothService.canToggle
toggle.onClicked: BluetoothService.toggle()
toggle.Accessible.name: "Bluetooth"
}
Entry {
title: "Network"
detail: "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s ↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s"
page: "metrics"
toggle.glyph: "󰛳"
toggle.fallback: "N"
toggle.onClicked: ShellState.openSettings("network")
toggle.Accessible.name: "Network settings"
}
}
+2
View File
@@ -1,3 +1,4 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
@@ -12,6 +13,7 @@ CCTile {
title: "Do Not Disturb"
detail: shellOwned ? (NotificationService.dnd ? "On" : "Off") : !info.available ? (info.notice || "No notification server") : info.enabled ? "On" : "Off"
glyph: "󰽥"
page: "notifications"
fallback: "☾"
// Shows acknowledged provider state; a failed request leaves it unchanged.
checked: shellOwned ? NotificationService.dnd : !!info.enabled
@@ -0,0 +1,16 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
// Game Mode switch; right click opens its options in Settings → Power.
CCTile {
objectName: "gameModeToggle"
title: "Game Mode"
detail: GameModeService.error ? GameModeService.error : GameModeService.active ? "On" : "Off"
page: "power"
glyph: "󰊴"
fallback: "G"
checked: GameModeService.active
onClicked: GameModeService.toggle()
}
@@ -0,0 +1,23 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
// Microphone level.
CCSlider {
readonly property var node: AudioService.source
objectName: "inputTile"
title: "Microphone"
glyph: "󰍬"
mutedGlyph: "󰍭"
fallback: "M"
sliderName: "microphoneSlider"
muteName: "microphoneMute"
muteable: true
enabled: !!node && !!node.audio
muted: enabled && node.audio.muted
value: enabled ? node.audio.volume : 0
notice: AudioService.available ? "" : "PipeWire is unavailable"
onMoved: value => AudioService.volume(true, value)
onMuteClicked: AudioService.mute(true)
}
+94 -5
View File
@@ -1,10 +1,99 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import ".."
import "../../core"
import "../../metrics"
import "../../services"
import "../../theme"
MetricsCard {
compact: true
radius: Math.max(12, Theme.radius * 0.75)
color: Theme.fill
border.color: Theme.hairline
// CPU, RAM and GPU load. Small tiles show the figures as text (1×1 just CPU);
// wide tall tiles show ring gauges. Click opens the Metrics settings.
CCModule {
id: root
readonly property var stats: [
{
label: "CPU",
value: MetricsService.cpu.percent
},
{
label: "RAM",
value: MetricsService.ram.percent
},
{
label: "GPU",
value: MetricsService.gpu.percent
}
]
readonly property int shown: compact ? 1 : Math.min(stats.length, wide ? cols : rows)
readonly property bool gauges: wide && tall
objectName: "metricsTile"
hovered: area.containsMouse
Demand {
service: MetricsService
}
MouseArea {
id: area
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: ShellState.openSettings("metrics")
}
GridLayout {
visible: !root.gauges
anchors.fill: parent
anchors.margins: 8
columns: root.wide ? root.shown : 1
rowSpacing: 4
columnSpacing: 4
Repeater {
model: root.stats.slice(0, root.shown)
ColumnLayout {
id: stat
required property var modelData
Layout.fillWidth: true
Layout.fillHeight: true
spacing: 0
Text {
text: MetricsService.value(stat.modelData.value, "%")
color: Theme.text
font.pixelSize: 17
font.weight: Font.DemiBold
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignBottom
Layout.fillWidth: true
Layout.fillHeight: true
}
Text {
text: stat.modelData.label
color: Theme.textSecondary
font.pixelSize: 10
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignTop
Layout.fillWidth: true
Layout.fillHeight: true
}
}
}
}
Row {
visible: root.gauges
anchors.centerIn: parent
Repeater {
model: root.gauges ? root.stats.slice(0, root.shown) : []
Item {
id: cell
required property var modelData
readonly property real scaleBy: Math.min(1, (root.width - 16) / root.shown / 100, (root.baseHeight - 16) / 106)
width: 100 * scaleBy
height: 106 * scaleBy
MetricGauge {
label: cell.modelData.label
value: cell.modelData.value
scale: cell.scaleBy
transformOrigin: Item.TopLeft
}
}
}
}
}
@@ -0,0 +1,42 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import ".."
import "../../core"
import "../../services"
import "../../theme"
// Live throughput. 1×1 shows just the two rates.
CCTile {
id: root
readonly property string down: "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s"
readonly property string up: "↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s"
objectName: "networkTile"
title: "Network"
detail: down + " " + up
page: "network"
glyph: "󰛳"
fallback: "N"
round: false
compactGlyph: false
onClicked: ShellState.openSettings("metrics")
Demand {
service: MetricsService
}
ColumnLayout {
visible: root.compact
anchors.centerIn: parent
spacing: 2
Repeater {
model: [root.down, root.up]
Text {
required property string modelData
text: modelData
color: Theme.text
font.pixelSize: 10
font.weight: Font.DemiBold
Layout.alignment: Qt.AlignHCenter
}
}
}
}
@@ -1,3 +1,4 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
@@ -10,6 +11,7 @@ CCTile {
title: "Night Light"
detail: !info.available ? "No gamma provider" : info.enabled ? "On" : "Off"
glyph: "󰖔"
page: "displays"
fallback: "N"
// Shows acknowledged provider state; a failed request leaves it unchanged.
checked: !!info.enabled
@@ -0,0 +1,268 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import Quickshell.Widgets
import ".."
import "../../components"
import "../../services"
import "../../theme"
// Now Playing tile. 1×1 is a round play button over the artwork; one row puts
// the artwork beside the track; taller tiles stack artwork, track and controls,
// with a progress bar from three rows.
CCModule {
id: root
readonly property bool canControl: !!MediaService.player && MediaService.player.canControl
readonly property bool showProgress: rows >= 3 && wide && MediaService.length > 0
objectName: "nowPlayingTile"
round: true
hovered: area.containsMouse
Demand {
service: MediaService
counter: "progressConsumers"
active: root.showProgress
}
component Art: ClippingRectangle {
id: artFrame
property real size: 48
implicitWidth: size
implicitHeight: size
radius: Math.max(8, size * 0.18)
color: Theme.surfaceVariant
Text {
anchors.centerIn: parent
visible: art.status !== Image.Ready
text: Icons.available ? "󰝚" : "♫"
font.family: Icons.available ? Icons.family : ""
font.pixelSize: Math.round(artFrame.size * 0.4)
color: Theme.textSecondary
}
Image {
id: art
anchors.fill: parent
source: MediaService.artwork
sourceSize: Qt.size(192, 192)
asynchronous: true
retainWhileLoading: true
fillMode: Image.PreserveAspectCrop
}
}
component Track: ColumnLayout {
property int titleSize: 13
property int align: Text.AlignLeft
spacing: 1
Text {
text: MediaService.title
color: Theme.text
font.pixelSize: parent.titleSize
font.weight: Font.DemiBold
elide: Text.ElideRight
horizontalAlignment: parent.align
Layout.fillWidth: true
}
Text {
text: MediaService.artist
visible: text !== ""
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
horizontalAlignment: parent.align
Layout.fillWidth: true
}
}
component Control: Item {
id: control
property string glyph
property string fallback
property bool main: false
property bool available: true
signal clicked
implicitWidth: main ? 34 : 28
implicitHeight: implicitWidth
enabled: root.canControl && available
opacity: enabled ? 1 : 0.4
Accessible.role: Accessible.Button
Rectangle {
anchors.fill: parent
radius: width / 2
color: control.main ? Qt.alpha(Theme.text, controlArea.containsMouse ? 0.2 : 0.12) : controlArea.containsMouse ? Theme.hover : Theme.transparent
}
Text {
anchors.centerIn: parent
text: Icons.available ? control.glyph : control.fallback
font.family: Icons.available ? Icons.family : ""
font.pixelSize: control.main ? 17 : 15
color: Theme.text
scale: controlArea.pressed ? 0.9 : 1
}
MouseArea {
id: controlArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: control.clicked()
}
}
component Controls: RowLayout {
property bool full: true
spacing: 4
Control {
visible: parent.full
glyph: "󰒮"
fallback: "⏮"
available: !!MediaService.player && MediaService.player.canGoPrevious
onClicked: MediaService.previous()
Accessible.name: "Previous track"
}
Control {
objectName: "ccMediaToggle"
main: true
glyph: MediaService.playing ? "󰏤" : "󰐊"
fallback: MediaService.playing ? "Ⅱ" : "▶"
available: !!MediaService.player && MediaService.player.canTogglePlaying
onClicked: MediaService.toggle()
Accessible.name: MediaService.playing ? "Pause" : "Play"
}
Control {
visible: parent.full
glyph: "󰒭"
fallback: "⏭"
available: !!MediaService.player && MediaService.player.canGoNext
onClicked: MediaService.next()
Accessible.name: "Next track"
}
}
MouseArea {
id: area
anchors.fill: parent
hoverEnabled: true
onClicked: if (root.compact && root.canControl)
MediaService.toggle()
}
GlassToolTip {
visible: root.compact && area.containsMouse
delay: 500
text: MediaService.title + (MediaService.artist ? " · " + MediaService.artist : "")
}
// 1×1: artwork filling the circle with the play state on top.
ClippingRectangle {
visible: root.compact
x: root.background.x
y: root.background.y
width: root.background.width
height: root.background.height
radius: width / 2
color: Theme.transparent
Image {
anchors.fill: parent
source: root.compact ? MediaService.artwork : ""
sourceSize: Qt.size(128, 128)
asynchronous: true
fillMode: Image.PreserveAspectCrop
opacity: 0.55
}
Text {
anchors.centerIn: parent
text: Icons.available ? (MediaService.playing ? "󰏤" : "󰐊") : (MediaService.playing ? "Ⅱ" : "▶")
font.family: Icons.available ? Icons.family : ""
font.pixelSize: Math.round(root.background.width * 0.32)
color: Theme.text
}
}
// One row: artwork, track, controls.
RowLayout {
visible: root.wide && !root.tall
anchors.fill: parent
anchors.margins: 10
anchors.rightMargin: 12
spacing: 10
Art {
size: root.baseHeight - 20
}
Track {
Layout.fillWidth: true
}
Controls {
full: root.cols >= 3
}
}
// One column: artwork above the play button.
ColumnLayout {
visible: !root.wide && root.tall
anchors.fill: parent
anchors.margins: 10
spacing: 8
Art {
size: Math.min(root.width - 20, root.baseHeight - 64)
Layout.alignment: Qt.AlignHCenter
}
Track {
visible: root.rows >= 3
titleSize: 11
align: Text.AlignHCenter
Layout.fillWidth: true
}
Item {
Layout.fillHeight: true
}
Controls {
full: false
Layout.alignment: Qt.AlignHCenter
}
}
// Large: artwork and track on top, controls along the bottom.
ColumnLayout {
visible: root.wide && root.tall
anchors.fill: parent
anchors.margins: 14
spacing: 8
RowLayout {
Layout.fillWidth: true
spacing: 12
Art {
size: Math.min(root.rows >= 3 ? 96 : 56, root.width / 2 - 14)
}
Track {
titleSize: root.cols >= 3 ? 15 : 13
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter
}
}
Item {
Layout.fillHeight: true
}
RowLayout {
visible: root.showProgress
Layout.fillWidth: true
spacing: 6
Text {
text: MediaService.time(MediaService.position)
color: Theme.textSecondary
font.pixelSize: 10
}
GlassSlider {
Layout.fillWidth: true
from: 0
to: Math.max(1, MediaService.length)
value: MediaService.position
enabled: MediaService.seekable
onMoved: MediaService.seek(value)
Accessible.name: "Track position"
}
Text {
text: "−" + MediaService.time(MediaService.length - MediaService.position)
color: Theme.textSecondary
font.pixelSize: 10
}
}
Controls {
Layout.alignment: Qt.AlignHCenter
}
}
}
@@ -0,0 +1,24 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
// Output volume. Right click (or spare rows) shows per-app volume.
CCSlider {
readonly property var node: AudioService.sink
objectName: "outputTile"
title: "Sound"
glyph: "󰕾"
mutedGlyph: "󰖁"
fallback: "♪"
sliderName: "volumeSlider"
muteName: "volumeMute"
muteable: true
enabled: !!node && !!node.audio
muted: enabled && node.audio.muted
value: enabled ? node.audio.volume : 0
notice: AudioService.available ? "" : "PipeWire is unavailable"
onMoved: value => AudioService.volume(false, value)
onMuteClicked: AudioService.mute(false)
extension: AudioMixer {}
}
@@ -0,0 +1,91 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import ".."
import "../../core"
import "../../services"
import "../../theme"
// A plugin's Control Center widget (Noctalia `controlCenterWidget` entry point)
// in a grid tile. The plugin draws and handles its own button; the tile scales
// it to fit and, when wide enough, adds the plugin's name and tooltip text.
CCModule {
id: root
readonly property string pluginId: moduleId.startsWith("plugin:") ? moduleId.slice("plugin:".length) : ""
readonly property string source: pluginId ? PluginService.entryUrl(pluginId, "control-center-widget") : ""
readonly property Item widget: loader.item as Item
// Plugin items are untyped.
readonly property var widgetObject: loader.item
readonly property string hint: widgetObject && typeof widgetObject.tooltipText === "string" ? widgetObject.tooltipText : ""
// Room for the widget: the circle at 1×1, else the first cell.
readonly property real room: compact ? background.width * 0.6 : Math.min(baseHeight, width) - 24
objectName: "pluginTile-" + pluginId
round: true
hovered: area.containsMouse
onSourceChanged: load()
Component.onCompleted: load()
function load() {
if (!source) {
loader.source = "";
return;
}
// Noctalia widgets get their pluginApi at creation, as in Noctalia.
loader.setSource(source, {
pluginApi: PluginService.noctaliaApi(pluginId),
screen: ShellState.activeScreen()
});
}
MouseArea {
id: area
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.NoButton
}
Item {
id: holder
readonly property real size: Math.min(root.room, 56)
x: root.wide && !root.tall ? (root.baseHeight - size) / 2 : root.wide ? 14 : (root.width - size) / 2
y: root.wide && root.tall ? 14 : !root.wide && root.tall ? 12 : (root.baseHeight - size) / 2
width: size
height: size
Loader {
id: loader
anchors.centerIn: parent
scale: root.widget && root.widget.implicitWidth > 0 ? Math.min(2.2, holder.size / Math.max(root.widget.implicitWidth, root.widget.implicitHeight)) : 1
}
}
ColumnLayout {
visible: !root.compact
x: root.wide ? (root.tall ? 14 : holder.x + holder.width + 10) : 8
y: root.wide ? (root.tall ? root.baseHeight - height - 14 : (root.baseHeight - height) / 2) : holder.y + holder.height + 8
width: root.width - x - (root.wide ? 14 : 8)
spacing: 1
Text {
text: root.pluginId ? PluginService.title(root.pluginId) : ""
color: Theme.text
font.pixelSize: 12
font.weight: Font.DemiBold
elide: Text.ElideRight
horizontalAlignment: root.wide ? Text.AlignLeft : Text.AlignHCenter
Layout.fillWidth: true
}
Text {
visible: text !== ""
text: root.hint
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
wrapMode: root.tall ? Text.Wrap : Text.NoWrap
maximumLineCount: Math.max(1, root.rows - 1)
horizontalAlignment: root.wide ? Text.AlignLeft : Text.AlignHCenter
Layout.fillWidth: true
}
}
Text {
visible: !root.source
anchors.centerIn: parent
text: "Plugin unavailable"
color: Theme.textSecondary
font.pixelSize: 10
}
}
+185 -55
View File
@@ -6,55 +6,94 @@ import "../../components"
import "../../services"
import "../../theme"
ControlCard {
// Session actions as round buttons, wrapped to the tile. When they do not fit
// it becomes one power button that extends into a list. Confirmation for
// destructive actions extends below the tile.
CCModule {
id: root
readonly property var actions: [
{
id: "lock",
glyph: "󰌾",
label: "Lock"
},
{
id: "logout",
glyph: "󰍃",
label: "Log out"
},
{
id: "suspend",
glyph: "󰤄",
label: "Suspend"
},
{
id: "reboot",
glyph: "󰜉",
label: "Reboot"
},
{
id: "shutdown",
glyph: "󰐥",
label: "Shut down"
}
]
readonly property real innerWidth: width - 20
readonly property real innerHeight: baseHeight - 12
readonly property int count: actions.length
function perRowFor(slot) {
return Math.max(1, Math.min(count, Math.floor((innerWidth + 4) / (slot + 4))));
}
function heightFor(perRow, rowHeight) {
return Math.ceil(count / perRow) * (rowHeight + 4) - 4;
}
// Labelled buttons where they fit on four-wide or taller tiles, else plain
// 34 px buttons, else one row of smaller ones, else the menu button.
readonly property bool labels: (cols >= 4 || rows >= 2) && heightFor(perRowFor(52), 49) <= innerHeight
readonly property bool plain: !labels && heightFor(perRowFor(34), 34) <= innerHeight
readonly property real squeezed: Math.min(innerHeight, Math.floor((innerWidth - 4 * (count - 1)) / count))
readonly property int perRow: labels ? perRowFor(52) : plain ? perRowFor(34) : count
readonly property real buttonSize: labels || plain ? 34 : squeezed
readonly property real buttonWidth: labels ? 52 : buttonSize
readonly property bool fits: labels || plain || squeezed >= 24
readonly property bool pending: PowerService.pending !== ""
round: !fits
hovered: menuArea.containsMouse
extraHeight: (pending || (expanded && !fits)) && extension.item ? extension.implicitHeight + 20 : 0
Component.onDestruction: PowerService.cancel()
RowLayout {
Layout.fillWidth: true
spacing: 4
function allowed(id) {
return (id === "lock" && ConfigService.ready && ConfigService.data.lock.enabled) || (!!SystemService.state.power && !!SystemService.state.power[id] && !SystemService.acting);
}
// Everything fits: a wrapped grid of buttons.
GridLayout {
visible: root.fits
anchors.horizontalCenter: parent.horizontalCenter
y: (root.baseHeight - height) / 2
columns: root.perRow
rowSpacing: 4
columnSpacing: Math.max(4, (root.innerWidth - root.perRow * root.buttonWidth) / Math.max(1, root.perRow - 1) - 2)
Repeater {
model: [
{
id: "lock",
glyph: "󰌾"
},
{
id: "logout",
glyph: "󰍃"
},
{
id: "suspend",
glyph: "󰤄"
},
{
id: "reboot",
glyph: "󰜉"
},
{
id: "shutdown",
glyph: "󰐥"
}
]
model: root.actions
ColumnLayout {
id: action
required property var modelData
readonly property string label: modelData.id === "logout" ? "Log out" : modelData.id === "shutdown" ? "Shut down" : modelData.id.charAt(0).toUpperCase() + modelData.id.slice(1)
Layout.fillWidth: true
Layout.preferredWidth: 1
spacing: 4
Layout.preferredWidth: root.buttonWidth
spacing: 3
CCToggle {
objectName: "power-" + action.modelData.id
Layout.alignment: Qt.AlignHCenter
size: 38
size: root.buttonSize
glyph: action.modelData.glyph
fallback: action.label.charAt(0)
fallback: action.modelData.label.charAt(0)
checked: PowerService.pending === action.modelData.id
enabled: (action.modelData.id === "lock" && ConfigService.ready && ConfigService.data.lock.enabled) || (!!SystemService.state.power && !!SystemService.state.power[action.modelData.id] && !SystemService.acting)
enabled: root.allowed(action.modelData.id)
onClicked: PowerService.request(action.modelData.id)
Accessible.name: action.label
Accessible.name: action.modelData.label
}
Text {
text: action.label
visible: root.labels
text: action.modelData.label
color: Theme.textSecondary
font.pixelSize: 10
elide: Text.ElideRight
@@ -64,28 +103,119 @@ ControlCard {
}
}
}
RowLayout {
visible: PowerService.pending !== ""
Layout.fillWidth: true
spacing: 8
Text {
text: "Confirm " + PowerService.pending + "? Unsaved work may be lost."
color: Theme.text
font.pixelSize: 12
wrapMode: Text.Wrap
Layout.fillWidth: true
// Too small: one button that extends into the list.
MouseArea {
id: menuArea
visible: !root.fits
width: parent.width
height: root.baseHeight
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.expanded = !root.expanded
Accessible.role: Accessible.Button
Accessible.name: "Power"
Column {
anchors.centerIn: parent
spacing: 2
Text {
anchors.horizontalCenter: parent.horizontalCenter
text: Icons.available ? "󰐥" : "⏻"
font.family: Icons.available ? Icons.family : ""
font.pixelSize: Math.min(26, root.innerHeight * 0.5)
color: Theme.text
}
Text {
visible: root.innerHeight >= 44
anchors.horizontalCenter: parent.horizontalCenter
text: "Power"
color: Theme.textSecondary
font.pixelSize: 10
}
}
GlassButton {
objectName: "powerCancel"
text: "Cancel"
onClicked: PowerService.cancel()
}
Loader {
id: extension
x: 10
y: root.baseHeight + 6
width: root.width - 20
active: root.pending || (root.expanded && !root.fits)
sourceComponent: root.pending ? confirm : menu
}
Component {
id: menu
ColumnLayout {
spacing: 2
Repeater {
model: root.actions
Rectangle {
id: item
required property var modelData
Layout.fillWidth: true
implicitHeight: 30
radius: 8
enabled: root.allowed(modelData.id)
opacity: enabled ? 1 : 0.45
color: itemArea.containsMouse ? Theme.hover : Theme.transparent
RowLayout {
anchors.fill: parent
anchors.leftMargin: 8
anchors.rightMargin: 8
spacing: 8
Text {
text: Icons.available ? item.modelData.glyph : ""
font.family: Icons.family
font.pixelSize: 14
color: Theme.text
}
Text {
text: item.modelData.label
color: Theme.text
font.pixelSize: 12
elide: Text.ElideRight
Layout.fillWidth: true
}
}
MouseArea {
id: itemArea
objectName: "power-" + item.modelData.id
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: PowerService.request(item.modelData.id)
}
}
}
}
GlassButton {
objectName: "powerConfirm"
text: "Confirm"
accented: true
enabled: !SystemService.acting
onClicked: PowerService.confirm()
}
Component {
id: confirm
ColumnLayout {
spacing: 8
Text {
text: "Confirm " + PowerService.pending + "? Unsaved work may be lost."
color: Theme.text
font.pixelSize: 12
wrapMode: Text.Wrap
Layout.fillWidth: true
}
RowLayout {
Layout.alignment: Qt.AlignRight
spacing: 8
GlassButton {
objectName: "powerCancel"
text: "Cancel"
onClicked: PowerService.cancel()
}
GlassButton {
objectName: "powerConfirm"
text: "Confirm"
accented: true
enabled: !SystemService.acting
onClicked: PowerService.confirm()
}
}
}
}
}
@@ -1,3 +1,4 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
@@ -15,6 +16,7 @@ CCTile {
title: "Power profile"
detail: !info.available ? "Unavailable" : current ? current.charAt(0).toUpperCase() + current.slice(1).replace(/-/g, " ") : "—"
glyph: current === "power-saver" ? "󰌪" : current === "performance" ? "󰓅" : "󰾅"
page: "power"
fallback: "P"
checked: info.available && current !== "" && current !== "balanced"
enabled: !!info.available && profiles.length > 1 && !SystemService.acting
+16
View File
@@ -0,0 +1,16 @@
pragma ComponentBehavior: Bound
import QtQuick
import ".."
import "../../services"
CCTile {
objectName: "wifiToggle"
title: "Wi-Fi"
detail: !NetworkService.available ? "No Wi-Fi adapter" : !NetworkService.backend.wifiHardwareEnabled ? "Hardware blocked" : NetworkService.enabled ? NetworkService.summary : "Off"
page: "network"
glyph: NetworkService.enabled ? "󰖩" : "󰖪"
fallback: "W"
checked: NetworkService.available && NetworkService.enabled
enabled: NetworkService.available && NetworkService.backend.wifiHardwareEnabled
onClicked: NetworkService.toggle()
}
+3
View File
@@ -4,3 +4,6 @@ ControlCard 1.0 ControlCard.qml
SystemTile 1.0 SystemTile.qml
CCToggle 1.0 CCToggle.qml
CCTile 1.0 CCTile.qml
CCModule 1.0 CCModule.qml
CCSlider 1.0 CCSlider.qml
AudioMixer 1.0 AudioMixer.qml
+1 -1
View File
@@ -123,7 +123,7 @@ Singleton {
available: true,
group: "shell",
icon: "󰕮",
keywords: ["Dashboard", "Placement", "Position", "Tab order", "Open from clock", "Remember last tab", "Equalizer", "EasyEffects", "Power menu"]
keywords: ["Dashboard", "Placement", "Position", "Tab order", "Remember last tab", "Equalizer", "EasyEffects", "Power menu"]
},
{
id: "plugins",
+9 -5
View File
@@ -54,7 +54,8 @@ Singleton {
}
property bool launcherOpen: false
property var launcherScreen: null
// "apps" searches applications and commands; "clipboard" is Clipboard History.
// "apps" searches applications and commands; "clipboard" is Clipboard History;
// "emoji" is the Emoji Picker.
// Changing it on an open launcher switches in place.
property string launcherMode: "apps"
function activeScreen() {
@@ -63,7 +64,7 @@ Singleton {
function openLauncher(mode) {
wallpaperPickerOpen=false;
dashboardOpen = false;
launcherMode = mode === "clipboard" ? "clipboard" : "apps";
launcherMode = mode === "clipboard" || mode === "emoji" ? mode : "apps";
if (launcherOpen)
return;
controlCenterOpen = false;
@@ -77,11 +78,14 @@ Singleton {
else
openLauncher();
}
function toggleClipboard() {
if (launcherOpen && launcherMode === "clipboard")
function toggleLauncherMode(mode) {
if (launcherOpen && launcherMode === mode)
launcherOpen = false;
else
openLauncher("clipboard");
openLauncher(mode);
}
function toggleClipboard() {
toggleLauncherMode("clipboard");
}
property var settingsWindow: null
property bool settingsOpen: false
+6 -4
View File
@@ -1,5 +1,5 @@
import QtQuick
import QtQuick.Controls
import "../components"
import "../services"
import "../theme"
@@ -133,7 +133,9 @@ Item {
Accessible.role: Accessible.Button
Accessible.name: group.name
Accessible.onPressAction: DockState.click(group.id, root)
ToolTip.visible: options.tooltips && mouse.containsMouse && !DockState.opened && !dragging
ToolTip.delay: 500
ToolTip.text: group.name + (group.windows.length ? " · " + group.windows.length + " window(s)" : group.entry ? "" : " · unavailable")
GlassToolTip {
visible: root.options.tooltips && mouse.containsMouse && !DockState.opened && !root.dragging
delay: 500
text: root.group.name + (root.group.windows.length ? " · " + root.group.windows.length + " window(s)" : root.group.entry ? "" : " · unavailable")
}
}
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Game Mode system side: turn animations, blur, shadows and HyprGlass off and
switch to the performance power profile, remembering the live values in a
journal so they come back exactly, even after a shell crash. Options Hyprland
does not have (no HyprGlass) and a missing power-profiles-daemon are skipped."""
import json,os,subprocess,sys
from pathlib import Path
KEYS=['animations:enabled','decoration:blur:enabled','decoration:shadow:enabled','plugin:hyprglass:enabled']
def run(args):
p=subprocess.run(['hyprctl',*args],text=True,capture_output=True,timeout=4)
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
return p.stdout.strip()
def get_many(keys):
# Missing options (an unloaded plugin) are left out.
out=run(['-j','--batch',';'.join('getoption '+k for k in keys)])
decoder,pos,found=json.JSONDecoder(),0,{}
while pos<len(out):
while pos<len(out) and out[pos].isspace():pos+=1
if pos>=len(out):break
try:data,pos=decoder.raw_decode(out,pos)
except ValueError:
# Non-JSON error text for a missing option: skip to the next object.
nxt=out.find('{',pos+1)
if nxt<0:break
pos=nxt;continue
if isinstance(data,dict) and ('int' in data or 'bool' in data):found[str(data.get('option',''))]=int(data.get('int',data.get('bool')))
return {k:found[k] for k in keys if k in found}
def lua_set(key,value):
# "decoration:blur:enabled" -> hl.config({ decoration = { blur = { enabled = false } } })
path=key.split(':');text='true' if value else 'false'
target='hl.config('
if path[0]=='plugin':target='hl.plugin.%s.config('%path[1];path=path[2:]
for part in reversed(path):text='{ '+part+' = '+text+' }'
return target+text+')'
def put_many(values):
if not values:return
out=run(['--batch',';'.join('eval '+lua_set(k,v) for k,v in values.items())])
bad=[line for line in out.splitlines() if line.strip() and line.strip()!='ok']
if bad:raise ValueError(bad[0][:350])
PROFILES=('net.hadess.PowerProfiles','/net/hadess/PowerProfiles','net.hadess.PowerProfiles')
def busctl(*args):
p=subprocess.run(['busctl','--system','--auto-start=no','--timeout=3','--json=short',*args],text=True,capture_output=True,timeout=5)
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
return json.loads(p.stdout)['data'] if p.stdout.strip() else None
def get_profile():
"""The active profile, or None without power-profiles-daemon or a performance profile."""
try:
names=[p['Profile']['data'] for p in busctl('get-property',*PROFILES,'Profiles')]
return busctl('get-property',*PROFILES,'ActiveProfile') if 'performance' in names else None
except (ValueError,KeyError,TypeError,subprocess.TimeoutExpired):return None
def set_profile(name):
p=subprocess.run(['busctl','--system','--auto-start=no','--timeout=3','set-property',*PROFILES,'ActiveProfile','s',name],text=True,capture_output=True,timeout=5)
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
def journal_path():
# Per Hyprland session: a journal from an older session is never applied.
sig=os.environ.get('HYPRLAND_INSTANCE_SIGNATURE','none')
return Path(os.environ.get('XDG_STATE_HOME',Path.home()/'.local/state'))/('glassMxrph/gamemode-%s.json'%sig)
def dispatch(req):
path=journal_path();action=req.get('action')
if action=='on':
if not path.exists():
saved={'keywords':get_many(KEYS) if req.get('effects',True) else {},
'profile':get_profile() if req.get('performance',True) else None}
path.parent.mkdir(parents=True,exist_ok=True)
temp=path.with_suffix('.tmp');temp.write_text(json.dumps(saved));temp.replace(path)
saved=json.loads(path.read_text())
put_many({k:0 for k in saved['keywords']})
if saved['profile'] and saved['profile']!='performance':set_profile('performance')
return dict(active=True)
if action=='off':
if path.exists():
saved=json.loads(path.read_text())
put_many(saved['keywords'])
if saved['profile'] and saved['profile']!='performance':set_profile(saved['profile'])
path.unlink()
return dict(active=False)
if action=='status':
return dict(active=path.exists())
raise ValueError('Unknown Game Mode action')
if __name__=='__main__':
try:print(json.dumps(dict(ok=True,**dispatch(json.loads(sys.argv[1])))))
except (OSError,ValueError,KeyError,subprocess.TimeoutExpired) as e:print(json.dumps(dict(ok=False,error=str(e))))
+16 -6
View File
@@ -8,6 +8,7 @@ RANGES={'blur_strength':(0,5),'blur_iterations':(1,5),'refraction_strength':(0,8
'chromatic_aberration':(0,1),'fresnel_strength':(0,1),'specular_strength':(0,1),
'edge_thickness':(0,.15),'lens_distortion':(0,1),'brightness':(.2,2),
'contrast':(.2,2),'saturation':(0,2),'vibrancy':(0,1),'adaptive_dim':(0,1)}
BOOLS={'enabled','layers:enabled'}
GHOSTTY={'blur_strength':.45,'blur_iterations':2,'refraction_strength':3,
'chromatic_aberration':.45,'fresnel_strength':.5,'specular_strength':.8,
'edge_thickness':.065,'lens_distortion':.25,'brightness':.95,
@@ -21,8 +22,8 @@ def run(args):
def get(key):
data=json.loads(run(['-j','getoption',PREFIX+key]))
for field in ['str','int','float']:
if field in data:return data[field]
for field in ['str','int','float','bool']:
if field in data:return int(data[field]) if field=='bool' else data[field]
raise ValueError('HyprGlass option unavailable: '+key)
def get_many(keys):
@@ -33,14 +34,23 @@ def get_many(keys):
while pos<len(out) and out[pos].isspace():pos+=1
if pos>=len(out):break
data,pos=decoder.raw_decode(out,pos)
value=next((data[f] for f in ['str','int','float'] if f in data),None)
value=next((data[f] for f in ['str','int','float','bool'] if f in data),None)
if isinstance(value,bool):value=int(value)
if value is not None:found[str(data.get('option','')).removeprefix(PREFIX)]=value
missing=[k for k in keys if k not in found]
if missing:raise ValueError('HyprGlass option unavailable: '+missing[0])
return found
def lua_table(key,value):
# "dark:brightness" -> { dark = { brightness = 0.9 } }
if key in BOOLS:text='true' if value else 'false'
elif isinstance(value,str):text="'"+value+"'"
else:text=repr(value)
for part in reversed(key.split(':')):text='{ '+part+' = '+text+' }'
return text
def put(key,value):
result=run(['keyword',PREFIX+key,str(value)])
result=run(['eval','hl.plugin.hyprglass.config('+lua_table(key,value)+')'])
if result!='ok':raise ValueError(result[:350])
if get(key)!=value:raise ValueError('HyprGlass did not accept '+key)
@@ -73,9 +83,9 @@ def save(path,data):
def probe():
try:
o=get_many(['default_preset','enabled','layers:enabled','layers:namespaces','layers:exclude_namespaces','layers:namespace_presets'])
o=get_many(['default_preset','enabled','layers:enabled'])
return dict(available=True,preset=o['default_preset'],enabled=bool(o['enabled']),layers=bool(o['layers:enabled']),
namespaces=o['layers:namespaces'],exclusions=o['layers:exclude_namespaces'],overrides=o['layers:namespace_presets'])
namespaces='',exclusions='',overrides='')
except (OSError,ValueError,subprocess.TimeoutExpired) as error:return dict(available=False,reason=str(error)[:200])
def dispatch(req):
+1 -1
View File
@@ -129,7 +129,7 @@ def action(req):
if value in ['logout','reboot','shutdown'] and req.get('confirmed') is not True:raise ValueError('Explicit confirmation required')
if not power(options['power']).get(value):raise ValueError('Power action unavailable')
if value=='lock':subprocess.Popen(lock_command(options['power']),stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
elif value=='logout':run(['hyprctl','dispatch','exit'])
elif value=='logout':run(['hyprctl','dispatch','hl.dsp.exit()'])
else:run(['busctl','--system','--auto-start=no','--timeout=10','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',{'suspend':'Suspend','reboot':'Reboot','shutdown':'PowerOff'}[value],'b','true'],15)
elif kind=='manager':
executable={'network':'nm-connection-editor','bluetooth':'blueman-manager'}.get(value)
+8
View File
@@ -23,6 +23,14 @@ Singleton {
kind: "Command",
stay: true,
run: () => ShellState.openLauncher("clipboard")
},
{
id: "emoji",
title: "Emoji Picker",
description: "Search and copy an emoji",
kind: "Command",
stay: true,
run: () => ShellState.openLauncher("emoji")
}
]
// Extensions are registered by trusted QML code, never interpreted from search text.
+179 -22
View File
@@ -14,6 +14,8 @@ import "../core"
// empty bar) browses every application as an icon grid; > lists commands.
// Clipboard mode (>clipboard, `glassmxrph clipboard`) lists cliphist history
// in the same bar, newest first, without closing the window to switch.
// Emoji mode (>emoji, `glassmxrph emoji`) shows a searchable emoji grid the
// same way; the selected emoji's name is the section label.
// Runtime selects the concrete Wayland layer implementation.
// qmllint disable uncreatable-type
PanelWindow {
@@ -39,10 +41,13 @@ PanelWindow {
})
readonly property string query: search.text.trim()
readonly property bool clipboardMode: ShellState.launcherMode === "clipboard"
readonly property bool commandMode: !clipboardMode && query.startsWith(">")
readonly property bool emojiMode: ShellState.launcherMode === "emoji"
readonly property bool commandMode: !clipboardMode && !emojiMode && query.startsWith(">")
property bool browsing: false
readonly property bool showList: clipboardMode || query !== ""
readonly property bool showGrid: !showList && browsing
readonly property bool showList: clipboardMode || !emojiMode && query !== ""
readonly property bool showGrid: !showList && !emojiMode && browsing
// Arrow keys move through whichever grid is showing.
readonly property int columns: emojiMode ? emojiColumns : showGrid ? gridColumns : 1
readonly property var allApps: ApplicationsService.launchable.map(entry => ({
id: entry.id,
title: entry.name,
@@ -55,15 +60,30 @@ PanelWindow {
description: "",
clip: e
})) : []
readonly property var results: clipboardMode ? clipboardResults : showList ? (commandMode ? commands.results : apps.results) : showGrid ? allApps : []
readonly property var emojiResults: emojiMode && ShellState.launcherOpen ? EmojiService.filter(query).map(e => ({
id: e.emoji,
title: e.name,
description: "",
glyph: e
})) : []
readonly property var results: clipboardMode ? clipboardResults : emojiMode ? emojiResults : showList ? (commandMode ? commands.results : apps.results) : showGrid ? allApps : []
property int selectedIndex: 0
property string launchError: ""
readonly property real targetWidth: Math.min(options.width, root.width - 40)
// Room is kept for the mode pills on the right of the bar.
readonly property int pillSize: 48
readonly property real pillsWidth: 2 * pillSize + 2 * 10
readonly property real targetWidth: Math.min(options.width, root.width - 40 - 2 * pillsWidth)
// A hovered mode pill names itself in the empty search bar.
property string pillHover: ""
readonly property int barHeight: 60
readonly property real maxBodyHeight: Math.min(460, root.height * 0.78 - barHeight - (root.height * 0.22))
// Clipboard mode shows the latest five rows; the rest scroll.
readonly property real clipboardRows: 5 * 48 - 2
readonly property real bodyHeight: showList ? Math.min(maxBodyHeight, Math.max(84, (clipboardMode ? Math.min(list.contentHeight, clipboardRows) : list.contentHeight) + 46 + (launchError ? 22 : 0))) : showGrid ? Math.min(maxBodyHeight, grid.contentHeight + 46) : 0
// Emoji mode shows six rows of the grid; the rest scroll.
readonly property int emojiCell: 52
readonly property int emojiColumns: Math.max(1, Math.floor((targetWidth - 24) / emojiCell))
readonly property real emojiRows: 6 * emojiCell
readonly property real bodyHeight: emojiMode ? Math.min(maxBodyHeight, Math.max(84, Math.min(emojiGrid.contentHeight, emojiRows) + 42)) : showList ? Math.min(maxBodyHeight, Math.max(84, (clipboardMode ? Math.min(list.contentHeight, clipboardRows) : list.contentHeight) + 46 + (launchError ? 22 : 0))) : showGrid ? Math.min(maxBodyHeight, grid.contentHeight + 46) : 0
// Mode switches resize without animating, so >clipboard lands in place.
property bool snapping: false
Timer {
@@ -76,12 +96,16 @@ PanelWindow {
selectedIndex = 0;
list.contentY = 0;
grid.contentY = 0;
emojiGrid.contentY = 0;
emojiGrid.hovered = "";
}
function select(offset) {
if (!results.length)
return;
selectedIndex = Math.max(0, Math.min(results.length - 1, selectedIndex + offset));
if (showGrid)
if (emojiMode)
emojiGrid.positionViewAtIndex(selectedIndex, GridView.Contain);
else if (showGrid)
grid.positionViewAtIndex(selectedIndex, GridView.Contain);
else
list.positionViewAtIndex(selectedIndex, ListView.Contain);
@@ -93,6 +117,9 @@ PanelWindow {
if (result.clip) {
ClipboardService.copy(result.clip);
ShellState.launcherOpen = false;
} else if (result.glyph) {
EmojiService.copy(result.glyph);
ShellState.launcherOpen = false;
} else if (result.command) {
const command = CommandRegistry.commands.find(c => c.id === result.id);
if (!command || !command.stay)
@@ -104,7 +131,7 @@ PanelWindow {
launchError = ApplicationsService.error;
}
function toggleBrowse() {
if (clipboardMode) {
if (clipboardMode || emojiMode) {
ShellState.launcherMode = "apps";
return;
}
@@ -125,10 +152,14 @@ PanelWindow {
root.launchError = "";
root.selectedIndex = 0;
ClipboardService.refresh();
if (root.emojiMode)
EmojiService.load();
Qt.callLater(() => search.forceActiveFocus());
}
}
function onLauncherModeChanged() {
if (root.emojiMode)
EmojiService.load();
if (!ShellState.launcherOpen)
return;
root.snapping = true;
@@ -156,6 +187,75 @@ PanelWindow {
anchors.fill: parent
onClicked: ShellState.launcherOpen = false
}
// Mode pills beside the search bar (macOS Spotlight style): each toggles
// its launcher mode; the active one is filled.
Row {
id: pills
objectName: "launcherPills"
x: panel.x + panel.width + 10
y: panel.y + (root.barHeight - root.pillSize) / 2
spacing: 10
opacity: panel.opacity
scale: panel.scale
Repeater {
model: [
{
mode: "clipboard",
label: "Clipboard",
glyph: "󰅌",
fallback: "⎘"
},
{
mode: "emoji",
label: "Emoji",
glyph: "󰞅",
fallback: "☺"
}
]
GlassPanel {
id: pill
required property var modelData
readonly property bool active: ShellState.launcherMode === modelData.mode
objectName: "launcherPill-" + modelData.mode
width: root.pillSize
height: root.pillSize
radius: width / 2
color: active ? Theme.accent : Qt.alpha(Theme.surface, Math.min(1, surfaceOpacity + (pillArea.containsMouse ? 0.18 : 0)))
Accessible.role: Accessible.Button
Accessible.name: modelData.label
scale: pillArea.pressed ? 0.92 : 1
Behavior on scale {
NumberAnimation {
duration: Theme.duration / 2
easing.type: Easing.OutCubic
}
}
Text {
anchors.centerIn: parent
text: Icons.available ? pill.modelData.glyph : pill.modelData.fallback
font.family: Icons.available ? Icons.family : ""
font.pixelSize: 21
color: pill.active ? Theme.accentText : Theme.text
}
MouseArea {
id: pillArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onContainsMouseChanged: {
if (containsMouse)
root.pillHover = pill.modelData.label;
else if (root.pillHover === pill.modelData.label)
root.pillHover = "";
}
onClicked: {
ShellState.launcherMode = pill.active ? "apps" : pill.modelData.mode;
search.forceActiveFocus();
}
}
}
}
}
GlassPanel {
id: panel
objectName: "launcherSurface"
@@ -212,7 +312,7 @@ PanelWindow {
radius: 12
color: root.browsing ? Theme.accent : browseArea.containsMouse ? Theme.hover : Theme.transparent
Accessible.role: Accessible.Button
Accessible.name: root.clipboardMode ? "Back to search" : root.browsing ? "Hide applications" : "Show all applications"
Accessible.name: root.clipboardMode || root.emojiMode ? "Back to search" : root.browsing ? "Hide applications" : "Show all applications"
Behavior on color {
ColorAnimation {
duration: Theme.duration / 2
@@ -220,7 +320,7 @@ PanelWindow {
}
Text {
anchors.centerIn: parent
text: root.commandMode ? ">" : !Icons.available ? (root.clipboardMode ? "⎘" : "⌕") : root.clipboardMode ? "󰅌" : "󰍉"
text: root.commandMode ? ">" : !Icons.available ? (root.clipboardMode ? "⎘" : root.emojiMode ? "☺" : "⌕") : root.clipboardMode ? "󰅌" : root.emojiMode ? "󰇵" : "󰍉"
font.family: Icons.available && !root.commandMode ? Icons.family : ""
color: root.browsing ? Theme.accentText : Theme.textSecondary
font.pixelSize: 20
@@ -232,16 +332,18 @@ PanelWindow {
cursorShape: Qt.PointingHandCursor
onClicked: root.toggleBrowse()
}
ToolTip.visible: browseArea.containsMouse
ToolTip.delay: 600
ToolTip.text: root.clipboardMode ? "Back to search" : root.browsing ? "Hide applications" : "All applications"
GlassToolTip {
visible: browseArea.containsMouse
delay: 600
text: root.clipboardMode || root.emojiMode ? "Back to search" : root.browsing ? "Hide applications" : "All applications"
}
}
TextField {
id: search
objectName: "launcherSearch"
Layout.fillWidth: true
Layout.preferredHeight: 40
placeholderText: root.clipboardMode ? "Clipboard History" : root.browsing ? "Search applications" : "Search :3"
placeholderText: root.pillHover || (root.clipboardMode ? "Clipboard History" : root.emojiMode ? "Search emoji" : root.browsing ? "Search applications" : "Search :3")
color: Theme.text
placeholderTextColor: Theme.textSecondary
selectByMouse: true
@@ -260,20 +362,20 @@ PanelWindow {
ShellState.launcherOpen = false;
}
Keys.onDownPressed: {
if (!root.showList && !root.browsing)
if (!root.showList && !root.browsing && !root.emojiMode)
root.browsing = true;
else
root.select(root.showGrid ? root.gridColumns : 1);
root.select(root.columns);
}
Keys.onUpPressed: root.select(root.showGrid ? -root.gridColumns : -1)
Keys.onUpPressed: root.select(-root.columns)
Keys.onRightPressed: event => {
if (root.showGrid || event.modifiers & Qt.ControlModifier)
if (root.columns > 1 || event.modifiers & Qt.ControlModifier)
root.select(1);
else
event.accepted = false;
}
Keys.onLeftPressed: event => {
if (root.showGrid || event.modifiers & Qt.ControlModifier)
if (root.columns > 1 || event.modifiers & Qt.ControlModifier)
root.select(-1);
else
event.accepted = false;
@@ -312,7 +414,7 @@ PanelWindow {
id: section
x: 22
y: 12
text: root.clipboardMode ? (!root.results.length ? "" : root.query ? "Matches" : "Recent") : root.showGrid ? "Applications" : root.commandMode ? "Settings" : root.results.length ? "Top hits" : ""
text: root.emojiMode ? (emojiGrid.hovered || (root.results[root.selectedIndex] || {}).title || "") : root.clipboardMode ? (!root.results.length ? "" : root.query ? "Matches" : "Recent") : root.showGrid ? "Applications" : root.commandMode ? "Settings" : root.results.length ? "Top hits" : ""
color: Theme.textSecondary
font.pixelSize: 11
font.weight: Font.DemiBold
@@ -479,11 +581,66 @@ PanelWindow {
Accessible.onPressAction: root.activate(index)
}
}
GridView {
id: emojiGrid
objectName: "launcherEmoji"
// Name of the emoji under the pointer, shown instead of the selection's.
property string hovered: ""
visible: root.emojiMode
anchors.fill: parent
anchors.topMargin: 32
anchors.leftMargin: 12
anchors.rightMargin: 12
anchors.bottomMargin: 10
clip: true
model: root.emojiMode ? root.results : []
cellWidth: Math.floor(width / root.emojiColumns)
cellHeight: root.emojiCell
boundsBehavior: Flickable.StopAtBounds
ScrollBar.vertical: ScrollBar {}
delegate: Item {
id: glyph
required property var modelData
required property int index
readonly property bool selected: root.selectedIndex === index
width: emojiGrid.cellWidth
height: emojiGrid.cellHeight
Rectangle {
anchors.fill: parent
anchors.margins: 3
radius: 12
color: glyph.selected ? Qt.alpha(Theme.accent, 0.35) : glyphArea.containsMouse ? Theme.hover : Theme.transparent
border.width: glyph.selected ? 1 : 0
border.color: Theme.accentVivid
}
Text {
anchors.centerIn: parent
text: glyph.modelData.id
textFormat: Text.PlainText
font.pixelSize: 28
}
MouseArea {
id: glyphArea
anchors.fill: parent
hoverEnabled: true
onContainsMouseChanged: {
if (containsMouse)
emojiGrid.hovered = glyph.modelData.title;
else if (emojiGrid.hovered === glyph.modelData.title)
emojiGrid.hovered = "";
}
onClicked: root.activate(glyph.index)
}
Accessible.role: Accessible.Button
Accessible.name: modelData.title
Accessible.onPressAction: root.activate(index)
}
}
Text {
anchors.centerIn: parent
anchors.verticalCenterOffset: 12
visible: root.showList && root.results.length === 0
text: root.clipboardMode ? (ClipboardService.error || (root.query ? "No matches" : ClipboardService.loaded ? "Clipboard history is empty" : "Loading…")) : root.commandMode ? "No matching settings" : "No results"
visible: (root.showList || root.emojiMode) && root.results.length === 0
text: root.emojiMode ? (EmojiService.loaded ? "No matching emoji" : "Loading…") : root.clipboardMode ? (ClipboardService.error || (root.query ? "No matches" : ClipboardService.loaded ? "Clipboard history is empty" : "Loading…")) : root.commandMode ? "No matching settings" : "No results"
color: Theme.textSecondary
font.pixelSize: 13
}
+4
View File
@@ -22,6 +22,10 @@ Singleton {
function clipboard(): void {
ShellState.toggleClipboard();
}
// Opens the Emoji Picker, or closes it when it is showing.
function emoji(): void {
ShellState.toggleLauncherMode("emoji");
}
function status(): string {
return JSON.stringify({
opened: ShellState.launcherOpen,
+29 -1
View File
@@ -10,9 +10,37 @@ Singleton {
readonly property var source: backend.defaultAudioSource
readonly property var outputs: backend.nodes.values.filter(n => n.audio && n.isSink && !n.isStream)
readonly property var inputs: backend.nodes.values.filter(n => n.audio && !n.isSink && !n.isStream)
// App playback streams, e.g. the players EasyEffects processes. Quickshell
// marks playback streams (Stream/Output/Audio) as sinks.
readonly property var streams: backend.nodes.values.filter(n => n.audio && n.isStream && n.isSink)
readonly property bool available: backend.ready
// Views listing streams hold a Demand on this, so their volumes are only
// tracked while shown.
property int streamConsumers: 0
PwObjectTracker {
objects: root.backend === Pipewire ? [root.sink, root.source].filter(n => n !== null) : []
objects: root.backend === Pipewire ? [root.sink, root.source].filter(n => n !== null).concat(root.streamConsumers > 0 ? root.streams : []) : []
}
function streamName(node) {
const p = node && node.properties || {};
return p["application.name"] || node.description || p["media.name"] || node.name || "Unknown";
}
// Icon path: the stream's own icon name, else its app's desktop entry.
function streamIcon(node) {
const p = node && node.properties || {};
const named = p["application.icon-name"] ? Quickshell.iconPath(p["application.icon-name"], true) : "";
return named || ApplicationsService.icon(ApplicationsService.byId(p["application.process.binary"] || "") || ApplicationsService.byId(p["application.name"] || ""));
}
function streamVolume(node, value) {
if (!node || !node.audio || !Number.isFinite(value))
return false;
node.audio.volume = Math.max(0, Math.min(1, value));
return true;
}
function streamMute(node) {
if (!node || !node.audio)
return false;
node.audio.muted = !node.audio.muted;
return true;
}
function volume(input, value) {
const node = input ? source : sink;
+37
View File
@@ -0,0 +1,37 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
// Keeps the session awake while on: holds a systemd idle and sleep inhibitor,
// which hypridle and logind both honour. Off again after a shell restart.
Singleton {
id: root
property bool active: false
property var command: ["systemd-inhibit", "--what=idle:sleep", "--who=glassMxrph", "--why=Caffeine", "--mode=block", "sleep", "infinity"]
readonly property bool running: inhibitor.running
function toggle() {
active = !active;
return true;
}
Process {
id: inhibitor
command: root.command
running: root.active
// The inhibitor exiting on its own (logind refused it) turns the tile off.
onRunningChanged: if (!running && root.active)
root.active = false
}
IpcHandler {
target: "caffeine"
function toggle(): bool {
return root.toggle();
}
function status(): string {
return JSON.stringify({
active: root.active,
running: inhibitor.running
});
}
}
}
+21 -2
View File
@@ -87,9 +87,10 @@ function validate(c) {
if(typeof c.osd.enabled!=="boolean" || !["slide","drop","fade","shrink"].includes(c.osd.animation) || !["top-right","top-center","bottom-center"].includes(c.osd.position) || !Number.isInteger(c.osd.timeout) || c.osd.timeout<500 || c.osd.timeout>5000 || !Number.isInteger(c.osd.step) || c.osd.step<1 || c.osd.step>20)throw Error("Invalid OSD preferences");
const notes=c.notifications;
if(!notes || ["enabled","doNotDisturb","criticalInDnd"].some(k=>typeof notes[k]!=="boolean") || !["slide","drop","fade","shrink"].includes(notes.animation) || !["top-right","top-center"].includes(notes.position) || !Number.isInteger(notes.timeout) || notes.timeout<1000 || notes.timeout>30000 || !Number.isInteger(notes.maxPopups) || notes.maxPopups<1 || notes.maxPopups>6)throw Error("Invalid notification preferences");
if(c.controlCenter.version !== 1 || !Number.isFinite(c.controlCenter.width) || c.controlCenter.width < 320 || c.controlCenter.width > 600 || !Array.isArray(c.controlCenter.modules))throw Error("Invalid Control Center configuration");
if(c.controlCenter.version !== 2 || !Number.isFinite(c.controlCenter.width) || c.controlCenter.width < 320 || c.controlCenter.width > 600 || !Array.isArray(c.controlCenter.modules))throw Error("Invalid Control Center configuration");
if(!c.gameMode || ["effects","doNotDisturb","performance"].some(k=>typeof c.gameMode[k]!=="boolean"))throw Error("Invalid Game Mode preferences");
const controlIds=new Set();
for(const m of c.controlCenter.modules) { if(!m || typeof m.id!=="string" || controlIds.has(m.id) || typeof m.enabled!=="boolean")throw Error("Invalid Control Center module"); controlIds.add(m.id); }
for(const m of c.controlCenter.modules) { if(!m || typeof m.id!=="string" || controlIds.has(m.id) || typeof m.enabled!=="boolean" || ["w","h"].some(k=>m[k]!==undefined && (!Number.isInteger(m[k]) || m[k]<1 || m[k]>4)) || [["x",3],["y",63]].some(([k,max])=>m[k]!==undefined && (!Number.isInteger(m[k]) || m[k]<0 || m[k]>max)))throw Error("Invalid Control Center module"); controlIds.add(m.id); }
for(const group of [c.system.brightness,c.system.nightLight]) for(const key of ["statusCommand","setCommand"])if(!Array.isArray(group[key]) || group[key].some(v=>typeof v!=="string" || !v.length))throw Error("Provider command must be an argument array");
if(typeof c.system.brightness.device!=="string" || !c.system.brightness.device || !Number.isInteger(c.system.nightLight.temperature) || c.system.nightLight.temperature<1000 || c.system.nightLight.temperature>6500 || !Array.isArray(c.system.power.lockCommand) || c.system.power.lockCommand.some(v=>typeof v!=="string" || !v.length))throw Error("Invalid system provider settings");
if(!Number.isInteger(c.metrics.interval) || c.metrics.interval<1 || c.metrics.interval>30)throw Error("Invalid metrics geometry or interval");
@@ -123,6 +124,24 @@ function load(defaults, user) {
migrated.controlCenter.modules = defaults.controlCenter.modules;
migrated.controlCenter.version = 1;
}
// Version 2 lays modules on a grid: the combined Connectivity and Audio
// cards split into their own tiles, in place, and Caffeine is offered.
if (migrated.controlCenter.version === 1 && Array.isArray(migrated.controlCenter.modules)) {
const parts = {connectivity: ["wifi", "bluetooth", "network"], audio: ["output", "input"]};
const old = migrated.controlCenter.modules, modules = [];
for (const m of old) {
if (!m || !parts[m.id]) {
modules.push(m);
continue;
}
for (const id of parts[m.id])
if (!old.some(o => o && o.id === id) && !modules.some(o => o && o.id === id))
modules.push({id: id, enabled: m.enabled});
}
if (old.length && !modules.some(m => m && m.id === "caffeine"))
modules.push({id: "caffeine", enabled: true});
migrated.controlCenter = Object.assign({}, migrated.controlCenter, {version: 2, modules: modules});
}
migrated.schemaVersion = 3;
return validate(merge(defaults, migrated));
}
+55
View File
@@ -0,0 +1,55 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
// Emoji for the launcher's emoji mode, from assets/emoji.tsv (scripts/emoji-data).
// The list is read the first time emoji mode opens and kept for the session.
Singleton {
id: root
// Unicode order: {emoji, name, keywords} with lower-case search text.
property var entries: []
property bool loaded: false
function load() {
if (!file.path)
file.path = Qt.resolvedUrl("../assets/emoji.tsv").toString().replace("file://", "");
}
// Space-separated terms, all required. Name matches come before keyword
// matches; Unicode order is kept within each.
function filter(query) {
const terms = query.toLowerCase().split(/\s+/).filter(t => t);
if (!terms.length)
return entries;
const named = [], tagged = [];
for (const e of entries) {
if (!terms.every(t => e.search.includes(t)))
continue;
(terms.every(t => e.lowerName.includes(t)) ? named : tagged).push(e);
}
return named.concat(tagged);
}
function copy(entry) {
if (!entry)
return false;
Quickshell.execDetached(["wl-copy", "--", entry.emoji]);
return true;
}
FileView {
id: file
onLoaded: {
root.entries = text().split("\n").filter(line => line).map(line => {
const [emoji, name, keywords] = line.split("\t");
const lowerName = name.toLowerCase();
return {
emoji: emoji,
name: name,
lowerName: lowerName,
search: lowerName + " " + (keywords || "")
};
});
root.loaded = true;
}
}
}
+81
View File
@@ -0,0 +1,81 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
// Game Mode: compositor effects off, performance power profile and Do Not
// Disturb while gaming, switched by hand. The helper journals what it changed,
// so effects and the profile come back even after a shell crash.
Singleton {
id: root
property string helper: "helpers/gamemode.py"
property bool active: false
property string error: ""
readonly property var options: ConfigService.ready ? ConfigService.data.gameMode : ({
effects: true,
doNotDisturb: true,
performance: true
})
// What is applied right now, and the DND state to put back.
property bool applied: false
property var restoreDnd: null
function toggle() {
active = !active;
return true;
}
// Debounced, so quick double clicks settle on the last state.
onActiveChanged: sync.restart()
Timer {
id: sync
interval: 250
onTriggered: root.apply()
}
function apply() {
if (root.active === root.applied)
return;
if (job.running) {
sync.restart();
return;
}
applied = active;
job.start({
action: active ? "on" : "off",
effects: options.effects,
performance: options.performance
});
if (active && options.doNotDisturb && NotificationService.active && !NotificationService.dnd) {
restoreDnd = false;
NotificationService.setDnd(true);
} else if (!active && restoreDnd !== null) {
NotificationService.setDnd(restoreDnd);
restoreDnd = null;
}
}
// A crash while on left effects off: put back what the journal holds.
Component.onCompleted: job.start({
action: "off"
})
ProviderJob {
id: job
helper: root.helper
onFinished: (request, result) => {
root.error = result.ok ? "" : result.error || "Game Mode request failed";
// A change while the request ran is applied now.
if (root.active !== root.applied)
sync.restart();
}
}
IpcHandler {
target: "gamemode"
function toggle(): bool {
return root.toggle();
}
function status(): string {
return JSON.stringify({
active: root.active,
applied: root.applied,
error: root.error
});
}
}
}
+2 -2
View File
@@ -44,7 +44,7 @@ Singleton {
if (window.handle)
window.handle.activate();
else if (/^(0x)?[0-9a-f]+$/i.test(address))
Hyprland.dispatch("focuswindow address:" + (address.startsWith("0x") ? address : "0x" + address));
Hyprland.dispatch("hl.dsp.focus({ window = 'address:" + (address.startsWith("0x") ? address : "0x" + address) + "' })");
else
return false;
return true;
@@ -56,7 +56,7 @@ Singleton {
if (window.handle)
window.handle.close();
else if (/^(0x)?[0-9a-f]+$/i.test(address))
Hyprland.dispatch("closewindow address:" + (address.startsWith("0x") ? address : "0x" + address));
Hyprland.dispatch("hl.dsp.window.close({ window = 'address:" + (address.startsWith("0x") ? address : "0x" + address) + "' })");
else
return false;
return true;
+2
View File
@@ -60,6 +60,8 @@ Singleton {
}
// Enabled plugins offering a bar widget, as bar module ids.
readonly property var barModules: plugins.filter(p => isEnabled(p.id) && kinds(p.id).includes("bar-widget")).map(p => "plugin:" + p.id)
// Enabled plugins offering a Control Center widget, as Control Center module ids.
readonly property var controlModules: plugins.filter(p => isEnabled(p.id) && kinds(p.id).includes("control-center-widget")).map(p => "plugin:" + p.id)
function schema(id) {
const p = plugin(id);
if (p && p.ecosystem === "noctalia")
+3
View File
@@ -18,3 +18,6 @@ singleton EasyEffectsService 1.0 EasyEffectsService.qml
singleton PluginService 1.0 PluginService.qml
singleton NotificationService 1.0 NotificationService.qml
singleton ClipboardService 1.0 ClipboardService.qml
singleton EmojiService 1.0 EmojiService.qml
singleton CaffeineService 1.0 CaffeineService.qml
singleton GameModeService 1.0 GameModeService.qml
+5 -4
View File
@@ -1,7 +1,6 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import "../../components"
import "../../core"
import "../../services"
@@ -209,9 +208,11 @@ Item {
spacing:8
Text {text:optionRow.modelData.label;color:Theme.textSecondary;font.pixelSize:11;Layout.fillWidth:true;elide:Text.ElideRight
HoverHandler {id:labelHover}
ToolTip.visible:labelHover.hovered && !!optionRow.modelData.description
ToolTip.text:optionRow.modelData.description || ""
ToolTip.delay:600}
GlassToolTip {
visible: labelHover.hovered && !!optionRow.modelData.description
delay: 600
text: optionRow.modelData.description || ""
}}
GlassComboBox {
objectName:"bar-option-"+card.modelData.id+"-"+optionRow.modelData.key
visible:optionRow.modelData.type==="choice"
+5 -4
View File
@@ -1,5 +1,4 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "../../components"
import "../../core"
@@ -144,9 +143,11 @@ Item {
}
Rectangle {
objectName: "reset-" + root.setting
ToolTip.visible: resetArea.containsMouse
ToolTip.delay: 500
ToolTip.text: "Reset to default"
GlassToolTip {
visible: resetArea.containsMouse
delay: 500
text: "Reset to default"
}
visible: root.modified
implicitWidth: 26
implicitHeight: 26
+5 -4
View File
@@ -1,6 +1,5 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "../controls"
import "../../components"
@@ -185,9 +184,11 @@ ColumnLayout {
color: modelData.value
border.width: selected ? 2 : 1
border.color: selected ? Theme.accent : Theme.border
ToolTip.visible: swatchArea.containsMouse
ToolTip.delay: 400
ToolTip.text: modelData.name
GlassToolTip {
visible: swatchArea.containsMouse
delay: 400
text: swatch.modelData.name
}
MouseArea {
id: swatchArea
anchors.fill: parent
+4 -4
View File
@@ -86,7 +86,7 @@ SettingsPage {
}
SettingsSection {
title: "Modules"
description: "Drag modules to reorder them; the switch shows or hides each card"
description: "The switch shows or hides each module. Move and resize tiles from Edit Controls in the Control Center; order here only decides where new tiles go"
ColumnLayout {
id: rows
objectName: "controlModuleList"
@@ -117,7 +117,7 @@ SettingsPage {
y: card.offset
scale: card.lifted ? 1.02 : 1
opacity: card.lifted ? 0.9 : 1
title: card.entry ? card.entry.title : card.modelData.id + " (unavailable)"
title: !card.entry ? card.modelData.id + " (unavailable)" : card.entry.section ? card.entry.title : card.entry.title + " · " + ControlRegistry.size(card.modelData).w + "×" + ControlRegistry.size(card.modelData).h
icon: "󰇙"
Behavior on scale {
NumberAnimation {
@@ -180,10 +180,10 @@ SettingsPage {
visible: addRepeater.count > 0
Repeater {
id: addRepeater
model: Object.keys(ControlRegistry.modules).filter(id => !ConfigService.data.controlCenter.modules.some(m => m.id === id))
model: ControlRegistry.ids.filter(id => !ConfigService.data.controlCenter.modules.some(m => m.id === id))
GlassButton {
required property string modelData
text: "+ " + ControlRegistry.modules[modelData].title
text: "+ " + ControlRegistry.entry(modelData).title
onClicked: ConfigService.setValue("controlCenter.modules", ConfigService.data.controlCenter.modules.concat([
{
id: modelData,
+1 -7
View File
@@ -27,18 +27,12 @@ SettingsPage {
}
SettingsSection {
title: "Dashboard"
description: "A tabbed glass panel below the bar. Open it from the clock, with “glassmxrph dashboard [tab]”, or bind that to a key. ←/→, Tab and 1–4 switch tabs."
description: "A tabbed glass panel below the bar. Open it with “glassmxrph dashboard [tab]”, or bind that to a key. ←/→, Tab and 1–4 switch tabs."
PreferenceToggle {
label: "Enable dashboard"
icon: "󰕮"
setting: "dashboard.enabled"
}
PreferenceToggle {
label: "Open from clock"
description: "Click the bar clock to toggle it"
icon: "󰥔"
setting: "dashboard.openFromClock"
}
PreferenceToggle {
label: "Remember last tab"
description: "Otherwise it opens on the first tab"
+25
View File
@@ -11,6 +11,31 @@ SettingsPage {
Modules.Profiles {
Layout.fillWidth: true
}
SettingsSection {
title: "Game Mode"
description: "What the Control Center's Game Mode tile changes while it is on"
PreferenceToggle {
label: "Turn off animations, blur, shadows and glass"
icon: "󰂵"
setting: "gameMode.effects"
}
PreferenceToggle {
label: "Performance power profile"
description: "Back to the previous profile afterwards"
icon: "󰓅"
setting: "gameMode.performance"
}
PreferenceToggle {
label: "Do Not Disturb"
description: "Built-in notifications only"
icon: "󰽥"
setting: "gameMode.doNotDisturb"
}
}
SettingNote {
warning: true
text: GameModeService.error
}
SettingsSection {
title: "Lock screen"
padded: true
+71 -1
View File
@@ -35,6 +35,32 @@ Item {
property bool muted: false
}
}
property var streamNode: QtObject {
property string name: "fixture-player"
property string description: ""
property bool isSink: true
property bool isStream: true
property var properties: ({
"application.name": "Fixture player"
})
property QtObject audio: QtObject {
property real volume: 0.5
property bool muted: false
}
}
property var recordingNode: QtObject {
property string name: "fixture-recorder"
property string description: ""
property bool isSink: false
property bool isStream: true
property var properties: ({
"application.name": "Fixture recorder"
})
property QtObject audio: QtObject {
property real volume: 1
property bool muted: false
}
}
property QtObject audioBackend: QtObject {
property bool ready: true
property var defaultAudioSink: root.audioNode
@@ -42,7 +68,7 @@ Item {
property var preferredDefaultAudioSink: root.audioNode
property var preferredDefaultAudioSource: root.audioInput
property QtObject nodes: QtObject {
property var values: [root.audioNode, root.audioInput]
property var values: [root.audioNode, root.audioInput, root.streamNode, root.recordingNode]
}
}
property QtObject wifi: QtObject {
@@ -139,6 +165,8 @@ Item {
NetworkService.backend = root.networkBackend;
BluetoothService.backend = root.btBackend;
SystemService.helper = "testing/recording_system.py";
CaffeineService.command = ["sleep", "infinity"];
GameModeService.helper = "testing/recording_gamemode.py";
SystemService.refresh();
return true;
}
@@ -158,6 +186,32 @@ Item {
input.mouseClick(item, item.width * .75, item.height / 2);
return true;
}
function rightClick(name: string): bool {
const item = root.child(name);
if (!item || !item.enabled)
return false;
root.reveal(item);
// Near the corner: clear of sliders and buttons on every layout.
input.mouseClick(item, 14, 14, Qt.RightButton);
return true;
}
// Presses an item and drags it by (dx, dy) in steps.
function drag(name: string, dx: real, dy: real): bool {
const item = root.child(name);
if (!item || !item.visible)
return false;
root.reveal(item);
// Window coordinates, like a real pointer: the item may move or grow.
const content = ShellState.controlCenterWindow.contentItem;
const p = item.mapToItem(content, item.width / 2, item.height / 2);
input.mousePress(content, p.x, p.y);
for (let i = 1; i <= 8; ++i)
input.mouseMove(content, p.x + dx * i / 8, p.y + dy * i / 8, 20);
input.wait(60);
input.mouseRelease(content, p.x + dx, p.y + dy);
input.wait(60);
return true;
}
function clickSystem(): bool {
const pill = ShellState.systemPills.find(p => p.barScreen === ScreenService.active) || ShellState.systemPills[0];
if (!pill)
@@ -189,6 +243,11 @@ Item {
input.mouseClick(item, item.width / 2, item.height / 2);
return true;
}
// A property of a named item, as JSON (plugin fixtures).
function itemValue(name: string, key: string): string {
const item = root.child(name);
return item ? JSON.stringify(item[key]) : "";
}
function value(name: string): real {
const item = root.child(name);
return item ? item.value : -1;
@@ -226,6 +285,17 @@ Item {
muted: AudioService.sink && AudioService.sink.audio ? AudioService.sink.audio.muted : false,
microphone: AudioService.source && AudioService.source.audio ? AudioService.source.audio.muted : false,
scan: fixtureWifi.scannerEnabled,
editing: ShellState.controlCenterWindow.editing,
tiles: ShellState.controlCenterWindow.plan.items,
cellWidth: ShellState.controlCenterWindow.cellWidth,
extras: ShellState.controlCenterWindow.extras,
streamVolume: root.streamNode.audio.volume,
streams: AudioService.streams.map(n => AudioService.streamName(n)),
streamMuted: root.streamNode.audio.muted,
caffeine: CaffeineService.active,
gameMode: GameModeService.active,
gameModeApplied: GameModeService.applied,
caffeineRunning: CaffeineService.running,
active: ScreenService.active.name,
screens: Quickshell.screens.map(s => s.name),
x: ShellState.controlCenterWindow.panelScreenX,
+13 -1
View File
@@ -56,7 +56,9 @@ Item {
query: root.search().text,
focused: root.search().activeFocus,
selected: w.selectedIndex,
results: w.results.map(r => ({
// IPC replies have a size limit; the emoji grid holds ~1900 results.
resultCount: w.results.length,
results: w.results.slice(0, 200).map(r => ({
id: r.id,
title: r.title,
command: !!r.command,
@@ -90,9 +92,19 @@ Item {
function browse(): void {
LauncherState.window.toggleBrowse();
}
function pill(mode: string): bool {
const item = input.findChild(LauncherState.window.contentItem, "launcherPill-" + mode);
if (!item || !item.visible)
return false;
input.mouseClick(item, item.width / 2, item.height / 2);
return true;
}
function screenshot(path: string): bool {
return input.findChild(LauncherState.window.contentItem, "launcherSurface").grabToImage(result => result.saveToFile(path));
}
function pillsShot(path: string): bool {
return input.findChild(LauncherState.window.contentItem, "launcherPills").grabToImage(result => result.saveToFile(path));
}
function extension(add: bool): bool {
if (!add) {
CommandRegistry.unregisterCommand("fixture");
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env python3
"""Test-only Game Mode adapter. Records requests; never calls hyprctl or D-Bus."""
import json,os,sys
from pathlib import Path
base=Path(os.environ['GLASSMXRPH_SYSTEM_EVENTS']).with_suffix('.gamemode')
req=json.loads(sys.argv[1])
with base.open('a') as f:f.write(json.dumps(req)+'\n')
print(json.dumps({'ok':True,'active':req.get('action')=='on'}))
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
"""Regenerates quickshell/assets/emoji.tsv for the launcher's Emoji Picker.
Usage: scripts/emoji-data EMOJI_TEST_TXT [KEYWORDS] > quickshell/assets/emoji.tsv
EMOJI_TEST_TXT is Unicode's emoji-test.txt (nixpkgs#unicode-emoji). KEYWORDS is an
optional "<emoji> <name and keywords>" list such as the rofi emopicker's ~/.config/.emoji.
Output: emoji, name, search keywords; tab-separated, in Unicode order, skin tones omitted."""
import re
import sys
LINE = re.compile(r'^([0-9A-F ]+?)\s*; fully-qualified\s*# (\S+) E[\d.]+ (.+)$')
TONES = {0x1F3FB, 0x1F3FC, 0x1F3FD, 0x1F3FE, 0x1F3FF}
extra = {}
if len(sys.argv) > 2:
for line in open(sys.argv[2], encoding='utf-8'):
emoji, _, words = line.strip().partition(' ')
extra[emoji.replace('️', '')] = words.lower().split()
subgroup = ''
for line in open(sys.argv[1], encoding='utf-8'):
if line.startswith('# subgroup:'):
subgroup = line.split(':', 1)[1].strip()
continue
match = LINE.match(line.strip())
if not match or TONES & {int(c, 16) for c in match[1].split()}:
continue
emoji, name = match[2], match[3].replace('\t', ' ')
seen = set(re.split(r'[\s:,]+', name.lower()))
words = []
for word in extra.get(emoji.replace('️', ''), []) + subgroup.split('-'):
if word not in seen:
seen.add(word)
words.append(word)
print(f'{emoji}\t{name}\t{" ".join(words)}')
+3 -3
View File
@@ -31,8 +31,8 @@ case "${1:-run}" in
launcher)
exec quickshell ipc --path "$project_dir/quickshell" call launcher toggle
;;
clipboard)
exec quickshell ipc --path "$project_dir/quickshell" call launcher clipboard
clipboard|emoji)
exec quickshell ipc --path "$project_dir/quickshell" call launcher "$1"
;;
plugin)
# glassmxrph plugin [list|install SOURCE|remove ID|enable ID|disable ID|summon ID|toggle ID]
@@ -70,5 +70,5 @@ case "${1:-run}" in
settings|close|status)
exec quickshell ipc --path "$project_dir/quickshell" call shell "$1"
;;
*) echo 'Usage: glassmxrph [run|wallpaper|launcher|clipboard|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|notifications ACTION|settings|close|status|doctor]' >&2; exit 2 ;;
*) echo 'Usage: glassmxrph [run|wallpaper|launcher|clipboard|emoji|dashboard [TAB]|plugin ACTION|controlcenter|lock|widgets|osd ACTION|notifications ACTION|settings|close|status|doctor]' >&2; exit 2 ;;
esac
+2
View File
@@ -6,10 +6,12 @@ node "$project_dir/tests/polish.test.cjs"
node "$project_dir/tests/dock.test.cjs"
node "$project_dir/tests/launcher.test.cjs"
node "$project_dir/tests/widgets.test.cjs"
node "$project_dir/tests/controlcenter.test.cjs"
python3 "$project_dir/tests/providers_test.py"
python3 "$project_dir/tests/system_providers_test.py"
python3 "$project_dir/tests/metrics_test.py"
python3 "$project_dir/tests/glass_test.py"
python3 "$project_dir/tests/gamemode_test.py"
python3 "$project_dir/tests/clipboard_test.py"
# compat/ holds vendored third-party UI kits (qs.compat.* imports qmllint cannot
# resolve); they are exercised by the plugin runtime test instead.
+11 -3
View File
@@ -70,11 +70,17 @@ console.log('Phase 5 preference merging, validation and immutable bar editing/re
assert.throws(() => api.update(phase5, 'bar.modules', {}), /must be an array/);
assert.equal(api.update(phase5, 'bar.modules', [{id:'nowPlaying',position:'right',enabled:true}]).bar.modules[0].id, 'nowPlaying');
const phase7=api.load(defaults,{schemaVersion:3,controlCenter:{modules:[]},dock:{pinnedApps:['keep.desktop']},future:{keep:true}});
assert.equal(phase7.controlCenter.version,1);assert(phase7.controlCenter.modules.length>0);assert.equal(phase7.dock.pinnedApps[0],'keep.desktop');assert(phase7.future.keep);
assert.equal(phase7.controlCenter.version,2);assert(phase7.controlCenter.modules.length>0);assert.equal(phase7.dock.pinnedApps[0],'keep.desktop');assert(phase7.future.keep);
assert.equal(api.load(defaults,{controlCenter:{version:1,modules:[]}}).controlCenter.modules.length,0);
const customCenter=api.load(defaults,{controlCenter:{modules:[{id:'custom',enabled:false,metadata:'preserved'}]}});
assert.equal(customCenter.controlCenter.modules[0].metadata,'preserved');assert.equal(customCenter.controlCenter.modules.length,1);
for(const controlCenter of [{version:2},{version:1,width:100},{version:1,modules:[{id:'audio',enabled:true},{id:'audio',enabled:false}]}])assert.throws(()=>api.load(defaults,{controlCenter}));
assert.equal(customCenter.controlCenter.modules[0].metadata,'preserved');assert.equal(customCenter.controlCenter.modules.map(m=>m.id).join(),'custom,caffeine');
for(const controlCenter of [{version:3},{version:1,width:100},{version:2,modules:[{id:'output',enabled:true},{id:'output',enabled:false}]},{version:2,modules:[{id:'wifi',enabled:true,w:5}]},{version:2,modules:[{id:'wifi',enabled:true,h:0}]},{version:2,modules:[{id:'wifi',enabled:true,w:1.5}]},{version:2,modules:[{id:'wifi',enabled:true,x:4}]},{version:2,modules:[{id:'wifi',enabled:true,y:-1}]},{version:2,modules:[{id:'wifi',enabled:true,y:64}]}])assert.throws(()=>api.load(defaults,{controlCenter}));
// Version 1 splits the combined cards in place, keeps enabled state and offers Caffeine.
const v1=api.load(defaults,{controlCenter:{version:1,modules:[{id:'connectivity',enabled:true},{id:'media',enabled:true},{id:'audio',enabled:false},{id:'notifications',enabled:true}]}}).controlCenter;
assert.equal(v1.version,2);assert.equal(v1.modules.map(m=>m.id+':'+m.enabled).join(),'wifi:true,bluetooth:true,network:true,media:true,output:false,input:false,notifications:true,caffeine:true');
assert.equal(JSON.stringify(api.load(defaults,{controlCenter:{version:2,modules:[{id:'wifi',enabled:true,w:4,h:1}]}}).controlCenter.modules),'[{"id":"wifi","enabled":true,"w":4,"h":1}]');
assert.equal(api.load(defaults,{controlCenter:{version:2,modules:[]}}).controlCenter.modules.length,0);
assert.equal(api.load(defaults,{controlCenter:{version:2,modules:[{id:'wifi',enabled:true,x:3,y:63}]}}).controlCenter.modules[0].y,63);
for(const system of [{brightness:{setCommand:'sh -c'}},{nightLight:{temperature:0}},{power:{lockCommand:['']}}])assert.throws(()=>api.load(defaults,{system}));
console.log('Phase 7 one-time module migration, intentional empty layouts, provider validation and preservation passed.');
@@ -98,3 +104,5 @@ assert.equal(settings.dropModule(modules,'a','right','').find(m=>m.id==='a').cus
assert.throws(()=>api.load(defaults,{hyprglass:{values:{blur_iterations:2.5}}}));
assert.throws(()=>api.load(defaults,{hyprglass:{values:{refraction_strength:99}}}));
console.log('Drag/drop preserves module options and validates global glass preferences.');
assert.equal(loaded.gameMode.effects,true);assert.equal(api.update(loaded,'gameMode.performance',false).gameMode.performance,false);for(const v of ['yes',1,null])assert.throws(()=>api.update(loaded,'gameMode.effects',v),/Game Mode/);
console.log('Game Mode preferences validate.');
+59
View File
@@ -0,0 +1,59 @@
const assert = require('assert'), fs = require('fs'), path = require('path'), vm = require('vm');
const api = vm.createContext({});
vm.runInContext(fs.readFileSync(path.join(__dirname, '../quickshell/controlcenter/GridLogic.js'), 'utf8'), api);
const show = plan => plan.items.map(i => i.id + '@' + i.col + ',' + i.row + ':' + i.w + 'x' + i.h).join(' ');
const at = (plan, col, row) => (plan.items.find(i => col >= i.col && col < i.col + i.w && row >= i.row && row < i.row + i.h) || {}).id;
// Without positions: first free spot in order, so small tiles backfill gaps.
let plan = api.layout([{id: 'wifi', w: 2, h: 1}, {id: 'media', w: 2, h: 2}, {id: 'bt', w: 1, h: 1}, {id: 'dnd', w: 1, h: 1}, {id: 'sound', w: 4, h: 1}]);
assert.equal(show(plan), 'wifi@0,0:2x1 media@2,0:2x2 bt@0,1:1x1 dnd@1,1:1x1 sound@0,2:4x1');
assert.equal(plan.rows, 3);
assert.equal(show(api.layout([{id: 'x', w: 9, h: 0}, {id: 'y', w: 1.4, h: 4.6}])), 'x@0,0:4x1 y@0,1:1x4');
assert.equal(api.layout([]).rows, 0);
// Positions are kept, gaps included; unpositioned tiles fill free spots.
plan = api.layout([{id: 'a', w: 1, h: 1, x: 3, y: 2}, {id: 'b', w: 2, h: 1, x: 0, y: 0}, {id: 'c', w: 1, h: 1}]);
assert.equal(show(plan), 'a@3,2:1x1 b@0,0:2x1 c@2,0:1x1');
assert.equal(plan.rows, 3);
assert.equal(at(plan, 0, 1), undefined);
// Overlapping saved positions: the earlier entry wins, the later one moves down.
assert.equal(show(api.layout([{id: 'a', w: 2, h: 2, x: 0, y: 0}, {id: 'b', w: 1, h: 1, x: 1, y: 1}])), 'a@0,0:2x2 b@1,2:1x1');
// Positions clamp inside the grid.
assert.equal(show(api.layout([{id: 'a', w: 3, h: 1, x: 3, y: -2}])), 'a@1,0:3x1');
// A free spot for a new tile.
plan = api.layout([{id: 'a', w: 4, h: 1, x: 0, y: 0}, {id: 'b', w: 1, h: 1, x: 0, y: 1}]);
assert.equal(JSON.stringify(api.freeSpot(plan, 2, 1)), '{"id":"\\u0000new","col":1,"row":1,"w":2,"h":1}');
// Moving into empty space leaves the old spot empty.
plan = api.layout([{id: 'wifi', w: 2, h: 1}, {id: 'bt', w: 1, h: 1}, {id: 'sound', w: 4, h: 1}]);
let moved = api.moveTo(plan, 'bt', {col: 3, row: 3});
assert.equal(show(moved), 'wifi@0,0:2x1 bt@3,3:1x1 sound@0,1:4x1');
assert.equal(at(moved, 2, 0), undefined);
assert.equal(moved.rows, 4);
assert.equal(show(plan), 'wifi@0,0:2x1 bt@2,0:1x1 sound@0,1:4x1', 'moveTo leaves the input plan alone');
// Landing on tiles pushes them straight down, cascading; nothing moves up.
moved = api.moveTo(plan, 'bt', {col: 0, row: 0});
assert.equal(show(moved), 'wifi@0,1:2x1 bt@0,0:1x1 sound@0,2:4x1');
// Resizing pushes the same way.
moved = api.moveTo(plan, 'wifi', {w: 3, h: 2});
assert.equal(show(moved), 'wifi@0,0:3x2 bt@2,2:1x1 sound@0,3:4x1');
// A tile pushed onto the moved one goes below it instead.
plan = api.layout([{id: 'tall', w: 1, h: 3, x: 0, y: 0}, {id: 'top', w: 2, h: 1, x: 1, y: 0}]);
moved = api.moveTo(plan, 'top', {col: 0, row: 1});
assert.equal(show(moved), 'tall@0,2:1x3 top@0,1:2x1');
// Moves clamp to the grid.
assert.equal(show(api.moveTo(plan, 'top', {col: 9, row: -4})), 'tall@0,0:1x3 top@2,0:2x1');
// Pixel corner to the nearest cell; resizing rounds to whole cells within 1..4.
assert.equal(JSON.stringify(api.cellAt(130, 40, 80, 68, 10)), '{"col":1,"row":1}');
assert.equal(JSON.stringify(api.resize({w: 1, h: 1}, 50, 0, 80, 68, 10)), '{"w":2,"h":1}');
assert.equal(JSON.stringify(api.resize({w: 2, h: 2}, -30, 400, 80, 68, 10)), '{"w":2,"h":4}');
assert.equal(JSON.stringify(api.resize({w: 1, h: 1}, -500, -500, 80, 68, 10)), '{"w":1,"h":1}');
// Geometry: an expanded tile pushes down everything from its bottom row.
plan = api.layout([{id: 'out', w: 2, h: 1}, {id: 'media', w: 2, h: 2}, {id: 'a', w: 1, h: 1}, {id: 'b', w: 4, h: 1}]);
let g = api.geometry(plan, 80, 68, 10);
assert.equal(JSON.stringify(g.tiles.media), '{"x":180,"y":0,"w":170,"h":146}');
assert.equal(g.height, 3 * 78 - 10);
g = api.geometry(plan, 80, 68, 10, {out: 100});
assert.equal(g.tiles.out.h, 68 + 110);
assert.equal(g.tiles.media.y, 0);
assert.equal(g.tiles.a.y, 78 + 110);
assert.equal(g.tiles.b.y, 156 + 110);
assert.equal(g.height, 3 * 78 - 10 + 110);
console.log('Control Center free placement, push-down moves and resizes, free spots and expansion geometry passed.');
+74 -8
View File
@@ -22,9 +22,13 @@ log=ROOT/'.cache/controlcenter-runtime.log';log.parent.mkdir(exist_ok=True)
monitors=json.loads(subprocess.check_output(['hyprctl','monitors','-j'],text=True));original=next((m['name'] for m in monitors if m['focused']),None)
with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
events=Path(tmp)/'events';cfg=Path(tmp)/'config/glassMxrph/config.json';cfg.parent.mkdir(parents=True)
# A Noctalia-style plugin offering a Control Center widget.
fixture=Path(tmp)/'data/glassMxrph/plugins/cc-fixture';fixture.mkdir(parents=True)
(fixture/'manifest.json').write_text(json.dumps({'id':'cc-fixture','name':'CC Fixture','version':'1.0.0','minNoctaliaVersion':'3.6.0','author':'tests','description':'Control Center widget fixture','entryPoints':{'controlCenterWidget':'ControlCenterWidget.qml'}}))
(fixture/'ControlCenterWidget.qml').write_text('import QtQuick\nItem {\n property var pluginApi: null\n property var screen: null\n property int clicks: 0\n property string tooltipText: "Fixture hint"\n objectName: "fixtureCcButton"\n implicitWidth: 30\n implicitHeight: 30\n MouseArea { anchors.fill: parent; onClicked: parent.clicks++ }\n}\n')
# The user's live shell owns the notification bus name; a second server would warn.
cfg.write_text(json.dumps({'schemaVersion':3,'media':{'enabled':False},'dock':{'enabled':False},'notifications':{'enabled':False}}))
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_CONTROL_TESTING='1',GLASSMXRPH_SYSTEM_EVENTS=str(events),QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
cfg.write_text(json.dumps({'schemaVersion':3,'media':{'enabled':False},'dock':{'enabled':False},'notifications':{'enabled':False},'plugins':{'enabled':['cc-fixture']}}))
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_DATA_HOME=tmp+'/data',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_CONTROL_TESTING='1',GLASSMXRPH_SYSTEM_EVENTS=str(events),QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
with log.open('w') as output:
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT)
try:
@@ -41,6 +45,23 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
assert ipc('controlTest','click','volumeMute');wait(lambda:state()['muted'],'mute click')
assert ipc('controlTest','slider','volumeSlider');wait(lambda:state()['volume']>.6,'volume slider')
assert ipc('controlTest','click','microphoneMute');wait(lambda:state()['microphone'],'microphone click')
# Per-app volume: right click extends Sound with the app streams.
assert ipc('controlTest','rightClick','outputTile');wait(lambda:state()['extras'].get('output',0)>0,'Sound extends')
time.sleep(.4)
assert state()['streams']==['Fixture player'],'only playback streams are listed: '+str(state()['streams'])
t=next(i for i in state()['tiles'] if i['id']=='input');assert t['row']>0
assert ipc('controlTest','slider','appSlider-Fixture player');wait(lambda:state()['streamVolume']>.6,'app volume slider')
assert ipc('controlTest','click','appMute-Fixture player');wait(lambda:state()['streamMuted'],'app mute')
assert ipc('controlTest','rightClick','outputTile');wait(lambda:not state()['extras'].get('output',0),'Sound folds back')
assert ipc('controlTest','click','caffeineToggle');wait(lambda:state()['caffeine'] and state()['caffeineRunning'],'Caffeine on')
assert ipc('controlTest','click','caffeineToggle');wait(lambda:not state()['caffeine'] and not state()['caffeineRunning'],'Caffeine off')
# Game Mode runs its helper on and off (recorded, never the real compositor).
gm=events.with_suffix('.gamemode')
assert ipc('controlTest','click','gameModeToggle');wait(lambda:state()['gameModeApplied'],'Game Mode on')
wait(lambda:gm.exists() and json.loads(gm.read_text().splitlines()[-1])['action']=='on','Game Mode helper on')
assert ipc('controlTest','checked','gameModeToggle')
assert ipc('controlTest','click','gameModeToggle');wait(lambda:not state()['gameMode'] and not state()['gameModeApplied'],'Game Mode off')
wait(lambda:json.loads(gm.read_text().splitlines()[-1])['action']=='off','Game Mode helper off')
assert ipc('controlTest','click','wifiToggle');wait(lambda:not state()['wifi'],'Wi-Fi toggle')
assert ipc('controlTest','click','bluetoothToggle');wait(lambda:not state()['bluetooth'],'Bluetooth toggle')
assert ipc('controlTest','click','bluetoothToggle')
@@ -67,7 +88,7 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
assert ipc('controlTest','click','power-reboot');assert ipc('controlTest','click','powerConfirm')
wait(lambda:not state()['busy'],'recorded confirmation')
actions=[json.loads(line) for line in events.read_text().splitlines()]
power=[a for a in actions if a['action']=='power'];assert len(power)==1 and power[0]['value']=='reboot' and power[0]['confirmed'] is True
power=[a for a in actions if a['action']=='power'];assert len(power)==1 and power[0]['value']=='reboot' and power[0]['confirmed'] is True,str(actions)
ipc('controlcenter','close');time.sleep(.3);ipc('controlcenter','open');time.sleep(.35)
assert ipc('controlTest','screenshot',str(ROOT/'.cache/controlcenter-preview.png'))
ipc('controlTest','outside');wait(lambda:not state()['windowVisible'],'outside closes')
@@ -84,12 +105,57 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
ipc('controlcenter','close');wait(lambda:not state()['windowVisible'],'reduced motion close')
pref('animation.reducedMotion',False)
ipc('controlcenter','open');ipc('launcher','open');wait(lambda:not ipc('controlcenter','status')['opened'],'launcher exclusivity');ipc('launcher','close')
# Edit mode: drag to reorder, resize from the handle, remove and add, Escape leaves it.
ipc('controlcenter','open');wait(lambda:state()['windowVisible'],'reopen for editing');time.sleep(.4)
assert ipc('controlTest','click','controlEdit');wait(lambda:state()['editing'],'edit mode')
time.sleep(.6);assert ipc('controlTest','screenshot',str(ROOT/'.cache/controlcenter-editing.png'))
s=state();tiles={t['id']:t for t in s['tiles']};step=s['cellWidth']+10
bt,wifi,caf=tiles['bluetooth'],tiles['wifi'],tiles['caffeine']
ids=lambda:[m['id'] for m in state()['modules']]
pos=lambda i:next((t for t in state()['tiles'] if t['id']==i),None)
cfgpos=lambda i:next(m for m in state()['modules'] if m['id']==i)
# Dropping on a tile takes its cell and pushes it straight down.
assert ipc('controlTest','drag','controlMove-bluetooth',(wifi['col']-bt['col'])*step,(wifi['row']-bt['row'])*78)
wait(lambda:cfgpos('bluetooth').get('x')==wifi['col'] and cfgpos('bluetooth').get('y')==wifi['row'],'drag places the tile')
assert pos('wifi')['row']>wifi['row'] and pos('wifi')['col']==wifi['col'],'tile underneath is pushed down: '+str(pos('wifi'))
# Dropping into empty space leaves an air gap where it was.
time.sleep(.3);s=state();caf=pos('caffeine');rows=max(t['row']+t['h'] for t in s['tiles'])
assert ipc('controlTest','drag','controlMove-caffeine',(3-caf['col'])*step,(rows-caf['row'])*78)
wait(lambda:pos('caffeine')['row']==rows and pos('caffeine')['col']==3,'drop into empty row')
cell=lambda c,r:[t['id'] for t in state()['tiles'] if t['col']<=c<t['col']+t['w'] and t['row']<=r<t['row']+t['h']]
assert cell(caf['col'],caf['row'])==[],'air gap kept: '+str(cell(caf['col'],caf['row']))
time.sleep(.3)
assert ipc('controlTest','drag','controlResize-wifi',step,78)
wait(lambda:any(m['id']=='wifi' and m.get('w')==3 and m.get('h')==2 for m in state()['modules']),'resize to 3x2')
assert next(t for t in state()['tiles'] if t['id']=='wifi')['w']==3
time.sleep(.3);dnd=pos('dnd')
assert ipc('controlTest','click','controlRemove-dnd')
wait(lambda:not next(m for m in state()['modules'] if m['id']=='dnd')['enabled'],'remove badge')
assert not any(t['id']=='dnd' for t in state()['tiles'])
assert cell(dnd['col'],dnd['row'])==[],'removing leaves a gap'
# Plugin Control Center widgets are offered as tiles and keep their own clicks.
assert ipc('controlTest','click','controlAdd-plugin:cc-fixture')
wait(lambda:pos('plugin:cc-fixture'),'plugin tile added')
assert ipc('controlTest','click','controlEdit');wait(lambda:not state()['editing'],'leave edit for plugin click')
time.sleep(.4);assert ipc('controlTest','click','fixtureCcButton')
wait(lambda:ipc('controlTest','itemValue','fixtureCcButton','clicks')==1,'plugin widget click')
assert ipc('controlTest','click','controlEdit');wait(lambda:state()['editing'],'edit again')
assert ipc('controlTest','click','controlAdd-dnd')
wait(lambda:any(t['id']=='dnd' for t in state()['tiles']),'add from tray')
ipc('controlTest','pressEscape');wait(lambda:not state()['editing'],'Escape leaves edit mode')
assert ipc('controlcenter','status')['opened']
time.sleep(.6);assert ipc('controlTest','screenshot',str(ROOT/'.cache/controlcenter-edited.png'))
assert ipc('controlTest','click','controlEdit');wait(lambda:state()['editing'],'edit mode again')
time.sleep(.5);assert ipc('controlTest','click','controlReset')
wait(lambda:all('w' not in m and 'x' not in m for m in state()['modules']) and ids()[0]=='wifi','reset layout')
assert ipc('controlTest','click','controlEdit');wait(lambda:not state()['editing'],'done')
ipc('controlcenter','close');wait(lambda:not state()['windowVisible'],'close after editing')
ipc('shell','openSettings','controlcenter');wait(lambda:state()['settingsVisible'],'module editor opens');time.sleep(.3)
second=state()['modules'][1]['id']
assert ipc('controlTest','settingsDrag','control-drag-connectivity','control-drag-'+second)
wait(lambda:state()['modules'][1]['id']=='connectivity','visual module reorder')
assert ipc('controlTest','settingsClick','control-enable-audio')
wait(lambda:not next(m for m in state()['modules'] if m['id']=='audio')['enabled'],'visual module toggle')
assert ipc('controlTest','settingsDrag','control-drag-wifi','control-drag-'+second)
wait(lambda:state()['modules'][1]['id']=='wifi','visual module reorder')
assert ipc('controlTest','settingsClick','control-enable-output')
wait(lambda:not next(m for m in state()['modules'] if m['id']=='output')['enabled'],'visual module toggle')
ipc('shell','close');wait(lambda:not state()['settingsVisible'],'settings closes')
for page in ['controlcenter','audio','network','bluetooth','displays','notifications','power']:
ipc('shell','openSettings',page);time.sleep(.3)
@@ -101,4 +167,4 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
shell.terminate();shell.wait(timeout=5)
if original:subprocess.run(['hyprctl','dispatch','focusmonitor',original],capture_output=True)
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
print('PASS: native read-only discovery, active-monitor placement, system pill, recording audio/network/Bluetooth/display/DND actions, power confirmation/cancel, outside/Escape/exclusivity, settings, clean logs.')
print('PASS: native read-only discovery, active-monitor placement, system pill, recording audio/per-app volume/Caffeine/Game Mode/network/Bluetooth/display/DND actions, free grid edit mode (place, push down, air gaps, resize, remove, add, plugin tiles, reset), power confirmation/cancel, outside/Escape/exclusivity, settings, clean logs.')
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Real Wayland Emoji Picker test on a private session bus.
Copying is global on Wayland, so the user's clipboard is saved and restored.
Run: dbus-run-session -- python3 tests/emoji_runtime.py [screenshot-dir]"""
import json,os,subprocess,sys,tempfile,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
SHOTS=Path(sys.argv[1]) if len(sys.argv)>1 else None
Key={'Return':0x01000004,'Right':0x01000014,'Down':0x01000015,'Escape':0x01000000}
def ipc(target,method,*args):
r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True)
out=r.stdout.strip()
if r.returncode or not out:return None
try:return json.loads(out)
except ValueError:return out
def snap():return ipc('launcherTest','snapshot') or {}
def wait(check,label,timeout=10):
end=time.monotonic()+timeout
while time.monotonic()<end:
try:
if check():return
except (TypeError,KeyError,ValueError,IndexError):pass
time.sleep(.08)
raise AssertionError(label+': '+json.dumps(snap(),ensure_ascii=False)[:600])
def shot(name):
if SHOTS:
time.sleep(.5);SHOTS.mkdir(parents=True,exist_ok=True)
subprocess.run(['grim','-o',snap()['screen'],str(SHOTS/(name+'.png'))],check=False)
def pasted():return subprocess.run(['wl-paste','--no-newline'],capture_output=True,text=True,timeout=5).stdout
if 'DBUS_SESSION_BUS_ADDRESS' not in os.environ or ipc('shell','status'):raise SystemExit('Run in a private dbus-run-session with no instance from this path.')
saved=subprocess.run(['wl-paste','--no-newline'],capture_output=True,timeout=5)
log=ROOT/'.cache/emoji-runtime.log';log.parent.mkdir(exist_ok=True)
total=sum(1 for _ in open(ROOT/'quickshell/assets/emoji.tsv',encoding='utf-8'))
with tempfile.TemporaryDirectory(prefix='glassmxrph-emoji-') as tmp:
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_LAUNCHER_TESTING='1',QT_NO_XDG_DESKTOP_PORTAL='1')
Path(tmp,'config/glassMxrph').mkdir(parents=True)
Path(tmp,'config/glassMxrph/config.json').write_text(json.dumps({'schemaVersion':3,'dock':{'enabled':False}}))
with log.open('w') as output:
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT)
try:
wait(lambda:ipc('shell','status')['ready'],'ready')
ipc('launcher','open');wait(lambda:snap()['opened'] and snap()['focused'],'launcher opens')
time.sleep(.4);before=snap()
ipc('launcherTest','query','>emoji')
wait(lambda:snap()['results'][0]['id']=='emoji','emoji command listed')
ipc('launcherTest','key',Key['Return'])
wait(lambda:snap()['mode']=='emoji' and snap()['resultCount']==total,'command switches to the emoji grid')
s=snap();assert s['opened'] and s['query']=='' and s['focused'],s
assert (s['x'],s['y'],s['width'])==(before['x'],before['y'],before['width']),(before,s)
assert s['results'][0]['id']=='😀' and s['results'][0]['title']=='grinning face',s['results'][0]
time.sleep(.3);shot('1-emoji')
# Six rows visible: the body stops growing past them.
assert abs(s['height']-(60+6*52+42))<=2,s['height']
ipc('launcherTest','key',Key['Right']);ipc('launcherTest','key',Key['Down'])
cols=snap()['selected']-1;assert cols>4,snap()['selected']
ipc('launcherTest','query','heart red')
wait(lambda:snap()['results'][0]['title']=='red heart','search ranks names first')
ipc('launcherTest','query','pizza')
wait(lambda:[r['id'] for r in snap()['results']]==['🍕'],'search filters')
shot('2-search')
ipc('launcherTest','key',Key['Return'])
wait(lambda:not snap()['opened'],'copying closes')
wait(lambda:pasted()=='🍕','emoji copied')
ipc('launcherTest','query','')
ipc('launcher','emoji');wait(lambda:snap()['opened'] and snap()['mode']=='emoji','IPC opens the emoji picker')
ipc('launcherTest','query','flag germany')
wait(lambda:[r['id'] for r in snap()['results']]==['🇩🇪'],'keyword search')
ipc('launcher','emoji');wait(lambda:not snap()['opened'],'IPC toggles it closed')
ipc('launcher','open');wait(lambda:snap()['opened'] and snap()['mode']=='apps','launcher reopens in app mode')
ipc('launcher','close')
print('Emoji picker: >emoji switches in place, grid of six rows, search, copy, IPC toggle passed.')
finally:
shell.terminate()
try:shell.wait(5)
except subprocess.TimeoutExpired:shell.kill()
if saved.returncode==0:
restore=subprocess.Popen(['wl-copy'],stdin=subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
restore.stdin.write(saved.stdout);restore.stdin.close()
+70
View File
@@ -0,0 +1,70 @@
import importlib.util,json,os,tempfile,unittest
from pathlib import Path
from unittest.mock import patch
spec=importlib.util.spec_from_file_location('gamemode',Path(__file__).resolve().parents[1]/'quickshell/helpers/gamemode.py')
gm=importlib.util.module_from_spec(spec);spec.loader.exec_module(gm)
class GameModeTests(unittest.TestCase):
def setUp(self):
# HyprGlass is not loaded here, and the user has shadows off.
self.state={'animations:enabled':1,'decoration:blur:enabled':1,'decoration:shadow:enabled':0}
def env(self,temp,sig='fixture'):
return patch.dict(os.environ,{'XDG_STATE_HOME':temp,'HYPRLAND_INSTANCE_SIGNATURE':sig})
def fakes(self,profile='balanced'):
self.profile=profile
def setp(name):self.profile=name
return patch.multiple(gm,get_many=lambda keys:{k:self.state[k] for k in keys if k in self.state},put_many=lambda values:self.state.update(values),get_profile=lambda:self.profile,set_profile=setp)
def test_on_off_restores_exact_values(self):
with tempfile.TemporaryDirectory() as temp,self.env(temp):
with self.fakes():
original=dict(self.state)
self.assertTrue(gm.dispatch({'action':'on'})['active'])
self.assertEqual(set(self.state.values()),{0})
self.assertEqual(self.profile,'performance')
self.assertNotIn('plugin:hyprglass:enabled',self.state)
self.assertTrue(gm.dispatch({'action':'status'})['active'])
self.assertFalse(gm.dispatch({'action':'off'})['active'])
self.assertEqual(self.state,original)
self.assertEqual(self.profile,'balanced')
self.assertFalse(gm.dispatch({'action':'status'})['active'])
def test_on_twice_keeps_first_journal(self):
with tempfile.TemporaryDirectory() as temp,self.env(temp):
with self.fakes():
gm.dispatch({'action':'on'});gm.dispatch({'action':'on'})
gm.dispatch({'action':'off'})
self.assertEqual(self.state['animations:enabled'],1)
def test_crash_recovery_and_other_sessions(self):
with tempfile.TemporaryDirectory() as temp:
with self.fakes():
with self.env(temp,'old'):gm.dispatch({'action':'on'})
# A new Hyprland session never applies the old journal.
with self.env(temp,'new'):
self.assertFalse(gm.dispatch({'action':'status'})['active'])
gm.dispatch({'action':'off'})
self.assertEqual(self.state['animations:enabled'],0)
# The same session (shell restarted) restores it.
with self.env(temp,'old'):
gm.dispatch({'action':'off'})
self.assertEqual(self.state['animations:enabled'],1)
def test_options_and_no_profiles_daemon(self):
with tempfile.TemporaryDirectory() as temp,self.env(temp):
with self.fakes(profile=None):
gm.dispatch({'action':'on','effects':False,'performance':True})
self.assertEqual(self.state['animations:enabled'],1)
self.assertIsNone(self.profile)
gm.dispatch({'action':'off'})
with self.fakes():
gm.dispatch({'action':'on','effects':True,'performance':False})
self.assertEqual(self.profile,'balanced')
gm.dispatch({'action':'off'})
self.assertEqual(self.state['animations:enabled'],1)
def test_parses_missing_options(self):
out='{"option": "animations:enabled", "int": 1, "set": true }\n\n\nno such option\n\n{"option": "decoration:blur:enabled", "int": 0, "set": true }\n'
with patch.object(gm,'run',lambda args:out):
self.assertEqual(gm.get_many(['animations:enabled','plugin:hyprglass:enabled','decoration:blur:enabled']),{'animations:enabled':1,'decoration:blur:enabled':0})
def test_rejected_keyword_raises(self):
with patch.object(gm,'run',lambda args:'ok\nconfig option <x> does not exist.'):
with self.assertRaises(ValueError):gm.put_many({'x':0,'y':0})
def test_unknown_action(self):
with tempfile.TemporaryDirectory() as temp,self.env(temp):
with self.assertRaises(ValueError):gm.dispatch({'action':'nope'})
if __name__=='__main__':unittest.main()
+10 -2
View File
@@ -61,7 +61,8 @@ Terminal={'true' if suffix=='Terminal' else 'false'}
''')
cfg=temp/'config/glassMxrph/config.json';cfg.parent.mkdir(parents=True)
# Hermetic: never scan the user's wallpaper folders (and their image formats).
cfg.write_text(json.dumps({'schemaVersion':3,'dock':{'enabled':False},'wallpaper':{'directories':[str(temp)]}}))
# The user's live shell owns the notification bus name; a second server would warn.
cfg.write_text(json.dumps({'schemaVersion':3,'dock':{'enabled':False},'notifications':{'enabled':False},'wallpaper':{'directories':[str(temp)]}}))
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_DATA_HOME=tmp+'/data',GLASSMXRPH_LAUNCHER_TESTING='1',QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
shell=None
try:
@@ -112,8 +113,15 @@ Terminal={'true' if suffix=='Terminal' else 'false'}
ipc('launcherTest','key',ESC)
eventually(lambda:not snapshot()['visible'],'Escape dismiss')
open_launcher();query('>')
eventually(lambda:{r['id'] for r in snapshot()['results']}=={'about','appearance','audio','bar','tray','bluetooth','controlcenter','display','dock','launcher','media','metrics','network','notifications','power','wallpaper','widgets','osd','lock','dashboard','plugins','clipboard'},'all commands registered')
eventually(lambda:{r['id'] for r in snapshot()['results']}=={'about','appearance','audio','bar','tray','bluetooth','controlcenter','display','dock','launcher','media','metrics','network','notifications','power','wallpaper','widgets','osd','lock','dashboard','plugins','clipboard','emoji'},'all commands registered')
time.sleep(.3);assert ipc('launcherTest','screenshot',str(ROOT/'.cache/launcher-preview.png'))
# Mode pills beside the bar switch to clipboard or emoji and back.
assert ipc('launcherTest','pill','clipboard');eventually(lambda:snapshot()['mode']=='clipboard','clipboard pill')
assert ipc('launcherTest','pill','clipboard');eventually(lambda:snapshot()['mode']=='apps','clipboard pill toggles back')
assert ipc('launcherTest','pill','emoji');eventually(lambda:snapshot()['mode']=='emoji' and snapshot()['opened'],'emoji pill')
time.sleep(.4);assert ipc('launcherTest','screenshot',str(ROOT/'.cache/launcher-emoji.png'));assert ipc('launcherTest','pillsShot',str(ROOT/'.cache/launcher-pills.png'))
assert ipc('launcherTest','pill','emoji');eventually(lambda:snapshot()['mode']=='apps','emoji pill toggles back')
query('>')
for text,page in [('>metrics','metrics'),('>dock','dock'),('>media','media'),('>tray','tray'),('>display','displays'),('>launcher','launcher'),('>appearance','appearance'),('>bar','bar'),('>network','network'),('>bluetooth','bluetooth'),('>audio','audio'),('>controlcenter','controlcenter'),('>notifications','notifications'),('>power','power'),('>about','about')]:
query(text)
ipc('launcherTest','key',ENTER)