From 7f1189606c4b1c91f26e9a461a377daa0c7b8d15 Mon Sep 17 00:00:00 2001 From: mx Date: Sat, 17 Oct 2026 22:02:18 +0200 Subject: [PATCH] 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 --- README.md | 6 +- docs/architecture.md | 11 +- quickshell/controlcenter/CCModule.qml | 2 + quickshell/controlcenter/ControlCenter.qml | 182 +++++++++++++------ quickshell/controlcenter/ControlRegistry.qml | 16 +- quickshell/controlcenter/GridLogic.js | 135 ++++++++------ quickshell/controlcenter/modules/Plugin.qml | 91 ++++++++++ quickshell/services/ConfigLogic.js | 2 +- quickshell/services/PluginService.qml | 2 + quickshell/settings/pages/ControlCenter.qml | 6 +- quickshell/testing/ControlDriver.qml | 5 + tests/config.test.cjs | 3 +- tests/controlcenter.test.cjs | 67 ++++--- tests/controlcenter_runtime.py | 41 ++++- 14 files changed, 412 insertions(+), 157 deletions(-) create mode 100644 quickshell/controlcenter/modules/Plugin.qml diff --git a/README.md b/README.md index abe9c07..f743650 100644 --- a/README.md +++ b/README.md @@ -180,8 +180,10 @@ Control Center opens at the active monitor's upper-right. Its modules sit on a 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. -**Edit Controls** at the bottom of the panel lets you drag tiles to reorder them, -resize them from the corner handle, remove them with the badge and add others. +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. Logout, reboot and shutdown require explicit confirmation. diff --git a/docs/architecture.md b/docs/architecture.md index 829bf08..0421f62 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -114,10 +114,13 @@ 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 on a 4-column grid (`controlcenter/GridLogic.js` packs -them first-fit in configured order); each has a default size in `ControlRegistry` -and an optional per-module `w`/`h` (1–4) in `controlCenter.modules`, set from the -panel's edit mode. Tiles adapt their layout to their size. A tile can extend below +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:` 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 diff --git a/quickshell/controlcenter/CCModule.qml b/quickshell/controlcenter/CCModule.qml index d4a900d..6e6c705 100644 --- a/quickshell/controlcenter/CCModule.qml +++ b/quickshell/controlcenter/CCModule.qml @@ -9,6 +9,8 @@ import "../theme" 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. diff --git a/quickshell/controlcenter/ControlCenter.qml b/quickshell/controlcenter/ControlCenter.qml index 4ec21c3..2b330bb 100644 --- a/quickshell/controlcenter/ControlCenter.qml +++ b/quickshell/controlcenter/ControlCenter.qml @@ -46,9 +46,11 @@ PanelWindow { Component.onCompleted: ShellState.controlCenterWindow = root Component.onDestruction: ShellState.controlCenterWindow = null - // Modules on a 4-column grid, packed first-fit in the configured order; - // Notifications is a section under it. Edit mode reorders by dragging, - // resizes from the corner handle, removes with the badge and adds from a tray. + // 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 @@ -56,27 +58,29 @@ PanelWindow { 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: Object.keys(ControlRegistry.modules).filter(id => !entries.some(m => m.id === id && m.enabled)) + readonly property var addable: ControlRegistry.ids.filter(id => !entries.some(m => m.id === id && m.enabled)) property bool editing: false - // Live edit previews: the order while a tile is dragged, a size while resized. - property var dragOrder: null + // 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: "" - property var resizeSize: null // Tile id -> pixels a tile extends below its cells. property var extras: ({}) - readonly property var order: dragOrder ? dragOrder.filter(id => tiles.some(m => m.id === id)) : tiles.map(m => m.id) - readonly property var plan: Grid.pack(order.map(id => { - const m = tiles.find(t => t.id === id); - const size = id === resizeId && resizeSize ? resizeSize : ControlRegistry.size(m); + readonly property var savedPlan: Grid.layout(tiles.map(m => { + const size = ControlRegistry.size(m); return { - id: id, + id: m.id, w: size.w, - h: size.h + 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) @@ -85,30 +89,58 @@ PanelWindow { next[id] = value; extras = next; } - function cellAt(p) { - return Qt.point(Math.floor(p.x / (cellWidth + gap)), Math.floor(p.y / (cellHeight + gap))); - } - // Writes the module list back, keeping entries that are not grid tiles. - function saveOrder(ids) { - const rest = entries.filter(m => !ids.includes(m.id)); - ConfigService.setValue("controlCenter.modules", ids.map(id => entries.find(m => m.id === id)).concat(rest)); - } - function saveSize(id, size) { - ConfigService.setValue("controlCenter.modules", entries.map(m => m.id === id ? Object.assign({}, m, { - w: size.w, - h: size.h - }) : m)); + // 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 + }); + 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) { - const known = entries.some(m => m.id === id); - ConfigService.setValue("controlCenter.modules", known ? entries.map(m => m.id === id ? Object.assign({}, m, { - enabled: on - }) : m) : entries.concat([ - { - id: id, - enabled: 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); @@ -297,8 +329,8 @@ PanelWindow { id: grid objectName: "controlGrid" Layout.fillWidth: true - implicitHeight: root.geometry.height - visible: root.tiles.length > 0 + 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 { @@ -306,6 +338,36 @@ PanelWindow { easing.type: Easing.OutCubic } } + // 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 { @@ -368,6 +430,12 @@ PanelWindow { // 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 @@ -434,12 +502,12 @@ PanelWindow { hoverEnabled: true preventStealing: true cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor - property point lastCell: Qt.point(-1, -1) + 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 = Qt.point(-1, -1); + lastCell = null; } onPositionChanged: mouse => { if (!pressed) @@ -448,27 +516,28 @@ PanelWindow { if (!root.dragId) { if (Math.hypot(p.x - root.dragPoint.x, p.y - root.dragPoint.y) < 6) return; - root.dragOrder = root.order.slice(); root.dragId = slot.modelData; } root.dragPoint = p; - const c = root.cellAt(p); - if (c.x === lastCell.x && c.y === lastCell.y) + // 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; - root.dragOrder = Grid.reorder(root.order, root.plan, slot.modelData, Math.max(0, Math.min(Grid.COLS - 1, c.x)), Math.max(0, c.y)); + // Always from the saved layout, so tiles pushed aside come back. + root.preview = Grid.moveTo(root.savedPlan, slot.modelData, c); } onReleased: { - const order = root.dragOrder; - const moved = !!root.dragId && order && order.join() !== root.tiles.map(m => m.id).join(); + const plan = root.preview; root.dragId = ""; - if (moved) - root.saveOrder(order); - root.dragOrder = null; + root.preview = null; + if (plan) + root.save(plan); } onCanceled: { root.dragId = ""; - root.dragOrder = null; + root.preview = null; } } Badge { @@ -523,7 +592,6 @@ PanelWindow { w: slot.cell.w, h: slot.cell.h }; - root.resizeSize = startSize; root.resizeId = slot.modelData; } onPositionChanged: mouse => { @@ -531,19 +599,19 @@ PanelWindow { 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 !== root.resizeSize.w || next.h !== root.resizeSize.h) - root.resizeSize = next; + if (next.w !== slot.cell.w || next.h !== slot.cell.h) + root.preview = Grid.moveTo(root.savedPlan, slot.modelData, next); } onReleased: { - const size = root.resizeSize; + const plan = root.preview; root.resizeId = ""; - root.resizeSize = null; - if (size && (size.w !== startSize.w || size.h !== startSize.h)) - root.saveSize(slot.modelData, size); + root.preview = null; + if (plan) + root.save(plan); } onCanceled: { root.resizeId = ""; - root.resizeSize = null; + root.preview = null; } } } diff --git a/quickshell/controlcenter/ControlRegistry.qml b/quickshell/controlcenter/ControlRegistry.qml index e7cbc59..6643110 100644 --- a/quickshell/controlcenter/ControlRegistry.qml +++ b/quickshell/controlcenter/ControlRegistry.qml @@ -1,12 +1,26 @@ 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. +// under the grid instead. Enabled plugins with a Control Center widget add +// "plugin:" 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. diff --git a/quickshell/controlcenter/GridLogic.js b/quickshell/controlcenter/GridLogic.js index e4a06de..a686499 100644 --- a/quickshell/controlcenter/GridLogic.js +++ b/quickshell/controlcenter/GridLogic.js @@ -1,6 +1,7 @@ -// Pure helpers for the Control Center grid: packing, drag reordering and -// resizing. -// Tiles are {id, w, h} in grid cells; the grid is `cols` wide and grows down. +// 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; @@ -10,66 +11,92 @@ function clampSize(n) { return Number.isFinite(n) ? Math.max(1, Math.min(MAX, n)) : 1; } -// Packs tiles first-fit in list order: each takes the first free spot, scanning -// rows top to bottom and columns left to right, so small tiles backfill gaps. -function pack(tiles, cols) { +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 occ = [], items = []; - let rows = 0; - function free(r, c, w, h) { - for (let y = r; y < r + h; y++) - for (let x = c; x < c + w; x++) - if (occ[y] && occ[y][x]) - return false; - return true; + 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) { - const w = Math.min(cols, clampSize(t.w)), h = clampSize(t.h); - let placed = false; - for (let r = 0; !placed; r++) { - for (let c = 0; c + w <= cols; c++) { - if (!free(r, c, w, h)) - continue; - for (let y = r; y < r + h; y++) { - occ[y] = occ[y] || []; - for (let x = c; x < c + w; x++) - occ[y][x] = true; - } - items.push({id: t.id, col: c, row: r, w: w, h: h}); - rows = Math.max(rows, r + h); - placed = true; + 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: rows}; + return {items: items, rows: rowsOf(items)}; } -// The packed tile covering a cell, or null. -function at(plan, col, row) { - return plan.items.find(i => col >= i.col && col < i.col + i.w && row >= i.row && row < i.row + i.h) || null; -} - -// Order after dragging `id` over the cell (col, row): it takes the index of the -// tile under the pointer. Over empty space it goes after the last tile that -// starts at or before that cell in reading order. -function reorder(ids, plan, id, col, row) { - if (ids.indexOf(id) < 0) - return ids.slice(); - const hit = at(plan, col, row); - if (hit && hit.id === id) - return ids.slice(); - const next = ids.filter(i => i !== id); - let to; - if (hit) { - // Moving forward lands after the hit tile, backward lands before it. - to = next.indexOf(hit.id) + (ids.indexOf(id) < ids.indexOf(hit.id) ? 1 : 0); - } else { - const before = plan.items.filter(i => i.id !== id && (i.row < row || (i.row === row && i.col <= col))); - to = before.length ? Math.max(...before.map(i => next.indexOf(i.id))) + 1 : 0; - } - next.splice(to, 0, id); - return next; +// 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. diff --git a/quickshell/controlcenter/modules/Plugin.qml b/quickshell/controlcenter/modules/Plugin.qml new file mode 100644 index 0000000..f57ce68 --- /dev/null +++ b/quickshell/controlcenter/modules/Plugin.qml @@ -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 + } +} diff --git a/quickshell/services/ConfigLogic.js b/quickshell/services/ConfigLogic.js index a31611a..8021fcf 100644 --- a/quickshell/services/ConfigLogic.js +++ b/quickshell/services/ConfigLogic.js @@ -89,7 +89,7 @@ function validate(c) { 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 !== 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"); 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" || ["w","h"].some(k=>m[k]!==undefined && (!Number.isInteger(m[k]) || m[k]<1 || m[k]>4)))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"); diff --git a/quickshell/services/PluginService.qml b/quickshell/services/PluginService.qml index 3ffaf64..098a26e 100644 --- a/quickshell/services/PluginService.qml +++ b/quickshell/services/PluginService.qml @@ -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") diff --git a/quickshell/settings/pages/ControlCenter.qml b/quickshell/settings/pages/ControlCenter.qml index f6c018e..000ec43 100644 --- a/quickshell/settings/pages/ControlCenter.qml +++ b/quickshell/settings/pages/ControlCenter.qml @@ -86,7 +86,7 @@ SettingsPage { } SettingsSection { title: "Modules" - description: "Drag modules to reorder them; the switch shows or hides each one. Resize tiles from Edit Controls in the Control Center" + 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" @@ -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, diff --git a/quickshell/testing/ControlDriver.qml b/quickshell/testing/ControlDriver.qml index 3bea956..10d575f 100644 --- a/quickshell/testing/ControlDriver.qml +++ b/quickshell/testing/ControlDriver.qml @@ -242,6 +242,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; diff --git a/tests/config.test.cjs b/tests/config.test.cjs index a28bb4c..d65665d 100644 --- a/tests/config.test.cjs +++ b/tests/config.test.cjs @@ -74,12 +74,13 @@ assert.equal(phase7.controlCenter.version,2);assert(phase7.controlCenter.modules 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.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}]}])assert.throws(()=>api.load(defaults,{controlCenter})); +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.'); diff --git a/tests/controlcenter.test.cjs b/tests/controlcenter.test.cjs index 2bcf56e..d171b36 100644 --- a/tests/controlcenter.test.cjs +++ b/tests/controlcenter.test.cjs @@ -1,35 +1,52 @@ 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 ids = plan => plan.items.map(i => i.id + '@' + i.col + ',' + i.row + ':' + i.w + 'x' + i.h).join(' '); -// First fit in list order; small tiles backfill gaps beside larger ones. -let plan = api.pack([{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(ids(plan), 'wifi@0,0:2x1 media@2,0:2x2 bt@0,1:1x1 dnd@1,1:1x1 sound@0,2:4x1'); +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); -plan = api.pack([{id: 'a', w: 3, h: 1}, {id: 'b', w: 2, h: 1}, {id: 'c', w: 1, h: 1}]); -assert.equal(ids(plan), 'a@0,0:3x1 b@0,1:2x1 c@3,0:1x1'); -// Sizes clamp to 1..4 cells. -assert.equal(ids(api.pack([{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.pack([]).rows, 0); -// Hit testing covers spanned cells. -plan = api.pack([{id: 'wifi', w: 2, h: 1}, {id: 'media', w: 2, h: 2}, {id: 'bt', w: 1, h: 1}]); -assert.equal(api.at(plan, 3, 1).id, 'media'); -assert.equal(api.at(plan, 3, 2), null); -// Dragging onto a tile takes its place in either direction; onto itself is a no-op. -const order = ['wifi', 'media', 'bt']; -assert.equal(api.reorder(order, plan, 'bt', 0, 0).join(), 'bt,wifi,media'); -assert.equal(api.reorder(order, plan, 'wifi', 0, 1).join(), 'media,bt,wifi'); -assert.equal(api.reorder(order, plan, 'wifi', 1, 0).join(), 'wifi,media,bt'); -// Empty space puts it after the last tile before that cell. -assert.equal(api.reorder(order, plan, 'wifi', 1, 1).join(), 'media,bt,wifi'); -assert.equal(api.reorder(order, plan, 'bt', 0, 5).join(), 'wifi,media,bt'); -assert.equal(api.reorder(order, plan, 'nope', 0, 0).join(), order.join()); -// Resizing rounds to whole cells within 1..4. +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.pack([{id: 'out', w: 2, h: 1}, {id: 'media', w: 2, h: 2}, {id: 'a', w: 1, h: 1}, {id: 'b', w: 4, h: 1}]); +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); @@ -39,4 +56,4 @@ 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 grid packing, hit testing, reordering, resizing and expansion geometry passed.'); +console.log('Control Center free placement, push-down moves and resizes, free spots and expansion geometry passed.'); diff --git a/tests/controlcenter_runtime.py b/tests/controlcenter_runtime.py index 5f1d692..937bc74 100644 --- a/tests/controlcenter_runtime.py +++ b/tests/controlcenter_runtime.py @@ -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: @@ -77,7 +81,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') @@ -99,25 +103,44 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp: 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=tiles['bluetooth'],tiles['wifi'] - assert ipc('controlTest','drag','controlMove-bluetooth',(wifi['col']-bt['col'])*step,(wifi['row']-bt['row'])*78) + bt,wifi,caf=tiles['bluetooth'],tiles['wifi'],tiles['caffeine'] ids=lambda:[m['id'] for m in state()['modules']] - wait(lambda:ids().index('bluetooth')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