Fork the desktop off Omarchy as a self-contained system

This commit is contained in:
2026-09-19 23:50:39 -04:00
parent 16a56f49a1
commit 9501f2bb4d
559 changed files with 43273 additions and 0 deletions
+268
View File
@@ -0,0 +1,268 @@
import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Wayland
import qs.Commons
import "AppSearch.js" as AppSearch
// Shared desktop-application library: the sorted entry list with hidden-entry
// filtering, the icon fallback index, launch feedback, and entry removal.
// Injected as shell.appLibrary; the menu's Apps submenu is the consumer.
Item {
id: root
property string blobPath: Quickshell.env("BLOB_PATH")
property var configuredHiddenEntryIds: ({})
property var desktopHiddenEntryIds: ({})
// Maps an icon name to a file on disk (e.g. "omacut" -> ".../apps/omacut.svg").
// Used as a fallback for icons that Qt's themed lookup misses because they were
// installed after this process started (its icon cache never re-scans). Refreshed
// whenever the app list changes, so newly installed apps get their icon live.
property var iconIndex: ({})
property var pendingIconIndex: ({})
property int launchSerial: 0
property int launchToplevelCount: 0
property var launchActiveToplevel: null
// True while the launch OSD is on screen. It outlives the launch that opened
// it: the OSD shows with duration 0, so only closeLaunchFeedback() takes it
// down.
property bool launchOsdOpen: false
property string launchOsdMessage: ""
// Emitted whenever the visible application set may have changed: desktop
// entries appeared or vanished, or the hidden-entry filters reloaded.
signal appsChanged()
function entryName(entry) {
return AppSearch.entryName(entry)
}
function entrySubtext(entry) {
return AppSearch.entrySubtext(entry)
}
function isHiddenEntry(entry) {
var id = String((entry && entry.id) || "")
return root.configuredHiddenEntryIds[id] === true || root.desktopHiddenEntryIds[id] === true
}
function sortedEntries(query) {
var values = DesktopEntries.applications.values || []
return AppSearch.sortedEntries(values, query, function(entry) { return root.isHiddenEntry(entry) })
}
function iconSource(icon) {
var value = String(icon || "")
if (value.length === 0) return Quickshell.iconPath("application-x-executable", true)
if (value.indexOf("file://") === 0 || value.indexOf("image://") === 0) return value
if (value.charAt(0) === "/") return Util.fileUrl(value)
// Prefer the context-limited app/device index. An unconstrained themed
// lookup can resolve an app name such as "zoom" to an action icon instead.
var found = root.iconIndex[value]
if (found) return Util.fileUrl(found)
var themed = Quickshell.iconPath(value, true)
if (themed.length > 0) return themed
return Quickshell.iconPath("application-x-executable", true)
}
// The shell may start before first-install packages have finished placing
// their icons; consumers call this when they open so icons appear live.
function refreshIcons() {
if (!iconIndexScan.running) iconIndexScan.running = true
}
function launch(desktopId, name) {
var id = String(desktopId || "")
if (!id) return
root.beginLaunchFeedback(name)
// Start gtk-launch inside a scope under app-graphical.slice so apps do not
// inherit wayland-wm@.service. Keeping gtk-launch as the desktop-entry
// resolver supports IDs with spaces and entries that UWSM rejects.
// Keep the .desktop suffix or ids like org.telegram.desktop won't resolve.
Util.execDetached("uwsm-app -- gtk-launch " + Util.shellQuote(id + ".desktop"))
}
function remove(desktopId, name) {
var id = String(desktopId || "")
if (!id) return
Util.execDetached(Util.shellQuote(root.blobPath + "/bin/blob-launcher-remove") + " " + Util.shellQuote(id) + " " + Util.shellQuote(String(name || id)))
}
function normalizeDesktopId(id) {
var value = String(id || "").trim()
if (value.slice(-8) === ".desktop") value = value.slice(0, -8)
return value
}
function loadConfiguredHides(rawText) {
var next = ({})
var lines = String(rawText || "").split(/\n/)
for (var i = 0; i < lines.length; i++) {
var id = root.normalizeDesktopId(lines[i])
if (id.length > 0) next[id] = true
}
root.configuredHiddenEntryIds = next
root.appsChanged()
}
function loadDesktopHiddenEntries(rawText) {
var next = ({})
var lines = String(rawText || "").split(/\n/)
for (var i = 0; i < lines.length; i++) {
var id = root.normalizeDesktopId(lines[i])
if (id.length > 0) next[id] = true
}
root.desktopHiddenEntryIds = next
root.appsChanged()
}
function iconIndexScanCommand() {
// List app/device icons across the XDG icon dirs and /usr/share/pixmaps as
// "<path>" lines. Some desktop entries, such as Print Settings, use device
// icons like "printer" instead of app icons. SVGs are emitted before PNGs
// so the parser, which keeps the first hit per name, prefers scalable icons.
return [
'dirs="$HOME/.icons $HOME/.local/share/icons";',
'IFS=":"; for d in ${XDG_DATA_DIRS:-/usr/local/share:/usr/share}; do dirs="$dirs $d/icons"; done; unset IFS;',
'for ext in svg png; do',
' for base in $dirs; do',
' [[ -d $base ]] && find "$base" \\( -path "*/apps/*" -o -path "*/devices/*" \\) -name "*.$ext" 2>/dev/null;',
' done;',
' find /usr/share/pixmaps -maxdepth 1 -name "*.$ext" 2>/dev/null;',
'done'
].join(' ')
}
function indexIconLine(path) {
var value = String(path || "").trim()
if (value.length === 0) return
var slash = value.lastIndexOf("/")
var file = slash >= 0 ? value.slice(slash + 1) : value
var dot = file.lastIndexOf(".")
var name = dot > 0 ? file.slice(0, dot) : file
if (name.length > 0 && root.pendingIconIndex[name] === undefined)
root.pendingIconIndex[name] = value
}
function hiddenEntryScanCommand() {
var desktop = [Quickshell.env("XDG_CURRENT_DESKTOP"), Quickshell.env("XDG_SESSION_DESKTOP"), Quickshell.env("DESKTOP_SESSION")].filter(function(v) { return String(v || "").length > 0 }).join(":")
var script = root.blobPath + "/shell/services/hidden-entries.sh"
return Util.shellQuote(script) + " " + Util.shellQuote(desktop)
}
function toplevelCount() {
try { return ToplevelManager.toplevels.values.length } catch (e) { return 0 }
}
function beginLaunchFeedback(name) {
root.launchSerial++
root.launchToplevelCount = root.toplevelCount()
root.launchActiveToplevel = ToplevelManager.activeToplevel
root.launchOsdMessage = "Launching " + String(name || "application") + "…"
launchDelay.restart()
launchTimeout.restart()
}
function closeLaunchFeedback(serial) {
if (serial !== root.launchSerial) return
launchDelay.stop()
launchTimeout.stop()
if (root.launchOsdOpen) {
Quickshell.execDetached(["blob-shell", "osd", "close"])
root.launchOsdOpen = false
}
}
function maybeFinishLaunchFeedback() {
if (!launchDelay.running && !launchTimeout.running && !root.launchOsdOpen) return
if (root.toplevelCount() <= root.launchToplevelCount && ToplevelManager.activeToplevel === root.launchActiveToplevel) return
root.closeLaunchFeedback(root.launchSerial)
}
QtObject {
id: hiddenEntryOutput
property string text: ""
}
// Both scans must run in non-login shells. A login shell sources the user's
// profile, and tools like mise touch ~/.local/share on activation — a
// directory the desktop-entry watcher monitors — so every scan would
// trigger the next one, pinning a core at idle.
Process {
id: hiddenEntryScan
command: ["bash", "-c", root.hiddenEntryScanCommand()]
stdout: SplitParser { onRead: function(line) { hiddenEntryOutput.text += line + "\n" } }
onStarted: hiddenEntryOutput.text = ""
onExited: root.loadDesktopHiddenEntries(hiddenEntryOutput.text)
}
Process {
id: iconIndexScan
command: ["bash", "-c", root.iconIndexScanCommand()]
stdout: SplitParser { onRead: function(line) { root.indexIconLine(line) } }
onStarted: root.pendingIconIndex = ({})
// Swapping the property re-evaluates every iconSource() binding, so
// newly found icons appear without rebuilding the list.
onExited: root.iconIndex = root.pendingIconIndex
}
// Coalesces bursts of app-list changes (a package install touches many
// entries) into a single rescan.
Timer {
id: iconIndexDebounce
interval: 750
onTriggered: if (!iconIndexScan.running) iconIndexScan.running = true
}
FileView {
path: root.blobPath + "/default/blob/launcher.hides"
watchChanges: true
printErrors: false
onLoaded: root.loadConfiguredHides(text())
onFileChanged: root.loadConfiguredHides(text())
onLoadFailed: root.loadConfiguredHides("")
}
Connections {
target: ToplevelManager.toplevels
function onValuesChanged() { root.maybeFinishLaunchFeedback() }
}
Connections {
target: ToplevelManager
function onActiveToplevelChanged() { root.maybeFinishLaunchFeedback() }
}
Timer {
id: launchDelay
interval: 2000
onTriggered: {
if (root.toplevelCount() > root.launchToplevelCount || ToplevelManager.activeToplevel !== root.launchActiveToplevel) return
root.launchOsdOpen = true
Quickshell.execDetached(["blob-shell", "osd", "show", JSON.stringify({ icon: "󱓞", message: root.launchOsdMessage, duration: 0 })])
}
}
Timer {
id: launchTimeout
interval: 15000
onTriggered: root.closeLaunchFeedback(root.launchSerial)
}
Connections {
target: DesktopEntries.applications
function onValuesChanged() {
hiddenEntryScan.running = true
iconIndexDebounce.restart()
root.appsChanged()
}
}
Component.onCompleted: {
hiddenEntryScan.running = true
iconIndexScan.running = true
}
}
+134
View File
@@ -0,0 +1,134 @@
function entryName(entry) {
return String((entry && entry.name) || (entry && entry.id) || "")
}
function entrySubtext(entry) {
return String((entry && entry.genericName) || "")
}
function entrySortKey(entry) {
return entryName(entry).toLowerCase()
}
function keywordText(entry) {
try {
if (entry && entry.keywords && typeof entry.keywords.join === "function") return entry.keywords.join(" ")
} catch (e) {
}
return ""
}
function entrySearchText(entry) {
if (!entry) return ""
return [entry.name, entry.genericName, entry.comment, keywordText(entry), entry.id].join(" ").toLowerCase()
}
function wordText(value) {
return String(value || "")
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[._:/\\-]+/g, " ")
.toLowerCase()
}
function words(value) {
var values = wordText(value).split(/[^a-z0-9]+/)
var result = []
for (var i = 0; i < values.length; i++) {
if (values[i]) result.push(values[i])
}
return result
}
function entryAcronym(entry) {
var values = words([entry && entry.name, entry && entry.genericName, keywordText(entry), entry && entry.id].join(" "))
var result = ""
for (var i = 0; i < values.length; i++) result += values[i].charAt(0)
return result
}
function termMatches(entry, term) {
if (!term) return true
var name = entryName(entry).toLowerCase()
var id = String((entry && entry.id) || "").toLowerCase()
var haystack = entrySearchText(entry)
if (name.indexOf(term) >= 0) return true
if (id.indexOf(term) >= 0) return true
if (haystack.indexOf(term) >= 0) return true
return term.length <= 5 && entryAcronym(entry).indexOf(term) >= 0
}
function allTermsMatch(entry, query) {
var terms = String(query || "").toLowerCase().trim().split(/\s+/)
for (var i = 0; i < terms.length; i++) {
if (terms[i] && !termMatches(entry, terms[i])) return false
}
return true
}
function fuzzyScore(entry, query) {
var q = String(query || "").trim().toLowerCase()
if (!q) return 0
if (!allTermsMatch(entry, q)) return -1
var name = entryName(entry).toLowerCase()
var id = String((entry && entry.id) || "").toLowerCase()
var haystack = entrySearchText(entry)
var directName = name.indexOf(q)
var directId = id.indexOf(q)
if (directName === 0) return 10000 - name.length
if (directId === 0) return 9500 - id.length
if (directName > 0) return 8000 - directName * 10 - name.length
if (directId > 0) return 7600 - directId * 10 - id.length
var hayIndex = haystack.indexOf(q)
if (hayIndex >= 0) return 6000 - hayIndex
var acronym = entryAcronym(entry)
var acronymIndex = acronym.indexOf(q)
if (acronymIndex === 0) return 5000 - acronym.length
if (acronymIndex > 0) return 4600 - acronymIndex * 10 - acronym.length
return 4000 - name.length
}
function sortedEntries(values, query, hiddenCallback) {
var q = String(query || "").trim()
var rows = []
for (var i = 0; i < values.length; i++) {
var entry = values[i]
if (!entry || entry.noDisplay) continue
if (hiddenCallback && hiddenCallback(entry)) continue
var name = entryName(entry)
if (!name) continue
var score = fuzzyScore(entry, q)
if (score < 0) continue
rows.push({ entry: entry, score: score, key: entrySortKey(entry), name: name.toLowerCase() })
}
rows.sort(function(a, b) {
if (q && a.score !== b.score) return b.score - a.score
if (a.key < b.key) return -1
if (a.key > b.key) return 1
if (a.name < b.name) return -1
if (a.name > b.name) return 1
return 0
})
return rows
}
if (typeof module !== "undefined") {
module.exports = {
entryName: entryName,
entrySubtext: entrySubtext,
entrySortKey: entrySortKey,
entrySearchText: entrySearchText,
entryAcronym: entryAcronym,
fuzzyScore: fuzzyScore,
sortedEntries: sortedEntries
}
}
+45
View File
@@ -0,0 +1,45 @@
// Intentionally not `.pragma library`: QML JavaScript imports get a private
// module instance per importing component. shell.qml's instance retains the
// authentication services; a third-party plugin importing this file receives
// a separate empty store rather than a shared path to credential-bearing QML.
var services = ({})
var trustedIds = ({})
function has(id) {
return services[String(id || "")] !== undefined
}
function put(id, service) {
var key = String(id || "")
if (!key || !service) return
trustedIds[key] = true
if (services[key] && services[key] !== service && typeof services[key].destroy === "function")
services[key].destroy()
services[key] = service
}
function isTrusted(id) {
return trustedIds[String(id || "")] === true
}
function ids() {
return Object.keys(services)
}
function updateManifest(id, manifest) {
var service = services[String(id || "")]
if (service && "manifest" in service) service.manifest = manifest
}
function destroy(id) {
var key = String(id || "")
var service = services[key]
if (service && typeof service.destroy === "function") service.destroy()
delete services[key]
}
function destroyAll() {
var keys = ids()
for (var i = 0; i < keys.length; i++) destroy(keys[i])
}
+49
View File
@@ -0,0 +1,49 @@
import QtQuick
// Instance, not a singleton — instantiated once by shell.qml and injected into
// plugins that need to read or extend the widget catalogue. Relative-path
// singleton imports were creating per-importer instances which prevented the
// shell host from seeing what the bar registered.
QtObject {
id: registry
// { widgetId: { component: Component, metadata: var } }
property var widgets: ({})
property int revision: 0
signal changed()
function register(id, component, metadata) {
var key = String(id)
if (!key) return
var next = {}
for (var k in widgets) next[k] = widgets[k]
next[key] = { component: component, metadata: metadata || {} }
widgets = next
revision++
changed()
}
function unregister(id) {
var key = String(id)
if (!widgets[key]) return
var next = {}
for (var k in widgets) if (k !== key) next[k] = widgets[k]
widgets = next
revision++
changed()
}
function metadataFor(id) {
var entry = widgets[String(id)]
return entry ? entry.metadata : null
}
function availableIds() {
return Object.keys(widgets)
}
function has(id) {
return widgets[String(id)] !== undefined
}
}
+46
View File
@@ -0,0 +1,46 @@
import QtQuick
// Detached application-library capability for third-party menus. Callbacks
// expose the supported app-list operations without retaining AppLibrary or its
// ShellRoot parent in the plugin-visible object graph.
QtObject {
required property string ownerPluginId
signal appsChanged()
property var _entryName: null
property var _entrySubtext: null
property var _sortedEntries: null
property var _iconSource: null
property var _refreshIcons: null
property var _launch: null
property var _remove: null
function entryName(entry) {
return _entryName ? _entryName(entry) : ""
}
function entrySubtext(entry) {
return _entrySubtext ? _entrySubtext(entry) : ""
}
function sortedEntries(query) {
return _sortedEntries ? _sortedEntries(String(query || "")) : []
}
function iconSource(icon) {
return _iconSource ? _iconSource(icon) : ""
}
function refreshIcons() {
if (_refreshIcons) _refreshIcons()
}
function launch(desktopId, name) {
if (_launch) _launch(String(desktopId || ""), String(name || ""))
}
function remove(desktopId, name) {
if (_remove) _remove(String(desktopId || ""), String(name || ""))
}
}
+12
View File
@@ -0,0 +1,12 @@
import QtQuick
// Scalar-only view of the active bar for plugins that position independent
// windows. The active Bar QObject is never retained here.
QtObject {
required property string ownerPluginId
property bool barHidden: false
property int barSize: 0
property string fontFamily: ""
property string position: "top"
}
@@ -0,0 +1,24 @@
import QtQuick
// Detached widget-catalogue snapshot for third-party full-bar implementations.
// Plugins can render the referenced components, but mutating this local view
// cannot replace a registration in the host registry.
QtObject {
id: api
property var widgets: ({})
property int revision: 0
function metadataFor(id) {
var entry = widgets[String(id || "")]
return entry ? entry.metadata : null
}
function availableIds() {
return Object.keys(widgets)
}
function has(id) {
return widgets[String(id || "")] !== undefined
}
}
@@ -0,0 +1,46 @@
import QtQuick
// Narrow proxy for the non-authentication first-party services used by the
// built-in bar. It intentionally has no generic property or method forwarding.
QtObject {
required property string ownerPluginId
required property string serviceId
property bool stayAwake: false
property bool enabled: false
property bool doNotDisturb: false
property var activePlayer: null
property var sourcePlayers: []
property var _setIdleEnabled: null
property var _setNightlight: null
property var _setDoNotDisturb: null
property var _runAction: null
property var _playerKey: null
property var _selectPlayer: null
function setIdleEnabled(value) {
if (serviceId === "blob.idle" && _setIdleEnabled) _setIdleEnabled(!!value)
}
function setNightlight(value) {
if (serviceId === "blob.nightlight" && _setNightlight) _setNightlight(!!value)
}
function setDoNotDisturb(value) {
if (serviceId === "blob.notifications" && _setDoNotDisturb) _setDoNotDisturb(!!value)
}
function runAction(action, showFeedback, playerId) {
if (serviceId === "blob.media" && _runAction)
_runAction(String(action || ""), !!showFeedback, String(playerId || ""))
}
function playerKey(player) {
return serviceId === "blob.media" && _playerKey ? _playerKey(player) : ""
}
function selectPlayer(playerId) {
if (serviceId === "blob.media" && _selectPlayer) _selectPlayer(String(playerId || ""))
}
}
+743
View File
@@ -0,0 +1,743 @@
import QtQuick
import Quickshell
import Quickshell.Io
import qs.Commons
// Instance, not a singleton — see BarWidgetRegistry for rationale.
QtObject {
id: registry
property string home: Quickshell.env("HOME")
property string pluginsDir: home + "/.config/blob/plugins"
// Set by shell.qml at startup so we can also scan bundled first-party plugins.
property string firstPartyDir: ""
// Wired by shell.qml so the registry can read the canonical shell.json
// without owning file IO itself. shellConfigProvider returns the current
// effective shell config; shellConfigMutator takes a function that receives
// a deep-cloned config it can mutate in place and persists the result.
property var shellConfigProvider: null
property var shellConfigMutator: null
// { pluginId: manifest } — manifests have source/trust metadata stamped in.
property var installedPlugins: ({})
property int registryRevision: 0
property bool scanning: false
property string lastEnableError: ""
signal pluginsChanged()
signal scanFinished()
signal pluginLoadFailed(string id, string error)
signal localPluginChanged(string id)
// ---------------------------------------------------------------- helpers
function isSafeEntryPoint(value) {
if (typeof value !== "string" || value.length === 0) return false
if (value.charAt(0) === "/") return false
if (value.indexOf("..") !== -1) return false
return true
}
function validateManifest(manifest, sourcePath) {
if (!Util.isPlainObject(manifest)) {
console.warn("PluginRegistry: manifest is not an object at " + sourcePath)
return null
}
if (manifest.schemaVersion !== 1) {
console.warn("PluginRegistry: unsupported schemaVersion at " + sourcePath)
return null
}
var required = ["id", "name", "version", "kinds", "entryPoints"]
for (var i = 0; i < required.length; i++) {
if (manifest[required[i]] === undefined) {
console.warn("PluginRegistry: missing required field '" + required[i] + "' at " + sourcePath)
return null
}
}
var id = String(manifest.id)
if (!id || id.indexOf("/") !== -1 || id.indexOf("..") !== -1 || id.charAt(0) === "/") {
console.warn("PluginRegistry: invalid plugin id '" + id + "' at " + sourcePath)
return null
}
if (!Array.isArray(manifest.kinds) || manifest.kinds.length === 0) {
console.warn("PluginRegistry: kinds must be a non-empty array at " + sourcePath)
return null
}
if (!Util.isPlainObject(manifest.entryPoints)) {
console.warn("PluginRegistry: entryPoints must be an object at " + sourcePath)
return null
}
if (manifest.barWidget !== undefined && Util.isPlainObject(manifest.barWidget)
&& manifest.barWidget.defaultSection !== undefined) {
var defaultSection = String(manifest.barWidget.defaultSection)
if (["left", "center", "right"].indexOf(defaultSection) === -1) {
console.warn("PluginRegistry: invalid barWidget.defaultSection at " + sourcePath)
return null
}
}
// Every entry point must be a relative path inside the plugin's source
// directory. Reject the whole manifest if an entry point escapes it.
for (var key in manifest.entryPoints) {
if (!isSafeEntryPoint(manifest.entryPoints[key])) {
console.warn("PluginRegistry: unsafe entryPoint '" + key + "'='"
+ manifest.entryPoints[key] + "' at " + sourcePath)
return null
}
}
return manifest
}
function trustedCapabilities(manifest) {
if (!manifest || !manifest.__isFirstParty) return []
var metadata = Util.isPlainObject(manifest.blob) ? manifest.blob : null
var declared = metadata && Array.isArray(metadata.capabilities) ? metadata.capabilities : []
var out = []
for (var i = 0; i < declared.length; i++) {
var capability = String(declared[i] || "")
if (capability && out.indexOf(capability) === -1) out.push(capability)
}
return out
}
function stampHostCapabilities(firstParty, thirdParty) {
for (var firstPartyId in firstParty)
firstParty[firstPartyId].__hostCapabilities = trustedCapabilities(firstParty[firstPartyId])
for (var thirdPartyId in thirdParty) {
var manifest = thirdParty[thirdPartyId]
var metadata = manifest && Util.isPlainObject(manifest.blob) ? manifest.blob : null
var clonedFrom = metadata ? String(metadata.clonedFrom || "") : ""
var source = clonedFrom ? firstParty[clonedFrom] : null
manifest.__hostCapabilities = source && Array.isArray(source.__hostCapabilities)
? source.__hostCapabilities.slice() : []
}
}
function entryPointUrl(manifest, kind) {
if (!Util.isPlainObject(manifest)) return ""
var ep = manifest.entryPoints ? manifest.entryPoints[kind] : null
if (!ep) return ""
var dir = manifest.__sourceDir || ""
if (!dir) return ""
// Defense in depth: even after validateManifest, confirm the resolved
// path stays inside the plugin's sourceDir.
var resolved = dir.replace(/\/$/, "") + "/" + String(ep)
var expectedPrefix = dir.replace(/\/$/, "") + "/"
if (resolved.indexOf(expectedPrefix) !== 0) {
console.warn("PluginRegistry: entry point escapes sourceDir: " + resolved)
return ""
}
return Util.fileUrl(resolved)
}
// Enabled = the plugin id is referenced somewhere in shell.json. That can
// be either the active bar option in `bar.id`, a layout entry inside
// `bar.layout.*` (bar widgets), or a top-level entry in `plugins[]` (panels,
// overlays, services).
//
// Special cases (implicitly always enabled, no shell.json entry needed):
// - the built-in bar option (`blob.bar`) is active when `bar.id` is
// missing or set to `blob.bar`.
// - first-party non-bar plugins are shell infrastructure (settings,
// image-picker, ...). Requiring users to add them to plugins[] just to
// summon them was a footgun: a stock shell.json with `plugins: []` would
// silently make `blob launch bar-settings` a no-op. Turning one off
// is therefore recorded the other way round, in `disabledPlugins[]`.
function isEnabled(id) {
var key = String(id)
var manifest = installedPlugins[key]
var config = shellConfigProvider ? shellConfigProvider() : null
if (manifest) {
if (Array.isArray(manifest.kinds) && manifest.kinds.indexOf("bar") !== -1) {
var selectedBar = ""
if (Util.isPlainObject(config) && Util.isPlainObject(config.bar))
selectedBar = Util.canonicalWidgetId(String(config.bar.id || ""))
if (!selectedBar) selectedBar = "blob.bar"
return selectedBar === key
}
if (isDisabled(config, key)) return false
if (manifest.__isFirstParty) return true
}
return findEntryLocation(config, key).found
}
function isDisabled(config, id) {
return Util.isPlainObject(config) && Array.isArray(config.disabledPlugins)
&& config.disabledPlugins.indexOf(Util.canonicalWidgetId(String(id))) !== -1
}
function resolveEnabledId(id) {
var key = Util.canonicalWidgetId(String(id || ""))
// Callers keep using the built-in id after cloning; the enabled local
// manifest is the implementation that should receive the call.
for (var candidate in installedPlugins) {
var manifest = installedPlugins[candidate]
var metadata = manifest && Util.isPlainObject(manifest.blob) ? manifest.blob : null
if (metadata && String(metadata.clonedFrom || "") === key && isEnabled(candidate))
return candidate
}
return key
}
// A bar widget is on when it sits in the bar, whoever shipped it. That is a
// different question from isEnabled(), which decides whether the widget's
// component is loaded at all — a built-in stays loadable so it can be put
// back, and so a plugin that is both a widget and a menu (blob.menu)
// cannot be locked out of the shell by taking its button off the bar.
function inBar(id) {
var config = shellConfigProvider ? shellConfigProvider() : null
return findEntryLocation(config, id).kind === "bar"
}
function defaultBarWidgetSection(manifest) {
var metadata = manifest && Util.isPlainObject(manifest.barWidget) ? manifest.barWidget : null
var section = metadata ? String(metadata.defaultSection || "") : ""
return ["left", "center", "right"].indexOf(section) !== -1 ? section : "center"
}
function barEntryId(entry) {
return Util.canonicalWidgetId(String(Util.isPlainObject(entry) ? entry.id : entry || ""))
}
function findBarLocation(config, id, section) {
if (!Util.isPlainObject(config) || !Util.isPlainObject(config.bar)
|| !Util.isPlainObject(config.bar.layout)) return { found: false }
var key = Util.canonicalWidgetId(String(id))
var sections = ["left", "center", "right"]
for (var s = 0; s < sections.length; s++) {
if (section && sections[s] !== section) continue
var entries = config.bar.layout[sections[s]]
if (!Array.isArray(entries)) continue
for (var i = 0; i < entries.length; i++) {
if (barEntryId(entries[i]) === key)
return { found: true, kind: "bar", section: sections[s], index: i }
}
}
return { found: false }
}
// A caller naming a widget that has been cloned means the clone that took
// its place, the way resolveEnabledId routes calls to it.
function findRelativeBarLocation(config, id, section) {
var location = findBarLocation(config, id, section)
if (location.found) return location
if (!Util.isPlainObject(config) || !Util.isPlainObject(config.bar)) return { found: false }
var clone = activeCloneFor(config, Util.canonicalWidgetId(String(id)))
return clone ? findBarLocation(config, clone, section) : { found: false }
}
function findEntryLocation(config, id) {
if (!Util.isPlainObject(config)) return { found: false }
var key = Util.canonicalWidgetId(String(id))
if (Util.isPlainObject(config.bar)) {
var selectedBar = Util.canonicalWidgetId(String(config.bar.id || ""))
if (selectedBar === key) return { found: true, kind: "bar-option" }
}
if (Util.isPlainObject(config.bar) && Util.isPlainObject(config.bar.layout)) {
var barLocation = findBarLocation(config, key, "")
if (barLocation.found) return barLocation
}
if (Array.isArray(config.plugins)) {
for (var j = 0; j < config.plugins.length; j++) {
if (config.plugins[j] && Util.canonicalWidgetId(config.plugins[j].id) === key) return { found: true, kind: "plugin", index: j }
}
}
return { found: false }
}
function barTarget(config, placement, fallbackSection) {
var target = placement || {}
var section = ["left", "center", "right"].indexOf(String(target.section || "")) !== -1
? String(target.section) : fallbackSection
var relativeId = String(target.before || target.after || "")
if (relativeId) {
var relative = findRelativeBarLocation(config, relativeId, section && target.section ? section : "")
if (!relative.found) return { error: "could not find target widget " + relativeId }
return {
section: relative.section,
index: relative.index + (target.after ? 1 : 0)
}
}
if (!Array.isArray(config.bar.layout[section])) config.bar.layout[section] = []
if (target.index !== undefined && target.index !== null) {
var requested = Math.max(0, Math.floor(Number(target.index)))
return { section: section, index: Math.min(requested, config.bar.layout[section].length) }
}
var anchors = { left: "blob.workspaces", center: "blob.weather", right: "blob.tray" }
var anchor = findRelativeBarLocation(config, anchors[section], section)
return {
section: section,
index: anchor.found ? anchor.index + 1 : config.bar.layout[section].length
}
}
function moveBarEntry(config, id, placement) {
var key = Util.canonicalWidgetId(String(id))
var source
if (placement.fromIndex !== undefined && placement.fromIndex !== null) {
var fromSection = String(placement.fromSection || "")
if (!fromSection) return "from-index requires from-section"
var entries = config.bar.layout[fromSection]
var fromIndex = Math.floor(Number(placement.fromIndex))
if (!Array.isArray(entries) || fromIndex < 0 || fromIndex >= entries.length)
return "no widget at " + fromSection + "[" + fromIndex + "]"
if (barEntryId(entries[fromIndex]) !== key)
return "widget at " + fromSection + "[" + fromIndex + "] is not " + key
source = { found: true, section: fromSection, index: fromIndex }
} else {
source = findBarLocation(config, key, String(placement.fromSection || ""))
if (!source.found) return "could not find widget " + key
}
var entry = config.bar.layout[source.section][source.index]
config.bar.layout[source.section].splice(source.index, 1)
var target = barTarget(config, placement, source.section)
if (target.error) {
config.bar.layout[source.section].splice(source.index, 0, entry)
return target.error
}
config.bar.layout[target.section].splice(target.index, 0, entry)
return ""
}
function moveBarWidget(id, placement) {
var error = ""
shellConfigMutator(function(config) {
ensureConfigShape(config)
error = moveBarEntry(config, id, placement || {})
})
if (error) return error
registryRevision++
pluginsChanged()
return ""
}
// put is the unattended verb: where enable errors, it falls back, and it
// leaves a widget that is already on the bar where its owner put it.
function putBarWidget(id, placement) {
if (inBar(id)) return ""
var config = shellConfigProvider ? shellConfigProvider() : null
// Enabling a source whose clone is active switches back to the built-in,
// which is the owner's call, not an unattended caller's.
if (findRelativeBarLocation(config, id, "").found) return ""
// The manifest scan is a subprocess and IPC answers before it returns, so
// an id it has not reached yet is not one that does not exist.
if (scanning && !installedPlugins[Util.canonicalWidgetId(String(id))]) return "not ready"
var target = Util.isPlainObject(placement) ? Util.cloneJson(placement) : {}
var relativeId = String(target.before || target.after || "")
if (relativeId) {
if (!findRelativeBarLocation(config, relativeId, String(target.section || "")).found) {
delete target.before
delete target.after
}
}
if (setEnabled(id, true, target)) return ""
return lastEnableError || "unknown"
}
function setBarWidget(id, key, value, selector) {
var error = ""
shellConfigMutator(function(config) {
ensureConfigShape(config)
var location
var requested = selector || {}
var section = String(requested.fromSection || requested.section || "")
var index = requested.fromIndex !== undefined && requested.fromIndex !== null
? requested.fromIndex : requested.index
if (index !== undefined && index !== null) {
if (!section) {
error = "index requires section"
return
}
var entries = config.bar.layout[section]
var numericIndex = Math.floor(Number(index))
if (!Array.isArray(entries) || numericIndex < 0 || numericIndex >= entries.length) {
error = "no widget at " + section + "[" + numericIndex + "]"
return
}
location = { found: true, section: section, index: numericIndex }
} else {
location = findBarLocation(config, id, section)
}
if (!location.found) {
error = "could not find widget " + id
return
}
if (barEntryId(config.bar.layout[location.section][location.index]) !== String(id)) {
error = "widget at " + location.section + "[" + location.index + "] is not " + id
return
}
var entry = config.bar.layout[location.section][location.index]
if (!Util.isPlainObject(entry)) {
error = "widget entry must be an object"
return
}
entry[String(key)] = value
})
if (error) return error
registryRevision++
pluginsChanged()
return ""
}
function ensureConfigShape(config) {
if (!Util.isPlainObject(config.bar)) config.bar = { layout: { left: [], center: [], right: [] } }
if (!Util.isPlainObject(config.bar.layout)) config.bar.layout = { left: [], center: [], right: [] }
var sections = ["left", "center", "right"]
for (var i = 0; i < sections.length; i++) {
if (!Array.isArray(config.bar.layout[sections[i]])) config.bar.layout[sections[i]] = []
}
if (!Array.isArray(config.plugins)) config.plugins = []
}
// Bar widgets use the default section declared in their manifest, falling
// back to center. Panels/overlays/menus/services go into the plugins[] array.
// Built-ins are already loaded, so shell.json only ever records the
// deviation: an added third-party plugin in plugins[], a switched-off
// built-in in disabledPlugins[].
function removeDisabled(config, id) {
if (!Array.isArray(config.disabledPlugins)) return
config.disabledPlugins = config.disabledPlugins.filter(function(entry) { return entry !== id })
if (config.disabledPlugins.length === 0) delete config.disabledPlugins
}
function addDisabled(config, id) {
if (isDisabled(config, id)) return
if (!Array.isArray(config.disabledPlugins)) config.disabledPlugins = []
config.disabledPlugins.push(id)
}
function cloneShouldRestoreSource(config, id) {
return Array.isArray(config.cloneSourceRestores) && config.cloneSourceRestores.indexOf(id) !== -1
}
function setCloneShouldRestoreSource(config, id, value) {
var restores = Array.isArray(config.cloneSourceRestores) ? config.cloneSourceRestores : []
restores = restores.filter(function(entry) { return entry !== id })
if (value) restores.push(id)
if (restores.length) config.cloneSourceRestores = restores
else delete config.cloneSourceRestores
}
function activeCloneFor(config, sourceId) {
for (var candidate in installedPlugins) {
var candidateManifest = installedPlugins[candidate]
var candidateMetadata = candidateManifest && Util.isPlainObject(candidateManifest.blob)
? candidateManifest.blob : null
if (!candidateMetadata || String(candidateMetadata.clonedFrom || "") !== sourceId) continue
if (Array.isArray(candidateManifest.kinds) && candidateManifest.kinds.indexOf("bar") !== -1) {
if (Util.canonicalWidgetId(String(config.bar.id || "")) === candidate) return candidate
} else if (findEntryLocation(config, candidate).found) {
return candidate
}
}
return ""
}
function restoreCloneSource(config, cloneId, sourceId) {
var cloneManifest = installedPlugins[cloneId]
var isBarOption = cloneManifest && Array.isArray(cloneManifest.kinds)
&& cloneManifest.kinds.indexOf("bar") !== -1
if (isBarOption) {
if (sourceId === "blob.bar") delete config.bar.id
else config.bar.id = sourceId
} else {
var cloneLocation = findEntryLocation(config, cloneId)
if (cloneLocation.kind === "bar") {
var cloneEntry = config.bar.layout[cloneLocation.section][cloneLocation.index]
var sections = ["left", "center", "right"]
for (var s = 0; s < sections.length; s++) {
for (var i = config.bar.layout[sections[s]].length - 1; i >= 0; i--) {
if (barEntryId(config.bar.layout[sections[s]][i]) === sourceId)
config.bar.layout[sections[s]].splice(i, 1)
}
}
cloneLocation = findBarLocation(config, cloneId, "")
if (cloneLocation.found) {
var restoredEntry = Util.isPlainObject(cloneEntry) ? Util.cloneJson(cloneEntry) : {}
restoredEntry.id = sourceId
config.bar.layout[cloneLocation.section][cloneLocation.index] = restoredEntry
}
} else if (cloneLocation.kind === "plugin") {
config.plugins.splice(cloneLocation.index, 1)
}
}
if (cloneShouldRestoreSource(config, cloneId)) removeDisabled(config, sourceId)
setCloneShouldRestoreSource(config, cloneId, false)
}
function setEnabled(id, value, placement) {
var key = Util.canonicalWidgetId(String(id))
lastEnableError = ""
if (!shellConfigMutator) {
console.warn("PluginRegistry.setEnabled called before shellConfigMutator wired")
return false
}
var manifest = installedPlugins[key]
if (value && !manifest) {
console.warn("PluginRegistry.setEnabled: unknown plugin " + key)
return false
}
var isBarOption = manifest && Array.isArray(manifest.kinds) && manifest.kinds.indexOf("bar") !== -1
var isBarWidget = manifest && Array.isArray(manifest.kinds) && manifest.kinds.indexOf("bar-widget") !== -1
var hasNonWidgetKind = manifest && Array.isArray(manifest.kinds)
&& manifest.kinds.some(function(kind) { return kind !== "bar-widget" })
var metadata = manifest && Util.isPlainObject(manifest.blob) ? manifest.blob : null
var clonedFrom = metadata ? Util.canonicalWidgetId(String(metadata.clonedFrom || "")) : ""
shellConfigMutator(function(config) {
ensureConfigShape(config)
if (value && placement && (placement.before || placement.after)) {
var relativeId = String(placement.before || placement.after)
if (!findRelativeBarLocation(config, relativeId, String(placement.section || "")).found) {
lastEnableError = "could not find target widget " + relativeId
return
}
}
if (value && manifest && manifest.__isFirstParty) {
var activeClone = activeCloneFor(config, key)
if (activeClone) {
restoreCloneSource(config, activeClone, key)
removeDisabled(config, key)
}
}
if (isBarOption) {
if (value) {
config.bar.id = key
} else if (Util.canonicalWidgetId(String(config.bar.id || "")) === key) {
if (clonedFrom && clonedFrom !== "blob.bar") config.bar.id = clonedFrom
else delete config.bar.id
}
return
}
var isFirstParty = manifest && manifest.__isFirstParty
var location = findEntryLocation(config, key)
if (value) {
removeDisabled(config, key)
var entry = { id: key }
var insertedWithPlacement = false
if (!location.found && isBarWidget) {
var sourceLocation = clonedFrom ? findEntryLocation(config, clonedFrom) : { found: false }
if (sourceLocation.kind === "bar") {
var sourceEntry = config.bar.layout[sourceLocation.section][sourceLocation.index]
var replacement = Util.isPlainObject(sourceEntry) ? Util.cloneJson(sourceEntry) : entry
replacement.id = key
config.bar.layout[sourceLocation.section][sourceLocation.index] = replacement
} else {
var section = defaultBarWidgetSection(manifest)
var target = barTarget(config, placement || {}, section)
config.bar.layout[target.section].splice(target.index, 0, entry)
insertedWithPlacement = true
}
} else if (!location.found && !isFirstParty) {
config.plugins.push(entry)
}
if (isBarWidget && !insertedWithPlacement && placement && Object.keys(placement).length)
moveBarEntry(config, key, placement)
if (clonedFrom && hasNonWidgetKind && !isDisabled(config, clonedFrom)) {
addDisabled(config, clonedFrom)
setCloneShouldRestoreSource(config, key, true)
}
return
}
if (clonedFrom) restoreCloneSource(config, key, clonedFrom)
else if (location.kind === "bar") config.bar.layout[location.section].splice(location.index, 1)
else if (location.kind === "plugin") config.plugins.splice(location.index, 1)
// Dropping the layout entry is the whole story for a widget. Anything
// else built-in loads by default, so switching it off has to be stated.
if (isFirstParty && !isBarWidget) addDisabled(config, key)
})
if (lastEnableError) return false
registryRevision++
pluginsChanged()
return true
}
// ---------------------------------------------------------------- scanning
// Output format produced by the rescan script:
// ===<kind>::<absolute-source-dir>===
// ... raw manifest.json content ...
// === EOM ===
// (repeating for every manifest found)
function parseScanOutput(text) {
var lines = String(text || "").split("\n")
var firstParty = {}
var thirdParty = {}
var currentSource = null
var currentKind = null
var currentJson = []
function flush() {
if (!currentSource) return
var raw = currentJson.join("\n").trim()
try {
var manifest = JSON.parse(raw)
manifest.__sourceDir = currentSource
manifest.__isFirstParty = (currentKind === "firstparty")
var validated = validateManifest(manifest, currentSource + "/manifest.json")
if (validated) {
if (currentKind === "firstparty") firstParty[validated.id] = validated
else thirdParty[validated.id] = validated
}
} catch (e) {
console.warn("PluginRegistry: bad manifest at " + currentSource + ": " + e)
}
currentSource = null
currentKind = null
currentJson = []
}
for (var i = 0; i < lines.length; i++) {
var line = lines[i]
var startMatch = line.match(/^===([a-z]+)::(.+)===$/)
if (startMatch) {
flush()
currentKind = startMatch[1]
currentSource = startMatch[2].replace(/\/$/, "")
currentJson = []
continue
}
if (line === "=== EOM ===") {
flush()
continue
}
if (currentSource) currentJson.push(line)
}
flush()
stampHostCapabilities(firstParty, thirdParty)
var merged = {}
for (var fk in firstParty) merged[fk] = firstParty[fk]
// Third-party plugins never shadow first-party ids. The whole
// `blob.*` namespace is reserved for built-ins, including bar widgets
// registered outside the manifest-based plugin registry.
for (var tk in thirdParty) {
if (firstParty[tk] || String(tk).indexOf("blob.") === 0) {
console.warn("PluginRegistry: plugin " + tk
+ " rejected: id is reserved for first-party Blob plugins")
continue
}
merged[tk] = thirdParty[tk]
}
installedPlugins = merged
registryRevision++
scanning = false
pluginsChanged()
scanFinished()
}
property Process scanProcess: Process {
onExited: function(exitCode) {
var output = scanStdout.text || ""
registry.parseScanOutput(output)
}
stdout: StdioCollector {
id: scanStdout
waitForEnd: true
}
}
property Process initProcess: Process {
onExited: {
localPluginWatcher.running = true
registry.rescan()
}
}
property Process localPluginWatcher: Process {
command: [
"inotifywait",
"-m",
"-r",
"-q",
"-e",
"close_write,create,delete,move",
"--format",
"%w%f",
registry.pluginsDir
]
stdout: SplitParser {
onRead: function(path) {
var pluginId = registry.localPluginIdForPath(path)
if (pluginId) registry.localPluginChanged(pluginId)
}
}
onExited: localPluginWatcherRestart.restart()
}
property Timer localPluginWatcherRestart: Timer {
interval: 1000
onTriggered: localPluginWatcher.running = true
}
function rescan() {
if (scanning) return
scanning = true
// $0 = first-party dir, $1 = third-party dir. Some bash versions need the explicit -- separator.
// First-party plugins may be grouped one level deeper, e.g. panels/audio
// or services/battery.
// First-party bar widgets can also carry sibling manifests such as
// widgets/Clock.manifest.json so multiple widgets can live in one source
// directory without wrapper folders.
// Third-party plugins stay at the top level of ~/.config/blob/plugins.
var script = ""
+ "emit_manifest() { local kind=\"$1\"; local manifest=\"$2\"; local sub; "
+ " if [[ ${manifest##*/} == \"manifest.json\" ]]; then sub=\"${manifest%/manifest.json}\"; else sub=\"$(dirname -- \"$manifest\")\"; fi; "
+ " printf '===%s::%s===\\n' \"$kind\" \"$sub\"; "
+ " cat \"$manifest\"; "
+ " printf '\\n=== EOM ===\\n'; "
+ "}; "
+ "scan_firstparty() { local dir=\"$1\"; "
+ " [[ -d \"$dir\" ]] || return 0; "
+ " while IFS= read -r manifest; do emit_manifest firstparty \"$manifest\"; done < <(find \"$dir\" -mindepth 2 -maxdepth 3 -type f \\( -name manifest.json -o -name '*.manifest.json' \\) | sort); "
+ "}; "
+ "scan_thirdparty() { local dir=\"$1\"; "
+ " [[ -d \"$dir\" ]] || return 0; "
+ " for sub in \"$dir\"/*/; do "
+ " [[ -f \"$sub/manifest.json\" ]] || continue; "
+ " emit_manifest thirdparty \"$sub/manifest.json\"; "
+ " done; "
+ "}; "
+ "scan_firstparty \"$0\"; "
+ "scan_thirdparty \"$1\""
scanProcess.command = ["bash", "-c", script, registry.firstPartyDir, registry.pluginsDir]
scanProcess.running = true
}
function ensureUserDir() {
initProcess.command = ["bash", "-c", "mkdir -p \"$0\"", registry.pluginsDir]
initProcess.running = true
}
function localPluginIdForPath(filePath) {
var base = pluginsDir.replace(/\/$/, "") + "/"
var path = String(filePath || "").trim()
if (path.indexOf(base) !== 0) return ""
var relative = path.slice(base.length)
// Hidden entries are not plugins: clone staging dirs, remove backups.
if (relative.indexOf(".") === 0) return ""
if (relative.indexOf("/.git/") !== -1 || relative.endsWith("/.git")) return ""
var slash = relative.indexOf("/")
return slash === -1 ? relative : relative.slice(0, slash)
}
Component.onCompleted: ensureUserDir()
}
+32
View File
@@ -0,0 +1,32 @@
import QtQuick
// Read-only, self-scoped registry view for an installed third-party plugin.
// The host updates manifest/enabled when it rescans; no host registry object is
// retained here, so `parent` and property traversal cannot reach ShellRoot.
QtObject {
id: api
required property string pluginId
property var manifest: null
property bool enabled: false
property var _entryPointUrl: null
readonly property var installedPlugins: {
var out = ({})
if (manifest) out[pluginId] = manifest
return out
}
function isEnabled(id) {
return String(id || "") === pluginId && enabled
}
function resolveEnabledId(id) {
return String(id || "") === pluginId ? pluginId : ""
}
function entryPointUrl(candidate, kind) {
if (!candidate || String(candidate.id || "") !== pluginId) return ""
return _entryPointUrl ? _entryPointUrl(String(kind || "")) : ""
}
}
+70
View File
@@ -0,0 +1,70 @@
import QtQuick
// Capability-scoped shell surface for installed third-party plugins.
//
// The callbacks are closed over one plugin id by shell.qml. A plugin can call
// them directly, but it cannot widen their scope: ordinary plugins are limited
// to their own id, and full-bar callbacks independently enforce their explicit
// non-authentication UI scope. This object avoids directly injecting the host
// shell, but it is not a QML sandbox: visual plugins share the host object tree.
QtObject {
id: api
required property string pluginId
property var appLibrary: null
property var bar: null
property var barConfig: ({})
property var idleConfig: ({})
property var _serviceLookup: null
property var _firstPartyServiceLookup: null
property var _barEntryShellLookup: null
property var _summon: null
property var _hide: null
property var _toggle: null
property var _isOpen: null
property var _updateSettings: null
property var _mutateBarConfig: null
function serviceFor(id) {
return _serviceLookup ? _serviceLookup(String(id || "")) : null
}
// Full-bar facades and configured Indicators clones under the trusted bar
// receive narrow proxies for their specific non-authentication services.
function firstPartyServiceFor(id) {
return _firstPartyServiceLookup
? _firstPartyServiceLookup(String(id || "")) : null
}
function pluginShellForBarEntry(ownerId, moduleName) {
return _barEntryShellLookup
? _barEntryShellLookup(String(ownerId || ""), String(moduleName || "")) : null
}
function summon(id, payloadJson) {
return _summon ? _summon(String(id || ""), String(payloadJson || "")) : false
}
function hide(id) {
return _hide ? _hide(String(id || "")) : false
}
function toggle(id, payloadJson) {
return _toggle ? _toggle(String(id || ""), String(payloadJson || "")) : false
}
function isPluginOpen(id) {
return _isOpen ? _isOpen(String(id || "")) : false
}
function updateEntryInline(id, settings) {
return _updateSettings ? _updateSettings(String(id || ""), settings) : false
}
function mutateShellConfig(mutator) {
return _mutateBarConfig && typeof mutator === "function"
? _mutateBarConfig(mutator) : false
}
}
+102
View File
@@ -0,0 +1,102 @@
#!/bin/bash
desktop_names=${1:-}
declare -A seen_ids
desktop_matches() {
local list=$1
local desktop_name
local entry
IFS=":" read -ra desktop_parts <<< "$desktop_names"
IFS=";" read -ra entries <<< "$list"
for desktop_name in "${desktop_parts[@]}"; do
[[ -z $desktop_name ]] && continue
for entry in "${entries[@]}"; do
[[ -z $entry ]] && continue
[[ $entry == "$desktop_name" ]] && return 0
done
done
return 1
}
desktop_id_for_file() {
local dir=$1
local file=$2
local rel=${file#"$dir"/}
rel=${rel%.desktop}
printf '%s\n' "${rel//\//-}"
}
is_hidden_desktop_file() {
local file=$1
local in_desktop_entry=0
local hidden=false
local only_show_in=
local not_show_in=
local line key value
while IFS= read -r line || [[ -n $line ]]; do
line=${line%$'\r'}
if [[ $line =~ ^\[(.*)\]$ ]]; then
[[ ${BASH_REMATCH[1]} == "Desktop Entry" ]] && in_desktop_entry=1 || in_desktop_entry=0
continue
fi
(( in_desktop_entry )) || continue
[[ $line == *=* ]] || continue
key=${line%%=*}
value=${line#*=}
case $key in
Hidden|NoDisplay)
[[ $value == "true" ]] && hidden=true
;;
OnlyShowIn)
only_show_in=$value
;;
NotShowIn)
not_show_in=$value
;;
esac
done < "$file"
[[ $hidden == "true" ]] && return 0
[[ -n $only_show_in ]] && ! desktop_matches "$only_show_in" && return 0
[[ -n $not_show_in ]] && desktop_matches "$not_show_in" && return 0
return 1
}
scan_dir() {
local dir=$1
local file id
[[ -d $dir ]] || return
while IFS= read -r -d '' file; do
id=$(desktop_id_for_file "$dir" "$file")
[[ -n ${seen_ids[$id]+set} ]] && continue
seen_ids[$id]=1
if is_hidden_desktop_file "$file"; then
printf '%s\n' "$id"
fi
done < <(find "$dir" -type f -name '*.desktop' -print0 2>/dev/null | sort -z)
}
scan_dir "$HOME/.local/share/applications"
IFS=":" read -ra data_dirs <<< "${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
for data_dir in "${data_dirs[@]}"; do
scan_dir "$data_dir/applications"
done
scan_dir "$HOME/.nix-profile/share/applications"