repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by admin
quickshell/nuguland/features/launcher/launch.js
Raw// launch.js — pure app-launcher logic: match tiers, frecency, desktop-entry mapping.
// NO I/O. Dual-mode: node `require` (tests) + QML import.
var GLYPH_APP = "\uF135"; // rocket fallback when themed icon misses
// Match tiers, strongest last. An app's tier is its weakest query term's tier;
// frecency only reorders apps inside one tier.
var TIER = { other: 1, fuzzy: 2, initials: 3, substring: 4, word: 5, prefix: 6, exact: 7 };
// Non-name fields, in descending weight: generic name, keywords, categories, comment, desktop id.
var OTHER_WEIGHTS = [40, 30, 20, 10, 0];
// Frecency: each launch adds 1 to a score that halves every week.
var HALF_LIFE_MS = 7 * 24 * 60 * 60 * 1000;
// Decayed below this (about a month without launches), an app is forgotten.
var FRECENCY_FLOOR = 0.05;
// Accent- and case-insensitive text: NFD, combining marks stripped, lowercase.
function stripMarks(text) {
return String(text == null ? "" : text).normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}
function normalize(text) {
return stripMarks(text).trim().toLowerCase();
}
function prefixIntent(raw) {
return { intent: "app", query: String(raw == null ? "" : raw).trim() };
}
// Whitespace and ASCII punctuation separate words; every other character is part of one.
function isWordChar(ch) {
return ch.length > 0 && !/[\s!-\/:-@\[-`{-~]/.test(ch);
}
function isLower(ch) {
return ch !== ch.toUpperCase() && ch === ch.toLowerCase();
}
function isUpper(ch) {
return ch !== ch.toLowerCase() && ch === ch.toUpperCase();
}
// A searchable field: folded text plus the index of every word start (after a
// separator or at a camelCase hump), computed once per app list.
function searchField(value) {
var raw = stripMarks(value);
var starts = [];
for (var i = 0; i < raw.length; i++) {
var ch = raw.charAt(i);
var prev = i > 0 ? raw.charAt(i - 1) : "";
if (isWordChar(ch) && (!isWordChar(prev) || (isLower(prev) && isUpper(ch))))
starts.push(i);
}
return { text: raw.toLowerCase(), starts: starts };
}
function wordStartAt(field, term, from) {
for (var i = 0; i < field.starts.length; i++) {
var p = field.starts[i];
if (p >= from && field.text.startsWith(term, p))
return p;
}
return -1;
}
function searchIndex(name, others) {
var field = searchField(name);
var initials = "";
for (var i = 0; i < field.starts.length; i++)
initials += field.text.charAt(field.starts[i]);
return { name: field, initials: initials, others: others.map(searchField) };
}
// Smallest window of the name holding the term's characters in order.
function tightestSpan(term, text) {
var best = null;
for (var s = text.indexOf(term.charAt(0)); s >= 0; s = text.indexOf(term.charAt(0), s + 1)) {
var p = s;
for (var k = 1; k < term.length; k++) {
p = text.indexOf(term.charAt(k), p + 1);
if (p < 0)
return best; // a later start cannot fit either
}
if (!best || p - s + 1 < best.span)
best = { start: s, span: p - s + 1 };
}
return best;
}
function tierMatch(tier, quality) {
return { tier: tier, quality: Math.max(0, Math.min(99, quality)) };
}
// One query term against the name: prefix, word start, substring, initials, or
// tight fuzzy, whose span may hold fewer skipped characters than the term has.
function nameMatch(term, index) {
var name = index.name;
if (name.text.startsWith(term))
return tierMatch(name.text === term ? TIER.exact : TIER.prefix, 99 - (name.text.length - term.length));
var word = wordStartAt(name, term, 1);
if (word >= 0)
return tierMatch(TIER.word, 99 - word);
if (term.length < 2)
return null;
var sub = name.text.indexOf(term);
if (sub >= 0)
return tierMatch(TIER.substring, 99 - sub);
if (index.initials.startsWith(term))
return tierMatch(TIER.initials, 99 - (index.initials.length - term.length));
if (term.length < 3)
return null;
var fuzzy = tightestSpan(term, name.text);
if (fuzzy && fuzzy.span - term.length < term.length)
return tierMatch(TIER.fuzzy, 99 - 4 * (fuzzy.span - term.length) - fuzzy.start);
return null;
}
// Other fields count only where one of their words starts with the term;
// the heaviest such field wins, a whole-word hit slightly more.
function otherMatch(term, index) {
var best = null;
for (var i = 0; i < index.others.length; i++) {
var field = index.others[i];
var p = wordStartAt(field, term, 0);
if (p < 0)
continue;
var end = p + term.length;
var whole = end === field.text.length || !isWordChar(field.text.charAt(end)) || field.starts.indexOf(end) >= 0;
var quality = OTHER_WEIGHTS[i] + (whole ? 5 : 0);
if (!best || quality > best.quality)
best = tierMatch(TIER.other, quality);
}
return best;
}
function queryTerms(query) {
var folded = normalize(query);
return folded.length > 0 ? folded.split(/\s+/) : [];
}
// Every term must match (AND). The whole query may still match the name
// exactly or as a prefix; otherwise the weakest term sets the tier and the
// mean of the per-term scores orders apps inside it.
function matchApp(terms, index) {
var whole = terms.join(" ");
if (index.name.text.startsWith(whole))
return tierMatch(index.name.text === whole ? TIER.exact : TIER.prefix, 99 - (index.name.text.length - whole.length));
var tier = TIER.exact;
var total = 0;
for (var i = 0; i < terms.length; i++) {
var m = nameMatch(terms[i], index) || otherMatch(terms[i], index);
if (!m)
return null;
tier = Math.min(tier, m.tier);
total += m.tier * 100 + m.quality;
}
return { tier: tier, quality: total / terms.length };
}
// Frecency store: { "<desktop id>": { score, at } }, score as of `at` (ms).
function frecencyScore(entry, now) {
if (!entry)
return 0;
var age = Math.max(0, (Number(now) - Number(entry.at)) || 0);
var score = (Number(entry.score) || 0) * Math.pow(0.5, age / HALF_LIFE_MS);
return score >= FRECENCY_FLOOR ? score : 0;
}
function recordLaunch(store, id, now) {
var next = {};
var src = store || {};
for (var key in src) {
if (frecencyScore(src[key], now) > 0)
next[key] = src[key];
}
next[id] = { score: frecencyScore(src[id], now) + 1, at: now };
return next;
}
function parseFrecency(text) {
try {
var data = JSON.parse(text || "{}");
return data && typeof data.apps === "object" && data.apps ? data.apps : {};
} catch (error) {
return {};
}
}
function serializeFrecency(store) {
return JSON.stringify({ apps: store || {} }, null, 2);
}
function list(value) {
var out = [];
var src = value || [];
for (var i = 0; i < src.length; i++) {
var text = String(src[i] || "").trim();
if (text.length > 0)
out.push(text);
}
return out;
}
function primaryCategory(categories) {
var skip = { Qt: true, KDE: true, GNOME: true, GTK: true, Application: true, Core: true };
for (var i = 0; i < categories.length; i++) {
var cat = categories[i];
if (!skip[cat])
return cat;
}
return categories[0] || "app";
}
function buildDesktopActions(actions) {
var rows = [];
var src = actions || [];
for (var i = 0; i < src.length; i++) {
var a = src[i];
if (!a || !a.name)
continue;
rows.push({
id: String(a.id || a.name),
title: String(a.name),
icon: String(a.icon || "")
});
}
return rows;
}
function buildApps(entries) {
var rows = [];
var src = entries || [];
for (var i = 0; i < src.length; i++) {
var e = src[i];
if (!e || !e.name)
continue;
var id = String(e.id || e.name);
var categories = list(e.categories);
var keywords = list(e.keywords);
var genericName = String(e.genericName || "");
var comment = String(e.comment || "");
var kind = genericName || primaryCategory(categories);
var category = primaryCategory(categories);
var actions = buildDesktopActions(e.actions);
rows.push({
id: "app:" + id,
title: String(e.name),
subtitle: kind + (category && category !== kind ? " · " + category : ""),
genericName: genericName,
comment: comment,
desktopId: id,
desktopPath: id + ".desktop",
startupClass: String(e.startupClass || ""),
workingDirectory: String(e.workingDirectory || ""),
icon: String(e.icon || ""),
terminal: !!e.runInTerminal,
categories: categories,
keywords: keywords,
actions: actions,
details: [
{ label: "category", value: category },
{ label: "keywords", value: keywords.slice(0, 4).join("; ") || "—" },
{ label: "terminal", value: e.runInTerminal ? "yes" : "no" }
],
search: searchIndex(e.name, [genericName, keywords.join(" "), categories.join(" "), comment, id]),
route: "desktop-entry"
});
}
rows.sort(function (a, b) {
return String(a.title).localeCompare(String(b.title));
});
return rows;
}
function shapeRow(row, provider, score) {
var next = Object.assign({}, row || {});
delete next.search; // matching data stays out of the search response
next.provider = "app";
next.iconRole = "desktop-entry";
next.verb = "open";
next.glyph = GLYPH_APP;
next.score = score;
next.keyboard = true;
return next;
}
// sources: { apps, frecency, now }. Order: tier, then frecency, then match
// quality, then title. An empty query lists every app, frecent ones first.
function rankResults(rawQuery, sources) {
var src = sources || {};
var apps = src.apps || [];
var frecency = src.frecency || {};
var now = Number(src.now) || 0;
var intent = prefixIntent(rawQuery);
var terms = queryTerms(intent.query);
var ranked = [];
for (var i = 0; i < apps.length; i++) {
var app = apps[i];
var index = app.search || searchIndex(app.title, []);
var m = terms.length > 0 ? matchApp(terms, index) : { tier: 0, quality: 0 };
if (m)
ranked.push({ app: app, tier: m.tier, quality: m.quality, frecency: frecencyScore(frecency[app.desktopId], now) });
}
ranked.sort(function (x, y) {
return y.tier - x.tier || y.frecency - x.frecency || y.quality - x.quality || String(x.app.title).localeCompare(String(y.app.title));
});
var results = ranked.map(function (r) {
return shapeRow(r.app, "app", r.tier * 1000 + Math.round(r.quality));
});
return {
results: results,
selectedIndex: results.length > 0 ? 0 : -1,
providerIntent: intent.intent
};
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
TIER: TIER,
HALF_LIFE_MS: HALF_LIFE_MS,
normalize: normalize,
prefixIntent: prefixIntent,
searchIndex: searchIndex,
matchApp: matchApp,
queryTerms: queryTerms,
frecencyScore: frecencyScore,
recordLaunch: recordLaunch,
parseFrecency: parseFrecency,
serializeFrecency: serializeFrecency,
buildDesktopActions: buildDesktopActions,
buildApps: buildApps,
shapeRow: shapeRow,
rankResults: rankResults
};
}