Moved to module structure to work in embeded qs processes
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
pragma Singleton
|
||||
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Io
|
||||
|
||||
QtObject {
|
||||
id: root
|
||||
|
||||
// Defaults. User config overrides any of these.
|
||||
property string fontFamily: "JetBrainsMono Nerd Font Propo"
|
||||
property int fontSize: 16
|
||||
property string giphyApiKey: ""
|
||||
property int panelWidth: 720
|
||||
property int panelHeight: 520
|
||||
property int padding: 5
|
||||
property int spacing: 5
|
||||
property int radius: 10
|
||||
property string backgroundColor: ""
|
||||
property string foregroundColor: ""
|
||||
property string idleColor: ""
|
||||
property string accentColor: ""
|
||||
property string overlayStrongColor: ""
|
||||
property string overlayWeakColor: ""
|
||||
property string borderColor: ""
|
||||
|
||||
property bool loaded: false
|
||||
readonly property string configPath: (Quickshell.env("XDG_CONFIG_HOME") || (Quickshell.env("HOME") + "/.config")) + "/omni-launcher/config.json"
|
||||
|
||||
function _apply(obj) {
|
||||
if (typeof obj.fontFamily === "string" && obj.fontFamily.length > 0) fontFamily = obj.fontFamily;
|
||||
if (typeof obj.fontSize === "number" && obj.fontSize > 0) fontSize = obj.fontSize;
|
||||
if (typeof obj.giphyApiKey === "string") giphyApiKey = obj.giphyApiKey;
|
||||
if (typeof obj.panelWidth === "number" && obj.panelWidth > 0) panelWidth = obj.panelWidth;
|
||||
if (typeof obj.panelHeight === "number" && obj.panelHeight > 0) panelHeight = obj.panelHeight;
|
||||
if (typeof obj.padding === "number" && obj.padding > 0) padding = obj.padding;
|
||||
if (typeof obj.spacing === "number" && obj.spacing > 0) spacing = obj.spacing;
|
||||
if (typeof obj.radius === "number" && obj.radius >= 0) radius = obj.radius;
|
||||
|
||||
const colors = obj.colors || {};
|
||||
if (typeof colors.background === "string" && colors.background.length > 0) backgroundColor = colors.background;
|
||||
if (typeof colors.foreground === "string" && colors.foreground.length > 0) foregroundColor = colors.foreground;
|
||||
if (typeof colors.idle === "string" && colors.idle.length > 0) idleColor = colors.idle;
|
||||
if (typeof colors.accent === "string" && colors.accent.length > 0) accentColor = colors.accent;
|
||||
if (typeof colors.overlayStrong === "string" && colors.overlayStrong.length > 0) overlayStrongColor = colors.overlayStrong;
|
||||
if (typeof colors.overlayWeak === "string" && colors.overlayWeak.length > 0) overlayWeakColor = colors.overlayWeak;
|
||||
if (typeof colors.border === "string" && colors.border.length > 0) borderColor = colors.border;
|
||||
}
|
||||
|
||||
Component.onCompleted: {
|
||||
_load();
|
||||
_startWatcher();
|
||||
}
|
||||
|
||||
function _load() {
|
||||
_loader.running = false;
|
||||
_loader.command = ["cat", configPath];
|
||||
_loader.running = true;
|
||||
}
|
||||
|
||||
function _startWatcher() {
|
||||
_watcher.running = false;
|
||||
_watcher.command = [
|
||||
"sh", "-c",
|
||||
"while inotifywait -q -e close_write " + JSON.stringify(configPath) + " 2>/dev/null; do echo CHANGED; done"
|
||||
];
|
||||
_watcher.running = true;
|
||||
}
|
||||
|
||||
property Process _watcher: Process {
|
||||
running: false
|
||||
stdout: SplitParser {
|
||||
splitMarker: "\n"
|
||||
onRead: line => {
|
||||
if (line.indexOf("CHANGED") >= 0) {
|
||||
console.log("omni-launcher: config changed, reloading");
|
||||
root._load();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onExited: root._startWatcher()
|
||||
}
|
||||
|
||||
property Process _loader: Process {
|
||||
running: false
|
||||
stdout: StdioCollector {
|
||||
onStreamFinished: {
|
||||
const text = (this.text || "").trim();
|
||||
if (text.length > 0) {
|
||||
try {
|
||||
root._apply(JSON.parse(text));
|
||||
} catch (e) {
|
||||
console.log("omni-launcher: config.json parse error:", e);
|
||||
}
|
||||
}
|
||||
root.loaded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import QtQuick
|
||||
import Quickshell.Hyprland
|
||||
import Quickshell.Hyprland._FocusGrab
|
||||
|
||||
Item {
|
||||
id: root
|
||||
|
||||
// Set by the Loader's parent — the launcher PanelWindow. We can't access
|
||||
// siblings directly, so pass it through this property.
|
||||
property var window: null
|
||||
property bool armed: false
|
||||
|
||||
HyprlandFocusGrab {
|
||||
active: root.armed && root.window !== null
|
||||
windows: root.window ? [root.window] : []
|
||||
onCleared: LauncherService.close()
|
||||
}
|
||||
|
||||
Connections {
|
||||
target: Hyprland
|
||||
function onFocusedWorkspaceChanged() {
|
||||
if (root.armed) LauncherService.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
|
||||
Item {
|
||||
id: root
|
||||
property var entry: null
|
||||
|
||||
readonly property bool noIcon: entry && entry._noIcon === true
|
||||
readonly property string iconName: entry && entry.icon ? entry.icon : ""
|
||||
readonly property string appName: entry && entry.name ? entry.name : "?"
|
||||
readonly property bool iconOk: !noIcon && iconName.length > 0 && Quickshell.hasThemeIcon(iconName)
|
||||
|
||||
visible: !noIcon
|
||||
|
||||
// Hash app name into a stable hue so each fallback tile is distinct but consistent.
|
||||
readonly property int hue: {
|
||||
let h = 0;
|
||||
for (let i = 0; i < appName.length; i++) h = (h * 31 + appName.charCodeAt(i)) | 0;
|
||||
return Math.abs(h) % 360;
|
||||
}
|
||||
|
||||
Image {
|
||||
id: img
|
||||
anchors.fill: parent
|
||||
source: root.iconOk ? Quickshell.iconPath(root.iconName) : ""
|
||||
fillMode: Image.PreserveAspectFit
|
||||
smooth: true
|
||||
asynchronous: true
|
||||
visible: root.iconOk
|
||||
sourceSize.width: width * 2
|
||||
sourceSize.height: height * 2
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
visible: !root.iconOk
|
||||
radius: width * 0.22
|
||||
color: Qt.hsla(root.hue / 360, 0.45, 0.35, 1)
|
||||
|
||||
Text {
|
||||
anchors.centerIn: parent
|
||||
text: root.appName.length > 0 ? root.appName.charAt(0).toUpperCase() : "?"
|
||||
color: "#ffffff"
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: parent.width * 0.55
|
||||
font.bold: true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
import QtQuick
|
||||
import QtQuick.Controls
|
||||
import QtQuick.Layouts
|
||||
import Quickshell
|
||||
import Quickshell.Wayland
|
||||
|
||||
PanelWindow {
|
||||
id: root
|
||||
|
||||
visible: LauncherService.visible
|
||||
color: "transparent"
|
||||
|
||||
anchors {
|
||||
top: true
|
||||
bottom: true
|
||||
left: true
|
||||
right: true
|
||||
}
|
||||
|
||||
exclusiveZone: 0
|
||||
WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive
|
||||
WlrLayershell.layer: WlrLayer.Overlay
|
||||
|
||||
readonly property int panelWidth: Config.panelWidth
|
||||
readonly property int panelHeight: Config.panelHeight
|
||||
|
||||
// Hyprland-only nicety: close on workspace switch + focus-grab dismissal.
|
||||
// Loaded lazily so the import only resolves on Hyprland.
|
||||
Loader {
|
||||
active: Quickshell.env("HYPRLAND_INSTANCE_SIGNATURE").length > 0
|
||||
source: "HyprlandIntegration.qml"
|
||||
onLoaded: {
|
||||
item.window = root;
|
||||
item.armed = Qt.binding(() => root.visible);
|
||||
}
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
onClicked: LauncherService.close()
|
||||
}
|
||||
|
||||
readonly property bool searching: LauncherService.query.length > 0
|
||||
readonly property bool gifMode: LauncherService.gifMode
|
||||
readonly property bool masonryActive: gifMode
|
||||
&& LauncherService.filtered.length > 0
|
||||
&& LauncherService.filtered[0]._isGif === true
|
||||
readonly property int columns: 6
|
||||
readonly property int cellSize: 100
|
||||
|
||||
// Hover-selection is disarmed whenever the query changes — so the list
|
||||
// rebuilding under a stationary cursor doesn't yank the keyboard selection
|
||||
// off the top result. Re-armed once the cursor actually moves.
|
||||
property bool hoverArmed: true
|
||||
|
||||
Connections {
|
||||
target: LauncherService
|
||||
function onQueryChanged() { root.hoverArmed = false }
|
||||
}
|
||||
|
||||
onVisibleChanged: {
|
||||
if (visible) {
|
||||
queryField.text = "";
|
||||
LauncherService.selectedIndex = 0;
|
||||
hoverArmed = false;
|
||||
Qt.callLater(() => queryField.forceActiveFocus());
|
||||
}
|
||||
}
|
||||
|
||||
HoverHandler {
|
||||
onPointChanged: root.hoverArmed = true
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
anchors.centerIn: parent
|
||||
width: root.panelWidth
|
||||
height: root.panelHeight
|
||||
color: Theme.opaque_background
|
||||
radius: Theme.radius
|
||||
border.color: Theme.border_subtle
|
||||
border.width: 1
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
acceptedButtons: Qt.AllButtons
|
||||
onPressed: mouse => mouse.accepted = true
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.margins: Theme.padding * 3
|
||||
spacing: Theme.spacing * 2
|
||||
|
||||
Rectangle {
|
||||
Layout.fillWidth: true
|
||||
implicitHeight: queryField.implicitHeight + Theme.padding * 2
|
||||
color: Theme.overlay_weak
|
||||
radius: Theme.radius / 2
|
||||
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: Theme.padding * 2
|
||||
anchors.rightMargin: Theme.padding * 2
|
||||
spacing: Theme.spacing
|
||||
|
||||
Text {
|
||||
text: ""
|
||||
color: Theme.idle
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: Theme.fontSize
|
||||
}
|
||||
|
||||
TextField {
|
||||
id: queryField
|
||||
Layout.fillWidth: true
|
||||
placeholderText: "Search applications… = calc . unicode ! gif"
|
||||
color: Theme.foreground
|
||||
placeholderTextColor: Theme.idle
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: Theme.fontSize
|
||||
background: Item {}
|
||||
selectByMouse: true
|
||||
onTextChanged: {
|
||||
LauncherService.query = text;
|
||||
LauncherService.selectedIndex = 0;
|
||||
}
|
||||
Keys.onPressed: event => {
|
||||
const list = LauncherService.filtered;
|
||||
const cols = root.searching ? 1 : root.columns;
|
||||
let idx = LauncherService.selectedIndex;
|
||||
if (event.key === Qt.Key_Escape) {
|
||||
LauncherService.close();
|
||||
event.accepted = true;
|
||||
} else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
|
||||
LauncherService.launchSelected();
|
||||
event.accepted = true;
|
||||
} else if (event.key === Qt.Key_Down) {
|
||||
idx = Math.min(list.length - 1, idx + cols);
|
||||
LauncherService.selectedIndex = idx;
|
||||
event.accepted = true;
|
||||
} else if (event.key === Qt.Key_Up) {
|
||||
idx = Math.max(0, idx - cols);
|
||||
LauncherService.selectedIndex = idx;
|
||||
event.accepted = true;
|
||||
} else if (event.key === Qt.Key_Right && (!root.searching || root.masonryActive)) {
|
||||
LauncherService.selectedIndex = Math.min(list.length - 1, idx + 1);
|
||||
event.accepted = true;
|
||||
} else if (event.key === Qt.Key_Left && (!root.searching || root.masonryActive)) {
|
||||
LauncherService.selectedIndex = Math.max(0, idx - 1);
|
||||
event.accepted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Grid view (empty query) ----------------------------------------
|
||||
GridView {
|
||||
id: gridView
|
||||
visible: !root.searching
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
clip: true
|
||||
cellWidth: width / root.columns
|
||||
cellHeight: root.cellSize
|
||||
model: visible ? LauncherService.filtered : null
|
||||
currentIndex: LauncherService.selectedIndex
|
||||
onCurrentIndexChanged: positionViewAtIndex(currentIndex, GridView.Contain)
|
||||
|
||||
delegate: Item {
|
||||
id: gridCell
|
||||
required property int index
|
||||
required property var modelData
|
||||
width: GridView.view.cellWidth
|
||||
height: GridView.view.cellHeight
|
||||
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
anchors.margins: 4
|
||||
radius: Theme.radius / 2
|
||||
color: (LauncherService.selectedIndex === gridCell.index)
|
||||
? Theme.overlay_strong
|
||||
: (hover.containsMouse ? Theme.overlay_weak : "transparent")
|
||||
border.color: (LauncherService.selectedIndex === gridCell.index)
|
||||
? Theme.border_subtle : "transparent"
|
||||
border.width: 1
|
||||
|
||||
ColumnLayout {
|
||||
anchors.fill: parent
|
||||
anchors.margins: Theme.padding
|
||||
spacing: 2
|
||||
|
||||
Item {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
Layout.preferredWidth: 48
|
||||
Layout.preferredHeight: 48
|
||||
IconOrFallback {
|
||||
anchors.fill: parent
|
||||
entry: gridCell.modelData
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
Layout.fillWidth: true
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
text: gridCell.modelData ? gridCell.modelData.name : ""
|
||||
color: Theme.foreground
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: Theme.fontSize * 0.75
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
elide: Text.ElideRight
|
||||
maximumLineCount: 2
|
||||
wrapMode: Text.Wrap
|
||||
}
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
id: hover
|
||||
anchors.fill: parent
|
||||
hoverEnabled: true
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
onClicked: LauncherService.launch(gridCell.modelData)
|
||||
onPositionChanged: if (root.hoverArmed) LauncherService.selectedIndex = gridCell.index
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// List view (with query) -----------------------------------------
|
||||
ListView {
|
||||
id: listView
|
||||
visible: root.searching && !root.masonryActive
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
clip: true
|
||||
spacing: 2
|
||||
model: visible ? LauncherService.filtered : null
|
||||
currentIndex: LauncherService.selectedIndex
|
||||
onCurrentIndexChanged: positionViewAtIndex(currentIndex, ListView.Contain)
|
||||
|
||||
delegate: Rectangle {
|
||||
required property int index
|
||||
required property var modelData
|
||||
width: ListView.view.width
|
||||
height: 48
|
||||
radius: Theme.radius / 2
|
||||
color: (LauncherService.selectedIndex === index)
|
||||
? Theme.overlay_strong
|
||||
: (rowHover.containsMouse ? Theme.overlay_weak : "transparent")
|
||||
|
||||
RowLayout {
|
||||
anchors.fill: parent
|
||||
anchors.leftMargin: Theme.padding * 2
|
||||
anchors.rightMargin: Theme.padding * 2
|
||||
spacing: Theme.spacing * 2
|
||||
|
||||
Item {
|
||||
Layout.preferredWidth: modelData && modelData._noIcon ? 0 : 32
|
||||
Layout.preferredHeight: 32
|
||||
visible: !(modelData && modelData._noIcon)
|
||||
IconOrFallback {
|
||||
anchors.fill: parent
|
||||
entry: modelData
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
visible: !!(modelData && modelData._glyph)
|
||||
Layout.preferredWidth: 36
|
||||
Layout.alignment: Qt.AlignVCenter
|
||||
text: modelData && modelData._glyph ? modelData._glyph : ""
|
||||
color: Theme.foreground
|
||||
font.family: "Noto Color Emoji"
|
||||
font.pixelSize: Theme.fontSize * 1.4
|
||||
horizontalAlignment: Text.AlignHCenter
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
Layout.fillWidth: true
|
||||
spacing: 0
|
||||
Text {
|
||||
Layout.fillWidth: true
|
||||
text: modelData ? modelData.name : ""
|
||||
color: Theme.foreground
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: Theme.fontSize
|
||||
elide: Text.ElideRight
|
||||
maximumLineCount: 1
|
||||
}
|
||||
Text {
|
||||
Layout.fillWidth: true
|
||||
visible: text.length > 0
|
||||
text: modelData ? (modelData.genericName || modelData.comment || "") : ""
|
||||
color: Theme.idle
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: Theme.fontSize * 0.7
|
||||
elide: Text.ElideRight
|
||||
maximumLineCount: 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
id: rowHover
|
||||
anchors.fill: parent
|
||||
hoverEnabled: true
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
onClicked: LauncherService.launch(modelData)
|
||||
onPositionChanged: if (root.hoverArmed) LauncherService.selectedIndex = index
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Masonry view (gif results) -------------------------------------
|
||||
Flickable {
|
||||
id: masonry
|
||||
visible: root.masonryActive
|
||||
Layout.fillWidth: true
|
||||
Layout.fillHeight: true
|
||||
clip: true
|
||||
contentWidth: width
|
||||
contentHeight: masonryRow.implicitHeight
|
||||
boundsBehavior: Flickable.StopAtBounds
|
||||
|
||||
RowLayout {
|
||||
id: masonryRow
|
||||
width: masonry.width
|
||||
spacing: Theme.spacing
|
||||
|
||||
Repeater {
|
||||
model: 3
|
||||
|
||||
ColumnLayout {
|
||||
required property int index
|
||||
Layout.fillWidth: true
|
||||
Layout.alignment: Qt.AlignTop
|
||||
spacing: Theme.spacing
|
||||
|
||||
Repeater {
|
||||
model: LauncherService.gifColumns[index] || []
|
||||
|
||||
delegate: Rectangle {
|
||||
required property var modelData
|
||||
Layout.fillWidth: true
|
||||
Layout.preferredHeight: width * (modelData._ratio || 1)
|
||||
radius: Theme.radius / 2
|
||||
color: "transparent"
|
||||
border.width: (LauncherService.selectedIndex === modelData._globalIndex) ? 2 : 0
|
||||
border.color: Theme.accent
|
||||
|
||||
AnimatedImage {
|
||||
anchors.fill: parent
|
||||
anchors.margins: 2
|
||||
source: modelData._previewUrl || ""
|
||||
fillMode: Image.PreserveAspectCrop
|
||||
asynchronous: true
|
||||
cache: true
|
||||
smooth: true
|
||||
}
|
||||
|
||||
MouseArea {
|
||||
anchors.fill: parent
|
||||
hoverEnabled: true
|
||||
cursorShape: Qt.PointingHandCursor
|
||||
onClicked: LauncherService.launch(modelData)
|
||||
onPositionChanged: if (root.hoverArmed) LauncherService.selectedIndex = modelData._globalIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
visible: LauncherService.filtered.length === 0
|
||||
text: root.gifMode ? "No GIFs match" : "No applications match"
|
||||
color: Theme.idle
|
||||
font.family: Theme.fontFamily
|
||||
font.pixelSize: Theme.fontSize
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
pragma Singleton
|
||||
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Io
|
||||
import "UnitConverter.js" as UnitConverter
|
||||
|
||||
QtObject {
|
||||
id: root
|
||||
|
||||
property bool visible: false
|
||||
property string query: ""
|
||||
property string debouncedQuery: ""
|
||||
property int selectedIndex: 0
|
||||
|
||||
onQueryChanged: debounceTimer.restart()
|
||||
|
||||
property Timer debounceTimer: Timer {
|
||||
interval: 80
|
||||
repeat: false
|
||||
onTriggered: root.debouncedQuery = root.query
|
||||
}
|
||||
|
||||
readonly property var allEntries: {
|
||||
const out = [];
|
||||
const apps = DesktopEntries.applications;
|
||||
const n = apps.values ? apps.values.length : apps.count;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const e = apps.values ? apps.values[i] : apps.get(i);
|
||||
if (!e || e.noDisplay) continue;
|
||||
out.push(e);
|
||||
}
|
||||
out.sort((a, b) => (a.name || "").localeCompare(b.name || ""));
|
||||
return out;
|
||||
}
|
||||
|
||||
readonly property var filtered: {
|
||||
const raw = (debouncedQuery || "").trim();
|
||||
if (!raw) return allEntries;
|
||||
|
||||
// Command-prefix dispatch. Each command returns synthetic entries
|
||||
// shaped like DesktopEntry (name, icon, comment) plus an internal
|
||||
// `_copy` field used by launch().
|
||||
if (raw.startsWith("=")) return calcResults(raw.substring(1).trim());
|
||||
if (raw.startsWith(".")) return unicodeResults(raw.substring(1).trim());
|
||||
if (raw.startsWith("!")) return gifResults(raw.substring(1).trim());
|
||||
|
||||
const q = raw.toLowerCase();
|
||||
const scored = [];
|
||||
for (let i = 0; i < allEntries.length; i++) {
|
||||
const e = allEntries[i];
|
||||
const s = fuzzyScore(q, (e.name || "").toLowerCase(),
|
||||
(e.genericName || "").toLowerCase(),
|
||||
(e.comment || "").toLowerCase());
|
||||
if (s > 0) scored.push({ entry: e, score: s });
|
||||
}
|
||||
scored.sort((a, b) => b.score - a.score);
|
||||
return scored.map(x => x.entry);
|
||||
}
|
||||
|
||||
// Unicode lookup: lazy-dumped once via Python's unicodedata, then filtered
|
||||
// in-memory by name substring.
|
||||
property var unicodeData: null // [{ ch, name }, ...]
|
||||
property bool unicodeLoading: false
|
||||
|
||||
function ensureUnicodeLoaded() {
|
||||
if (unicodeData !== null || unicodeLoading) return;
|
||||
unicodeLoading = true;
|
||||
unicodeProc.running = false;
|
||||
unicodeProc.running = true;
|
||||
}
|
||||
|
||||
function unicodeResults(q) {
|
||||
ensureUnicodeLoaded();
|
||||
if (!unicodeData || unicodeData.length === 0 || q.length < 2) {
|
||||
const hint = unicodeLoading ? "Loading unicode database…"
|
||||
: (!q ? "Type to search unicode (min 2 chars)"
|
||||
: q.length < 2 ? "Type at least 2 characters…" : "");
|
||||
return hint ? [{ name: hint, genericName: "", comment: "",
|
||||
icon: "accessories-character-map" }] : [];
|
||||
}
|
||||
const ql = q.toUpperCase();
|
||||
const out = [];
|
||||
const limit = 50;
|
||||
const t0 = Date.now();
|
||||
for (let i = 0; i < unicodeData.length && out.length < limit; i++) {
|
||||
const e = unicodeData[i];
|
||||
if (e.name.indexOf(ql) >= 0) {
|
||||
const cp = e.ch.codePointAt(0).toString(16).toUpperCase();
|
||||
out.push({
|
||||
name: e.name,
|
||||
genericName: "U+" + cp.padStart(4, "0"),
|
||||
comment: "Press Enter to copy",
|
||||
icon: "",
|
||||
_noIcon: true,
|
||||
_glyph: e.ch,
|
||||
_copy: e.ch
|
||||
});
|
||||
}
|
||||
}
|
||||
console.log("unicode filter '" + q + "' →", out.length, "results in", (Date.now() - t0), "ms (scanned", unicodeData.length, "entries)");
|
||||
return out;
|
||||
}
|
||||
|
||||
property Process unicodeProc: Process {
|
||||
command: ["python3", "-c",
|
||||
"import unicodedata,sys\n" +
|
||||
"for cp in range(0x110000):\n" +
|
||||
" try: n = unicodedata.name(chr(cp))\n" +
|
||||
" except ValueError: continue\n" +
|
||||
" sys.stdout.write(f'{cp:X}\\t{n}\\n')\n"]
|
||||
running: false
|
||||
stdout: StdioCollector {
|
||||
onStreamFinished: {
|
||||
const t0 = Date.now();
|
||||
const lines = this.text.split("\n");
|
||||
const out = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const tab = lines[i].indexOf("\t");
|
||||
if (tab <= 0) continue;
|
||||
const cp = parseInt(lines[i].substring(0, tab), 16);
|
||||
if (!cp) continue;
|
||||
out.push({ ch: String.fromCodePoint(cp), name: lines[i].substring(tab + 1) });
|
||||
}
|
||||
root.unicodeData = out;
|
||||
root.unicodeLoading = false;
|
||||
console.log("unicode load: parsed", out.length, "entries in", (Date.now() - t0), "ms");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// In-memory currency rate cache: { "<YYYY-MM-DD>_<BASE>": { TGT: rate, ... } }
|
||||
// Populated lazily when a currency query is typed; the same day's table is
|
||||
// reused for any further conversions from that base.
|
||||
property var currencyRates: ({})
|
||||
property string currencyFetching: "" // "<date>_<base>" currently in flight, "" if idle
|
||||
|
||||
function todayKey() {
|
||||
return new Date().toISOString().substring(0, 10);
|
||||
}
|
||||
|
||||
function fetchCurrency(base) {
|
||||
const key = todayKey() + "_" + base;
|
||||
if (currencyRates[key] || currencyFetching === key) return;
|
||||
currencyFetching = key;
|
||||
currencyProc.command = ["curl", "-sSL", "--max-time", "5",
|
||||
"https://api.frankfurter.dev/v1/latest?base=" + base];
|
||||
currencyProc.running = true;
|
||||
}
|
||||
|
||||
property Process currencyProc: Process {
|
||||
command: []
|
||||
running: false
|
||||
stdout: StdioCollector {
|
||||
onStreamFinished: {
|
||||
root.currencyFetching = "";
|
||||
try {
|
||||
const data = JSON.parse(this.text);
|
||||
if (!data || !data.base || !data.rates) return;
|
||||
// Cache under today's date (the request-side key), not
|
||||
// data.date — Frankfurter reports the last *business* day,
|
||||
// which won't match today on weekends/holidays and would
|
||||
// cause a perpetual cache miss + refetch loop.
|
||||
const key = root.todayKey() + "_" + data.base;
|
||||
const updated = Object.assign({}, root.currencyRates);
|
||||
const rates = Object.assign({}, data.rates);
|
||||
rates[data.base] = 1;
|
||||
updated[key] = rates;
|
||||
root.currencyRates = updated;
|
||||
} catch (e) {
|
||||
console.log("currency: parse failed:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatConv(v) {
|
||||
return Number.isInteger(v) ? String(v) : String(+v.toPrecision(10));
|
||||
}
|
||||
|
||||
function formatMoney(v) {
|
||||
return (Math.round(v * 100) / 100).toFixed(2);
|
||||
}
|
||||
|
||||
function convEntry(conv, expr) {
|
||||
const text = formatConv(conv.value);
|
||||
return {
|
||||
name: text + " " + conv.to,
|
||||
genericName: "= " + expr + (expr.match(/\s(to|in|->)(\s|$)/i) ? "" : " (" + conv.from + " → " + conv.to + ")"),
|
||||
comment: "Press Enter to copy",
|
||||
icon: "accessories-calculator",
|
||||
_copy: text
|
||||
};
|
||||
}
|
||||
|
||||
function currencyResults(parsed, expr) {
|
||||
const base = parsed.from.toUpperCase();
|
||||
const key = todayKey() + "_" + base;
|
||||
const rates = currencyRates[key];
|
||||
if (!rates) {
|
||||
fetchCurrency(base);
|
||||
return [{
|
||||
name: "Fetching rates…",
|
||||
genericName: "= " + expr,
|
||||
comment: base + " — Frankfurter",
|
||||
icon: "accessories-calculator"
|
||||
}];
|
||||
}
|
||||
const convs = UnitConverter.currencyConvert(parsed.amount, base, parsed.partial, rates);
|
||||
return convs.map(c => {
|
||||
const text = formatMoney(c.value);
|
||||
return {
|
||||
name: text + " " + c.to,
|
||||
genericName: "= " + expr,
|
||||
comment: "Press Enter to copy",
|
||||
icon: "accessories-calculator",
|
||||
_copy: text
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function calcResults(expr) {
|
||||
if (!expr) return [];
|
||||
const conv = UnitConverter.convert(expr);
|
||||
if (conv) return [convEntry(conv, expr)];
|
||||
const parsed = UnitConverter.parseQuery(expr);
|
||||
if (parsed && UnitConverter.isCurrency(parsed.from)) return currencyResults(parsed, expr);
|
||||
const suggestions = UnitConverter.suggest(expr);
|
||||
if (suggestions) return suggestions.map(c => convEntry(c, expr));
|
||||
// Whitelist: digits, operators, parens, dot, comma, whitespace,
|
||||
// and identifiers (for Math.* / pi / e). Reject anything else.
|
||||
if (!/^[0-9a-zA-Z_+\-*/%().,\s^!]+$/.test(expr)) return [];
|
||||
let src = expr.replace(/\^/g, "**");
|
||||
try {
|
||||
const fn = new Function("Math", "pi", "e",
|
||||
"\"use strict\"; return (" + src + ");");
|
||||
const v = fn(Math, Math.PI, Math.E);
|
||||
if (typeof v !== "number" || !isFinite(v)) return [];
|
||||
const text = Number.isInteger(v) ? String(v) : String(+v.toFixed(10));
|
||||
return [{
|
||||
name: text,
|
||||
genericName: "= " + expr,
|
||||
comment: "Press Enter to copy",
|
||||
icon: "accessories-calculator",
|
||||
_copy: text
|
||||
}];
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// GIF search (Giphy v1). Key comes from Config (config.json -> giphyApiKey).
|
||||
// Results are cached per-query for the session. Each result exposes
|
||||
// `_isGif`, `_previewUrl` (small animated preview), `_ratio` (h/w for
|
||||
// masonry packing), and `_copy` (the direct .gif URL — what FB Messenger
|
||||
// / Discord / etc. need to inline the animation).
|
||||
readonly property string gifApiKey: Config.giphyApiKey
|
||||
readonly property bool gifApiKeyLoaded: Config.loaded
|
||||
property var gifCache: ({})
|
||||
property string gifFetching: ""
|
||||
|
||||
readonly property bool gifMode: (debouncedQuery || "").trim().startsWith("!")
|
||||
|
||||
function fetchGifs(q) {
|
||||
if (!gifApiKey || !q || gifCache[q] || gifFetching === q) return;
|
||||
gifFetching = q;
|
||||
gifProc.command = ["curl", "-sSL", "--max-time", "8",
|
||||
"https://api.giphy.com/v1/gifs/search?api_key=" + gifApiKey +
|
||||
"&q=" + encodeURIComponent(q) +
|
||||
"&limit=24&rating=pg-13&bundle=messaging_non_clips"];
|
||||
gifProc.running = true;
|
||||
}
|
||||
|
||||
property Process gifProc: Process {
|
||||
command: []
|
||||
running: false
|
||||
stdout: StdioCollector {
|
||||
onStreamFinished: {
|
||||
const q = root.gifFetching;
|
||||
root.gifFetching = "";
|
||||
if (!q) return;
|
||||
try {
|
||||
const data = JSON.parse(this.text);
|
||||
if (!data || !data.data) return;
|
||||
const out = [];
|
||||
for (let i = 0; i < data.data.length; i++) {
|
||||
const r = data.data[i];
|
||||
const imgs = r.images || {};
|
||||
// Preview: fixed_width (200px wide, animated) is the
|
||||
// standard small-grid asset. fixed_width_small (100px)
|
||||
// is even lighter but blurs at column widths > 160px.
|
||||
const prev = imgs.fixed_width || imgs.fixed_width_small
|
||||
|| imgs.preview_gif || imgs.original;
|
||||
const full = imgs.original;
|
||||
if (!prev || !prev.url || !full || !full.url) continue;
|
||||
const w = parseFloat(full.width) || 1;
|
||||
const h = parseFloat(full.height) || 1;
|
||||
out.push({
|
||||
name: r.title || "GIF",
|
||||
_isGif: true,
|
||||
_previewUrl: prev.url,
|
||||
_ratio: w > 0 ? h / w : 1,
|
||||
_copy: full.url
|
||||
});
|
||||
}
|
||||
const updated = Object.assign({}, root.gifCache);
|
||||
updated[q] = out;
|
||||
root.gifCache = updated;
|
||||
} catch (e) {
|
||||
console.log("gif: parse failed:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function gifResults(q) {
|
||||
if (!gifApiKeyLoaded) {
|
||||
return [{ name: "Loading config…", genericName: "",
|
||||
comment: "~/.config/omni-launcher/config.json",
|
||||
icon: "image-x-generic" }];
|
||||
}
|
||||
if (!gifApiKey) {
|
||||
return [{ name: "Missing Giphy API key",
|
||||
genericName: "~/.config/omni-launcher/config.json",
|
||||
comment: "Set \"giphyApiKey\" in config.json.",
|
||||
icon: "dialog-warning" }];
|
||||
}
|
||||
if (!q) {
|
||||
return [{ name: "Type to search Giphy…", genericName: "",
|
||||
comment: "", icon: "image-x-generic" }];
|
||||
}
|
||||
const cached = gifCache[q];
|
||||
if (!cached) {
|
||||
fetchGifs(q);
|
||||
return [{ name: "Searching Giphy…", genericName: "",
|
||||
comment: q, icon: "image-x-generic" }];
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
// Masonry packing: 3 columns, each item appended to the leftmost
|
||||
// shortest column. Tracks cumulative h/w ratio per column — column
|
||||
// widths are equal so ratio sum is proportional to rendered height.
|
||||
// Adds `_globalIndex` to each entry so the delegate can compare against
|
||||
// `selectedIndex` regardless of column placement.
|
||||
readonly property var gifColumns: {
|
||||
const empty = [[], [], []];
|
||||
if (!gifMode) return empty;
|
||||
const items = filtered;
|
||||
if (!items || items.length === 0 || !items[0]._isGif) return empty;
|
||||
const cols = [[], [], []];
|
||||
const heights = [0, 0, 0];
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const it = items[i];
|
||||
if (!it._isGif) continue;
|
||||
let pick = 0;
|
||||
for (let j = 1; j < 3; j++) if (heights[j] < heights[pick]) pick = j;
|
||||
cols[pick].push(Object.assign({}, it, { _globalIndex: i }));
|
||||
heights[pick] += it._ratio || 1;
|
||||
}
|
||||
return cols;
|
||||
}
|
||||
|
||||
function fuzzyScore(q, name, generic, comment) {
|
||||
const nameIdx = name.indexOf(q);
|
||||
if (nameIdx === 0) return 1000 - name.length;
|
||||
if (nameIdx > 0) return 500 - name.length + (name[nameIdx - 1] === ' ' ? 200 : 0);
|
||||
if (generic.indexOf(q) >= 0) return 200;
|
||||
if (comment.indexOf(q) >= 0) return 100;
|
||||
// Subsequence match in name with word-start bonuses.
|
||||
let qi = 0, score = 0, prev = ' ';
|
||||
for (let i = 0; i < name.length && qi < q.length; i++) {
|
||||
if (name[i] === q[qi]) {
|
||||
score += 1;
|
||||
if (prev === ' ' || prev === '-' || prev === '_' || prev === '.') score += 5;
|
||||
qi++;
|
||||
}
|
||||
prev = name[i];
|
||||
}
|
||||
return qi === q.length ? score : 0;
|
||||
}
|
||||
|
||||
function open() {
|
||||
query = "";
|
||||
debouncedQuery = "";
|
||||
debounceTimer.stop();
|
||||
selectedIndex = 0;
|
||||
visible = true;
|
||||
}
|
||||
|
||||
function close() {
|
||||
visible = false;
|
||||
query = "";
|
||||
debouncedQuery = "";
|
||||
debounceTimer.stop();
|
||||
selectedIndex = 0;
|
||||
}
|
||||
|
||||
function toggle() {
|
||||
if (visible) close(); else open();
|
||||
}
|
||||
|
||||
function launchSelected() {
|
||||
const list = filtered;
|
||||
if (selectedIndex < 0 || selectedIndex >= list.length) return;
|
||||
launch(list[selectedIndex]);
|
||||
}
|
||||
|
||||
function launch(entry) {
|
||||
if (!entry) return;
|
||||
close();
|
||||
if (entry._isGif && entry._copy) {
|
||||
// Save the .gif to a temp file and put a text/uri-list entry on
|
||||
// the clipboard. Web apps (Discord, Messenger) translate file-URI
|
||||
// pastes into the file-upload flow and preserve animation, which
|
||||
// they do NOT do for image/gif blob pastes.
|
||||
copyProc.running = false;
|
||||
copyProc.command = ["bash", "-c",
|
||||
"f=$(mktemp --suffix=.gif) && " +
|
||||
"curl -sSL --max-time 15 \"$1\" -o \"$f\" && " +
|
||||
"printf 'file://%s\\r\\n' \"$f\" | wl-copy --type text/uri-list",
|
||||
"_", String(entry._copy)];
|
||||
copyProc.running = true;
|
||||
return;
|
||||
}
|
||||
if (entry._copy !== undefined) {
|
||||
copyProc.running = false;
|
||||
copyProc.command = ["wl-copy", "--", String(entry._copy)];
|
||||
copyProc.running = true;
|
||||
return;
|
||||
}
|
||||
if (entry.execute) entry.execute();
|
||||
}
|
||||
|
||||
property Process copyProc: Process {
|
||||
command: []
|
||||
running: false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
pragma Singleton
|
||||
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Io
|
||||
|
||||
QtObject {
|
||||
id: root
|
||||
|
||||
// Qt platform theme: respects qt6ct, KDE, qgnomeplatform, etc.
|
||||
property SystemPalette _palette: SystemPalette { colorGroup: SystemPalette.Active }
|
||||
|
||||
// Portal-reported state. Defaults match "prefer dark, neutral accent".
|
||||
// 0 = no preference, 1 = dark, 2 = light (per xdg-desktop-portal spec).
|
||||
property int colorScheme: 1
|
||||
property color portalAccent: "#5e9eff"
|
||||
property bool _portalLoaded: false
|
||||
|
||||
readonly property bool dark: colorScheme !== 2
|
||||
|
||||
// Foreground is locked to the same dark/light axis as the panel
|
||||
// background — mixing portal color-scheme with SystemPalette text led to
|
||||
// unreadable combinations (dark bg + dark text) when the Qt platform
|
||||
// theme disagrees with the portal.
|
||||
readonly property color accent: Config.accentColor.length > 0
|
||||
? Config.accentColor : portalAccent
|
||||
readonly property color foreground: Config.foregroundColor.length > 0
|
||||
? Config.foregroundColor : (dark ? "#e6e6e6" : "#1a1a1a")
|
||||
readonly property color idle: Config.idleColor.length > 0
|
||||
? Config.idleColor : (dark ? Qt.rgba(1, 1, 1, 0.55)
|
||||
: Qt.rgba(0, 0, 0, 0.55))
|
||||
readonly property color opaque_background: Config.backgroundColor.length > 0
|
||||
? Config.backgroundColor : (dark
|
||||
? Qt.rgba(0, 0, 0, 0.8)
|
||||
: Qt.rgba(1, 1, 1, 0.9))
|
||||
readonly property color overlay_strong: Config.overlayStrongColor.length > 0
|
||||
? Config.overlayStrongColor : (dark ? Qt.rgba(1, 1, 1, 0.14) : Qt.rgba(0, 0, 0, 0.10))
|
||||
readonly property color overlay_weak: Config.overlayWeakColor.length > 0
|
||||
? Config.overlayWeakColor : (dark ? Qt.rgba(1, 1, 1, 0.06) : Qt.rgba(0, 0, 0, 0.04))
|
||||
readonly property color border_subtle: Config.borderColor.length > 0
|
||||
? Config.borderColor : (dark ? Qt.rgba(1, 1, 1, 0.10) : Qt.rgba(0, 0, 0, 0.10))
|
||||
|
||||
readonly property string fontFamily: Config.fontFamily
|
||||
readonly property int fontSize: Config.fontSize
|
||||
|
||||
readonly property int padding: Config.padding
|
||||
readonly property int spacing: Config.spacing
|
||||
readonly property int radius: Config.radius
|
||||
|
||||
// Read the portal once at startup. The portal also emits a SettingChanged
|
||||
// signal we could subscribe to, but a one-shot read keeps us out of a
|
||||
// long-lived dbus monitor for a feature this rarely changes mid-session.
|
||||
property Process _portalProc: Process {
|
||||
running: true
|
||||
command: ["gdbus", "call", "--session",
|
||||
"--dest", "org.freedesktop.portal.Desktop",
|
||||
"--object-path", "/org/freedesktop/portal/desktop",
|
||||
"--method", "org.freedesktop.portal.Settings.ReadAll",
|
||||
"[\"org.freedesktop.appearance\"]"]
|
||||
stdout: StdioCollector {
|
||||
onStreamFinished: {
|
||||
// Output shape:
|
||||
// ({'org.freedesktop.appearance': {'color-scheme': <uint32 1>,
|
||||
// 'accent-color': <(0.37, 0.62, 1.0)>}},)
|
||||
const text = this.text || "";
|
||||
const cs = text.match(/'color-scheme':\s*<uint32\s+(\d+)>/);
|
||||
if (cs) root.colorScheme = parseInt(cs[1], 10);
|
||||
const ac = text.match(/'accent-color':\s*<\(([-\d.eE+]+),\s*([-\d.eE+]+),\s*([-\d.eE+]+)\)>/);
|
||||
if (ac) {
|
||||
const r = parseFloat(ac[1]), g = parseFloat(ac[2]), b = parseFloat(ac[3]);
|
||||
if (r >= 0 && g >= 0 && b >= 0) root.portalAccent = Qt.rgba(r, g, b, 1);
|
||||
}
|
||||
root._portalLoaded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
.pragma library
|
||||
|
||||
// Unit conversion. Linear units map to a base via { dim, f }; temperature
|
||||
// uses explicit to/from-base helpers to handle the offset.
|
||||
const TABLE = {
|
||||
// length (base: meter)
|
||||
"m": { dim: "len", f: 1 }, "meter": { dim: "len", f: 1 }, "meters": { dim: "len", f: 1 },
|
||||
"km": { dim: "len", f: 1000 }, "cm": { dim: "len", f: 0.01 },
|
||||
"mm": { dim: "len", f: 0.001 }, "um": { dim: "len", f: 1e-6 }, "nm": { dim: "len", f: 1e-9 },
|
||||
"in": { dim: "len", f: 0.0254 }, "inch": { dim: "len", f: 0.0254 }, "inches": { dim: "len", f: 0.0254 },
|
||||
"ft": { dim: "len", f: 0.3048 }, "foot": { dim: "len", f: 0.3048 }, "feet": { dim: "len", f: 0.3048 },
|
||||
"yd": { dim: "len", f: 0.9144 }, "yard": { dim: "len", f: 0.9144 }, "yards": { dim: "len", f: 0.9144 },
|
||||
"mi": { dim: "len", f: 1609.344 }, "mile": { dim: "len", f: 1609.344 }, "miles": { dim: "len", f: 1609.344 },
|
||||
"nmi": { dim: "len", f: 1852 },
|
||||
// mass (base: gram)
|
||||
"g": { dim: "mass", f: 1 }, "gram": { dim: "mass", f: 1 }, "grams": { dim: "mass", f: 1 },
|
||||
"kg": { dim: "mass", f: 1000 }, "mg": { dim: "mass", f: 0.001 },
|
||||
"lb": { dim: "mass", f: 453.59237 }, "lbs": { dim: "mass", f: 453.59237 },
|
||||
"oz": { dim: "mass", f: 28.349523125 },
|
||||
"ton": { dim: "mass", f: 1e6 }, "tonne": { dim: "mass", f: 1e6 }, "t": { dim: "mass", f: 1e6 },
|
||||
// volume (base: liter)
|
||||
"l": { dim: "vol", f: 1 }, "liter": { dim: "vol", f: 1 }, "liters": { dim: "vol", f: 1 },
|
||||
"ml": { dim: "vol", f: 0.001 }, "cl": { dim: "vol", f: 0.01 },
|
||||
"gal": { dim: "vol", f: 3.785411784 }, "gallon": { dim: "vol", f: 3.785411784 },
|
||||
"qt": { dim: "vol", f: 0.946352946 }, "pt": { dim: "vol", f: 0.473176473 },
|
||||
"cup": { dim: "vol", f: 0.2365882365 }, "cups": { dim: "vol", f: 0.2365882365 },
|
||||
"floz": { dim: "vol", f: 0.0295735295625 }, "tbsp": { dim: "vol", f: 0.01478676478125 },
|
||||
"tsp": { dim: "vol", f: 0.00492892159375 },
|
||||
// time (base: second)
|
||||
"s": { dim: "time", f: 1 }, "sec": { dim: "time", f: 1 }, "secs": { dim: "time", f: 1 },
|
||||
"ms": { dim: "time", f: 0.001 }, "us": { dim: "time", f: 1e-6 },
|
||||
"min": { dim: "time", f: 60 }, "mins": { dim: "time", f: 60 },
|
||||
"h": { dim: "time", f: 3600 }, "hr": { dim: "time", f: 3600 }, "hrs": { dim: "time", f: 3600 },
|
||||
"hour": { dim: "time", f: 3600 }, "hours": { dim: "time", f: 3600 },
|
||||
"day": { dim: "time", f: 86400 }, "days": { dim: "time", f: 86400 },
|
||||
"week": { dim: "time", f: 604800 }, "weeks": { dim: "time", f: 604800 },
|
||||
"year": { dim: "time", f: 31557600 }, "years": { dim: "time", f: 31557600 },
|
||||
// data (base: byte; SI and binary)
|
||||
"b": { dim: "data", f: 1 }, "byte": { dim: "data", f: 1 }, "bytes": { dim: "data", f: 1 },
|
||||
"kb": { dim: "data", f: 1e3 }, "mb": { dim: "data", f: 1e6 },
|
||||
"gb": { dim: "data", f: 1e9 }, "tb": { dim: "data", f: 1e12 }, "pb": { dim: "data", f: 1e15 },
|
||||
"kib": { dim: "data", f: 1024 }, "mib": { dim: "data", f: 1048576 },
|
||||
"gib": { dim: "data", f: 1073741824 }, "tib": { dim: "data", f: 1099511627776 },
|
||||
"bit": { dim: "data", f: 0.125 }, "bits": { dim: "data", f: 0.125 },
|
||||
// speed (base: m/s)
|
||||
"mps": { dim: "speed", f: 1 },
|
||||
"kph": { dim: "speed", f: 1 / 3.6 }, "kmh": { dim: "speed", f: 1 / 3.6 },
|
||||
"mph": { dim: "speed", f: 0.44704 },
|
||||
"knot": { dim: "speed", f: 0.514444 }, "knots": { dim: "speed", f: 0.514444 },
|
||||
// angle (base: radian)
|
||||
"rad": { dim: "angle", f: 1 }, "deg": { dim: "angle", f: Math.PI / 180 },
|
||||
"turn": { dim: "angle", f: 2 * Math.PI }, "grad": { dim: "angle", f: Math.PI / 200 },
|
||||
// temperature (offset; handled specially)
|
||||
"c": { dim: "temp" }, "celsius": { dim: "temp" },
|
||||
"f": { dim: "temp" }, "fahrenheit": { dim: "temp" },
|
||||
"k": { dim: "temp" }, "kelvin": { dim: "temp" }
|
||||
};
|
||||
|
||||
function tempToK(v, u) {
|
||||
if (u === "c" || u === "celsius") return v + 273.15;
|
||||
if (u === "f" || u === "fahrenheit") return (v - 32) * 5 / 9 + 273.15;
|
||||
return v;
|
||||
}
|
||||
function tempFromK(v, u) {
|
||||
if (u === "c" || u === "celsius") return v - 273.15;
|
||||
if (u === "f" || u === "fahrenheit") return (v - 273.15) * 9 / 5 + 32;
|
||||
return v;
|
||||
}
|
||||
|
||||
// ISO codes Frankfurter supports. Used to detect currency queries before we
|
||||
// have rates cached (rates are fetched lazily and cached per-day).
|
||||
const CURRENCIES = ["AUD","BGN","BRL","CAD","CHF","CNY","CZK","DKK","EUR","GBP",
|
||||
"HKD","HUF","IDR","ILS","INR","ISK","JPY","KRW","MXN","NOK",
|
||||
"NZD","PHP","PLN","RON","SEK","SGD","THB","TRY","USD","ZAR"];
|
||||
const CURRENCY_SET = (function() { const s = {}; for (const c of CURRENCIES) s[c] = 1; return s; })();
|
||||
|
||||
function isCurrency(code) {
|
||||
return !!CURRENCY_SET[code.toUpperCase()];
|
||||
}
|
||||
|
||||
// Parse the "<num> <from> to[ <partial-to>]" shape used by both unit and
|
||||
// currency conversion. Returns null if it doesn't match.
|
||||
function parseQuery(expr) {
|
||||
const m = expr.match(/^(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*([a-zA-Z]+)\s+(?:to|in|->)(?:\s+([a-zA-Z]*))?$/i);
|
||||
if (!m) return null;
|
||||
return {
|
||||
amount: parseFloat(m[1]),
|
||||
from: m[2].toLowerCase(),
|
||||
partial: (m[3] || "").toLowerCase()
|
||||
};
|
||||
}
|
||||
|
||||
function applyConversion(v, fu, tu) {
|
||||
const fd = TABLE[fu], td = TABLE[tu];
|
||||
if (fd.dim === "temp") return tempFromK(tempToK(v, fu), tu);
|
||||
return v * fd.f / td.f;
|
||||
}
|
||||
|
||||
// Parse "<number> <from> to|in|-> <to>" and return { value, from, to } or null.
|
||||
function convert(expr) {
|
||||
const m = expr.match(/^(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*([a-zA-Z]+)\s+(?:to|in|->)\s+([a-zA-Z]+)$/i);
|
||||
if (!m) return null;
|
||||
const v = parseFloat(m[1]);
|
||||
const fu = m[2].toLowerCase();
|
||||
const tu = m[3].toLowerCase();
|
||||
const fd = TABLE[fu], td = TABLE[tu];
|
||||
if (!fd || !td || fd.dim !== td.dim) return null;
|
||||
return { value: applyConversion(v, fu, tu), from: fu, to: tu };
|
||||
}
|
||||
|
||||
// Build, per dimension, the list of canonical unit names — deduped so e.g.
|
||||
// "m"/"meter"/"meters" don't all appear; prefer the shortest alias.
|
||||
const CANONICAL_BY_DIM = (function() {
|
||||
const byDim = {};
|
||||
const tempCanon = { "c": 1, "f": 1, "k": 1 };
|
||||
for (const name in TABLE) {
|
||||
const td = TABLE[name];
|
||||
if (!byDim[td.dim]) byDim[td.dim] = {};
|
||||
const bucket = byDim[td.dim];
|
||||
const key = td.dim === "temp" ? name : String(td.f);
|
||||
if (td.dim === "temp" && !tempCanon[name]) continue;
|
||||
if (bucket[key] === undefined || name.length < bucket[key].length) {
|
||||
bucket[key] = name;
|
||||
}
|
||||
}
|
||||
const out = {};
|
||||
for (const dim in byDim) out[dim] = Object.values(byDim[dim]);
|
||||
return out;
|
||||
})();
|
||||
|
||||
// Given a fetched-rate table { TGT: rate, ... } where amount-of-base * rate =
|
||||
// amount-of-target, return ordered { value, from, to } entries filtered by
|
||||
// `partial`. Mirrors suggest() for units.
|
||||
function currencyConvert(amount, base, partial, rates) {
|
||||
const baseU = base.toUpperCase();
|
||||
const candidates = Object.keys(rates).filter(c => c !== baseU);
|
||||
let ordered;
|
||||
if (!partial) {
|
||||
ordered = candidates.slice().sort();
|
||||
} else {
|
||||
const p = partial.toUpperCase();
|
||||
const scored = [];
|
||||
for (const c of candidates) {
|
||||
const s = scoreFuzzy(p, c);
|
||||
if (s > 0) scored.push({ c, s });
|
||||
}
|
||||
scored.sort((a, b) => b.s - a.s);
|
||||
ordered = scored.map(x => x.c);
|
||||
}
|
||||
return ordered.map(c => ({ value: amount * rates[c], from: baseU, to: c }));
|
||||
}
|
||||
|
||||
function scoreFuzzy(q, name) {
|
||||
const idx = name.indexOf(q);
|
||||
if (idx === 0) return 1000 - name.length;
|
||||
if (idx > 0) return 500 - name.length;
|
||||
let qi = 0;
|
||||
for (let i = 0; i < name.length && qi < q.length; i++) {
|
||||
if (name[i] === q[qi]) qi++;
|
||||
}
|
||||
return qi === q.length ? 100 - name.length : 0;
|
||||
}
|
||||
|
||||
// Parse "<number> <from> to|in|->[ <partial>]" and return an array of
|
||||
// { value, from, to } for every unit in <from>'s dimension that fuzzy-matches
|
||||
// <partial> (or all of them if <partial> is empty). Returns null if the input
|
||||
// doesn't fit the "awaiting target unit" shape.
|
||||
function suggest(expr) {
|
||||
const m = expr.match(/^(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*([a-zA-Z]+)\s+(?:to|in|->)(?:\s+([a-zA-Z]*))?$/i);
|
||||
if (!m) return null;
|
||||
const v = parseFloat(m[1]);
|
||||
const fu = m[2].toLowerCase();
|
||||
const partial = (m[3] || "").toLowerCase();
|
||||
const fd = TABLE[fu];
|
||||
if (!fd) return null;
|
||||
const candidates = (CANONICAL_BY_DIM[fd.dim] || []).filter(u => u !== fu);
|
||||
let ordered;
|
||||
if (!partial) {
|
||||
ordered = candidates.slice().sort();
|
||||
} else {
|
||||
const scored = [];
|
||||
for (const u of candidates) {
|
||||
const s = scoreFuzzy(partial, u);
|
||||
if (s > 0) scored.push({ u, s });
|
||||
}
|
||||
scored.sort((a, b) => b.s - a.s);
|
||||
ordered = scored.map(x => x.u);
|
||||
}
|
||||
return ordered.map(tu => ({ value: applyConversion(v, fu, tu), from: fu, to: tu }));
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
module OmniLauncher
|
||||
singleton Config 1.0 Config.qml
|
||||
singleton LauncherService 1.0 LauncherService.qml
|
||||
singleton Theme 1.0 Theme.qml
|
||||
Launcher 1.0 Launcher.qml
|
||||
IconOrFallback 1.0 IconOrFallback.qml
|
||||
HyprlandIntegration 1.0 HyprlandIntegration.qml
|
||||
Reference in New Issue
Block a user