Add glassMxrph shell sources

Initial commit of the Quickshell desktop suite: bar, dock, launcher,
settings, Control Center, dashboard, OSD, lock screen, desktop widgets,
plugin host with the vendored Noctalia/Omarchy compatibility layer,
helpers, packaging, tests and phase documentation.

Includes the optimization work so far: usage widgets and dashboard
gauges no longer animate continuously, desktop widgets pause while
covered, system controls stop flickering on background polls, dock app
matching uses an indexed catalog, and workspace ghosts are created only
for occupied slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mxandClaude Opus 5.5 committed 2026-10-07 22:36:17 +02:00
commit 99e64a7713
433 files changed
+57792

No files matched your search

@@ -0,0 +1,16 @@
Tabler Licenses - Detailed Usage Rights and Guidelines
This is a legal agreement between you, the Purchaser, and Tabler. Purchasing or downloading of any Tabler product (Tabler Admin Template, Tabler Icons, Tabler Emails, Tabler Illustrations), constitutes your acceptance of the terms of this license, Tabler terms of service and Tabler private policy.
Tabler Admin Template and Tabler Icons License*
Tabler Admin Template and Tabler Icons are available under MIT License.
Copyright (c) 2018-2025 Tabler
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
See more at Tabler Admin Template MIT License See more at Tabler Icons MIT License
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,120 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../theme" as G
// glassMxrph replacement for Noctalia's Color singleton. Same Material-style
// roles and helpers, but every role comes from the glassMxrph theme (glass
// tint, accent, text), so Noctalia plugins render in the glassMxrph look.
// Noctalia's colors.json is not read.
Singleton {
id: root
property bool reloadColors: false
property bool skipTransition: false
property bool isTransitioning: false
function scheduleExternalColorReload() {
}
function startTransition() {
}
property color mPrimary: G.Theme.accent
property color mOnPrimary: G.Theme.accentText
property color mSecondary: G.Theme.accentVivid
property color mOnSecondary: G.Theme.accentText
property color mTertiary: G.Theme.accentVivid
property color mOnTertiary: G.Theme.accentText
property color mError: G.Theme.urgent
property color mOnError: "#000000"
// Panels and cards: the shell's glass tint; widgets sit on surfaceVariant.
property color mSurface: G.Theme.surface
property color mOnSurface: G.Theme.text
property color mSurfaceVariant: G.Theme.surfaceVariant
property color mOnSurfaceVariant: G.Theme.textSecondary
property color mOutline: G.Theme.border
property color mShadow: "#000000"
// Noctalia hovers with a solid accent; glassMxrph uses a soft highlight.
property color mHover: Qt.alpha(G.Theme.text, 0.12)
property color mOnHover: G.Theme.text
function resolveColorKey(key) {
switch (key) {
case "primary":
return root.mPrimary;
case "secondary":
return root.mSecondary;
case "tertiary":
return root.mTertiary;
case "error":
return root.mError;
default:
return root.mOnSurface;
}
}
function resolveOnColorKey(key) {
switch (key) {
case "primary":
return root.mOnPrimary;
case "secondary":
return root.mOnSecondary;
case "tertiary":
return root.mOnTertiary;
case "error":
return root.mOnError;
default:
return root.mSurface;
}
}
function resolveColorKeyOptional(key) {
switch (key) {
case "primary":
return root.mPrimary;
case "secondary":
return root.mSecondary;
case "tertiary":
return root.mTertiary;
case "error":
return root.mError;
default:
return "transparent";
}
}
// glassMxrph is dark-only; panels follow the shell's glass opacity.
function adaptiveOpacity(baseOpacity) {
return baseOpacity;
}
function smartAlpha(baseColor, minAlpha = 0.4) {
return Qt.alpha(baseColor, Math.max(minAlpha, Math.min(baseColor.a, G.Theme.glassOpacity)));
}
readonly property var colorKeyModel: [
{
"key": "none",
"name": "None"
},
{
"key": "primary",
"name": "Primary"
},
{
"key": "secondary",
"name": "Secondary"
},
{
"key": "tertiary",
"name": "Tertiary"
},
{
"key": "error",
"name": "Error"
}
]
}
@@ -0,0 +1,883 @@
pragma Singleton
import QtQuick
import Quickshell
Singleton {
id: root
// Public API
function go(search, targets, options) {
return _go(search, targets, options);
}
function single(search, target) {
return _single(search, target);
}
function highlight(result, open, close) {
if (open === undefined)
open = '<b>';
if (close === undefined)
close = '</b>';
return _highlight(result, open, close);
}
function prepare(target) {
return _prepare(target);
}
function cleanup() {
return _cleanup();
}
// Internal implementation
readonly property var _INFINITY: Infinity
readonly property var _NEGATIVE_INFINITY: -Infinity
readonly property var _NULL: null
property var _noResults: {
let r = [];
r.total = 0;
return r;
}
property var _noTarget: _prepare('')
property var _preparedCache: new Map()
property var _preparedSearchCache: new Map()
property var _matchesSimple: []
property var _matchesStrict: []
property var _nextBeginningIndexesChanges: []
property var _keysSpacesBestScores: []
property var _allowPartialMatchScores: []
property var _tmpTargets: []
property var _tmpResults: []
property var _q: _fastpriorityqueue()
function _fastpriorityqueue() {
var e = [], o = 0, a = {};
var v = function (r) {
for (var a = 0, vc = e[a], c = 1; c < o; ) {
var s = c + 1;
a = c;
if (s < o && e[s]._score < e[c]._score)
a = s;
e[a - 1 >> 1] = e[a];
c = 1 + (a << 1);
}
for (var f = a - 1 >> 1; a > 0 && vc._score < e[f]._score; f = (a = f) - 1 >> 1)
e[a] = e[f];
e[a] = vc;
};
a.add = function (r) {
var ac = o;
e[o++] = r;
for (var vc = ac - 1 >> 1; ac > 0 && r._score < e[vc]._score; vc = (ac = vc) - 1 >> 1)
e[ac] = e[vc];
e[ac] = r;
};
a.poll = function () {
if (o !== 0) {
var ac = e[0];
e[0] = e[--o];
v();
return ac;
}
};
a.peek = function () {
if (o !== 0)
return e[0];
};
a.replaceTop = function (r) {
e[0] = r;
v();
};
return a;
}
function _createResult() {
return {
target: '',
obj: _NULL,
_score: _NEGATIVE_INFINITY,
_indexes: [],
_targetLower: '',
_targetLowerCodes: _NULL,
_nextBeginningIndexes: _NULL,
_bitflags: 0,
get indexes() {
return this._indexes.slice(0, this._indexes.len).sort((a, b) => a - b);
},
set indexes(idx) {
this._indexes = idx;
},
highlight: function (open, close) {
return root._highlight(this, open, close);
},
get score() {
return root._normalizeScore(this._score);
},
set score(s) {
this._score = root._denormalizeScore(s);
}
};
}
function _createKeysResult(len) {
var arr = new Array(len);
arr._score = _NEGATIVE_INFINITY;
arr.obj = _NULL;
Object.defineProperty(arr, 'score', {
get: function () {
return root._normalizeScore(this._score);
},
set: function (s) {
this._score = root._denormalizeScore(s);
}
});
return arr;
}
function _new_result(target, options) {
var result = _createResult();
result.target = target;
result.obj = options.obj ?? _NULL;
result._score = options._score ?? _NEGATIVE_INFINITY;
result._indexes = options._indexes ?? [];
result._targetLower = options._targetLower ?? '';
result._targetLowerCodes = options._targetLowerCodes ?? _NULL;
result._nextBeginningIndexes = options._nextBeginningIndexes ?? _NULL;
result._bitflags = options._bitflags ?? 0;
return result;
}
function _normalizeScore(score) {
if (score === _NEGATIVE_INFINITY)
return 0;
if (score > 1)
return score;
return Math.E ** (((-score + 1) ** 0.04307 - 1) * -2);
}
function _denormalizeScore(normalizedScore) {
if (normalizedScore === 0)
return _NEGATIVE_INFINITY;
if (normalizedScore > 1)
return normalizedScore;
return 1 - Math.pow((Math.log(normalizedScore) / -2 + 1), 1 / 0.04307);
}
function _remove_accents(str) {
return str.replace(/\p{Script=Latin}+/gu, match => match.normalize('NFD')).replace(/[\u0300-\u036f]/g, '');
}
function _prepareLowerInfo(str) {
str = _remove_accents(str);
var strLen = str.length;
var lower = str.toLowerCase();
var lowerCodes = [];
var bitflags = 0;
var containsSpace = false;
for (var i = 0; i < strLen; ++i) {
var lowerCode = lowerCodes[i] = lower.charCodeAt(i);
if (lowerCode === 32) {
containsSpace = true;
continue;
}
var bit = lowerCode >= 97 && lowerCode <= 122 ? lowerCode - 97 : lowerCode >= 48 && lowerCode <= 57 ? 26 : lowerCode <= 127 ? 30 : 31;
bitflags |= 1 << bit;
}
return {
lowerCodes: lowerCodes,
bitflags: bitflags,
containsSpace: containsSpace,
_lower: lower
};
}
function _prepareBeginningIndexes(target) {
var targetLen = target.length;
var beginningIndexes = [];
var beginningIndexesLen = 0;
var wasUpper = false;
var wasAlphanum = false;
for (var i = 0; i < targetLen; ++i) {
var targetCode = target.charCodeAt(i);
var isUpper = targetCode >= 65 && targetCode <= 90;
var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57;
var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum;
wasUpper = isUpper;
wasAlphanum = isAlphanum;
if (isBeginning)
beginningIndexes[beginningIndexesLen++] = i;
}
return beginningIndexes;
}
function _prepareNextBeginningIndexes(target) {
target = _remove_accents(target);
var targetLen = target.length;
var beginningIndexes = _prepareBeginningIndexes(target);
var nextBeginningIndexes = [];
var lastIsBeginning = beginningIndexes[0];
var lastIsBeginningI = 0;
for (var i = 0; i < targetLen; ++i) {
if (lastIsBeginning > i) {
nextBeginningIndexes[i] = lastIsBeginning;
} else {
lastIsBeginning = beginningIndexes[++lastIsBeginningI];
nextBeginningIndexes[i] = lastIsBeginning === undefined ? targetLen : lastIsBeginning;
}
}
return nextBeginningIndexes;
}
function _prepareSearch(search) {
if (typeof search === 'number')
search = '' + search;
else if (typeof search !== 'string')
search = '';
search = search.trim();
var info = _prepareLowerInfo(search);
var spaceSearches = [];
if (info.containsSpace) {
var searches = search.split(/\s+/);
searches = [...new Set(searches)];
for (var i = 0; i < searches.length; i++) {
if (searches[i] === '')
continue;
var _info = _prepareLowerInfo(searches[i]);
spaceSearches.push({
lowerCodes: _info.lowerCodes,
_lower: searches[i].toLowerCase(),
containsSpace: false
});
}
}
return {
lowerCodes: info.lowerCodes,
_lower: info._lower,
containsSpace: info.containsSpace,
bitflags: info.bitflags,
spaceSearches: spaceSearches
};
}
function _prepare(target) {
if (typeof target === 'number')
target = '' + target;
else if (typeof target !== 'string')
target = '';
var info = _prepareLowerInfo(target);
return _new_result(target, {
_targetLower: info._lower,
_targetLowerCodes: info.lowerCodes,
_bitflags: info.bitflags
});
}
function _cleanup() {
_preparedCache.clear();
_preparedSearchCache.clear();
}
function _isPrepared(x) {
return typeof x === 'object' && typeof x._bitflags === 'number';
}
function _getPrepared(target) {
if (target.length > 999)
return _prepare(target);
var targetPrepared = _preparedCache.get(target);
if (targetPrepared !== undefined)
return targetPrepared;
targetPrepared = _prepare(target);
_preparedCache.set(target, targetPrepared);
return targetPrepared;
}
function _getPreparedSearch(search) {
if (search.length > 999)
return _prepareSearch(search);
var searchPrepared = _preparedSearchCache.get(search);
if (searchPrepared !== undefined)
return searchPrepared;
searchPrepared = _prepareSearch(search);
_preparedSearchCache.set(search, searchPrepared);
return searchPrepared;
}
function _getValue(obj, prop) {
var tmp = obj[prop];
if (tmp !== undefined)
return tmp;
if (typeof prop === 'function')
return prop(obj);
var segs = prop;
if (!Array.isArray(prop))
segs = prop.split('.');
var len = segs.length;
var i = -1;
while (obj && (++i < len))
obj = obj[segs[i]];
return obj;
}
function _single(search, target) {
if (!search || !target)
return _NULL;
var preparedSearch = _getPreparedSearch(search);
if (!_isPrepared(target))
target = _getPrepared(target);
var searchBitflags = preparedSearch.bitflags;
if ((searchBitflags & target._bitflags) !== searchBitflags)
return _NULL;
return _algorithm(preparedSearch, target);
}
function _highlight(result, open, close) {
if (open === undefined)
open = '<b>';
if (close === undefined)
close = '</b>';
var callback = typeof open === 'function' ? open : undefined;
var target = result.target;
var targetLen = target.length;
var indexes = result.indexes;
var highlighted = '';
var matchI = 0;
var indexesI = 0;
var opened = false;
var parts = [];
for (var i = 0; i < targetLen; ++i) {
var ch = target[i];
if (indexes[indexesI] === i) {
++indexesI;
if (!opened) {
opened = true;
if (callback) {
parts.push(highlighted);
highlighted = '';
} else {
highlighted += open;
}
}
if (indexesI === indexes.length) {
if (callback) {
highlighted += ch;
parts.push(callback(highlighted, matchI++));
highlighted = '';
parts.push(target.substr(i + 1));
} else {
highlighted += ch + close + target.substr(i + 1);
}
break;
}
} else {
if (opened) {
opened = false;
if (callback) {
parts.push(callback(highlighted, matchI++));
highlighted = '';
} else {
highlighted += close;
}
}
}
highlighted += ch;
}
return callback ? parts : highlighted;
}
function _all(targets, options) {
var results = [];
results.total = targets.length;
var limit = options?.limit || _INFINITY;
if (options?.key) {
for (var i = 0; i < targets.length; i++) {
var obj = targets[i];
var target = _getValue(obj, options.key);
if (target == _NULL)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
var result = _new_result(target.target, {
_score: target._score,
obj: obj
});
results.push(result);
if (results.length >= limit)
return results;
}
} else if (options?.keys) {
for (var i = 0; i < targets.length; i++) {
var obj = targets[i];
var objResults = _createKeysResult(options.keys.length);
for (var keyI = options.keys.length - 1; keyI >= 0; --keyI) {
var target = _getValue(obj, options.keys[keyI]);
if (!target) {
objResults[keyI] = _noTarget;
continue;
}
if (!_isPrepared(target))
target = _getPrepared(target);
target._score = _NEGATIVE_INFINITY;
target._indexes.len = 0;
objResults[keyI] = target;
}
objResults.obj = obj;
objResults._score = _NEGATIVE_INFINITY;
results.push(objResults);
if (results.length >= limit)
return results;
}
} else {
for (var i = 0; i < targets.length; i++) {
var target = targets[i];
if (target == _NULL)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
target._score = _NEGATIVE_INFINITY;
target._indexes.len = 0;
results.push(target);
if (results.length >= limit)
return results;
}
}
return results;
}
function _algorithm(preparedSearch, prepared, allowSpaces, allowPartialMatch) {
if (allowSpaces === undefined)
allowSpaces = false;
if (allowPartialMatch === undefined)
allowPartialMatch = false;
if (allowSpaces === false && preparedSearch.containsSpace)
return _algorithmSpaces(preparedSearch, prepared, allowPartialMatch);
var searchLower = preparedSearch._lower;
var searchLowerCodes = preparedSearch.lowerCodes;
var searchLowerCode = searchLowerCodes[0];
var targetLowerCodes = prepared._targetLowerCodes;
var searchLen = searchLowerCodes.length;
var targetLen = targetLowerCodes.length;
var searchI = 0;
var targetI = 0;
var matchesSimpleLen = 0;
for (; ; ) {
var isMatch = searchLowerCode === targetLowerCodes[targetI];
if (isMatch) {
_matchesSimple[matchesSimpleLen++] = targetI;
++searchI;
if (searchI === searchLen)
break;
searchLowerCode = searchLowerCodes[searchI];
}
++targetI;
if (targetI >= targetLen)
return _NULL;
}
searchI = 0;
var successStrict = false;
var matchesStrictLen = 0;
var nextBeginningIndexes = prepared._nextBeginningIndexes;
if (nextBeginningIndexes === _NULL)
nextBeginningIndexes = prepared._nextBeginningIndexes = _prepareNextBeginningIndexes(prepared.target);
targetI = _matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[_matchesSimple[0] - 1];
var backtrackCount = 0;
if (targetI !== targetLen)
for (; ; ) {
if (targetI >= targetLen) {
if (searchI <= 0)
break;
++backtrackCount;
if (backtrackCount > 200)
break;
--searchI;
var lastMatch = _matchesStrict[--matchesStrictLen];
targetI = nextBeginningIndexes[lastMatch];
} else {
var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI];
if (isMatch) {
_matchesStrict[matchesStrictLen++] = targetI;
++searchI;
if (searchI === searchLen) {
successStrict = true;
break;
}
++targetI;
} else {
targetI = nextBeginningIndexes[targetI];
}
}
}
var substringIndex = searchLen <= 1 ? -1 : prepared._targetLower.indexOf(searchLower, _matchesSimple[0]);
var isSubstring = !!~substringIndex;
var isSubstringBeginning = !isSubstring ? false : substringIndex === 0 || prepared._nextBeginningIndexes[substringIndex - 1] === substringIndex;
if (isSubstring && !isSubstringBeginning) {
for (var i = 0; i < nextBeginningIndexes.length; i = nextBeginningIndexes[i]) {
if (i <= substringIndex)
continue;
for (var s = 0; s < searchLen; s++)
if (searchLowerCodes[s] !== prepared._targetLowerCodes[i + s])
break;
if (s === searchLen) {
substringIndex = i;
isSubstringBeginning = true;
break;
}
}
}
var calculateScore = function (matches) {
var score = 0;
var extraMatchGroupCount = 0;
for (var i = 1; i < searchLen; ++i) {
if (matches[i] - matches[i - 1] !== 1) {
score -= matches[i];
++extraMatchGroupCount;
}
}
var unmatchedDistance = matches[searchLen - 1] - matches[0] - (searchLen - 1);
score -= (12 + unmatchedDistance) * extraMatchGroupCount;
if (matches[0] !== 0)
score -= matches[0] * matches[0] * 0.2;
if (!successStrict) {
score *= 1000;
} else {
var uniqueBeginningIndexes = 1;
for (var i = nextBeginningIndexes[0]; i < targetLen; i = nextBeginningIndexes[i])
++uniqueBeginningIndexes;
if (uniqueBeginningIndexes > 24)
score *= (uniqueBeginningIndexes - 24) * 10;
}
score -= (targetLen - searchLen) / 2;
if (isSubstring)
score /= 1 + searchLen * searchLen * 1;
if (isSubstringBeginning)
score /= 1 + searchLen * searchLen * 1;
score -= (targetLen - searchLen) / 2;
return score;
};
var matchesBest, score;
if (!successStrict) {
if (isSubstring)
for (var i = 0; i < searchLen; ++i)
_matchesSimple[i] = substringIndex + i;
matchesBest = _matchesSimple;
score = calculateScore(matchesBest);
} else {
if (isSubstringBeginning) {
for (var i = 0; i < searchLen; ++i)
_matchesSimple[i] = substringIndex + i;
matchesBest = _matchesSimple;
score = calculateScore(_matchesSimple);
} else {
matchesBest = _matchesStrict;
score = calculateScore(_matchesStrict);
}
}
prepared._score = score;
for (var i = 0; i < searchLen; ++i)
prepared._indexes[i] = matchesBest[i];
prepared._indexes.len = searchLen;
var result = _createResult();
result.target = prepared.target;
result._score = prepared._score;
result._indexes = prepared._indexes;
return result;
}
function _algorithmSpaces(preparedSearch, target, allowPartialMatch) {
var seen_indexes = new Set();
var score = 0;
var result = _NULL;
var first_seen_index_last_search = 0;
var searches = preparedSearch.spaceSearches;
var searchesLen = searches.length;
var changeslen = 0;
var resetNextBeginningIndexes = function () {
for (let i = changeslen - 1; i >= 0; i--)
target._nextBeginningIndexes[_nextBeginningIndexesChanges[i * 2 + 0]] = _nextBeginningIndexesChanges[i * 2 + 1];
};
var hasAtLeast1Match = false;
for (var i = 0; i < searchesLen; ++i) {
_allowPartialMatchScores[i] = _NEGATIVE_INFINITY;
var search = searches[i];
result = _algorithm(search, target);
if (allowPartialMatch) {
if (result === _NULL)
continue;
hasAtLeast1Match = true;
} else {
if (result === _NULL) {
resetNextBeginningIndexes();
return _NULL;
}
}
var isTheLastSearch = i === searchesLen - 1;
if (!isTheLastSearch) {
var indexes = result._indexes;
var indexesIsConsecutiveSubstring = true;
for (let j = 0; j < indexes.len - 1; j++) {
if (indexes[j + 1] - indexes[j] !== 1) {
indexesIsConsecutiveSubstring = false;
break;
}
}
if (indexesIsConsecutiveSubstring) {
var newBeginningIndex = indexes[indexes.len - 1] + 1;
var toReplace = target._nextBeginningIndexes[newBeginningIndex - 1];
for (let j = newBeginningIndex - 1; j >= 0; j--) {
if (toReplace !== target._nextBeginningIndexes[j])
break;
target._nextBeginningIndexes[j] = newBeginningIndex;
_nextBeginningIndexesChanges[changeslen * 2 + 0] = j;
_nextBeginningIndexesChanges[changeslen * 2 + 1] = toReplace;
changeslen++;
}
}
}
score += result._score / searchesLen;
_allowPartialMatchScores[i] = result._score / searchesLen;
if (result._indexes[0] < first_seen_index_last_search) {
score -= (first_seen_index_last_search - result._indexes[0]) * 2;
}
first_seen_index_last_search = result._indexes[0];
for (var j = 0; j < result._indexes.len; ++j)
seen_indexes.add(result._indexes[j]);
}
if (allowPartialMatch && !hasAtLeast1Match)
return _NULL;
resetNextBeginningIndexes();
var allowSpacesResult = _algorithm(preparedSearch, target, true);
if (allowSpacesResult !== _NULL && allowSpacesResult._score > score) {
if (allowPartialMatch) {
for (var i = 0; i < searchesLen; ++i) {
_allowPartialMatchScores[i] = allowSpacesResult._score / searchesLen;
}
}
return allowSpacesResult;
}
if (allowPartialMatch)
result = target;
result._score = score;
var idx = 0;
for (let index of seen_indexes)
result._indexes[idx++] = index;
result._indexes.len = idx;
return result;
}
function _go(search, targets, options) {
if (!search)
return options?.all ? _all(targets, options) : _noResults;
var preparedSearch = _getPreparedSearch(search);
var searchBitflags = preparedSearch.bitflags;
var containsSpace = preparedSearch.containsSpace;
var threshold = _denormalizeScore(options?.threshold ?? 0.35);
var limit = options?.limit || _INFINITY;
var resultsLen = 0;
var limitedCount = 0;
var targetsLen = targets.length;
function push_result(result) {
if (resultsLen < limit) {
_q.add(result);
++resultsLen;
} else {
++limitedCount;
if (result._score > _q.peek()._score)
_q.replaceTop(result);
}
}
if (options?.key) {
var key = options.key;
for (var i = 0; i < targetsLen; ++i) {
var obj = targets[i];
var target = _getValue(obj, key);
if (!target)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
if ((searchBitflags & target._bitflags) !== searchBitflags)
continue;
var result = _algorithm(preparedSearch, target);
if (result === _NULL)
continue;
if (result._score < threshold)
continue;
result.obj = obj;
push_result(result);
}
} else if (options?.keys) {
var keys = options.keys;
var keysLen = keys.length;
outer: for (var i = 0; i < targetsLen; ++i) {
var obj = targets[i];
var keysBitflags = 0;
for (var keyI = 0; keyI < keysLen; ++keyI) {
var key = keys[keyI];
var target = _getValue(obj, key);
if (!target) {
_tmpTargets[keyI] = _noTarget;
continue;
}
if (!_isPrepared(target))
target = _getPrepared(target);
_tmpTargets[keyI] = target;
keysBitflags |= target._bitflags;
}
if ((searchBitflags & keysBitflags) !== searchBitflags)
continue;
if (containsSpace)
for (let j = 0; j < preparedSearch.spaceSearches.length; j++)
_keysSpacesBestScores[j] = _NEGATIVE_INFINITY;
for (var keyI = 0; keyI < keysLen; ++keyI) {
target = _tmpTargets[keyI];
if (target === _noTarget) {
_tmpResults[keyI] = _noTarget;
continue;
}
_tmpResults[keyI] = _algorithm(preparedSearch, target, false, containsSpace);
if (_tmpResults[keyI] === _NULL) {
_tmpResults[keyI] = _noTarget;
continue;
}
if (containsSpace)
for (let j = 0; j < preparedSearch.spaceSearches.length; j++) {
if (_allowPartialMatchScores[j] > -1000) {
if (_keysSpacesBestScores[j] > _NEGATIVE_INFINITY) {
var tmp = (_keysSpacesBestScores[j] + _allowPartialMatchScores[j]) / 4;
if (tmp > _keysSpacesBestScores[j])
_keysSpacesBestScores[j] = tmp;
}
}
if (_allowPartialMatchScores[j] > _keysSpacesBestScores[j])
_keysSpacesBestScores[j] = _allowPartialMatchScores[j];
}
}
if (containsSpace) {
for (let j = 0; j < preparedSearch.spaceSearches.length; j++)
if (_keysSpacesBestScores[j] === _NEGATIVE_INFINITY)
continue outer;
} else {
var hasAtLeast1Match = false;
for (let j = 0; j < keysLen; j++)
if (_tmpResults[j]._score !== _NEGATIVE_INFINITY) {
hasAtLeast1Match = true;
break;
}
if (!hasAtLeast1Match)
continue;
}
var objResults = _createKeysResult(keysLen);
for (let j = 0; j < keysLen; j++)
objResults[j] = _tmpResults[j];
var score;
if (containsSpace) {
score = 0;
for (let j = 0; j < preparedSearch.spaceSearches.length; j++)
score += _keysSpacesBestScores[j];
} else {
score = _NEGATIVE_INFINITY;
for (let j = 0; j < keysLen; j++) {
var res = objResults[j];
if (res._score > -1000) {
if (score > _NEGATIVE_INFINITY) {
var tmp = (score + res._score) / 4;
if (tmp > score)
score = tmp;
}
}
if (res._score > score)
score = res._score;
}
}
objResults.obj = obj;
objResults._score = score;
if (options?.scoreFn) {
score = options.scoreFn(objResults);
if (!score)
continue;
score = _denormalizeScore(score);
objResults._score = score;
}
if (score < threshold)
continue;
push_result(objResults);
}
} else {
for (var i = 0; i < targetsLen; ++i) {
var target = targets[i];
if (!target)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
if ((searchBitflags & target._bitflags) !== searchBitflags)
continue;
var result = _algorithm(preparedSearch, target);
if (result === _NULL)
continue;
if (result._score < threshold)
continue;
push_result(result);
}
}
if (resultsLen === 0)
return _noResults;
var results = new Array(resultsLen);
for (var i = resultsLen - 1; i >= 0; --i)
results[i] = _q.poll();
results.total = resultsLen + limitedCount;
return results;
}
}
+375
View File
@@ -0,0 +1,375 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import qs.compat.noctalia.Commons
Singleton {
id: root
property bool isLoaded: false
property string langCode: ""
property var locale: Qt.locale()
property string systemDetectedLangCode: ""
property string fullLocaleCode: "" // Preserves regional locale variants
property var translations: ({})
property var fallbackTranslations: ({})
// Static list of available translations — update when adding/removing translation files
property var availableLanguages: ["en", "en-GB", "cs", "de", "es", "fr", "hu", "it", "ja", "ko-KR", "ku", "nl", "nn-HN", "nn-NO", "pl", "pt", "ru", "sv", "tr", "uk-UA", "vi", "zh-CN", "zh-TW"]
// Default date format per language (used by lock screen, etc.)
readonly property var dateFormats: ({
"cs": "dddd d. MMMM",
"de": "dddd, d. MMMM",
"en": "dddd, MMMM d",
"es": "dddd, d 'de' MMMM",
"fr": "dddd d MMMM",
"hu": "MMMM d., dddd",
"it": "dddd d MMMM",
"ja": "yyyy年M月d日 dddd",
"ko": "yyyy년 M월 d일 dddd",
"ku": "dddd, dê MMMM",
"nl": "dddd d MMMM",
"nn": "dddd d. MMMM",
"pl": "dddd, d MMMM",
"pt": "dddd, d 'de' MMMM",
"ro": "dddd, d MMMM",
"ru": "dddd, d MMMM",
"sv": "dddd d MMMM",
"tr": "dddd, d MMMM",
"uk": "dddd, d MMMM",
"vi": "dddd, d 'tháng' M",
"zh": "yyyy年M月d日 dddd"
})
// Signals for reactive updates
signal languageChanged(string newLanguage)
signal translationsLoaded
// FileView to load translation files
property FileView translationFile: FileView {
id: fileView
printErrors: false
watchChanges: true
onFileChanged: reload()
onLoaded: {
try {
var data = JSON.parse(text());
root.translations = data;
Logger.i("I18n", `Loaded translations for "${root.langCode}"`);
root.isLoaded = true;
root.translationsLoaded();
// Load English fallback for non-English languages (only after main file succeeds)
if (root.langCode !== "en") {
fallbackFileView.path = `file://${Quickshell.shellDir}/compat/noctalia/Assets/Translations/en.json`;
}
} catch (e) {
Logger.e("I18n", `Failed to parse translation file: ${e}`);
setLanguage("en");
}
}
onLoadFailed: function (error) {
if (root.langCode === "en") {
Logger.e("I18n", `Failed to load English translation file: ${error}`);
// English also failed - still emit signal to unblock startup
root.isLoaded = true;
root.translationsLoaded();
return;
}
// Qt.callLater is needed because FileView doesn't re-trigger when path
// is changed inside its own onLoadFailed handler
var strippedCode = stripScript(root.langCode);
if (strippedCode !== root.langCode) {
Logger.d("I18n", `Translation file for "${root.langCode}" not found, trying "${strippedCode}"`);
root.langCode = strippedCode;
Qt.callLater(loadTranslations);
} else {
// Try language-only code (e.g. "zh-CN" → "zh")
var shortCode = root.langCode.substring(0, 2);
if (shortCode !== root.langCode) {
Logger.d("I18n", `Translation file for "${root.langCode}" not found, trying "${shortCode}"`);
root.langCode = shortCode;
Qt.callLater(loadTranslations);
} else {
Logger.w("I18n", `Translation file for "${root.langCode}" not found, falling back to English`);
root.langCode = "en";
root.fullLocaleCode = "en";
root.locale = Qt.locale("en");
Qt.callLater(loadTranslations);
}
}
}
}
// FileView to load fallback translation files
property FileView fallbackTranslationFile: FileView {
id: fallbackFileView
watchChanges: true
onFileChanged: reload()
onLoaded: {
try {
var data = JSON.parse(text());
root.fallbackTranslations = data;
Logger.d("I18n", `Loaded english fallback translations`);
} catch (e) {
Logger.e("I18n", `Failed to parse fallback translation file: ${e}`);
}
}
onLoadFailed: function (error) {
Logger.e("I18n", `Failed to load fallback translation file: ${error}`);
}
}
// Correct language when settings finish loading from disk (or user changes it)
Connections {
target: Settings.data.general
function onLanguageChanged() {
var userLang = Settings.data.general.language;
if (userLang !== "" && userLang !== root.langCode && availableLanguages.includes(userLang)) {
Logger.i("I18n", `Applying user language preference: "${userLang}"`);
setLanguage(userLang);
} else if (userLang === "" && root.systemDetectedLangCode !== "" && root.systemDetectedLangCode !== root.langCode) {
Logger.i("I18n", `Language reset to default, reverting to system language: "${root.systemDetectedLangCode}"`);
setLanguage(root.systemDetectedLangCode);
}
}
}
Component.onCompleted: {
Logger.i("I18n", "Service started");
var lang = determineFastLanguage();
langCode = lang.code;
fullLocaleCode = lang.fullLocale;
locale = Qt.locale(lang.fullLocale);
systemDetectedLangCode = lang.code;
Logger.i("I18n", `Loading "${lang.code}" (locale: "${lang.fullLocale}")`);
loadTranslations();
}
// Strip 4-letter script subtag from a BCP 47 tag (e.g. "fr-Latn-FR" → "fr-FR")
function stripScript(tag) {
var parts = tag.split("-");
var result = [];
for (var i = 0; i < parts.length; i++) {
if (parts[i].length === 4 && /^[A-Za-z]{4}$/.test(parts[i])) {
continue;
}
result.push(parts[i]);
}
return result.join("-");
}
// Determine the best language match against availableLanguages
function determineFastLanguage() {
// User preference from Settings (defaults to "" if not yet loaded from disk)
var userLang = Settings.data.general.language;
if (userLang !== "" && availableLanguages.includes(userLang)) {
return {
code: userLang,
fullLocale: userLang
};
}
// Match system locale against available translations
for (var i = 0; i < Qt.locale().uiLanguages.length; i++) {
var fullLang = Qt.locale().uiLanguages[i];
// Exact match (e.g. "zh-CN")
if (availableLanguages.includes(fullLang)) {
return {
code: fullLang,
fullLocale: fullLang
};
}
// Script-stripped match (e.g. "zh-Hans-CN" → "zh-CN")
var stripped = stripScript(fullLang);
if (stripped !== fullLang && availableLanguages.includes(stripped)) {
return {
code: stripped,
fullLocale: fullLang
};
}
// Language-only match (e.g. "fr-FR" → "fr")
var short_ = fullLang.substring(0, 2);
if (availableLanguages.includes(short_)) {
return {
code: short_,
fullLocale: fullLang
};
}
}
return {
code: "en",
fullLocale: "en"
};
}
function dateFormat() {
var lang = langCode.split("-")[0];
return dateFormats[lang] || "dddd, d MMMM";
}
// -------------------------------------------
function setLanguage(newLangCode, fullLocale) {
if (typeof fullLocale === "undefined") {
fullLocale = newLangCode;
}
if (newLangCode !== langCode && availableLanguages.includes(newLangCode)) {
langCode = newLangCode;
fullLocaleCode = fullLocale;
locale = Qt.locale(fullLocale);
Logger.i("I18n", `Language set to "${langCode}" with locale "${fullLocale}"`);
languageChanged(langCode);
loadTranslations();
} else if (!availableLanguages.includes(newLangCode)) {
Logger.w("I18n", `Language "${newLangCode}" is not available`);
}
}
// -------------------------------------------
function loadTranslations() {
if (langCode === "")
return;
const filePath = `file://${Quickshell.shellDir}/compat/noctalia/Assets/Translations/${langCode}.json`;
fileView.path = filePath;
isLoaded = false;
}
// -------------------------------------------
// Check if a translation exists
function hasTranslation(key) {
if (!isLoaded)
return false;
const keys = key.split(".");
var value = translations;
for (var i = 0; i < keys.length; i++) {
if (value && typeof value === "object" && keys[i] in value) {
value = value[keys[i]];
} else {
return false;
}
}
return typeof value === "string";
}
// -------------------------------------------
// Get all translation keys (useful for debugging)
function getAllKeys(obj, prefix) {
if (typeof obj === "undefined")
obj = translations;
if (typeof prefix === "undefined")
prefix = "";
var keys = [];
for (var key in (obj || {})) {
const value = obj[key];
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof value === "object" && value !== null) {
keys = keys.concat(getAllKeys(value, fullKey));
} else if (typeof value === "string") {
keys.push(fullKey);
}
}
return keys;
}
// -------------------------------------------
// Reload translations (useful for development)
function reload() {
Logger.d("I18n", "Reloading translations");
loadTranslations();
}
// -------------------------------------------
// Main translation function
function tr(key, interpolations) {
if (typeof interpolations === "undefined")
interpolations = {};
if (!isLoaded) {
//Logger.d("I18n", "Translations not loaded yet")
return key;
}
// Navigate nested keys (e.g., "menu.file.open")
const keys = key.split(".");
// Look-up translation in the active language
var value = translations;
var notFound = false;
for (var i = 0; i < keys.length; i++) {
if (value && typeof value === "object" && keys[i] in value) {
value = value[keys[i]];
} else {
Logger.d("I18n", `Translation key "${key}" not found at part "${keys[i]}"`);
Logger.d("I18n", `Available keys: ${Object.keys(value || {}).join(", ")}`);
notFound = true;
break;
}
}
// Fallback to english if not found
if (notFound && availableLanguages.includes("en") && langCode !== "en") {
value = fallbackTranslations;
for (var i = 0; i < keys.length; i++) {
if (value && typeof value === "object" && keys[i] in value) {
value = value[keys[i]];
} else {
// Indicate this key does not even exists in the english fallback
return `!!${key}!!`;
}
}
} else if (notFound) {
// No fallback available
return `!!${key}!!`;
}
if (typeof value !== "string") {
Logger.d("I18n", `Translation key "${key}" is not a string`);
return key;
}
// Handle interpolations (e.g., "Hello {name}!")
var result = value;
for (var placeholder in interpolations) {
const regex = new RegExp(`\\{${placeholder}\\}`, 'g');
result = result.replace(regex, interpolations[placeholder]);
}
return result;
}
// -------------------------------------------
// Plural translation function
function trp(key, count, interpolations) {
if (typeof interpolations === "undefined") {
interpolations = {};
}
// Use key for singular, key-plural for plural
const realKey = count === 1 ? key : `${key}-plural`;
// Merge interpolations with count
var finalInterpolations = {
"count": count
};
for (var prop in interpolations) {
finalInterpolations[prop] = interpolations[prop];
}
return tr(realKey, finalInterpolations);
}
}
@@ -0,0 +1,85 @@
pragma Singleton
import QtQuick
import QtQuick.Controls
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
// Expose the font family name for easy access
readonly property string fontFamily: currentFontLoader ? currentFontLoader.name : ""
readonly property string defaultIcon: IconsTabler.defaultIcon
readonly property var icons: IconsTabler.icons
readonly property var aliases: IconsTabler.aliases
readonly property string fontPath: "/compat/noctalia/Assets/Fonts/tabler/noctalia-tabler-icons.ttf"
// Current active font loader
property FontLoader currentFontLoader: null
property int fontVersion: 0
// Create a unique cache-busting path
readonly property string cacheBustingPath: Quickshell.shellDir + fontPath + "?v=" + fontVersion + "&t=" + Date.now()
// Signal emitted when font is reloaded
signal fontReloaded
Component.onCompleted: {
Logger.i("Icons", "Service started");
loadFontWithCacheBusting();
}
Connections {
target: Quickshell
function onReloadCompleted() {
Logger.d("Icons", "Quickshell reload completed - forcing font reload");
reloadFont();
}
}
// ---------------------------------------
function get(iconName) {
// Check in aliases first
if (aliases[iconName] !== undefined) {
iconName = aliases[iconName];
}
// Find the appropriate codepoint
return icons[iconName];
}
function loadFontWithCacheBusting() {
Logger.d("Icons", "Loading font with cache busting");
// Destroy old loader first
if (currentFontLoader) {
currentFontLoader.destroy();
currentFontLoader = null;
}
// Create new loader with cache-busting URL
currentFontLoader = Qt.createQmlObject(`
import QtQuick
FontLoader {
source: "${cacheBustingPath}"
}
`, root, "dynamicFontLoader_" + fontVersion);
// Connect to the new loader's status changes
currentFontLoader.statusChanged.connect(function () {
if (currentFontLoader.status === FontLoader.Ready) {
Logger.d("Icons", "Font loaded successfully:", currentFontLoader.name, "(version " + fontVersion + ")");
fontReloaded();
} else if (currentFontLoader.status === FontLoader.Error) {
Logger.e("Icons", "Font failed to load (version " + fontVersion + ")");
}
});
}
function reloadFont() {
Logger.d("Icons", "Forcing font reload...");
fontVersion++;
loadFontWithCacheBusting();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,201 @@
pragma Singleton
import QtQuick
QtObject {
function getKeybindString(event) {
let keyStr = "";
if (event.modifiers & Qt.ControlModifier)
keyStr += "Ctrl+";
if (event.modifiers & Qt.AltModifier)
keyStr += "Alt+";
if (event.modifiers & Qt.ShiftModifier)
keyStr += "Shift+";
let keyName = "";
let rawText = event.text;
if (event.key >= Qt.Key_A && event.key <= Qt.Key_Z || event.key >= Qt.Key_0 && event.key <= Qt.Key_9) {
keyName = String.fromCharCode(event.key);
} else if (event.key >= Qt.Key_F1 && event.key <= Qt.Key_F12) {
keyName = "F" + (event.key - Qt.Key_F1 + 1);
} else if (rawText && rawText.length > 0 && rawText.charCodeAt(0) > 31 && rawText.charCodeAt(0) !== 127) {
keyName = rawText.toUpperCase();
if (event.modifiers & Qt.ShiftModifier) {
const shiftMap = {
"!": "1",
"\"": "2",
"§": "3",
"$": "4",
"%": "5",
"&": "6",
"/": "7",
"(": "8",
")": "9",
"=": "0",
"@": "2",
"#": "3",
"^": "6",
"*": "8"
};
if (shiftMap[keyName]) {
keyName = shiftMap[keyName];
}
}
} else {
switch (event.key) {
case Qt.Key_Escape:
keyName = "Esc";
break;
case Qt.Key_Space:
keyName = "Space";
break;
case Qt.Key_Return:
keyName = "Return";
break;
case Qt.Key_Enter:
keyName = "Enter";
break;
case Qt.Key_Tab:
keyName = "Tab";
break;
case Qt.Key_Backspace:
keyName = "Backspace";
break;
case Qt.Key_Delete:
keyName = "Del";
break;
case Qt.Key_Insert:
keyName = "Ins";
break;
case Qt.Key_Home:
keyName = "Home";
break;
case Qt.Key_End:
keyName = "End";
break;
case Qt.Key_PageUp:
keyName = "PgUp";
break;
case Qt.Key_PageDown:
keyName = "PgDn";
break;
case Qt.Key_Left:
keyName = "Left";
break;
case Qt.Key_Right:
keyName = "Right";
break;
case Qt.Key_Up:
keyName = "Up";
break;
case Qt.Key_Down:
keyName = "Down";
break;
case Qt.Key_BracketLeft:
keyName = "[";
break;
case Qt.Key_BracketRight:
keyName = "]";
break;
case Qt.Key_Backslash:
keyName = "\\";
break;
case Qt.Key_Slash:
keyName = "/";
break;
case Qt.Key_QuoteLeft:
case Qt.Key_AsciiTilde:
case Qt.Key_Dead_Grave:
keyName = "`";
break;
}
}
if (!keyName)
return "";
return keyStr + keyName;
}
function checkKey(event, settingName, settings) {
// Accept both simplified names ("remove") and full property names ("keyRemove")
// so callers are less error-prone.
var normalized = String(settingName || "");
if (!normalized)
return false;
var propName = normalized.startsWith("key") ? normalized : ("key" + normalized.charAt(0).toUpperCase() + normalized.slice(1));
var boundKeys = settings.data.general.keybinds[propName];
if (!boundKeys || boundKeys.length === 0)
return false;
var eventString = getKeybindString(event);
for (var i = 0; i < boundKeys.length; i++) {
if (boundKeys[i] === eventString)
return true;
}
return false;
}
/**
* Check if a keybind string conflicts with any other existing keybinds.
* @param {string} keyStr - The keybind string to check (e.g., "Ctrl+A").
* @param {string} currentPath - The settings path of the keybind being edited (to skip checking itself).
* @param {object} data - The settings data object (from Settings.data).
* @returns {string|null} - The name of the conflicting action, or null if no conflict.
*/
function getKeybindConflict(keyStr, currentPath, data) {
if (!keyStr || !data)
return null;
const searchKey = String(keyStr).trim().toLowerCase();
// 1. Check navigation keybinds
const navKeybinds = data.general ? data.general.keybinds : null;
const navMap = {
"keyUp": "Navigation: Up",
"keyDown": "Navigation: Down",
"keyLeft": "Navigation: Left",
"keyRight": "Navigation: Right",
"keyEnter": "Navigation: Enter",
"keyEscape": "Navigation: Escape"
};
if (navKeybinds) {
for (const prop in navMap) {
const fullPath = "general.keybinds." + prop;
if (fullPath === currentPath)
continue;
const boundKeys = navKeybinds[prop];
if (boundKeys && boundKeys.length !== undefined) {
for (let i = 0; i < boundKeys.length; i++) {
if (String(boundKeys[i]).trim().toLowerCase() === searchKey) {
return navMap[prop];
}
}
}
}
}
// 2. Check session menu power options
const sessionMenu = data.sessionMenu;
if (sessionMenu && sessionMenu.powerOptions) {
const powerOptions = sessionMenu.powerOptions;
for (let i = 0; i < powerOptions.length; i++) {
const entry = powerOptions[i];
const fullPath = "sessionMenu.powerOptions[" + i + "].keybind";
if (fullPath === currentPath)
continue;
if (entry.keybind && String(entry.keybind).trim().toLowerCase() === searchKey) {
// Capitalize action name
const actionName = entry.action ? entry.action.charAt(0).toUpperCase() + entry.action.slice(1) : "Unknown";
return "Session Menu: " + actionName;
}
}
}
return null;
}
}
@@ -0,0 +1,69 @@
pragma Singleton
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
function _formatMessage(...args) {
var t = Time.getFormattedTimestamp();
if (args.length > 1) {
const maxLength = 14;
var module = args.shift().substring(0, maxLength).padStart(maxLength, " ");
return `\x1b[36m[${t}]\x1b[0m \x1b[35m${module}\x1b[0m ` + args.join(" ");
} else {
return `[\x1b[36m[${t}]\x1b[0m ` + args.join(" ");
}
}
function _getStackTrace() {
try {
throw new Error("Stack trace");
} catch (e) {
return e.stack;
}
}
// Debug log (only when Settings.isDebug is true)
function d(...args) {
if (Settings?.isDebug) {
var msg = _formatMessage(...args);
console.debug(msg);
}
}
// Info log (always visible)
function i(...args) {
var msg = _formatMessage(...args);
console.info(msg);
}
// Warning log (always visible)
function w(...args) {
var msg = _formatMessage(...args);
console.warn(msg);
}
// Error log (always visible)
function e(...args) {
var msg = _formatMessage(...args);
console.error(msg);
}
function callStack() {
var stack = _getStackTrace();
Logger.i("Debug", "--------------------------");
Logger.i("Debug", "Current call stack");
// Split the stack into lines and log each one
var stackLines = stack.split('\n');
for (var i = 0; i < stackLines.length; i++) {
var line = stackLines[i].trim(); // Remove leading/trailing whitespace
if (line.length > 0) {
// Only log non-empty lines
Logger.i("Debug", `- ${line}`);
}
}
Logger.i("Debug", "--------------------------");
}
}
@@ -0,0 +1,23 @@
import QtQuick
QtObject {
id: root
// Migrate from version < 27 to version 27
// Converts settingsPanelAttachToBar boolean to settingsPanelMode string
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v27");
// Check rawJson for old property (adapter doesn't expose removed properties)
if (rawJson?.ui?.settingsPanelAttachToBar !== undefined) {
if (rawJson.ui.settingsPanelAttachToBar === true) {
adapter.ui.settingsPanelMode = "attached";
} else {
adapter.ui.settingsPanelMode = "centered";
}
logger.i("Settings", "Migrated settingsPanelAttachToBar to settingsPanelMode: " + adapter.ui.settingsPanelMode);
}
return true;
}
}
@@ -0,0 +1,37 @@
import QtQuick
QtObject {
id: root
// Migrate TaskbarGrouped widgets to Workspace with showApplications: true
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v28");
// Check bar widgets in all sections
const sections = ["left", "center", "right"];
for (const section of sections) {
if (!rawJson?.bar?.widgets?.[section])
continue;
const widgets = rawJson.bar.widgets[section];
for (let i = 0; i < widgets.length; i++) {
if (widgets[i].id === "TaskbarGrouped") {
// Convert TaskbarGrouped to Workspace with showApplications
const oldWidget = widgets[i];
adapter.bar.widgets[section][i] = {
id: "Workspace",
showApplications: true,
labelMode: oldWidget.labelMode || "index",
hideUnoccupied: oldWidget.hideUnoccupied || false,
showLabelsOnlyWhenOccupied: oldWidget.showLabelsOnlyWhenOccupied ?? true,
colorizeIcons: oldWidget.colorizeIcons || false
};
logger.i("Settings", "Migrated TaskbarGrouped to Workspace in " + section + " section");
}
}
}
return true;
}
}
@@ -0,0 +1,18 @@
import QtQuick
QtObject {
id: root
// Migrate systemMonitor.enableNvidiaGpu to systemMonitor.enableDgpuMonitoring
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v32");
// Check rawJson for old property (adapter doesn't expose removed properties)
if (rawJson?.systemMonitor?.enableNvidiaGpu !== undefined) {
adapter.systemMonitor.enableDgpuMonitoring = rawJson.systemMonitor.enableNvidiaGpu;
logger.i("Settings", "Migrated systemMonitor.enableNvidiaGpu to enableDgpuMonitoring: " + adapter.systemMonitor.enableDgpuMonitoring);
}
return true;
}
}
@@ -0,0 +1,26 @@
import QtQuick
QtObject {
id: root
// Migrate wallpaper.randomEnabled to wallpaper.wallpaperChangeMode
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v33");
if (rawJson?.wallpaper?.randomEnabled !== undefined) {
// We'll keep randomEnabled for backward compatibility but set wallpaperChangeMode
if (rawJson.wallpaper.randomEnabled === true) {
adapter.wallpaper.wallpaperChangeMode = "random";
logger.i("Settings", "Migrated wallpaper.randomEnabled=true to wallpaperChangeMode=random");
} else {
adapter.wallpaper.wallpaperChangeMode = "random";
logger.i("Settings", "Set wallpaperChangeMode=random (randomEnabled was false)");
}
} else {
adapter.wallpaper.wallpaperChangeMode = "random";
logger.i("Settings", "Set default wallpaperChangeMode=random");
}
return true;
}
}
@@ -0,0 +1,20 @@
import QtQuick
QtObject {
id: root
// Migrate bar.transparent to bar.backgroundOpacity + bar.useSeparateOpacity
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v35");
if (rawJson?.bar?.transparent !== undefined) {
if (rawJson.bar.transparent === true) {
adapter.bar.backgroundOpacity = 0;
adapter.bar.useSeparateOpacity = true;
logger.i("Settings", "Migrated bar.transparent=true to backgroundOpacity=0, useSeparateOpacity=true");
}
}
return true;
}
}
@@ -0,0 +1,29 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
// Clear legacy emoji usage cache to adopt new format
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v36");
const usagePath = Settings.cacheDir + "emoji_usage.json";
if (!usagePath.endsWith("emoji_usage.json")) {
logger.w("Settings", "Skipping emoji usage cleanup due to unexpected path: " + usagePath);
return true;
}
try {
// Ensure dir exists then remove the file
Quickshell.execDetached(["sh", "-c", `mkdir -p "${Settings.cacheDir}" && rm -f -- "${usagePath}"`]);
logger.i("Settings", "Cleared legacy emoji usage file at: " + usagePath);
} catch (e) {
logger.w("Settings", "Failed to clear emoji usage cache: " + e);
}
return true;
}
}
@@ -0,0 +1,79 @@
import QtQuick
QtObject {
id: root
// Rename WiFi widgets/shortcuts to Network
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v37 (WiFi → Network)");
let changed = false;
function migrateArray(contextName, rawArr, adapterArr, setItem) {
if (!adapterArr)
return;
const len = adapterArr.length;
for (let i = 0; i < len; i++) {
// Prefer raw item if present, otherwise use adapter item
const item = rawArr && rawArr[i] !== undefined ? rawArr[i] : adapterArr[i];
if (item === undefined || item === null)
continue;
// Case 1: simple string entries
if (typeof item === "string") {
if (item === "WiFi") {
setItem(i, "Network");
changed = true;
logger.i("Settings", `Migrated ${contextName}[${i}] from WiFi to Network (string entry)`);
}
continue;
}
// Case 2: object entries with id
let id = item.id !== undefined ? item.id : (item.widgetId !== undefined ? item.widgetId : undefined);
if (id === "WiFi") {
var newObj = {};
for (var key in item)
newObj[key] = item[key];
if (newObj.id !== undefined)
newObj.id = "Network";
if (newObj.widgetId !== undefined && newObj.id === undefined)
newObj.widgetId = "Network"; // fallback if older schema used widgetId
setItem(i, newObj);
changed = true;
logger.i("Settings", `Migrated ${contextName}[${i}] from WiFi to Network (object entry)`);
}
}
}
// --- Bar widgets: left/center/right
const sections = ["left", "center", "right"];
for (const section of sections) {
const rawArr = rawJson?.bar?.widgets?.[section];
const adapterArr = adapter?.bar?.widgets?.[section];
migrateArray(`bar.widgets.${section}`, rawArr, adapterArr, function (i, v) {
adapter.bar.widgets[section][i] = v;
});
}
// --- Control Center shortcuts: left/right
const rawLeft = rawJson?.controlCenter?.shortcuts?.left;
const adLeft = adapter?.controlCenter?.shortcuts?.left;
migrateArray("controlCenter.shortcuts.left", rawLeft, adLeft, function (i, v) {
adapter.controlCenter.shortcuts.left[i] = v;
});
const rawRight = rawJson?.controlCenter?.shortcuts?.right;
const adRight = adapter?.controlCenter?.shortcuts?.right;
migrateArray("controlCenter.shortcuts.right", rawRight, adRight, function (i, v) {
adapter.controlCenter.shortcuts.right[i] = v;
});
if (!changed) {
logger.i("Settings", "No WiFi widget IDs found to migrate; leaving settings unchanged");
}
return true;
}
}
@@ -0,0 +1,27 @@
import QtQuick
import qs.compat.noctalia.Commons
QtObject {
function migrate(adapter, logger, rawJson) {
logger.i("Migration38", "Migrating bar margins from percentages to integers");
// Use rawJson to read original values, adapter to write new values (following migration patterns)
const rawVertical = rawJson?.bar?.marginVertical;
const rawHorizontal = rawJson?.bar?.marginHorizontal;
// Only migrate if values exist and are percentages (<= 1.0)
if (rawVertical !== undefined && typeof rawVertical === 'number' && rawVertical <= 1.0) {
const marginXL = 18; // Standard value of Style.marginXL
adapter.bar.marginVertical = Math.round(rawVertical * marginXL);
logger.d("Migration38", "Converted marginVertical from " + rawVertical + " to " + adapter.bar.marginVertical + "px");
}
if (rawHorizontal !== undefined && typeof rawHorizontal === 'number' && rawHorizontal <= 1.0) {
const marginXL = 18; // Standard value of Style.marginXL
adapter.bar.marginHorizontal = Math.round(rawHorizontal * marginXL);
logger.d("Migration38", "Converted marginHorizontal from " + rawHorizontal + " to " + adapter.bar.marginHorizontal + "px");
}
return true;
}
}
@@ -0,0 +1,43 @@
import QtQuick
QtObject {
id: root
// List of all template IDs that existed as booleans in the old format
readonly property var templateIds: ["gtk", "qt", "kcolorscheme", "alacritty", "kitty", "ghostty", "foot", "wezterm", "fuzzel", "discord", "pywalfox", "vicinae", "walker", "code", "spicetify", "telegram", "cava", "yazi", "emacs", "niri", "hyprland", "mango", "zed", "helix", "zenBrowser"]
function migrate(adapter, logger, rawJson) {
logger.i("Migration39", "Migrating templates from boolean format to activeTemplates array");
// Check if old format exists (any boolean template property)
const oldTemplates = rawJson?.templates;
if (!oldTemplates) {
logger.d("Migration39", "No templates section found, skipping migration");
return true;
}
// Check if already migrated (has activeTemplates array)
if (Array.isArray(oldTemplates.activeTemplates)) {
logger.d("Migration39", "Already has activeTemplates array, skipping migration");
return true;
}
// Build the new activeTemplates array from old boolean values
const activeTemplates = [];
for (const templateId of templateIds) {
if (oldTemplates[templateId] === true) {
activeTemplates.push({
"id": templateId,
"enabled": true
});
logger.d("Migration40", "Migrated enabled template: " + templateId);
}
}
// Write the new format
adapter.templates.activeTemplates = activeTemplates;
logger.i("Migration40", "Migrated " + activeTemplates.length + " templates to new array format");
return true;
}
}
@@ -0,0 +1,28 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration42", "Migrating randomEnabled to automationEnabled");
const wallpaper = rawJson?.wallpaper;
if (!wallpaper) {
logger.d("Migration42", "No wallpaper section found, skipping migration");
return true;
}
// Check if already migrated (has automationEnabled)
if (wallpaper.automationEnabled !== undefined) {
logger.d("Migration42", "Already has automationEnabled, skipping migration");
return true;
}
// Migrate randomEnabled to automationEnabled
const oldValue = wallpaper.randomEnabled ?? false;
adapter.wallpaper.automationEnabled = oldValue;
logger.i("Migration42", "Migrated randomEnabled=" + oldValue + " to automationEnabled=" + oldValue);
return true;
}
}
@@ -0,0 +1,29 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration43", "Migrating recursiveSearch to viewMode");
const wallpaper = rawJson?.wallpaper;
if (!wallpaper) {
logger.d("Migration43", "No wallpaper section found, skipping migration");
return true;
}
// Check if already migrated (has viewMode)
if (wallpaper.viewMode !== undefined) {
logger.d("Migration43", "Already has viewMode, skipping migration");
return true;
}
// Migrate recursiveSearch to viewMode
const oldValue = wallpaper.recursiveSearch ?? false;
const newValue = oldValue ? "recursive" : "single";
adapter.wallpaper.viewMode = newValue;
logger.i("Migration43", "Migrated recursiveSearch=" + oldValue + " to viewMode=" + newValue);
return true;
}
}
@@ -0,0 +1,35 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration44", "Updating PAM pam/password.conf");
const configDir = Settings.configDir;
const pamConfigDir = configDir + "pam";
const pamConfigFile = pamConfigDir + "/password.conf";
const pamConfigDirEsc = pamConfigDir.replace(/'/g, "'\\''");
const pamConfigFileEsc = pamConfigFile.replace(/'/g, "'\\''");
// Ensure directory exists
Quickshell.execDetached(["mkdir", "-p", pamConfigDir]);
// Generate the PAM config file content (updated version)
var configContent = "auth sufficient pam_fprintd.so timeout=-1\n";
configContent += "auth sufficient /run/current-system/sw/lib/security/pam_fprintd.so timeout=-1 # for NixOS\n";
configContent += "auth required pam_unix.so\n";
// Write the config file using heredoc
var script = `cat > '${pamConfigFileEsc}' << 'EOF'\n`;
script += configContent;
script += "EOF\n";
Quickshell.execDetached(["sh", "-c", script]);
logger.d("Migration44", "PAM config file updated at:", pamConfigFile);
return true;
}
}
@@ -0,0 +1,18 @@
import QtQuick
QtObject {
/**
* Migration 45: Migrate 'floating' bar setting to 'barType'
*/
function migrate(adapter, logger, rawJson) {
logger.i("Migration45", "Migrating bar settings...");
if (rawJson?.bar?.floating) {
adapter.bar.barType = "floating";
} else {
adapter.bar.barType = "simple";
}
return true;
}
}
@@ -0,0 +1,21 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration46", "Removing legacy PAM configuration file");
const configDir = Settings.configDir;
const pamConfigDir = configDir + "pam";
// Remove the entire pam directory if it exists
const script = `rm -rf '${pamConfigDir}'`;
Quickshell.execDetached(["sh", "-c", script]);
logger.d("Migration46", "Cleaned up legacy PAM config");
return true;
}
}
@@ -0,0 +1,18 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration47", "Removing network_stats.json cache");
const networkStatsFile = Settings.cacheDir + "network_stats.json";
Quickshell.execDetached(["rm", "-f", networkStatsFile]);
logger.d("Migration47", "Removed network_stats.json");
return true;
}
}
@@ -0,0 +1,22 @@
import QtQuick
QtObject {
id: root
// Migrate battery thresholds from notifications to systemMonitor
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v48");
if (rawJson?.notifications?.batteryWarningThreshold !== undefined) {
adapter.systemMonitor.batteryWarningThreshold = rawJson.notifications.batteryWarningThreshold;
logger.i("Settings", "Migrated notifications.batteryWarningThreshold to systemMonitor: " + adapter.systemMonitor.batteryWarningThreshold);
}
if (rawJson?.notifications?.batteryCriticalThreshold !== undefined) {
adapter.systemMonitor.batteryCriticalThreshold = rawJson.notifications.batteryCriticalThreshold;
logger.i("Settings", "Migrated notifications.batteryCriticalThreshold to systemMonitor: " + adapter.systemMonitor.batteryCriticalThreshold);
}
return true;
}
}
@@ -0,0 +1,17 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
// Remove old launcher_app_usage.json (usage tracking moved to ShellState)
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v49");
Quickshell.execDetached(["rm", "-f", Settings.cacheDir + "launcher_app_usage.json"]);
logger.i("Settings", "Removed old launcher_app_usage.json");
return true;
}
}
@@ -0,0 +1,24 @@
import QtQuick
QtObject {
id: root
// Migrate keybinds from single strings to arrays of strings
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v50");
const keybinds = rawJson?.general?.keybinds;
if (!keybinds)
return true;
const keys = ["keyUp", "keyDown", "keyLeft", "keyRight", "keyEnter", "keyEscape"];
for (const key of keys) {
if (keybinds[key] !== undefined && typeof keybinds[key] === "string") {
adapter.general.keybinds[key] = [keybinds[key]];
logger.i("Settings", "Migrated keybinds." + key + " from string to array: [" + keybinds[key] + "]");
}
}
return true;
}
}
@@ -0,0 +1,39 @@
import QtQuick
QtObject {
id: root
// Add default keybinds (1-6) to session menu power options if none are defined
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v53");
const powerOptions = rawJson?.sessionMenu?.powerOptions;
if (!powerOptions || !Array.isArray(powerOptions))
return true;
// Check if any power option has a keybind defined
const hasAnyKeybind = powerOptions.some(opt => opt.keybind && opt.keybind !== "");
if (hasAnyKeybind)
return true;
// No keybinds defined — apply defaults matching the action order
const defaultKeybinds = {
"lock": "1",
"suspend": "2",
"hibernate": "3",
"reboot": "4",
"logout": "5",
"shutdown": "6"
};
for (let i = 0; i < powerOptions.length; i++) {
const action = powerOptions[i].action;
if (defaultKeybinds[action]) {
adapter.sessionMenu.powerOptions[i].keybind = defaultKeybinds[action];
logger.i("Settings", "Set keybind '" + defaultKeybinds[action] + "' for session menu action: " + action);
}
}
return true;
}
}
@@ -0,0 +1,28 @@
import QtQuick
QtObject {
id: root
// Add numpad Enter as a second default keybind for keyEnter
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v54");
const keybinds = rawJson?.general?.keybinds;
if (!keybinds)
return true;
const keyEnter = keybinds.keyEnter;
if (!keyEnter || !Array.isArray(keyEnter))
return true;
// Only add "Enter" if the first entry is "Return" and "Enter" isn't already present
if (keyEnter[0] === "Return" && !keyEnter.includes("Enter")) {
var updated = Array.from(keyEnter);
updated.splice(1, 0, "Enter");
adapter.general.keybinds.keyEnter = updated;
logger.i("Settings", "Added 'Enter' (numpad) as second default keybind for keyEnter");
}
return true;
}
}
@@ -0,0 +1,22 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v55");
// Check if the old setting exists
if (rawJson.controlCenter && rawJson.controlCenter.openAtMouseOnBarRightClick !== undefined) {
if (!rawJson.bar)
rawJson.bar = {};
rawJson.bar.rightClickFollowMouse = rawJson.controlCenter.openAtMouseOnBarRightClick;
delete rawJson.controlCenter.openAtMouseOnBarRightClick;
logger.i("Settings", "Successfully moved openAtMouseOnBarRightClick to bar.rightClickFollowMouse");
}
return true;
}
}
@@ -0,0 +1,21 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v56 (Color Scheme Migration)");
const scriptPath = Quickshell.shellDir + "/Scripts/python/src/theming/migrate-colorschemes.py";
const configDir = Settings.configDir;
logger.i("Settings", `Running color scheme migration script: ${scriptPath} with configDir: ${configDir}`);
// Run the migration script detached
Quickshell.execDetached(["python3", scriptPath, configDir]);
return true;
}
}
@@ -0,0 +1,16 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v57 (cavaFrameRate -> spectrumFrameRate)");
if (rawJson && rawJson.audio && rawJson.audio.cavaFrameRate !== undefined) {
adapter.audio.spectrumFrameRate = rawJson.audio.cavaFrameRate;
logger.i("Settings", "Migrated cavaFrameRate:", rawJson.audio.cavaFrameRate, "-> spectrumFrameRate");
}
return true;
}
}
@@ -0,0 +1,14 @@
import QtQuick
QtObject {
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v58 (dock.dockType: static -> attached)");
if (rawJson && rawJson.dock && rawJson.dock.dockType === "static") {
adapter.dock.dockType = "attached";
logger.i("Settings", "Migrated dock.dockType: static -> attached");
}
return true;
}
}
@@ -0,0 +1,25 @@
import QtQuick
QtObject {
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v59 (wallpaper.transitionType: string -> array)");
if (rawJson && rawJson.wallpaper && typeof rawJson.wallpaper.transitionType === "string") {
var oldValue = rawJson.wallpaper.transitionType;
var newValue;
if (oldValue === "random") {
newValue = ["fade", "disc", "stripes", "wipe", "pixelate", "honeycomb"];
} else if (oldValue === "none") {
newValue = [];
} else {
newValue = [oldValue];
}
adapter.wallpaper.transitionType = newValue;
logger.i("Settings", "Migrated wallpaper.transitionType:", oldValue, "->", JSON.stringify(newValue));
}
return true;
}
}
@@ -0,0 +1,63 @@
pragma Singleton
import QtQuick
QtObject {
id: root
// Map of version number to migration component
readonly property var migrations: ({
27: migration27Component,
28: migration28Component,
32: migration32Component,
33: migration33Component,
35: migration35Component,
36: migration36Component,
37: migration37Component,
38: migration38Component,
40: migration40Component,
42: migration42Component,
43: migration43Component,
44: migration44Component,
45: migration45Component,
46: migration46Component,
47: migration47Component,
48: migration48Component,
49: migration49Component,
50: migration50Component,
53: migration53Component,
54: migration54Component,
55: migration55Component,
56: migration56Component,
57: migration57Component,
58: migration58Component,
59: migration59Component
})
// Migration components
property Component migration27Component: Migration27 {}
property Component migration28Component: Migration28 {}
property Component migration32Component: Migration32 {}
property Component migration33Component: Migration33 {}
property Component migration35Component: Migration35 {}
property Component migration36Component: Migration36 {}
property Component migration37Component: Migration37 {}
property Component migration38Component: Migration38 {}
property Component migration40Component: Migration40 {}
property Component migration42Component: Migration42 {}
property Component migration43Component: Migration43 {}
property Component migration44Component: Migration44 {}
property Component migration45Component: Migration45 {}
property Component migration46Component: Migration46 {}
property Component migration47Component: Migration47 {}
property Component migration48Component: Migration48 {}
property Component migration49Component: Migration49 {}
property Component migration50Component: Migration50 {}
property Component migration53Component: Migration53 {}
property Component migration54Component: Migration54 {}
property Component migration55Component: Migration55 {}
property Component migration56Component: Migration56 {}
property Component migration57Component: Migration57 {}
property Component migration58Component: Migration58 {}
property Component migration59Component: Migration59 {}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,287 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import "../Helpers/QtObj2JS.js" as QtObj2JS
import qs.compat.noctalia.Services.Power
import qs.compat.noctalia.Services.System
import qs.compat.noctalia.Services.UI
// Centralized shell state management for small cache files
Singleton {
id: root
property string stateFile: ""
property bool isLoaded: false
// State properties for different services
readonly property alias data: adapter
// Signals for state changes
signal displayStateChanged
signal notificationsStateChanged
signal changelogStateChanged
signal colorSchemesListChanged
Component.onCompleted: {
// Setup state file path (needs Settings to be available)
Qt.callLater(() => {
if (typeof Settings !== 'undefined' && Settings.cacheDir) {
stateFile = Settings.cacheDir + "shell-state.json";
stateFileView.path = stateFile;
}
});
}
// FileView for shell state
FileView {
id: stateFileView
printErrors: false
watchChanges: false
adapter: JsonAdapter {
id: adapter
// CompositorService: display scales
property var display: ({})
// NotificationService: notification state
property var notificationsState: ({
lastSeenTs: 0
})
// UpdateService: changelog state
property var changelogState: ({
lastSeenVersion: ""
})
// SchemeDownloader: color schemes list
property var colorSchemesList: ({
schemes: [],
timestamp: 0
})
// UI state: settings panel, etc.
property var ui: ({
settingsSidebarExpanded: true
})
// Telemetry state
property var telemetry: ({
instanceId: ""
})
// Launcher app usage counts
property var launcherUsage: ({})
}
onLoaded: {
root.isLoaded = true;
Logger.d("ShellState", "Loaded state file");
}
onLoadFailed: error => {
if (error === 2) {
// File doesn't exist, will be created on first write
root.isLoaded = true;
Logger.d("ShellState", "State file doesn't exist, will create on first write");
} else {
Logger.e("ShellState", "Failed to load state file:", error);
root.isLoaded = true;
}
}
}
// Launcher usage
function getLauncherUsageCount(key) {
const m = adapter.launcherUsage;
if (!m)
return 0;
const v = m[key];
return typeof v === 'number' && isFinite(v) ? v : 0;
}
function recordLauncherUsage(key) {
let counts = Object.assign({}, adapter.launcherUsage || {});
counts[key] = getLauncherUsageCount(key) + 1;
adapter.launcherUsage = counts;
save();
}
// Migrate usage from one key to another, merging counts in a single save
function migrateLauncherUsage(fromKey, toKey) {
let counts = Object.assign({}, adapter.launcherUsage || {});
const fromCount = typeof counts[fromKey] === 'number' && isFinite(counts[fromKey]) ? counts[fromKey] : 0;
const toCount = typeof counts[toKey] === 'number' && isFinite(counts[toKey]) ? counts[toKey] : 0;
counts[toKey] = toCount + fromCount;
delete counts[fromKey];
adapter.launcherUsage = counts;
save();
}
// Debounced save timer
Timer {
id: saveTimer
interval: 500
onTriggered: performSave()
}
property bool saveQueued: false
function save() {
saveQueued = true;
saveTimer.restart();
}
function performSave() {
if (!saveQueued || !stateFile) {
return;
}
saveQueued = false;
try {
// Ensure cache directory exists
Quickshell.execDetached(["mkdir", "-p", Settings.cacheDir]);
Qt.callLater(() => {
try {
stateFileView.writeAdapter();
Logger.d("ShellState", "Saved state file");
} catch (writeError) {
Logger.e("ShellState", "Failed to write state file:", writeError);
}
});
} catch (error) {
Logger.e("ShellState", "Failed to save state:", error);
}
}
// Convenience functions for each service
// Display state (CompositorService)
function setDisplay(displayData) {
adapter.display = displayData;
save();
displayStateChanged();
}
function getDisplay() {
return adapter.display || {};
}
// Notifications state (NotificationService)
function setNotificationsState(stateData) {
adapter.notificationsState = stateData;
save();
notificationsStateChanged();
}
function getNotificationsState() {
return adapter.notificationsState || {
lastSeenTs: 0
};
}
// Changelog state (UpdateService)
function setChangelogState(stateData) {
adapter.changelogState = stateData;
save();
changelogStateChanged();
}
function getChangelogState() {
return adapter.changelogState || {
lastSeenVersion: ""
};
}
// Color schemes list (SchemeDownloader)
function setColorSchemesList(listData) {
adapter.colorSchemesList = listData;
save();
colorSchemesListChanged();
}
function getColorSchemesList() {
return adapter.colorSchemesList || {
schemes: [],
timestamp: 0
};
}
// UI state
function setUiState(stateData) {
adapter.ui = stateData;
save();
}
function getUiState() {
return adapter.ui || {
settingsSidebarExpanded: true
};
}
function setSettingsSidebarExpanded(expanded) {
let uiState = getUiState();
uiState.settingsSidebarExpanded = expanded;
setUiState(uiState);
}
function getSettingsSidebarExpanded() {
return getUiState().settingsSidebarExpanded !== false; // default to true
}
// Telemetry state
function setTelemetryState(stateData) {
adapter.telemetry = stateData;
save();
}
function getTelemetryState() {
return adapter.telemetry || {
instanceId: ""
};
}
function getTelemetryInstanceId() {
return getTelemetryState().instanceId || "";
}
function setTelemetryInstanceId(instanceId) {
let state = getTelemetryState();
state.instanceId = instanceId;
setTelemetryState(state);
}
// -----------------------------------------------------
function buildStateSnapshot() {
try {
const settingsData = QtObj2JS.qtObjectToPlainObject(Settings.data);
const shellStateData = ShellState?.data ? QtObj2JS.qtObjectToPlainObject(ShellState.data) || {} : {};
return {
settings: settingsData,
state: {
doNotDisturb: NotificationService.doNotDisturb,
noctaliaPerformanceMode: PowerProfileService.noctaliaPerformanceMode,
barVisible: BarService.isVisible,
openedPanel: PanelService.openedPanel?.objectName || "",
lockScreenActive: PanelService.lockScreen?.active || false,
wallpapers: WallpaperService.getWallpapersEffectiveMap(),
desktopWidgetsEditMode: DesktopWidgetRegistry.editMode || false,
// -------------
display: shellStateData.display || {},
notificationsState: shellStateData.notificationsState || {},
changelogState: shellStateData.changelogState || {},
colorSchemesList: shellStateData.colorSchemesList || {},
ui: shellStateData.ui || {}
}
};
} catch (error) {
Logger.e("Settings", "Failed to build state snapshot:", error);
return null;
}
}
}
@@ -0,0 +1,203 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Services.Power
import "../../../theme" as G
import "../../../core" as Core
Singleton {
id: root
// glassMxrph: radii, bar sizes, animation and panel opacity follow the
// glassMxrph theme so Noctalia plugins match the shell.
readonly property real glassRadiusRatio: G.Theme.radius / 20
readonly property real glassBarHeight: Core.BarDrawers.height
readonly property real glassCapsuleHeight: Core.ModuleRegistry.pillHeight
// Font size
readonly property real fontSizeXXS: 8
readonly property real fontSizeXS: 9
readonly property real fontSizeS: 10
readonly property real fontSizeM: 11
readonly property real fontSizeL: 13
readonly property real fontSizeXL: 16
readonly property real fontSizeXXL: 18
readonly property real fontSizeXXXL: 24
// Font weight
readonly property int fontWeightRegular: 400
readonly property int fontWeightMedium: 500
readonly property int fontWeightSemiBold: 600
readonly property int fontWeightBold: 700
// Container Radii: major layout sections (sidebars, cards, content panels)
readonly property int radiusXXXS: Math.round(3 * root.glassRadiusRatio)
readonly property int radiusXXS: Math.round(4 * root.glassRadiusRatio)
readonly property int radiusXS: Math.round(8 * root.glassRadiusRatio)
readonly property int radiusS: Math.round(12 * root.glassRadiusRatio)
readonly property int radiusM: Math.round(16 * root.glassRadiusRatio)
readonly property int radiusL: Math.round(20 * root.glassRadiusRatio)
// Input radii: interactive elements (buttons, toggles, text fields)
readonly property int iRadiusXXXS: Math.round(3 * root.glassRadiusRatio)
readonly property int iRadiusXXS: Math.round(4 * root.glassRadiusRatio)
readonly property int iRadiusXS: Math.round(8 * root.glassRadiusRatio)
readonly property int iRadiusS: Math.round(12 * root.glassRadiusRatio)
readonly property int iRadiusM: Math.round(16 * root.glassRadiusRatio)
readonly property int iRadiusL: Math.round(20 * root.glassRadiusRatio)
readonly property int screenRadius: Math.round(20 * Settings.data.general.screenRadiusRatio)
// Border
readonly property int borderS: Math.max(1, Math.round(1 * uiScaleRatio))
readonly property int borderM: Math.max(1, Math.round(2 * uiScaleRatio))
readonly property int borderL: Math.max(1, Math.round(3 * uiScaleRatio))
// Margins (for margins and spacing)
readonly property int marginXXXS: Math.round(1 * uiScaleRatio)
readonly property int marginXXS: Math.round(2 * uiScaleRatio)
readonly property int marginXS: Math.round(4 * uiScaleRatio)
readonly property int marginS: Math.round(6 * uiScaleRatio)
readonly property int marginM: Math.round(9 * uiScaleRatio)
readonly property int marginL: Math.round(13 * uiScaleRatio)
readonly property int marginXL: Math.round(18 * uiScaleRatio)
// Double margins, for proper container sizing only (e.g. height: id.implicitHeight + Style.margin2M)
readonly property int margin2XXXS: marginXXXS * 2
readonly property int margin2XXS: marginXXS * 2
readonly property int margin2XS: marginXS * 2
readonly property int margin2S: marginS * 2
readonly property int margin2M: marginM * 2
readonly property int margin2L: marginL * 2
readonly property int margin2XL: marginXL * 2
// Opacity
readonly property real opacityNone: 0.0
readonly property real opacityLight: 0.25
readonly property real opacityMedium: 0.5
readonly property real opacityHeavy: 0.75
readonly property real opacityAlmost: 0.95
readonly property real opacityFull: 1.0
readonly property real effectivePanelOpacity: G.Theme.glassOpacity
readonly property real effectiveBarOpacity: G.Theme.glassOpacity
// Shadows
readonly property real shadowOpacity: 0.85
readonly property real shadowBlur: 1.0
readonly property int shadowBlurMax: 22
readonly property real shadowHorizontalOffset: Settings.data.general.shadowOffsetX
readonly property real shadowVerticalOffset: Settings.data.general.shadowOffsetY
// Animation duration (ms)
readonly property int animationFaster: Math.round(G.Theme.duration * 0.35)
readonly property int animationFast: Math.round(G.Theme.duration * 0.7)
readonly property int animationNormal: Math.round(G.Theme.duration * 1.3)
readonly property int animationSlow: Math.round(G.Theme.duration * 2)
readonly property int animationSlowest: Math.round(G.Theme.duration * 3.3)
// Delays
readonly property int tooltipDelay: 300
readonly property int tooltipDelayLong: 1200
readonly property int pillDelay: 500
// Widgets base size
readonly property real baseWidgetSize: 33
readonly property real sliderWidth: 200
readonly property real uiScaleRatio: 1.0
// Bar Height
readonly property real barHeight: glassBarHeight
readonly property real capsuleHeight: glassCapsuleHeight
readonly property real _barBaseFontSize: 12
readonly property real barFontSize: 12
readonly property color capsuleColor: "transparent"
readonly property color capsuleBorderColor: "transparent"
readonly property int capsuleBorderWidth: 0
readonly property color boxBorderColor: Color.mOutline
// Pixel-perfect utility for centering content without subpixel positioning
function pixelAlignCenter(containerSize, contentSize) {
return Math.round((containerSize - contentSize) / 2);
}
// Ensures a number is always odd (rounds down to nearest odd)
function toOdd(n) {
return Math.floor(n / 2) * 2 + 1;
}
// Ensures a number is always even (rounds down to nearest even)
function toEven(n) {
return Math.floor(n / 2) * 2;
}
// Get bar height for a specific density and orientation
function getBarHeightForDensity(density, isVertical) {
let h;
switch (density) {
case "mini":
h = isVertical ? 23 : 21;
break;
case "compact":
h = isVertical ? 27 : 25;
break;
case "comfortable":
h = isVertical ? 39 : 37;
break;
case "spacious":
h = isVertical ? 49 : 47;
break;
default:
case "default":
h = isVertical ? 33 : 31;
}
return toOdd(h);
}
// Get capsule height for a specific density and bar height
function getCapsuleHeightForDensity(density, barHeight) {
let h;
switch (density) {
case "mini":
h = Math.round(barHeight * 0.90);
break;
case "compact":
h = Math.round(barHeight * 0.85);
break;
case "comfortable":
h = Math.round(barHeight * 0.75);
break;
case "spacious":
h = Math.round(barHeight * 0.65);
break;
default:
h = Math.round(barHeight * 0.82);
break;
}
return toOdd(h);
}
// Get bar font size for a specific bar height, capsule height, and orientation
function getBarFontSizeForDensity(barHeight, capsuleHeight, isVertical) {
const baseFontSize = Math.max(1, (barHeight / capsuleHeight) * Style.fontSizeXXS);
return isVertical ? baseFontSize * 0.9 * Settings.data.bar.fontScale : baseFontSize * Settings.data.bar.fontScale;
}
// Convenience functions for per-screen bar sizing
function getBarHeightForScreen(screenName) {
return glassBarHeight;
}
function getCapsuleHeightForScreen(screenName) {
return glassCapsuleHeight;
}
function getBarFontSizeForScreen(screenName) {
return barFontSize;
}
}
@@ -0,0 +1,289 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
property real scoreThreshold: 0.2
// Manual overrides for tricky apps
property var substitutions: ({
"code-url-handler": "visual-studio-code",
"Code": "visual-studio-code",
"gnome-tweaks": "org.gnome.tweaks",
"pavucontrol-qt": "pavucontrol",
"wps": "wps-office2019-kprometheus",
"wpsoffice": "wps-office2019-kprometheus",
"footclient": "foot"
})
// Dynamic fixups
property var regexSubstitutions: [
{
"regex": /^steam_app_(\d+)$/,
"replace": "steam_icon_$1"
},
{
"regex": /Minecraft.*/,
"replace": "minecraft-launcher"
},
{
"regex": /.*polkit.*/,
"replace": "system-lock-screen"
},
{
"regex": /gcr.prompter/,
"replace": "system-lock-screen"
}
]
property list<DesktopEntry> entryList: []
property var preppedNames: []
property var preppedIcons: []
property var preppedIds: []
Component.onCompleted: refreshEntries()
Connections {
target: DesktopEntries.applications
function onValuesChanged() {
refreshEntries();
}
}
function refreshEntries() {
if (typeof DesktopEntries === 'undefined')
return;
const values = Array.from(DesktopEntries.applications.values);
if (values) {
entryList = values.sort((a, b) => a.name.localeCompare(b.name));
updatePreppedData();
}
}
function updatePreppedData() {
if (typeof FuzzySort === 'undefined')
return;
const list = Array.from(entryList);
preppedNames = list.map(a => ({
name: FuzzySort.prepare(`${a.name} `),
entry: a
}));
preppedIcons = list.map(a => ({
name: FuzzySort.prepare(`${a.icon} `),
entry: a
}));
preppedIds = list.map(a => ({
name: FuzzySort.prepare(`${a.id} `),
entry: a
}));
}
function iconForAppId(appId, fallbackName) {
const fallback = fallbackName || "application-x-executable";
if (!appId)
return iconFromName(fallback, fallback);
const entry = findAppEntry(appId);
if (entry) {
return iconFromName(entry.icon, fallback);
}
return iconFromName(appId, fallback);
}
// Robust lookup strategy
function findAppEntry(str) {
if (!str || str.length === 0)
return null;
let result = null;
if (result = checkHeuristic(str))
return result;
if (result = checkSubstitutions(str))
return result;
if (result = checkRegex(str))
return result;
if (result = checkSimpleTransforms(str))
return result;
if (result = checkFuzzySearch(str))
return result;
if (result = checkCleanMatch(str))
return result;
return null;
}
function iconFromName(iconName, fallbackName) {
const fallback = fallbackName || "application-x-executable";
try {
if (iconName && typeof Quickshell !== 'undefined' && Quickshell.iconPath) {
const p = Quickshell.iconPath(iconName, fallback);
if (p && p !== "")
return p;
}
} catch (e) {}
try {
return Quickshell.iconPath ? (Quickshell.iconPath(fallback, true) || "") : "";
} catch (e2) {
return "";
}
}
function distroLogoPath() {
try {
return (typeof OSInfo !== 'undefined' && OSInfo.distroIconPath) ? OSInfo.distroIconPath : "";
} catch (e) {
return "";
}
}
// --- Lookup Helpers ---
function checkHeuristic(str) {
if (typeof DesktopEntries !== 'undefined' && DesktopEntries.heuristicLookup) {
const entry = DesktopEntries.heuristicLookup(str);
if (entry)
return entry;
}
return null;
}
function checkSubstitutions(str) {
let effectiveStr = substitutions[str];
if (!effectiveStr)
effectiveStr = substitutions[str.toLowerCase()];
if (effectiveStr && effectiveStr !== str) {
return findAppEntry(effectiveStr);
}
return null;
}
function checkRegex(str) {
for (let i = 0; i < regexSubstitutions.length; i++) {
const sub = regexSubstitutions[i];
const replaced = str.replace(sub.regex, sub.replace);
if (replaced !== str) {
return findAppEntry(replaced);
}
}
return null;
}
function checkSimpleTransforms(str) {
if (typeof DesktopEntries === 'undefined' || !DesktopEntries.byId)
return null;
const lower = str.toLowerCase();
const variants = [str, lower, getFromReverseDomain(str), getFromReverseDomain(str)?.toLowerCase(), normalizeWithHyphens(str), str.replace(/_/g, '-').toLowerCase(), str.replace(/-/g, '_').toLowerCase()];
for (let i = 0; i < variants.length; i++) {
const variant = variants[i];
if (variant) {
const entry = DesktopEntries.byId(variant);
if (entry)
return entry;
}
}
return null;
}
function checkFuzzySearch(str) {
if (typeof FuzzySort === 'undefined')
return null;
// Check filenames (IDs) first
if (preppedIds.length > 0) {
let results = fuzzyQuery(str, preppedIds);
if (results.length === 0) {
const underscored = str.replace(/-/g, '_').toLowerCase();
if (underscored !== str)
results = fuzzyQuery(underscored, preppedIds);
}
if (results.length > 0)
return results[0];
}
// Then icons
if (preppedIcons.length > 0) {
const results = fuzzyQuery(str, preppedIcons);
if (results.length > 0)
return results[0];
}
// Then names
if (preppedNames.length > 0) {
const results = fuzzyQuery(str, preppedNames);
if (results.length > 0)
return results[0];
}
return null;
}
function checkCleanMatch(str) {
if (!str || str.length <= 3)
return null;
if (typeof DesktopEntries === 'undefined' || !DesktopEntries.byId)
return null;
// Aggressive fallback: strip all separators
const cleanStr = str.toLowerCase().replace(/[\.\-_]/g, '');
const list = Array.from(entryList);
for (let i = 0; i < list.length; i++) {
const entry = list[i];
const cleanId = (entry.id || "").toLowerCase().replace(/[\.\-_]/g, '');
if (cleanId.includes(cleanStr) || cleanStr.includes(cleanId)) {
return entry;
}
}
return null;
}
function fuzzyQuery(search, preppedData) {
if (!search || !preppedData || preppedData.length === 0)
return [];
return FuzzySort.go(search, preppedData, {
all: true,
key: "name"
}).map(r => r.obj.entry);
}
function iconExists(iconName) {
if (!iconName || iconName.length === 0)
return false;
if (iconName.startsWith("/"))
return true;
const path = Quickshell.iconPath(iconName, true);
return path && path.length > 0 && !path.includes("image-missing");
}
function getFromReverseDomain(str) {
if (!str)
return "";
return str.split('.').slice(-1)[0];
}
function normalizeWithHyphens(str) {
if (!str)
return "";
return str.toLowerCase().replace(/\s+/g, "-");
}
// Deprecated shim
function guessIcon(str) {
const entry = findAppEntry(str);
return entry ? entry.icon : "image-missing";
}
}
+232
View File
@@ -0,0 +1,232 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.System
Singleton {
id: root
// Current date
property var now: new Date()
// Unix timestamp of the last update
property real _lastUpdateTs: Date.now()
// Signal emitted when a significant time jump is detected (e.g. system resume)
signal resumed
// Returns a Unix Timestamp (in seconds)
readonly property int timestamp: {
return Math.floor(root.now / 1000);
}
// Timer state (for countdown/stopwatch)
property bool timerRunning: false
property bool timerStopwatchMode: false
property int timerRemainingSeconds: 0
property int timerTotalSeconds: 0
property int timerElapsedSeconds: 0
property bool timerSoundPlaying: false
property int timerStartTimestamp: 0 // Unix timestamp when timer was started
property int timerPausedAt: 0 // Value when paused (for resuming)
Timer {
id: updateTimer
interval: 1000
repeat: true
running: true
triggeredOnStart: false
onTriggered: {
var newTime = new Date();
var currentTs = newTime.getTime();
// Detect time jump (e.g. system resume) - threshold: 5 seconds
if (currentTs - root._lastUpdateTs > 5000) {
Logger.i("Time", "Time jump detected (" + Math.round((currentTs - root._lastUpdateTs) / 1000) + "s) - likely system resume");
root.resumed();
}
root._lastUpdateTs = currentTs;
root.now = newTime;
// Update timer if running
if (root.timerRunning && root.timerStartTimestamp > 0) {
const elapsedSinceStart = root.timestamp - root.timerStartTimestamp;
if (root.timerStopwatchMode) {
root.timerElapsedSeconds = root.timerPausedAt + elapsedSinceStart;
} else {
root.timerRemainingSeconds = root.timerTotalSeconds - elapsedSinceStart;
if (root.timerRemainingSeconds <= 0) {
root.timerOnFinished();
}
}
}
// Adjust next interval to sync with the start of the next second
var msIntoSecond = newTime.getMilliseconds();
if (msIntoSecond > 100) {
// If we're more than 100ms into the second, adjust for next time
updateTimer.interval = 1000 - msIntoSecond + 10; // +10ms buffer
updateTimer.restart();
} else {
updateTimer.interval = 1000;
}
}
}
Component.onCompleted: {
// Start by syncing to the next second boundary
var now = new Date();
var msUntilNextSecond = 1000 - now.getMilliseconds();
updateTimer.interval = msUntilNextSecond + 10; // +10ms buffer
updateTimer.restart();
}
// Formats a Date object into a YYYYMMDD-HHMMSS string.
function getFormattedTimestamp(date) {
if (!date) {
date = new Date();
}
const year = date.getFullYear();
// getMonth() is zero-based, so we add 1
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}${month}${day}-${hours}${minutes}${seconds}`;
}
// Format an easy to read approximate duration ex: 4h 32m
// Used to display the time remaining on the Battery widget, computer uptime, etc..
function formatVagueHumanReadableDuration(totalSeconds) {
if (typeof totalSeconds !== 'number' || totalSeconds < 0) {
return '0s';
}
// Floor the input to handle decimal seconds
totalSeconds = Math.floor(totalSeconds);
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const parts = [];
if (days)
parts.push(`${days}d`);
if (hours)
parts.push(`${hours}h`);
if (minutes)
parts.push(`${minutes}m`);
// Only show seconds if no hours and no minutes
if (!hours && !minutes) {
parts.push(`${seconds}s`);
}
return parts.join(' ');
}
// Format a date into
function formatRelativeTime(date) {
if (!date)
return "";
const diff = Date.now() - date.getTime();
if (diff < 60000)
return I18n.tr("notifications.time.now");
if (diff < 120000)
return I18n.tr("notifications.time.diff-m");
if (diff < 3600000)
return I18n.tr("notifications.time.diff-mm", {
"diff": Math.floor(diff / 60000)
});
if (diff < 7200000)
return I18n.tr("notifications.time.diff-h");
if (diff < 86400000)
return I18n.tr("notifications.time.diff-hh", {
"diff": Math.floor(diff / 3600000)
});
if (diff < 172800000)
return I18n.tr("notifications.time.diff-d");
return I18n.tr("notifications.time.diff-dd", {
"diff": Math.floor(diff / 86400000)
});
}
// Timer functions
function timerStart() {
if (root.timerStopwatchMode) {
root.timerRunning = true;
root.timerStartTimestamp = root.timestamp;
root.timerPausedAt = root.timerElapsedSeconds;
} else {
if (root.timerRemainingSeconds <= 0) {
return;
}
root.timerRunning = true;
root.timerTotalSeconds = root.timerRemainingSeconds;
root.timerStartTimestamp = root.timestamp;
root.timerPausedAt = 0;
}
}
function timerPause() {
if (root.timerRunning) {
// Calculate and set remainingSeconds BEFORE changing timerRunning
// This ensures the UI sees the correct value when it reacts to timerRunning changing
if (root.timerStopwatchMode) {
root.timerPausedAt = root.timerElapsedSeconds;
} else {
// Calculate remaining seconds at the exact moment of pause
// Use current time directly to avoid stale timestamp issues
const currentTimestamp = Math.floor(Date.now() / 1000);
const elapsedSinceStart = currentTimestamp - root.timerStartTimestamp;
const currentRemaining = root.timerTotalSeconds - elapsedSinceStart;
root.timerPausedAt = Math.max(0, currentRemaining);
// CRITICAL: Update timerRemainingSeconds to the paused value BEFORE changing timerRunning
// This ensures UI sees correct value when it reacts to timerRunning change
root.timerRemainingSeconds = root.timerPausedAt;
}
}
root.timerRunning = false;
root.timerStartTimestamp = 0;
// Stop any repeating notification sound when pausing
SoundService.stopSound("alarm-beep.wav");
root.timerSoundPlaying = false;
}
function timerReset() {
root.timerRunning = false;
root.timerStartTimestamp = 0;
if (root.timerStopwatchMode) {
root.timerElapsedSeconds = 0;
root.timerPausedAt = 0;
} else {
root.timerRemainingSeconds = 0;
root.timerTotalSeconds = 0;
root.timerPausedAt = 0;
}
// Stop any repeating notification sound
SoundService.stopSound("alarm-beep.wav");
root.timerSoundPlaying = false;
}
function timerOnFinished() {
root.timerRunning = false;
root.timerRemainingSeconds = 0;
// Play notification sound with repeat at lower volume
root.timerSoundPlaying = true;
SoundService.playSound("alarm-beep.wav", {
repeat: true,
volume: 0.3
});
}
}
@@ -0,0 +1,161 @@
// AdvancedMath.js - Lightweight math library for Noctalia Calculator
// Provides advanced mathematical functions beyond basic arithmetic
// Helper function to convert degrees to radians
function toRadians(degrees) {
return degrees * (Math.PI / 180);
}
// Helper function to convert radians to degrees
function toDegrees(radians) {
return radians * (180 / Math.PI);
}
// Constants
var constants = {
PI: Math.PI,
E: Math.E,
LN2: Math.LN2,
LN10: Math.LN10,
LOG2E: Math.LOG2E,
LOG10E: Math.LOG10E,
SQRT1_2: Math.SQRT1_2,
SQRT2: Math.SQRT2
};
// Safe evaluation function that handles advanced math
function evaluate(expression) {
try {
// Fixes decimal arithmetic
var cleanExpr = expression.replace(/\s+/g, '').toLowerCase();
// Allows numbers (including decimals), basic operators, and explicitly permitted math terms only
var safeRegex = /^(\d*\.?\d+|[+\-*/()^%,]|sin|cos|tan|asin|acos|atan|atan2|sinh|cosh|tanh|asinh|acosh|atanh|log|ln|exp|pow|sqrt|cbrt|abs|floor|ceil|round|trunc|min|max|random|pi|e|sind|cosd|tand)+$/;
if (!safeRegex.test(cleanExpr)) {
throw new Error("Invalid characters or unauthorized functions in expression");
}
// Replace mathematical constants (Original Structure)
var processed = cleanExpr
.replace(/\bpi\b/gi, Math.PI)
.replace(/\be\b/gi, Math.E);
// Replace function calls with Math object equivalents
processed = processed
// Trigonometric functions
.replace(/\bsin\s*\(/g, 'Math.sin(')
.replace(/\bcos\s*\(/g, 'Math.cos(')
.replace(/\btan\s*\(/g, 'Math.tan(')
.replace(/\basin\s*\(/g, 'Math.asin(')
.replace(/\bacos\s*\(/g, 'Math.acos(')
.replace(/\batan\s*\(/g, 'Math.atan(')
.replace(/\batan2\s*\(/g, 'Math.atan2(')
// Hyperbolic functions
.replace(/\bsinh\s*\(/g, 'Math.sinh(')
.replace(/\bcosh\s*\(/g, 'Math.cosh(')
.replace(/\btanh\s*\(/g, 'Math.tanh(')
.replace(/\basinh\s*\(/g, 'Math.asinh(')
.replace(/\bacosh\s*\(/g, 'Math.acosh(')
.replace(/\batanh\s*\(/g, 'Math.atanh(')
// Logarithmic and exponential functions
.replace(/\blog\s*\(/g, 'Math.log10(')
.replace(/\bln\s*\(/g, 'Math.log(')
.replace(/\bexp\s*\(/g, 'Math.exp(')
.replace(/\bpow\s*\(/g, 'Math.pow(')
// Root functions
.replace(/\bsqrt\s*\(/g, 'Math.sqrt(')
.replace(/\bcbrt\s*\(/g, 'Math.cbrt(')
// Rounding and absolute
.replace(/\babs\s*\(/g, 'Math.abs(')
.replace(/\bfloor\s*\(/g, 'Math.floor(')
.replace(/\bceil\s*\(/g, 'Math.ceil(')
.replace(/\bround\s*\(/g, 'Math.round(')
.replace(/\btrunc\s*\(/g, 'Math.trunc(')
// Min/Max
.replace(/\bmin\s*\(/g, 'Math.min(')
.replace(/\bmax\s*\(/g, 'Math.max(')
// Random
.replace(/\brandom\s*\(\s*\)/g, 'Math.random()');
// Handle degree versions of trig functions
processed = processed
.replace(/\bsind\s*\(/g, '(function(x) { return Math.sin(' + (Math.PI / 180) + ' * x); })(')
.replace(/\bcosd\s*\(/g, '(function(x) { return Math.cos(' + (Math.PI / 180) + ' * x); })(')
.replace(/\btand\s*\(/g, '(function(x) { return Math.tan(' + (Math.PI / 180) + ' * x); })(');
// Handle ^ for exponentiation: convert 2^3 to Math.pow(2,3)
processed = processed.replace(/([\d.]+|\))\^([\d.]+|\([^)]*\))/g, 'Math.pow($1,$2)');
// Replacing eval() with a scoped function constructor
// This is safe because the strict whitelist guarantees only math reaches this point
var result = new Function('return ' + processed)();
if (!isFinite(result) || isNaN(result)) {
throw new Error("Invalid result");
}
return result;
} catch (error) {
throw new Error("Evaluation failed: " + error.message);
}
}
// Format result for display
function formatResult(result) {
if (Number.isInteger(result)) {
return result.toString();
}
// Handle very large or very small numbers
if (Math.abs(result) >= 1e15 || (Math.abs(result) < 1e-6 && result !== 0)) {
return result.toExponential(6);
}
// Normal decimal formatting
return parseFloat(result.toFixed(10)).toString();
}
// Get list of available functions for help
function getAvailableFunctions() {
return [
// Basic arithmetic: +, -, *, /, %, ^, ()
// Trigonometric functions
"sin(x), cos(x), tan(x) - trigonometric functions (radians)",
"sind(x), cosd(x), tand(x) - trigonometric functions (degrees)",
"asin(x), acos(x), atan(x) - inverse trigonometric",
"atan2(y, x) - two-argument arctangent",
// Hyperbolic functions
"sinh(x), cosh(x), tanh(x) - hyperbolic functions",
"asinh(x), acosh(x), atanh(x) - inverse hyperbolic",
// Logarithmic and exponential
"log(x) - base 10 logarithm",
"ln(x) - natural logarithm",
"exp(x) - e^x",
"pow(x, y) - x^y",
// Root functions
"sqrt(x) - square root",
"cbrt(x) - cube root",
// Rounding and absolute
"abs(x) - absolute value",
"floor(x), ceil(x), round(x), trunc(x)",
// Min/Max/Random
"min(a, b, ...), max(a, b, ...)",
"random() - random number 0-1",
// Constants
"pi, e - mathematical constants"
];
}
@@ -0,0 +1,127 @@
.pragma library
// Address helpers
var macFromDevice = (dev) => {
if (!dev) return "";
if (dev.address && dev.address.length > 0) return dev.address;
if (dev.nativePath && dev.nativePath.indexOf("/dev_") !== -1)
return dev.nativePath.split("dev_")[1].split("_").join(":");
return "";
};
var deviceKey = (dev) => {
if (!dev) return "";
if (dev.address && dev.address.length > 0) return dev.address.toUpperCase();
if (dev.nativePath && dev.nativePath.length > 0) return dev.nativePath;
if (dev.devicePath && dev.devicePath.length > 0) return dev.devicePath;
return (dev.name || dev.deviceName || "") + "|" + (dev.icon || "");
};
var dedupeDevices = (list) => {
if (!list || list.length === 0) return [];
var seen = ({});
var out = [];
for (var i = 0; i < list.length; ++i) {
var d = list[i];
if (!d) continue;
var k = deviceKey(d);
if (k && !seen[k]) { seen[k] = true; out.push(d); }
}
return out;
};
// RSSI parsing
var parseRssiOutput = (text) => {
try {
text = text || "";
var mParen = text.match(/\(\s*(-?\d+)\s*(?:d?b?m?)?\s*\)/i);
if (mParen && mParen.length > 1) return Number(mParen[1]);
var mDec = text.match(/RSSI:\s*(-?\d+)/i);
if (mDec && mDec.length > 1) return Number(mDec[1]);
var mHex = text.match(/RSSI:\s*0x([0-9a-fA-F]+)/i);
if (mHex && mHex.length > 1) {
var v = parseInt(mHex[1], 16);
if (v >= 0x80000000) v = v - 0x100000000; // 32-bit two's complement
else if (v >= 0x8000) v = v - 0x10000; // 16-bit
else if (v >= 0x80) v = v - 0x100; // 8-bit
return v;
}
} catch (e) {}
return null;
};
var dbmToPercent = (dbm) => {
if (dbm === null || dbm === undefined || isNaN(dbm)) return null;
// Clamp simple linear map roughly from -100..0 dBm to 0..100%
var pct = Math.round((Number(dbm) + 100) * 2);
if (isNaN(pct)) return null;
return Math.max(0, Math.min(100, pct));
};
// Signal helpers
var signalPercent = (device, cache, _version) => {
if (!device) return null;
try {
var addr = macFromDevice(device);
if (addr && cache && cache[addr] !== undefined) {
var cached = Number(cache[addr]) | 0;
return Math.max(0, Math.min(100, cached));
}
} catch (e) {}
var s = device && device.signalStrength;
if (s === undefined || s <= 0) return null;
var p = Number(s) | 0;
return Math.max(0, Math.min(100, p));
};
var signalIcon = (p) => {
if (p === null) return "antenna-bars-off";
if (p >= 80) return "antenna-bars-5";
if (p >= 60) return "antenna-bars-4";
if (p >= 40) return "antenna-bars-3";
if (p >= 20) return "antenna-bars-2";
return "antenna-bars-1";
};
// Icon mapping
var deviceIcon = (name, icon) => {
var s1 = String(name || "").toLowerCase();
var s2 = String(icon || "").toLowerCase();
// Prefer icon-based hints for display devices first to avoid "audio" catching TVs
var displayHints = ["display", "tv", "monitor", "projector", "screen", "chromecast", "cast"];
for (var dh = 0; dh < displayHints.length; dh++) {
if (s2.indexOf(displayHints[dh]) !== -1) return "bt-device-tv";
}
var tests = [
[["controller", "gamepad"], "bt-device-gamepad"],
[["microphone"], "bt-device-microphone"],
[["pod", "bud", "minor"], "bt-device-earbuds"],
[["headset", "arctis", "major"], "bt-device-headset"],
[["headphone"], "bt-device-headphones"],
[["mouse"], "bt-device-mouse"],
[["keyboard"], "bt-device-keyboard"],
[["watch"], "bt-device-watch"],
[["display", "tv", "monitor", "projector", "screen", "chromecast", "cast"], "bt-device-tv"],
[["speaker", "audio", "sound"], "bt-device-speaker"],
[["phone", "iphone", "android", "samsung"], "bt-device-phone"]
];
for (var i = 0; i < tests.length; i++) {
var keys = tests[i][0];
var out = tests[i][1];
for (var j = 0; j < keys.length; j++) {
var k = keys[j];
if (s1.indexOf(k) !== -1 || s2.indexOf(k) !== -1) return out;
}
}
return "bt-device-generic";
};
// Battery percent helper
var batteryPercent = (device) => {
if (!device || !device.batteryAvailable || device.battery === undefined) return null;
var val = Math.round(Number(device.battery) * 100);
if (isNaN(val)) return null;
return Math.max(0, Math.min(100, val));
};
@@ -0,0 +1,187 @@
var colors = [
// --- REDS ---
{ name: "MistyRose", color: "mistyrose" },
{ name: "LightPink", color: "lightpink" },
{ name: "Pink", color: "pink" },
{ name: "PaleVioletRed", color: "palevioletred" },
{ name: "Pink 500", color: "#E91E63" }, // Material
{ name: "HotPink", color: "hotpink" },
{ name: "DeepPink", color: "deeppink" },
{ name: "MediumVioletRed", color: "mediumvioletred" },
{ name: "LightSalmon", color: "lightsalmon" },
{ name: "Salmon", color: "salmon" },
{ name: "DarkSalmon", color: "darksalmon" },
{ name: "LightCoral", color: "lightcoral" },
{ name: "IndianRed", color: "indianred" },
{ name: "Alizarin", color: "#E74C3C" }, // Flat UI
{ name: "Red 500", color: "#F44336" }, // Material
{ name: "Crimson", color: "crimson" },
{ name: "Red", color: "red" },
{ name: "FireBrick", color: "firebrick" },
{ name: "DarkRed", color: "darkred" },
{ name: "Maroon", color: "maroon" },
{ name: "Brown", color: "brown" },
// --- ORANGES & BROWNS ---
{ name: "Coral", color: "coral" },
{ name: "Tomato", color: "tomato" },
{ name: "OrangeRed", color: "orangered" },
{ name: "Deep Orange 500", color: "#FF5722" }, // Material
{ name: "DarkOrange", color: "darkorange" },
{ name: "Carrot", color: "#E67E22" }, // Flat UI
{ name: "Orange 500", color: "#FF9800" }, // Material
{ name: "Orange", color: "orange" },
{ name: "SandyBrown", color: "sandybrown" },
{ name: "Peru", color: "peru" },
{ name: "Chocolate", color: "chocolate" },
{ name: "SaddleBrown", color: "saddlebrown" },
{ name: "Sienna", color: "sienna" },
{ name: "Brown 500", color: "#795548" }, // Material
// --- YELLOWS, BEIGES & GOLDS ---
{ name: "LightYellow", color: "lightyellow" },
{ name: "LemonChiffon", color: "lemonchiffon" },
{ name: "LightGoldenrodYellow", color: "lightgoldenrodyellow" },
{ name: "PapayaWhip", color: "papayawhip" },
{ name: "Moccasin", color: "moccasin" },
{ name: "PeachPuff", color: "peachpuff" },
{ name: "NavajoWhite", color: "navajowhite" },
{ name: "Wheat", color: "wheat" },
{ name: "BurlyWood", color: "burlywood" },
{ name: "Tan", color: "tan" },
{ name: "Bisque", color: "bisque" },
{ name: "BlanchedAlmond", color: "blanchedalmond" },
{ name: "Cornsilk", color: "cornsilk" },
{ name: "PaleGoldenrod", color: "palegoldenrod" },
{ name: "Khaki", color: "khaki" },
{ name: "DarkKhaki", color: "darkkhaki" },
{ name: "Goldenrod", color: "goldenrod" },
{ name: "DarkGoldenrod", color: "darkgoldenrod" },
{ name: "Sun Flower", color: "#F1C40F" }, // Flat UI
{ name: "Yellow 500", color: "#FFEB3B" }, // Material
{ name: "Yellow", color: "yellow" },
{ name: "Gold", color: "gold" },
{ name: "Amber 500", color: "#FFC107" }, // Material
// --- GREENS ---
{ name: "GreenYellow", color: "greenyellow" },
{ name: "Chartreuse", color: "chartreuse" },
{ name: "LawnGreen", color: "lawngreen" },
{ name: "Lime 500", color: "#CDDC39" }, // Material
{ name: "Lime", color: "lime" },
{ name: "LimeGreen", color: "limegreen" },
{ name: "PaleGreen", color: "palegreen" },
{ name: "LightGreen", color: "lightgreen" },
{ name: "Light Green 500", color: "#8BC34A" }, // Material
{ name: "MediumSpringGreen", color: "mediumspringgreen" },
{ name: "SpringGreen", color: "springgreen" },
{ name: "Emerald", color: "#2ECC71" }, // Flat UI
{ name: "Green 500", color: "#4CAF50" }, // Material
{ name: "MediumSeaGreen", color: "mediumseagreen" },
{ name: "SeaGreen", color: "seagreen" },
{ name: "ForestGreen", color: "forestgreen" },
{ name: "Green", color: "green" },
{ name: "DarkGreen", color: "darkgreen" },
{ name: "YellowGreen", color: "yellowgreen" },
{ name: "OliveDrab", color: "olivedrab" },
{ name: "Olive", color: "olive" },
{ name: "DarkOliveGreen", color: "darkolivegreen" },
// --- TEALS & CYANS ---
{ name: "MediumAquamarine", color: "mediumaquamarine" },
{ name: "DarkSeaGreen", color: "darkseagreen" },
{ name: "LightSeaGreen", color: "lightseagreen" },
{ name: "DarkCyan", color: "darkcyan" },
{ name: "Teal", color: "teal" },
{ name: "Turquoise", color: "#1ABC9C" }, // Flat UI
{ name: "LightCyan", color: "lightcyan" },
{ name: "PaleTurquoise", color: "paleturquoise" },
{ name: "Aquamarine", color: "aquamarine" },
{ name: "Turquoise", color: "turquoise" },
{ name: "MediumTurquoise", color: "mediumturquoise" },
{ name: "DarkTurquoise", color: "darkturquoise" },
{ name: "Aqua", color: "aqua" },
{ name: "Cyan", color: "cyan" },
{ name: "Cyan 500", color: "#00BCD4" }, // Material
{ name: "CadetBlue", color: "cadetblue" },
{ name: "Teal 500", color: "#009688" }, // Material
{ name: "DarkSlateGray", color: "darkslategray" },
// --- BLUES ---
{ name: "PowderBlue", color: "powderblue" },
{ name: "LightBlue", color: "lightblue" },
{ name: "SkyBlue", color: "skyblue" },
{ name: "LightSkyBlue", color: "lightskyblue" },
{ name: "Light Blue 500", color: "#03A9F4" }, // Material
{ name: "DeepSkyBlue", color: "deepskyblue" },
{ name: "DodgerBlue", color: "dodgerblue" },
{ name: "CornflowerBlue", color: "cornflowerblue" },
{ name: "Peter River", color: "#3498DB" }, // Flat UI
{ name: "Blue 500", color: "#2196F3" }, // Material
{ name: "SteelBlue", color: "steelblue" },
{ name: "LightSteelBlue", color: "lightsteelblue" },
{ name: "RoyalBlue", color: "royalblue" },
{ name: "Blue", color: "blue" },
{ name: "MediumBlue", color: "mediumblue" },
{ name: "Belize Hole", color: "#2980B9" }, // Flat UI
{ name: "DarkBlue", color: "darkblue" },
{ name: "Navy", color: "navy" },
{ name: "MidnightBlue", color: "midnightblue" },
{ name: "Midnight Blue", color: "#2C3E50" }, // Flat UI (Same name, different color)
{ name: "Indigo 500", color: "#3F51B5" }, // Material
{ name: "DarkSlateBlue", color: "darkslateblue" },
{ name: "MediumSlateBlue", color: "mediumslateblue" },
{ name: "SlateBlue", color: "slateblue" },
// --- PURPLES & MAGENTAS ---
{ name: "Lavender", color: "lavender" },
{ name: "Thistle", color: "thistle" },
{ name: "Plum", color: "plum" },
{ name: "Violet", color: "violet" },
{ name: "Orchid", color: "orchid" },
{ name: "Fuchsia", color: "fuchsia" },
{ name: "Magenta", color: "magenta" },
{ name: "MediumOrchid", color: "mediumorchid" },
{ name: "MediumPurple", color: "mediumpurple" },
{ name: "Amethyst", color: "#9B59B6" }, // Flat UI
{ name: "Purple 500", color: "#9C27B0" }, // Material
{ name: "BlueViolet", color: "blueviolet" },
{ name: "DarkViolet", color: "darkviolet" },
{ name: "DarkOrchid", color: "darkorchid" },
{ name: "DarkMagenta", color: "darkmagenta" },
{ name: "Purple", color: "purple" },
{ name: "Deep Purple 500", color: "#673AB7" }, // Material
{ name: "Indigo", color: "indigo" },
// --- NEUTRALS ---
{ name: "White", color: "white" },
{ name: "Snow", color: "snow" },
{ name: "HoneyDew", color: "honeydew" },
{ name: "MintCream", color: "mintcream" },
{ name: "Azure", color: "azure" },
{ name: "AliceBlue", color: "aliceblue" },
{ name: "GhostWhite", color: "ghostwhite" },
{ name: "WhiteSmoke", color: "whitesmoke" },
{ name: "Seashell", color: "seashell" },
{ name: "Beige", color: "beige" },
{ name: "OldLace", color: "oldlace" },
{ name: "FloralWhite", color: "floralwhite" },
{ name: "Ivory", color: "ivory" },
{ name: "AntiqueWhite", color: "antiquewhite" },
{ name: "Linen", color: "linen" },
{ name: "LavenderBlush", color: "lavenderblush" },
{ name: "Gainsboro", color: "gainsboro" },
{ name: "LightGray", color: "lightgray" },
{ name: "Silver", color: "silver" },
{ name: "DarkGray", color: "darkgray" },
{ name: "Gray", color: "gray" },
{ name: "Grey 500", color: "#9E9E9E" }, // Material
{ name: "Concrete", color: "#95A5A6" }, // Flat UI
{ name: "DimGray", color: "dimgray" },
{ name: "LightSlateGray", color: "lightslategray" },
{ name: "SlateGray", color: "slategray" },
{ name: "Asbestos", color: "#7F8C8D" }, // Flat UI
{ name: "Blue Grey 500", color: "#607D8B" }, // Material
{ name: "Wet Asphalt", color: "#34495E" }, // Flat UI
{ name: "Black", color: "black" }
]
@@ -0,0 +1,270 @@
// Convert hex color to HSL
function hexToHSL(hex) {
const rgb = hexToRgb(hex);
if (!rgb) return null;
return rgbToHsl(rgb.r, rgb.g, rgb.b);
}
// Convert HSL to hex color
function hslToHex(h, s, l) {
const rgb = hslToRgb(h, s, l);
return rgbToHex(rgb.r, rgb.g, rgb.b);
}
// Convert hex color to RGB
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : { r: 0, g: 0, b: 0 };
}
// Convert RGB to hex color
function rgbToHex(r, g, b) {
return "#" + [r, g, b].map(x => {
const hex = Math.round(Math.max(0, Math.min(255, x))).toString(16);
return hex.length === 1 ? "0" + hex : hex;
}).join("");
}
// Convert RGB to HSL
function rgbToHsl(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return { h: h * 360, s: s * 100, l: l * 100 };
}
// Convert HSL to RGB
function hslToRgb(h, s, l) {
h /= 360;
s /= 100;
l /= 100;
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
// Convert RGB to HSV
function rgbToHsv(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0;
} else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s * 100, v: v * 100 };
}
// Convert HSV to RGB
function hsvToRgb(h, s, v) {
h /= 360;
s /= 100;
v /= 100;
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
// Calculate relative luminance (WCAG standard)
function getLuminance(hex) {
const rgb = hexToRgb(hex);
const [r, g, b] = [rgb.r, rgb.g, rgb.b].map(val => {
val /= 255;
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Calculate contrast ratio between two colors
function getContrastRatio(hex1, hex2) {
const lum1 = getLuminance(hex1);
const lum2 = getLuminance(hex2);
const brightest = Math.max(lum1, lum2);
const darkest = Math.min(lum1, lum2);
return (brightest + 0.05) / (darkest + 0.05);
}
// Check if a color is considered "light"
function isLightColor(hex) {
return getLuminance(hex) > 0.5;
}
// Adjust color lightness
function adjustLightness(hex, amount) {
const hsl = hexToHSL(hex);
hsl.l = Math.max(0, Math.min(100, hsl.l + amount));
return hslToHex(hsl.h, hsl.s, hsl.l);
}
// Adjust color saturation
function adjustSaturation(hex, amount) {
const hsl = hexToHSL(hex);
hsl.s = Math.max(0, Math.min(100, hsl.s + amount));
return hslToHex(hsl.h, hsl.s, hsl.l);
}
// Adjust both lightness and saturation
function adjustLightnessAndSaturation(hex, lightnessAmount, saturationAmount) {
const hsl = hexToHSL(hex);
hsl.l = Math.max(0, Math.min(100, hsl.l + lightnessAmount));
hsl.s = Math.max(0, Math.min(100, hsl.s + saturationAmount));
return hslToHex(hsl.h, hsl.s, hsl.l);
}
// Generate "on" color with proper contrast (for text/icons)
function generateOnColor(baseColor, isDarkMode) {
const isBaseLight = isLightColor(baseColor);
// If base is light, we need dark text; if base is dark, we need light text
if (isBaseLight) {
// Try darker variants
let testColor = "#000000";
if (getContrastRatio(baseColor, testColor) >= 4.5) {
return testColor;
}
// Fallback to dark gray
return "#1c1b1f";
} else {
// Try lighter variants
let testColor = "#ffffff";
if (getContrastRatio(baseColor, testColor) >= 4.5) {
return testColor;
}
// Fallback to light gray
return "#e6e1e5";
}
}
// Generate container color (lighter in light mode, darker in dark mode)
function generateContainerColor(baseColor, isDarkMode) {
const rgb = hexToRgb(baseColor);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
if (isDarkMode) {
// In dark mode, containers are darker and more saturated
hsl.l = Math.max(10, Math.min(30, hsl.l - 20));
hsl.s = Math.min(100, hsl.s + 10);
} else {
// In light mode, containers are lighter and less saturated
hsl.l = Math.min(90, Math.max(75, hsl.l + 30));
hsl.s = Math.max(0, hsl.s - 10);
}
const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l);
return rgbToHex(newRgb.r, newRgb.g, newRgb.b);
}
// Generate surface variant colors
function generateSurfaceVariant(backgroundColor, step, isDarkMode) {
const rgb = hexToRgb(backgroundColor);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
if (isDarkMode) {
// In dark mode, variants get progressively lighter
hsl.l = Math.min(100, hsl.l + (step * 3));
} else {
// In light mode, variants get progressively darker
hsl.l = Math.max(0, hsl.l - (step * 2));
}
const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l);
return rgbToHex(newRgb.r, newRgb.g, newRgb.b);
}
@@ -0,0 +1,25 @@
// Helper function to stringify even if there are circular refs.
function stringify(obj, replacer, spaces, cycleReplacer) {
return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
}
function serializer(replacer, cycleReplacer) {
var stack = [], keys = []
if (cycleReplacer == null) cycleReplacer = function(key, value) {
if (stack[0] === value) return "[Circular ~]"
return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
}
return function(key, value) {
if (stack.length > 0) {
var thisPos = stack.indexOf(this)
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
}
else stack.push(value)
return replacer == null ? value : replacer.call(this, key, value)
}
}
@@ -0,0 +1,114 @@
// -----------------------------------------------------
// Helper function to convert Qt objects to plain JavaScript objects
// Only used when generating settings-default.json
function qtObjectToPlainObject(obj) {
if (obj === null || obj === undefined) {
return obj;
}
// Handle primitive types
if (typeof obj !== "object") {
return obj;
}
// Handle native JavaScript arrays
if (Array.isArray(obj)) {
return obj.map((item) => qtObjectToPlainObject(item));
}
// Detect QML arrays FIRST (before color detection)
// QML arrays have a numeric length property and indexed properties
if (typeof obj.length === "number" && obj.length >= 0) {
// Check if it has indexed properties - be more flexible about detection
var hasIndexedProps = true;
var hasNumericKeys = false;
// Check if we have at least some numeric properties
for (var i = 0; i < obj.length; i++) {
if (obj.hasOwnProperty(i) || obj[i] !== undefined) {
hasNumericKeys = true;
break;
}
}
// If we have length > 0 and some numeric keys, treat as array
if (obj.length > 0 && hasNumericKeys) {
var arr = [];
for (var i = 0; i < obj.length; i++) {
// Use direct property access, handle undefined gracefully
var item = obj[i];
if (item !== undefined) {
arr.push(qtObjectToPlainObject(item));
}
}
return arr; // Return here to avoid processing as object
}
// Handle empty arrays (length = 0)
if (obj.length === 0) {
return [];
}
}
// Detect and convert QML color objects to hex strings
if (
typeof obj.r === "number" &&
typeof obj.g === "number" &&
typeof obj.b === "number" &&
typeof obj.a === "number" &&
typeof obj.valid === "boolean"
) {
// This looks like a QML color object
try {
// Try to get the string representation (should be hex like "#000000")
if (typeof obj.toString === "function") {
return obj.toString();
} else {
// Fallback: convert RGBA to hex manually
var r = Math.round(obj.r * 255);
var g = Math.round(obj.g * 255);
var b = Math.round(obj.b * 255);
var hex =
"#" +
r.toString(16).padStart(2, "0") +
g.toString(16).padStart(2, "0") +
b.toString(16).padStart(2, "0");
return hex;
}
} catch (e) {
// If conversion fails, fall through to regular object handling
}
}
// Handle regular objects
var plainObj = {};
// Get all property names, but filter out Qt-specific ones
var propertyNames = Object.getOwnPropertyNames(obj);
for (var i = 0; i < propertyNames.length; i++) {
var propName = propertyNames[i];
// Skip Qt-specific properties, functions, and array-like properties
if (
propName === "objectName" ||
propName === "objectNameChanged" ||
propName === "length" || // Skip length property
/^\d+$/.test(propName) || // Skip numeric keys (0, 1, 2, etc.)
propName.endsWith("Changed") ||
typeof obj[propName] === "function"
) {
continue;
}
try {
var value = obj[propName];
plainObj[propName] = qtObjectToPlainObject(value);
} catch (e) {
// Skip properties that can't be accessed
continue;
}
}
return plainObj;
}
@@ -0,0 +1,192 @@
function sha256(message) {
// SHA-256 constants
const K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// Initial hash values
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
// Convert string to UTF-8 bytes manually
const msgBytes = stringToUtf8Bytes(message);
const msgLength = msgBytes.length;
const bitLength = msgLength * 8;
// Calculate padding
// Message + 1 bit (0x80) + padding zeros + 8 bytes for length = multiple of 64 bytes
const totalBitsNeeded = bitLength + 1 + 64; // message bits + padding bit + 64-bit length
const totalBytesNeeded = Math.ceil(totalBitsNeeded / 8);
const paddedLength = Math.ceil(totalBytesNeeded / 64) * 64; // Round up to multiple of 64
const paddedMsg = new Array(paddedLength).fill(0);
// Copy original message
for (let i = 0; i < msgLength; i++) {
paddedMsg[i] = msgBytes[i];
}
// Add padding bit (0x80 = 10000000 in binary)
paddedMsg[msgLength] = 0x80;
// Add length as 64-bit big-endian integer at the end
// JavaScript numbers are not precise enough for 64-bit integers, so we handle high/low separately
const highBits = Math.floor(bitLength / 0x100000000);
const lowBits = bitLength % 0x100000000;
// Write 64-bit length in big-endian format
paddedMsg[paddedLength - 8] = (highBits >>> 24) & 0xFF;
paddedMsg[paddedLength - 7] = (highBits >>> 16) & 0xFF;
paddedMsg[paddedLength - 6] = (highBits >>> 8) & 0xFF;
paddedMsg[paddedLength - 5] = highBits & 0xFF;
paddedMsg[paddedLength - 4] = (lowBits >>> 24) & 0xFF;
paddedMsg[paddedLength - 3] = (lowBits >>> 16) & 0xFF;
paddedMsg[paddedLength - 2] = (lowBits >>> 8) & 0xFF;
paddedMsg[paddedLength - 1] = lowBits & 0xFF;
// Process message in 512-bit (64-byte) chunks
for (let chunk = 0; chunk < paddedLength; chunk += 64) {
const w = new Array(64);
// Break chunk into sixteen 32-bit big-endian words
for (let i = 0; i < 16; i++) {
const offset = chunk + i * 4;
w[i] = (paddedMsg[offset] << 24) |
(paddedMsg[offset + 1] << 16) |
(paddedMsg[offset + 2] << 8) |
paddedMsg[offset + 3];
// Ensure unsigned 32-bit
w[i] = w[i] >>> 0;
}
// Extend the sixteen 32-bit words into sixty-four 32-bit words
for (let i = 16; i < 64; i++) {
const s0 = rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >>> 3);
const s1 = rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
}
// Initialize working variables for this chunk
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
// Main loop
for (let i = 0; i < 64; i++) {
const S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25);
const ch = (e & f) ^ (~e & g);
const temp1 = (h + S1 + ch + K[i] + w[i]) >>> 0;
const S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (S0 + maj) >>> 0;
h = g;
g = f;
f = e;
e = (d + temp1) >>> 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) >>> 0;
}
// Add this chunk's hash to result so far
h0 = (h0 + a) >>> 0;
h1 = (h1 + b) >>> 0;
h2 = (h2 + c) >>> 0;
h3 = (h3 + d) >>> 0;
h4 = (h4 + e) >>> 0;
h5 = (h5 + f) >>> 0;
h6 = (h6 + g) >>> 0;
h7 = (h7 + h) >>> 0;
}
// Produce the final hash value as a hex string
return [h0, h1, h2, h3, h4, h5, h6, h7]
.map(h => h.toString(16).padStart(8, '0'))
.join('');
}
function stringToUtf8Bytes(str) {
const bytes = [];
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i);
if (code < 0x80) {
// 1-byte character (ASCII)
bytes.push(code);
} else if (code < 0x800) {
// 2-byte character
bytes.push(0xC0 | (code >> 6));
bytes.push(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
// 3-byte character (not surrogate)
bytes.push(0xE0 | (code >> 12));
bytes.push(0x80 | ((code >> 6) & 0x3F));
bytes.push(0x80 | (code & 0x3F));
} else {
// 4-byte character (surrogate pair)
i++; // Move to next character
const code2 = str.charCodeAt(i);
const codePoint = 0x10000 + (((code & 0x3FF) << 10) | (code2 & 0x3FF));
bytes.push(0xF0 | (codePoint >> 18));
bytes.push(0x80 | ((codePoint >> 12) & 0x3F));
bytes.push(0x80 | ((codePoint >> 6) & 0x3F));
bytes.push(0x80 | (codePoint & 0x3F));
}
}
return bytes;
}
function rightRotate(value, amount) {
return ((value >>> amount) | (value << (32 - amount))) >>> 0;
}
// Test function to verify implementation
// function testSHA256() {
// const tests = [
// {
// input: "",
// expected:
// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
// },
// {
// input: "Hello World",
// expected:
// "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e",
// },
// {
// input: "abc",
// expected:
// "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
// },
// {
// input: "The quick brown fox jumps over the lazy dog",
// expected:
// "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",
// },
// ];
// console.log("Running SHA-256 tests:");
// tests.forEach((test, i) => {
// const result = Crypto.sha256(test.input);
// const passed = result === test.expected;
// console.log(`Test ${i + 1}: ${passed ? "PASS" : "FAIL"}`);
// if (!passed) {
// console.log(` Input: "${test.input}"`);
// console.log(` Expected: ${test.expected}`);
// console.log(` Got: ${result}`);
// }
// });
// }
@@ -0,0 +1,103 @@
import QtQuick
import Quickshell
import Quickshell.Wayland
import "../../../components" as C
import "../../../core" as Core
import "../../../services" as GS
// Hosts a Noctalia v4 plugin's Panel.qml as a glassMxrph bar drawer: it grows
// out of the bar under the button that opened it, sized from the panel's
// contentPreferredWidth/Height. Escape or an outside click closes it.
PanelWindow {
id: root
required property var api
property url source: ""
readonly property bool open: !!api && !!api.panelOpenScreen
// Lets test drivers find this panel.
Component.onCompleted: GS.PluginService.panelWindows[api.pluginId] = root
// Keep the last screen while the drawer animates closed.
property var lastScreen: null
onOpenChanged: {
if (open)
lastScreen = api.panelOpenScreen;
else
GS.PluginService.releasePopout(api);
}
screen: open ? api.panelOpenScreen : lastScreen
readonly property Item anchorItem: api && api.panelAnchor ? api.panelAnchor : null
readonly property var anchorWindow: anchorItem && anchorItem.QsWindow ? anchorItem.QsWindow.window : null
readonly property bool fromBar: !!anchorWindow && GS.TrayService.barWindows.includes(anchorWindow)
readonly property real screenW: screen ? screen.width : 1920
readonly property real screenH: screen ? screen.height : 1080
readonly property real anchorCenter: {
root.open;
if (!fromBar)
return screenW / 2;
const p = anchorItem.mapToItem(anchorWindow.contentItem, anchorItem.width / 2, 0);
return p.x;
}
readonly property Item panel: loader.item
readonly property var panelObject: loader.item
readonly property real preferredWidth: panelObject && panelObject.contentPreferredWidth > 0 ? panelObject.contentPreferredWidth : 400
readonly property real preferredHeight: panelObject && panelObject.contentPreferredHeight > 0 ? panelObject.contentPreferredHeight : 320
readonly property real drawerX: Core.BarDrawers.clampX(anchorCenter, drawer.width, screenW)
anchors {
top: true
left: true
}
// qmllint disable unqualified unresolved-type
margins.left: root.drawerX
// qmllint enable unqualified unresolved-type
implicitWidth: Math.max(1, Math.round(drawer.width))
implicitHeight: Math.max(1, Math.round(Core.BarDrawers.bottom + drawer.contentHeight))
visible: open || drawer.shown
color: "transparent"
exclusionMode: ExclusionMode.Ignore
WlrLayershell.namespace: "glassMxrph-plugin-panel"
WlrLayershell.layer: WlrLayer.Overlay
WlrLayershell.keyboardFocus: open ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None
MouseArea {
x: -20000
y: -20000
width: 40000
height: 40000
enabled: root.open
onPressed: root.api.closePanel(null)
}
C.BarDrawer {
id: drawer
objectName: "noctaliaPanelSurface"
y: Core.BarDrawers.bottom
open: root.open
contentWidth: Math.min(root.preferredWidth, root.screenW - 2 * (Core.BarDrawers.margin + Core.BarDrawers.radius + ear))
contentHeight: Math.min(root.preferredHeight, root.screenH - Core.BarDrawers.bottom - 20)
drawerId: "noctalia-panel-" + (root.api ? root.api.pluginId : "")
screenName: root.screen ? root.screen.name : ""
screenX: root.drawerX
focus: root.open
Keys.onEscapePressed: root.api.closePanel(null)
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.AllButtons
}
Loader {
id: loader
anchors.fill: parent
active: root.open || drawer.shown
onActiveChanged: if (active)
setSource(root.source, {
pluginApi: root.api
})
onLoaded: {
if ("screen" in item)
item.screen = Qt.binding(() => root.screen);
}
}
}
}
@@ -0,0 +1,134 @@
import QtQuick
import Quickshell
import Quickshell.Io
// glassMxrph implementation of Noctalia v4's per-plugin `pluginApi`: same
// properties and functions (settings, translations, panel control), backed by
// glassMxrph. Settings persist to settings.json in the plugin's folder, like
// in Noctalia; panels open as glassMxrph bar drawers (see PluginService).
QtObject {
id: api
required property string pluginId
required property string pluginDir
property var manifest: ({})
property var pluginSettings: ({})
property var mainInstance: null
property var barWidget: null
property var desktopWidget: null
property var launcherProvider: null
property var controlCenterWidget: null
// The screen the panel is open on (null when closed), and the button it hangs from.
property var panelOpenScreen: null
property var panelAnchor: null
property var ipcHandlers: ({})
property var pluginTranslations: ({})
property var pluginFallbackTranslations: ({})
property string currentLanguage: (Qt.locale().name || "en").split("_")[0]
property int translationVersion: 0
// Host callbacks (set by glassMxrph's PluginService).
property var _currentScreen: null
property var _requestPanel: null
function nested(obj, path) {
let current = obj;
for (const key of String(path).split(".")) {
if (current === undefined || current === null)
return undefined;
current = current[key];
}
return current;
}
function saveSettings() {
settingsFile.setText(JSON.stringify(api.pluginSettings, null, 2));
api.pluginSettings = Object.assign({}, api.pluginSettings);
}
function openPanel(screen, buttonItem) {
api.panelAnchor = buttonItem || api.barWidget || null;
api.panelOpenScreen = screen || (api._currentScreen ? api._currentScreen() : Quickshell.screens[0]);
if (api._requestPanel)
api._requestPanel(api);
return true;
}
function closePanel(screen) {
if (!api.panelOpenScreen)
return false;
api.panelOpenScreen = null;
return true;
}
// Lets glassMxrph's popout coordinator close this panel like any other.
function close() {
api.closePanel(null);
}
function togglePanel(screen, buttonItem) {
if (api.panelOpenScreen && (!screen || screen === api.panelOpenScreen))
return api.closePanel(screen);
return api.openPanel(screen, buttonItem);
}
function openLauncher(screen) {
}
function closeLauncher(screen) {
}
function toggleLauncher(screen) {
}
function withCurrentScreen(callback) {
callback(api._currentScreen ? api._currentScreen() : Quickshell.screens[0]);
}
function tr(key, interpolations) {
let translation = api.nested(api.pluginTranslations, key);
if (typeof translation !== "string")
translation = api.nested(api.pluginFallbackTranslations, key);
if (typeof translation !== "string")
return "!!" + key + "!!";
for (const placeholder in (interpolations || {}))
translation = translation.replace(new RegExp("\\{" + placeholder + "\\}", "g"), interpolations[placeholder]);
return translation;
}
function trp(key, count, interpolations) {
return api.tr(count === 1 ? key : key + "-plural", Object.assign({
"count": count
}, interpolations || {}));
}
function hasTranslation(key) {
return api.nested(api.pluginTranslations, key) !== undefined || api.nested(api.pluginFallbackTranslations, key) !== undefined;
}
function parse(text) {
try {
return JSON.parse(text);
} catch (e) {
return {};
}
}
property FileView settingsFile: FileView {
path: api.pluginDir + "/settings.json"
blockLoading: true
printErrors: false
onLoaded: api.pluginSettings = Object.assign({}, (api.manifest.metadata && api.manifest.metadata.defaultSettings) || {}, api.parse(text()))
onLoadFailed: api.pluginSettings = Object.assign({}, (api.manifest.metadata && api.manifest.metadata.defaultSettings) || {})
}
property FileView languageFile: FileView {
path: api.pluginDir + "/i18n/" + api.currentLanguage + ".json"
blockLoading: true
printErrors: false
onLoaded: {
api.pluginTranslations = api.parse(text());
api.translationVersion++;
}
}
property FileView fallbackFile: FileView {
path: api.pluginDir + "/i18n/en.json"
blockLoading: true
printErrors: false
onLoaded: {
api.pluginFallbackTranslations = api.parse(text());
api.translationVersion++;
}
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 noctalia-dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
import QtQuick
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Commons.Migrations
import qs.compat.noctalia.Modules.OSD
import qs.compat.noctalia.Services.Compositor
import qs.compat.noctalia.Services.Hardware
import qs.compat.noctalia.Services.Location
import qs.compat.noctalia.Services.Media
import qs.compat.noctalia.Services.Networking
import qs.compat.noctalia.Services.Noctalia
import qs.compat.noctalia.Services.Power
import qs.compat.noctalia.Services.System
import qs.compat.noctalia.Services.UI
import qs.compat.noctalia.Widgets
import qs.compat.noctalia.Widgets.AudioSpectrum
// Quickshell indexes qs.* modules from the shell's own import graph. Plugins
// live outside the shell folder, so this file pulls every Noctalia
// compatibility module into that graph for them. It renders nothing.
QtObject {
}
@@ -0,0 +1,11 @@
import QtQuick
// glassMxrph stub: Noctalia's Settings reads OSD.Type; glassMxrph has its own OSD.
QtObject {
enum Type {
Volume,
InputVolume,
Brightness,
LockKey
}
}
+14
View File
@@ -0,0 +1,14 @@
Noctalia v4 shell kit (Commons, Widgets, Helpers and selected Services),
vendored so Noctalia v4 plugins run inside glassMxrph.
Source: https://github.com/noctalia-dev/noctalia-shell (branch legacy-v4). MIT, see LICENSE.
Tabler icon font: Assets/Fonts/tabler (MIT, see tabler-icons-license.txt).
glassMxrph changes:
- Imports point at qs.compat.noctalia.* (Modules.qml registers them).
- Commons/Color.qml is replaced: Material roles come from the glassMxrph theme.
- Commons/Style.qml: radii, bar/capsule size, animation and opacity follow glassMxrph.
- Commons/Settings.qml stores its file in ~/.config/glassMxrph/noctalia-compat.
- Services/UI, Noctalia, Compositor, Networking, System/NotificationService and
Media/SpectrumService are small glassMxrph-backed stand-ins; Hardware/Battery,
Power/PowerProfile, Location, System/SystemStat and System/Sound are Noctalia's own.
- Host/ holds glassMxrph's pluginApi and the bar-drawer panel host.
@@ -0,0 +1,31 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Hyprland
// glassMxrph stand-in: glassMxrph runs on Hyprland.
Singleton {
readonly property bool isHyprland: true
readonly property bool isNiri: false
readonly property bool isSway: false
readonly property bool isMango: false
readonly property bool isLabwc: false
readonly property bool overviewActive: false
readonly property var workspaces: Hyprland.workspaces.values.map(w => ({
"id": w.id,
"idx": w.id,
"name": w.name,
"output": w.monitor ? w.monitor.name : "",
"isFocused": w.focused,
"isActive": w.active,
"isUrgent": w.urgent,
"isOccupied": w.toplevels.values.length > 0
}))
function getDisplayScale(screenName) {
const s = Quickshell.screens.find(x => x.name === screenName);
return s ? s.devicePixelRatio : 1;
}
function switchToWorkspace(workspace) {
Hyprland.dispatch("workspace " + (workspace && workspace.id !== undefined ? workspace.id : workspace));
}
}
@@ -0,0 +1,368 @@
pragma Singleton
import QtQml
import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Services.UPower
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.Networking
import qs.compat.noctalia.Services.UI
Singleton {
id: root
readonly property var primaryDevice: _laptopBattery || _bluetoothBattery || null // Primary battery device (prioritizes laptop over Bluetooth)
readonly property real batteryPercentage: getPercentage(primaryDevice)
readonly property bool batteryCharging: isCharging(primaryDevice)
readonly property bool batteryPluggedIn: isPluggedIn(primaryDevice)
readonly property bool batteryReady: isDeviceReady(primaryDevice)
readonly property bool batteryPresent: isDevicePresent(primaryDevice)
readonly property real warningThreshold: Settings.data.systemMonitor.batteryWarningThreshold
readonly property real criticalThreshold: Settings.data.systemMonitor.batteryCriticalThreshold
readonly property string batteryIcon: getIcon(batteryPercentage, batteryCharging, batteryPluggedIn, batteryReady)
readonly property var laptopBatteries: UPower.devices.values.filter(d => d.isLaptopBattery).sort((x, y) => {
// Force DisplayDevice to the top
if (x.nativePath.includes("DisplayDevice"))
return -1;
if (y.nativePath.includes("DisplayDevice"))
return 1;
// Standard string comparison works for BAT0 vs BAT1
return x.nativePath.localeCompare(y.nativePath, undefined, {
numeric: true
});
})
readonly property var bluetoothBatteries: {
var list = [];
var btArray = BluetoothService.devices?.values || [];
for (var i = 0; i < btArray.length; i++) {
var btd = btArray[i];
if (btd && btd.connected && btd.batteryAvailable) {
list.push(btd);
}
}
return list;
}
readonly property var _laptopBattery: UPower.displayDevice.isPresent ? UPower.displayDevice : (laptopBatteries.length > 0 ? laptopBatteries[0] : null)
readonly property var _bluetoothBattery: bluetoothBatteries.length > 0 ? bluetoothBatteries[0] : null
property var deviceModel: {
var model = [
{
"key": "__default__",
"name": I18n.tr("bar.battery.device-default")
}
];
const devices = UPower.devices?.values || [];
for (let d of devices) {
if (!d || d.type === UPowerDeviceType.LinePower) {
continue;
}
model.push({
key: d.nativePath || "",
name: d.model || d.nativePath || I18n.tr("common.unknown")
});
}
return model;
}
property var _hasNotified: ({})
function findDevice(nativePath) {
if (!nativePath || nativePath === "__default__" || nativePath === "DisplayDevice") {
return _laptopBattery;
}
if (!UPower.devices) {
return null;
}
const devices = UPower.devices?.values || [];
for (let d of devices) {
if (d && d.nativePath === nativePath) {
if (d.type === UPowerDeviceType.LinePower) {
continue;
}
return d;
}
}
return null;
}
function isDevicePresent(device) {
if (!device) {
return false;
}
// Handle Bluetooth devices (identified by having batteryAvailable property)
if (device.batteryAvailable !== undefined) {
return device.connected === true;
}
// Handle UPower devices
if (device.type !== undefined) {
if (device.type === UPowerDeviceType.Battery && device.isPresent !== undefined) {
return device.isPresent === true;
}
// Fallback for non-battery UPower devices or if isPresent is missing
return device.ready && device.percentage !== undefined;
}
return false;
}
function isDeviceReady(device) {
if (!isDevicePresent(device)) {
return false;
}
if (device.batteryAvailable !== undefined) {
return device.battery !== undefined;
}
return device.ready && device.percentage !== undefined;
}
function getPercentage(device) {
if (!device) {
return -1;
}
if (device.batteryAvailable !== undefined) {
return Math.round((device.battery || 0) * 100);
}
return Math.round((device.percentage || 0) * 100);
}
function isCharging(device) {
if (!device || isBluetoothDevice(device)) {
// Tracking bluetooth devices can charge or not is a loop hole, none of my devices has it, even if it possible?!
return false; // Assuming not charging until someone/quickshell brings a way to do pretty unlikely.
}
if (device.state !== undefined) {
return device.state === UPowerDeviceState.Charging;
}
return false;
}
function isPluggedIn(device) {
if (!device || isBluetoothDevice(device)) {
// Tracking bluetooth devices can charge or not is a loop hole, none of my devices has it, even if it possible?!
return false; // Assuming not charging until someone/quickshell brings a way to do pretty unlikely.
}
if (device.state !== undefined) {
return device.state === UPowerDeviceState.FullyCharged || device.state === UPowerDeviceState.PendingCharge;
}
return false;
}
function isCriticalBattery(device) {
return (!isCharging(device) && !isPluggedIn(device)) && getPercentage(device) <= criticalThreshold;
}
function isLowBattery(device) {
return (!isCharging(device) && !isPluggedIn(device)) && getPercentage(device) <= warningThreshold && getPercentage(device) > criticalThreshold;
}
function isBluetoothDevice(device) {
if (!device) {
return false;
}
// Check for Quickshell Bluetooth device property
if (device.batteryAvailable !== undefined) {
return true;
}
// Check for UPower device path indicating it's a Bluetooth device
if (device.nativePath && (device.nativePath.includes("bluez") || device.nativePath.includes("bluetooth"))) {
return true;
}
return false;
}
function getDeviceName(device) {
if (!isDeviceReady(device)) {
return "";
}
if (!isBluetoothDevice(device) && device.isLaptopBattery) {
// If there is more than one battery explicitly name them
// Logger.e("BatteryDebug", "Available Battery count: " + laptopBatteries.length); // can be useful for debugging
if (laptopBatteries.length > 1 && device.nativePath) {
if (device.nativePath === "DisplayDevice") {
return I18n.tr("battery.all-batteries");
}
var match = device.nativePath.match(/(\d+)$/);
if (match) {
// In case of 2 batteries: bat0 => bat1 bat1 => bat2
return I18n.tr("common.battery") + " " + (parseInt(match[1]) + 1); // Append numbers
}
}
// Return Battery if there is only one
return I18n.tr("common.battery");
}
if (isBluetoothDevice(device) && device.name) {
return device.name;
}
if (device.model) {
return device.model;
}
return "";
}
function getIcon(percent, charging, pluggedIn, isReady) {
if (!isReady) {
return "battery-exclamation";
}
if (charging) {
return "battery-charging";
}
if (pluggedIn) {
return "battery-charging-2";
}
const icons = [
{
threshold: 86,
icon: "battery-4"
},
{
threshold: 56,
icon: "battery-3"
},
{
threshold: 31,
icon: "battery-2"
},
{
threshold: 11,
icon: "battery-1"
},
{
threshold: 0,
icon: "battery"
}
];
const match = icons.find(tier => percent >= tier.threshold);
return match ? match.icon : "battery-off"; // New fallback icon clearly represent if nothing is true here.
}
function getRateText(device) {
if (!device || device.changeRate === undefined) {
return "";
}
const rate = Math.abs(device.changeRate);
if (device.timeToFull > 0) {
return I18n.tr("battery.charging-rate", {
"rate": rate.toFixed(2)
});
} else if (device.timeToEmpty > 0) {
return I18n.tr("battery.discharging-rate", {
"rate": rate.toFixed(2)
});
}
}
function getTimeRemainingText(device) {
if (!isDeviceReady(device)) {
return I18n.tr("battery.no-battery-detected");
}
if (isPluggedIn(device)) {
return I18n.tr("battery.plugged-in");
} else if (device.timeToFull > 0) {
return I18n.tr("battery.time-until-full", {
"time": Time.formatVagueHumanReadableDuration(device.timeToFull)
});
} else if (device.timeToEmpty > 0) {
return I18n.tr("battery.time-left", {
"time": Time.formatVagueHumanReadableDuration(device.timeToEmpty)
});
}
return I18n.tr("common.idle");
}
function checkDevice(device) {
if (!device || !isDeviceReady(device)) {
return;
}
const percentage = getPercentage(device);
const charging = isCharging(device);
const pluggedIn = isPluggedIn(device);
const level = isLowBattery(device) ? "low" : (isCriticalBattery(device) ? "critical" : "");
var deviceKey = device.nativePath;
if (!_hasNotified[deviceKey]) {
_hasNotified[deviceKey] = {
low: false,
critical: false
};
}
if (charging || pluggedIn) {
_hasNotified[deviceKey].low = false;
_hasNotified[deviceKey].critical = false;
}
if (percentage > warningThreshold) {
_hasNotified[deviceKey].low = false;
_hasNotified[deviceKey].critical = false;
} else if (percentage > criticalThreshold) {
_hasNotified[deviceKey].critical = false;
}
if (level) {
if (!_hasNotified[deviceKey][level]) {
notify(device, level);
_hasNotified[deviceKey][level] = true;
}
}
}
function notify(device, level) {
if (!Settings.data.notifications.enableBatteryToast) {
return;
}
var name = getDeviceName(device);
var titleKey = level === "critical" ? "toast.battery.critical" : "toast.battery.low";
var descKey = level === "critical" ? "toast.battery.critical-desc" : "toast.battery.low-desc";
var title = I18n.tr(titleKey);
var desc = I18n.tr(descKey, {
"percent": getPercentage(device)
});
var icon = level === "critical" ? "battery-exclamation" : "battery-charging-2";
if (device == _bluetoothBattery && name) {
title = title + " " + name;
}
// Only 'showNotice' supports custom icons
ToastService.showNotice(title, desc, icon, 6000);
}
Instantiator {
model: deviceModel
delegate: Connections {
required property var modelData
property var device: findDevice(modelData.key)
target: device
function onPercentageChanged() {
if (device.isLaptopBattery && modelData.key !== "__default__") {
return;
}
checkDevice(device);
}
function onStateChanged() {
if (device.isLaptopBattery && modelData.key !== "__default__") {
return;
}
checkDevice(device);
}
}
}
}
@@ -0,0 +1,397 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import qs.compat.noctalia.Commons
// Location and weather service with decoupled geocoding and weather fetching.
Singleton {
id: root
property string locationFile: Quickshell.env("NOCTALIA_WEATHER_FILE") || (Settings.cacheDir + "location.json")
property int weatherUpdateFrequency: 30 * 60
property bool isFetchingWeather: false
// Talia weather
readonly property int taliaMascotWeatherMonth: 3
readonly property int taliaMascotWeatherDay: 1
readonly property bool taliaWeatherMascotDayActive: {
const d = Time.now;
return d.getMonth() === root.taliaMascotWeatherMonth && d.getDate() === root.taliaMascotWeatherDay;
}
readonly property bool taliaWeatherMascotActive: taliaWeatherMascotDayActive || Settings.data.location.weatherTaliaMascotAlways
readonly property alias data: adapter
// True when the user has set a location name or enabled auto-locate
readonly property bool locationConfigured: Settings.data.location.name !== "" || Settings.data.location.autoLocate
// Stable UI properties - only updated when location is successfully geocoded
property bool coordinatesReady: false
property string stableLatitude: ""
property string stableLongitude: ""
property string stableName: ""
FileView {
id: locationFileView
path: locationFile
printErrors: false
onAdapterUpdated: saveTimer.start()
onLoaded: {
Logger.d("Location", "Loaded cached data");
if (adapter.latitude !== "" && adapter.longitude !== "" && adapter.weatherLastFetch > 0) {
root.stableLatitude = adapter.latitude;
root.stableLongitude = adapter.longitude;
root.stableName = adapter.name;
root.coordinatesReady = true;
Logger.i("Location", "Coordinates ready");
}
update();
}
onLoadFailed: function (error) {
update();
}
JsonAdapter {
id: adapter
property string latitude: ""
property string longitude: ""
property string name: ""
property int weatherLastFetch: 0
property var weather: null
}
}
// Formatted coordinates for UI display
readonly property string displayCoordinates: {
if (!root.coordinatesReady || root.stableLatitude === "" || root.stableLongitude === "") {
return "";
}
const lat = parseFloat(root.stableLatitude).toFixed(4);
const lon = parseFloat(root.stableLongitude).toFixed(4);
return `${lat}, ${lon}`;
}
// Auto-geolocate timer - periodically updates location via IP geolocation
Timer {
id: autoLocateTimer
interval: 30 * 60 * 1000
running: Settings.data.location.autoLocate
repeat: true
triggeredOnStart: true
onTriggered: root.geolocateAndApply()
}
// Update timer runs when weather is enabled or location-based scheduling is active
Timer {
id: updateTimer
interval: 20 * 1000
running: Settings.data.location.weatherEnabled || Settings.data.colorSchemes.schedulingMode == "location"
repeat: true
onTriggered: {
update();
}
}
Timer {
id: saveTimer
running: false
interval: 1000
onTriggered: locationFileView.writeAdapter()
}
function init() {
Logger.i("Location", "Service started");
}
function resetWeather() {
Logger.i("Location", "Resetting location and weather data");
root.coordinatesReady = false;
root.stableLatitude = "";
root.stableLongitude = "";
root.stableName = "";
adapter.latitude = "";
adapter.longitude = "";
adapter.name = "";
adapter.weatherLastFetch = 0;
adapter.weather = null;
isFetchingWeather = false;
update();
}
// Main update function - geocodes location if needed, then fetches weather if enabled
function update() {
updateLocation();
if (Settings.data.location.weatherEnabled) {
updateWeatherData();
}
}
// Runs independently of weather toggle
function updateLocation() {
const locationChanged = adapter.name !== Settings.data.location.name;
const needsGeocoding = (adapter.latitude === "") || (adapter.longitude === "") || locationChanged;
if (!needsGeocoding) {
return;
}
if (isFetchingWeather) {
return;
}
isFetchingWeather = true;
if (locationChanged) {
root.coordinatesReady = false;
Logger.d("Location", "Location changed from", adapter.name, "to", Settings.data.location.name);
}
geocodeLocation(Settings.data.location.name, function (latitude, longitude, name, country) {
adapter.name = Settings.data.location.name;
adapter.latitude = latitude.toString();
adapter.longitude = longitude.toString();
root.stableLatitude = adapter.latitude;
root.stableLongitude = adapter.longitude;
root.stableName = `${name}, ${country}`;
root.coordinatesReady = true;
isFetchingWeather = false;
Logger.i("Location", `Geocoded ${Settings.data.location.name}: ${root.stableLatitude}, ${root.stableLongitude}`);
if (locationChanged) {
adapter.weatherLastFetch = 0;
updateWeatherData();
}
}, errorCallback);
}
// Fetch weather data if enabled and coordinates are available
function updateWeatherData() {
if (!Settings.data.location.weatherEnabled) {
return;
}
if (isFetchingWeather) {
return;
}
if (adapter.latitude === "" || adapter.longitude === "") {
Logger.w("Location", "Cannot fetch weather without coordinates");
return;
}
const needsWeatherUpdate = (adapter.weatherLastFetch === "") || (adapter.weather === null) || (Time.timestamp >= adapter.weatherLastFetch + weatherUpdateFrequency);
if (needsWeatherUpdate) {
isFetchingWeather = true;
fetchWeatherData(adapter.latitude, adapter.longitude, errorCallback);
}
}
// Query geocoding API to convert location name to coordinates
function geocodeLocation(locationName, callback, errorCallback) {
if (locationName === "") {
isFetchingWeather = false;
return;
}
Logger.d("Location", "Geocoding location name");
var geoUrl = "https://api.noctalia.dev/geocode?city=" + encodeURIComponent(locationName);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
var geoData = JSON.parse(xhr.responseText);
if (geoData.lat != null) {
callback(geoData.lat, geoData.lng, geoData.name, geoData.country);
} else {
errorCallback("Location", "could not resolve location name");
}
} catch (e) {
errorCallback("Location", "Failed to parse geocoding data: " + e);
}
} else {
errorCallback("Location", `Geocoding error: ${xhr.status} ${xhr.responseText}`);
}
}
};
xhr.open("GET", geoUrl);
xhr.send();
}
// Fetch weather data from Open-Meteo API
function fetchWeatherData(latitude, longitude, errorCallback) {
Logger.d("Location", "Fetching weather from api.open-meteo.com");
var url = "https://api.open-meteo.com/v1/forecast?latitude=" + latitude + "&longitude=" + longitude + "&current_weather=true&current=relativehumidity_2m,surface_pressure,is_day&daily=temperature_2m_max,temperature_2m_min,weathercode,sunset,sunrise&timezone=auto";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
var weatherData = JSON.parse(xhr.responseText);
//console.log(JSON.stringify(weatherData))
// Save core data
data.weather = weatherData;
data.weatherLastFetch = Time.timestamp;
// Update stable display values only when complete and successful
root.stableLatitude = data.latitude = weatherData.latitude.toString();
root.stableLongitude = data.longitude = weatherData.longitude.toString();
root.coordinatesReady = true;
isFetchingWeather = false;
Logger.d("Location", "Cached weather to disk - stable coordinates updated");
} catch (e) {
errorCallback("Location", "Failed to parse weather data");
}
} else {
errorCallback("Location", `Weather error: ${xhr.status} ${xhr.responseText}`);
}
}
};
xhr.open("GET", url);
xhr.send();
}
// Geolocate via IP address using the Noctalia API
function geolocate(callback, errorCallback) {
Logger.d("Location", "Geolocating via IP");
var url = "https://api.noctalia.dev/geolocate";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
var data = JSON.parse(xhr.responseText);
if (data.lat != null) {
callback(data.lat, data.lng, data.city, data.country);
} else {
errorCallback("Location", "Geolocate: no coordinates returned");
}
} catch (e) {
errorCallback("Location", "Failed to parse geolocate data: " + e);
}
} else {
errorCallback("Location", `Geolocate error: ${xhr.status} ${xhr.responseText}`);
}
}
};
xhr.open("GET", url);
xhr.send();
}
// Geolocate via IP and apply the result as the current location
function geolocateAndApply() {
if (isFetchingWeather) {
Logger.w("Location", "Geolocate skipped, fetch already in progress");
return;
}
geolocate(function (lat, lng, city, country) {
Logger.i("Location", "Geolocated to", city + ",", country + ":", lat + "," + lng);
const locationChanged = adapter.name !== city;
Settings.data.location.name = city;
adapter.name = city;
adapter.latitude = lat.toString();
adapter.longitude = lng.toString();
root.stableLatitude = adapter.latitude;
root.stableLongitude = adapter.longitude;
root.stableName = `${city}, ${country}`;
root.coordinatesReady = true;
if (locationChanged) {
adapter.weatherLastFetch = 0;
adapter.weather = null;
}
if (Settings.data.location.weatherEnabled) {
updateWeatherData();
}
}, errorCallback);
}
// --------------------------------
function errorCallback(module, message) {
Logger.w(module, message);
isFetchingWeather = false;
}
// --------------------------------
function weatherSymbolFromCode(code) {
var isDay = data.weather ? data.weather.current_weather.is_day : true;
if (code === 0)
return isDay ? "weather-sun" : "weather-moon";
if (code === 1 || code === 2)
return isDay ? "weather-cloud-sun" : "weather-moon-stars";
if (code === 3)
return "weather-cloud";
if (code >= 45 && code <= 48)
return "weather-cloud-haze";
if (code >= 51 && code <= 67)
return "weather-cloud-rain";
if (code >= 80 && code <= 82)
return "weather-cloud-rain";
if (code >= 71 && code <= 77)
return "weather-cloud-snow";
if (code >= 71 && code <= 77)
return "weather-cloud-snow";
if (code >= 85 && code <= 86)
return "weather-cloud-snow";
if (code >= 95 && code <= 99)
return "weather-cloud-lightning";
return "weather-cloud";
}
// --------------------------------
function taliaWeatherImageFromCode(code) {
var isDay = data.weather ? data.weather.current_weather.is_day : true;
if (code >= 40 && code <= 49)
return Quickshell.shellDir + "/Assets/Talia/TaliaDazed.png";
if (code >= 95 && code <= 99)
return Quickshell.shellDir + "/Assets/Talia/TaliaFear.png";
var wet = (code >= 51 && code <= 67) || (code >= 80 && code <= 82) || (code >= 71 && code <= 77) || (code >= 85 && code <= 86);
if (wet)
return Quickshell.shellDir + "/Assets/Talia/TaliaSob.png";
if ((code === 0 || code === 1 || code === 2) && isDay === false)
return Quickshell.shellDir + "/Assets/Talia/TaliaVampire.png";
if ((code === 0 && isDay === true) || code === 1 || code === 2)
return Quickshell.shellDir + "/Assets/Talia/TaliaParty.png";
return Quickshell.shellDir + "/Assets/Talia/TaliaBlank.png";
}
// --------------------------------
function weatherDescriptionFromCode(code) {
if (code === 0)
return "Clear sky";
if (code === 1)
return "Mainly clear";
if (code === 2)
return "Partly cloudy";
if (code === 3)
return "Overcast";
if (code === 45 || code === 48)
return "Fog";
if (code >= 51 && code <= 67)
return "Drizzle";
if (code >= 71 && code <= 77)
return "Snow";
if (code >= 80 && code <= 82)
return "Rain showers";
if (code >= 95 && code <= 99)
return "Thunderstorm";
return "Unknown";
}
// --------------------------------
function celsiusToFahrenheit(celsius) {
return 32 + celsius * 1.8;
}
}
@@ -0,0 +1,35 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in: the audio spectrum comes from glassMxrph's Cava
// (Noctalia's PwAudioSpectrum is not in Quickshell 0.3.1).
Singleton {
id: root
property var _registeredComponents: ({})
readonly property int _registeredCount: Object.keys(_registeredComponents).length
readonly property var values: GS.CavaService.bars
readonly property bool isIdle: !GS.CavaService.wanted
property bool subscribed: false
on_RegisteredCountChanged: {
const want = _registeredCount > 0;
if (want !== subscribed) {
GS.CavaService.widgetConsumers += want ? 1 : -1;
subscribed = want;
}
}
function registerComponent(componentId) {
const next = Object.assign({}, _registeredComponents);
next[componentId] = true;
_registeredComponents = next;
}
function unregisterComponent(componentId) {
const next = Object.assign({}, _registeredComponents);
delete next[componentId];
_registeredComponents = next;
}
function isRegistered(componentId) {
return !!_registeredComponents[componentId];
}
}
@@ -0,0 +1,11 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Bluetooth
// glassMxrph stand-in: only what other compatibility services read.
Singleton {
readonly property var adapter: Bluetooth.defaultAdapter
readonly property var devices: Bluetooth.devices
readonly property bool enabled: !!adapter && adapter.enabled
}
@@ -0,0 +1,46 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in: answers from glassMxrph's installed plugins.
Singleton {
readonly property string pluginsDir: (Quickshell.env("XDG_DATA_HOME") || Quickshell.env("HOME") + "/.local/share") + "/glassMxrph/plugins"
readonly property var pluginSources: []
function getPluginManifest(pluginId) {
const p = GS.PluginService.plugin(pluginId);
return p ? p.manifest : null;
}
function getPluginDir(pluginId) {
const p = GS.PluginService.plugin(pluginId);
return p ? p.dir : "";
}
function getAllInstalledPluginIds() {
return GS.PluginService.plugins.map(p => p.id);
}
function isPluginEnabled(pluginId) {
return GS.PluginService.isEnabled(pluginId);
}
function isMainSource(url) {
return true;
}
function getPluginSourceUrl(pluginId) {
const p = GS.PluginService.plugin(pluginId);
return p ? p.source : "";
}
function parseCompositeKey(key) {
return {
"pluginId": String(key),
"sourceHash": ""
};
}
function getSourceNameByHash(hash) {
return "";
}
function addPluginSource(name, url) {
}
function removePluginSource(url) {
}
function setSourceEnabled(url, enabled) {
}
}
@@ -0,0 +1,46 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in: Noctalia plugins talk to glassMxrph's plugin service.
Singleton {
readonly property bool initialized: GS.PluginService.loaded
readonly property bool pluginsFullyLoaded: GS.PluginService.loaded
readonly property var availablePlugins: []
readonly property var pluginUpdates: ({})
readonly property int pluginUpdatesPending: 0
readonly property var installingPlugins: ({})
readonly property int activeFetches: 0
function getPluginAPI(pluginId) {
return GS.PluginService.noctaliaApi(pluginId);
}
function hasPluginError(pluginId) {
return false;
}
function getPluginError(pluginId) {
return "";
}
function enablePlugin(pluginId) {
GS.PluginService.setEnabled(pluginId, true);
}
function disablePlugin(pluginId) {
GS.PluginService.setEnabled(pluginId, false);
}
function uninstallPlugin(pluginId) {
GS.PluginService.remove(pluginId);
}
function installPlugin(plugin) {
}
function updatePlugin(pluginId) {
}
function checkForUpdates() {
}
function refreshAvailablePlugins() {
}
function isPluginHotReloadEnabled(pluginId) {
return false;
}
function togglePluginHotReload(pluginId) {
}
}
@@ -0,0 +1,132 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Services.UPower
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
Singleton {
id: root
readonly property var powerProfiles: PowerProfiles
readonly property bool available: powerProfiles && powerProfiles.hasPerformanceProfile
property int profile: powerProfiles ? powerProfiles.profile : PowerProfile.Balanced
// Not a power profile but a volatile property to quickly disable shadows, animations, etc..
property bool noctaliaPerformanceMode: false
function getName(p) {
if (!available)
return "Unknown";
const prof = (p !== undefined) ? p : profile;
switch (prof) {
case PowerProfile.Performance:
return "Performance";
case PowerProfile.Balanced:
return "Balanced";
case PowerProfile.PowerSaver:
return "Power saver";
default:
return "Unknown";
}
}
function getIcon(p) {
if (!available)
return "balanced";
const prof = (p !== undefined) ? p : profile;
switch (prof) {
case PowerProfile.Performance:
return "performance";
case PowerProfile.Balanced:
return "balanced";
case PowerProfile.PowerSaver:
return "powersaver";
default:
return "balanced";
}
}
function init() {
Logger.d("PowerProfileService", "Service started");
}
function setProfile(p) {
if (!available)
return;
try {
powerProfiles.profile = p;
} catch (e) {
Logger.e("PowerProfileService", "Failed to set profile:", e);
}
}
function cycleProfile() {
if (!available)
return;
const current = powerProfiles.profile;
if (current === PowerProfile.Performance)
setProfile(PowerProfile.PowerSaver);
else if (current === PowerProfile.Balanced)
setProfile(PowerProfile.Performance);
else if (current === PowerProfile.PowerSaver)
setProfile(PowerProfile.Balanced);
}
function cycleProfileReverse() {
if (!available)
return;
const current = powerProfiles.profile;
if (current === PowerProfile.Performance)
setProfile(PowerProfile.Balanced);
else if (current === PowerProfile.Balanced)
setProfile(PowerProfile.PowerSaver);
else if (current === PowerProfile.PowerSaver)
setProfile(PowerProfile.Performance);
}
function isDefault() {
if (!available)
return true;
return (profile === PowerProfile.Balanced);
}
Connections {
target: powerProfiles
function onProfileChanged() {
root.profile = powerProfiles.profile;
// Only show toast if we have a valid profile name (not "Unknown")
const profileName = root.getName();
if (profileName !== "Unknown") {
ToastService.showNotice(I18n.tr("toast.power-profile.profile-name", {
"profile": profileName
}), I18n.tr("toast.power-profile.changed"), profileName.toLowerCase().replace(" ", ""));
}
}
}
// Noctalia Performance Mode
// - Turning shadow off
// - Turning animation off
// - Do Not Disturb
function toggleNoctaliaPerformance() {
noctaliaPerformanceMode = !noctaliaPerformanceMode;
}
function setNoctaliaPerformance(value) {
noctaliaPerformanceMode = value;
}
onNoctaliaPerformanceModeChanged: {
if (noctaliaPerformanceMode) {
ToastService.showNotice(I18n.tr("toast.noctalia-performance.label"), I18n.tr("toast.noctalia-performance.enabled"), "rocket");
} else {
ToastService.showNotice(I18n.tr("toast.noctalia-performance.label"), I18n.tr("toast.noctalia-performance.disabled"), "rocket-off");
}
}
}
@@ -0,0 +1,8 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: notifications are handled outside the shell.
Singleton {
property bool doNotDisturb: false
}
@@ -0,0 +1,205 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
// Map to track active sound players: resolvedPath -> MediaPlayer instance
property var activePlayers: ({})
// Check if QtMultimedia is available
property bool multimediaAvailable: false
// Container for dynamically created players
Item {
id: playersContainer
}
Component.onCompleted: {
// Test if QtMultimedia is available by trying to create a simple component
try {
var testComponent = Qt.createQmlObject(`
import QtQuick
import QtMultimedia
Item {}
`, root, "MultimediaTest");
if (testComponent) {
multimediaAvailable = true;
testComponent.destroy();
Logger.i("SoundService", "QtMultimedia found - sound playback enabled");
}
} catch (e) {
multimediaAvailable = false;
Logger.w("SoundService", "QtMultimedia not available - no audio will be played from noctalia-shell");
}
}
function resolvePath(soundPath) {
if (!soundPath || soundPath === "") {
return "";
}
let resolvedPath = soundPath;
// If it's just a filename (no path separators), assume it's in Assets/Sounds/
if (!soundPath.includes("/") && !soundPath.startsWith("file://")) {
resolvedPath = Quickshell.shellDir + "/Assets/Sounds/" + soundPath;
} else if (!soundPath.startsWith("/") && !soundPath.startsWith("file://")) {
// Relative path - assume it's relative to shellDir
resolvedPath = Quickshell.shellDir + "/" + soundPath;
} else if (soundPath.startsWith("file://")) {
resolvedPath = soundPath.substring(7); // Remove "file://" prefix
}
// Absolute paths are used as-is
return resolvedPath;
}
function playSound(soundPath, options) {
if (!soundPath || soundPath === "") {
Logger.w("SoundService", "No sound path provided");
return;
}
if (!multimediaAvailable) {
Logger.d("SoundService", "QtMultimedia not available, cannot play sound:", soundPath);
return;
}
const opts = options || {};
const volume = opts.volume !== undefined ? opts.volume : 1.0;
const fallback = opts.fallback !== undefined ? opts.fallback : false;
const repeat = opts.repeat !== undefined ? opts.repeat : false;
// Resolve path
const resolvedPath = resolvePath(soundPath);
// Stop any existing player for this path if it's looping
if (repeat && activePlayers[resolvedPath]) {
stopSound(soundPath);
}
// Create MediaPlayer instance dynamically with QtMultimedia import
const loopsValue = repeat ? "MediaPlayer.Infinite" : "1";
const escapedPath = resolvedPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
const playerQml = `
import QtQuick
import QtMultimedia
import Quickshell
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.System
MediaPlayer {
id: mediaPlayer
property string resolvedPath: "${escapedPath}"
property bool shouldFallback: ${fallback && !repeat}
property real soundVolume: ${Math.max(0, Math.min(1, volume))}
source: "file://${escapedPath}"
loops: ${loopsValue}
audioOutput: AudioOutput {
volume: soundVolume
}
onErrorOccurred: {
Logger.w("SoundService", "Error playing sound:", source, error, errorString);
if (shouldFallback) {
const fallbackPath = Quickshell.shellDir + "/Assets/Sounds/notification.mp3";
if (fallbackPath !== resolvedPath) {
SoundService.playSound(fallbackPath, {
volume: soundVolume,
fallback: false,
repeat: false
});
}
}
if (SoundService.activePlayers[resolvedPath]) {
delete SoundService.activePlayers[resolvedPath];
}
destroy();
}
onPlaybackStateChanged: function (state) {
if (state === MediaPlayer.StoppedState && loops === 1) {
if (SoundService.activePlayers[resolvedPath]) {
delete SoundService.activePlayers[resolvedPath];
}
destroy();
}
}
Component.onCompleted: {
play();
}
}
`;
try {
const player = Qt.createQmlObject(playerQml, playersContainer, "MediaPlayer_" + resolvedPath.replace(/[^a-zA-Z0-9]/g, "_"));
if (!player) {
Logger.w("SoundService", "Failed to create MediaPlayer for:", resolvedPath);
// Try fallback if requested
if (fallback && !repeat) {
const defaultSound = Quickshell.shellDir + "/Assets/Sounds/notification.mp3";
if (defaultSound !== resolvedPath) {
playSound(defaultSound, {
volume: volume,
fallback: false,
repeat: false
});
}
}
return;
}
// Store player in activePlayers map
activePlayers[resolvedPath] = player;
Logger.d("SoundService", "Playing sound:", resolvedPath, `(volume: ${Math.round(volume * 100)}%)`, repeat ? "(repeat)" : "");
} catch (e) {
Logger.w("SoundService", "Failed to create MediaPlayer:", e);
// Try fallback if requested
if (fallback && !repeat) {
const defaultSound = Quickshell.shellDir + "/Assets/Sounds/notification.mp3";
if (defaultSound !== resolvedPath) {
playSound(defaultSound, {
volume: volume,
fallback: false,
repeat: false
});
}
}
}
}
function stopSound(soundPath) {
if (!multimediaAvailable) {
// If multimedia isn't available, there are no active players to stop
return;
}
if (soundPath) {
// Resolve path the same way as playSound
const resolvedPath = resolvePath(soundPath);
// Stop and remove the player for this specific sound
if (activePlayers[resolvedPath]) {
const player = activePlayers[resolvedPath];
player.stop();
delete activePlayers[resolvedPath];
player.destroy();
Logger.d("SoundService", "Stopped sound:", resolvedPath);
}
} else {
// Stop all active players (typically used for repeating sounds)
const paths = Object.keys(activePlayers);
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const player = activePlayers[path];
player.stop();
player.destroy();
}
activePlayers = {};
Logger.d("SoundService", "Stopped all sounds");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,22 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../core" as Core
import "../../../../services" as GS
// glassMxrph stand-in: the bar is glassMxrph's own top bar.
Singleton {
readonly property bool isVisible: true
property int widgetsRevision: 0
function getTooltipDirection(screenName) {
return "bottom";
}
function getPillDirection(widgetInstance) {
return !widgetInstance || widgetInstance.section !== "left";
}
// Plugin settings live in Settings → Plugins.
function openPluginSettings(screen, pluginManifest) {
GS.PluginService.focusedSettings = pluginManifest && pluginManifest.id ? pluginManifest.id : "";
Core.ShellState.openSettings("plugins");
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,55 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Hyprland
import "../../../../core" as Core
// glassMxrph stand-in: context menus open where the plugin asks and close on
// an outside click (Hyprland focus grab); launcher calls use glassMxrph's.
Singleton {
id: root
property var openedPanel: null
property var lockScreen: null
property bool isKeybindRecording: false
property var menu: null
function showContextMenu(contextMenu, anchorItem, screen, targetItem) {
if (!contextMenu || !anchorItem)
return;
closeContextMenu(screen);
menu = contextMenu;
contextMenu.openAtItem(anchorItem, screen, targetItem);
Qt.callLater(() => grab.active = !!root.menu);
}
function closeContextMenu(screen) {
grab.active = false;
if (menu && typeof menu.close === "function")
menu.close();
menu = null;
}
function getPopupMenuWindow(screen) {
return null;
}
function getPanel(name, screen) {
return null;
}
function isLauncherOpen() {
return Core.ShellState.launcherOpen;
}
function closeLauncher() {
Core.ShellState.launcherOpen = false;
}
function openLauncherWithSearch(text) {
Core.ShellState.openLauncher();
}
function setLauncherSearchText(text) {
}
function getLauncherSearchText() {
return "";
}
HyprlandFocusGrab {
id: grab
windows: root.menu ? [root.menu] : []
onCleared: root.closeContextMenu(null)
}
}
@@ -0,0 +1,24 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia toasts become desktop notifications.
Singleton {
function notify(urgency, title, description, duration) {
Quickshell.execDetached(["notify-send", "-a", "glassMxrph", "-u", urgency, "-t", String(duration || 4000), String(title || ""), String(description || "")]);
}
function showNotice(title, description = "", icon = "", duration = 3000, actionLabel = "", actionCallback = null) {
notify("low", title, description, duration);
}
function showInfo(title, description = "", icon = "", duration = 3000) {
notify("low", title, description, duration);
}
function showWarning(title, description = "", duration = 4000, actionLabel = "", actionCallback = null) {
notify("normal", title, description, duration);
}
function showError(title, description = "", duration = 6000, actionLabel = "", actionCallback = null) {
notify("critical", title, description, duration);
}
function dismissToast() {
}
}
@@ -0,0 +1,40 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../core" as Core
import "../../../../services" as GS
// glassMxrph stand-in: tooltips of bar widgets use the shell's hover popout
// (it hangs from the bar); tooltips elsewhere are not shown.
Singleton {
id: root
property var current: null
function inBar(target) {
const w = target && target.QsWindow ? target.QsWindow.window : null;
return !!w && GS.TrayService.barWindows.includes(w);
}
function show(target, content, direction, delay, fontFamily) {
if (!target || !content || !inBar(target))
return;
current = target;
Core.PopoutState.hover(target, "tooltip", String(content));
}
function hide(target) {
if (target && current !== target)
return;
if (current)
Core.PopoutState.unhover(current);
current = null;
}
function hideImmediately() {
current = null;
Core.PopoutState.close();
}
function updateContent(newContent) {
updateText(newContent);
}
function updateText(newText) {
if (current && Core.PopoutState.anchor === current)
Core.PopoutState.text = String(newText);
}
}
@@ -0,0 +1,29 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in for wallpaper queries.
Singleton {
readonly property bool isInitialized: true
readonly property var currentWallpapers: GS.ConfigService.ready ? GS.ConfigService.data.wallpaper.byMonitor : ({})
signal wallpaperProcessingComplete
function getWallpaper(screenName) {
return currentWallpapers[screenName] || "";
}
function getWallpapersEffectiveMap() {
return currentWallpapers;
}
function changeWallpaper(path, screenName) {
GS.WallpaperService.apply(path);
}
function isSolidColorPath(path) {
return String(path).startsWith("solid://");
}
function getSolidColor(path) {
return String(path).replace("solid://", "");
}
function getFillModeUniform() {
return 1;
}
}
@@ -0,0 +1,49 @@
import QtQuick
import qs.compat.noctalia.Commons
Item {
id: root
property color fillColor: Color.mPrimary
property color strokeColor: Color.mOnSurface
property int strokeWidth: 0
property var values: []
property bool vertical: false
property string barPosition: "top" // "top", "bottom", "left", "right"
property bool mirrored: true
// Minimum signal properties
property bool showMinimumSignal: false
property real minimumSignalValue: 0.01 // Default to 1% of height
// Pre compute horizontal mirroring
readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0
readonly property int totalBars: mirrored ? valuesCount * 2 : valuesCount
readonly property real barSlotSize: totalBars > 0 ? (vertical ? height : width) / totalBars : 0
readonly property bool highQuality: (Settings.data.audio.visualizerType === "low") ? false : true
Repeater {
model: root.totalBars
Rectangle {
property int valueIndex: root.mirrored ? (index < root.valuesCount ? root.valuesCount - 1 - index : index - root.valuesCount) : index
property real rawAmp: (root.values && root.values[valueIndex] !== undefined) ? root.values[valueIndex] : 0
property real amp: (root.showMinimumSignal && rawAmp === 0) ? root.minimumSignalValue : rawAmp
color: root.fillColor
border.color: root.strokeColor
border.width: root.strokeWidth
antialiasing: root.highQuality
smooth: root.highQuality
// Only update when value actually changes - reduces GPU load
width: vertical ? root.width * amp : root.barSlotSize * 0.5
height: vertical ? root.barSlotSize * 0.5 : root.height * amp
x: vertical ? (root.barPosition === "left" ? 0 : root.width - width) : index * root.barSlotSize + (root.barSlotSize * 0.25)
y: vertical ? index * root.barSlotSize + (root.barSlotSize * 0.25) : root.height - height
// Disable updates when invisible to save GPU
visible: root.visible
}
}
}
@@ -0,0 +1,51 @@
import QtQuick
import qs.compat.noctalia.Commons
Item {
id: root
property color fillColor: Color.mPrimary
property color strokeColor: Color.mOnSurface
property int strokeWidth: 0
property var values: []
property bool vertical: false
property bool mirrored: true
// Minimum signal properties
property bool showMinimumSignal: false
property real minimumSignalValue: 0.01 // Default to 1% of height
// Pre-compute mirroring
readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0
readonly property int totalBars: mirrored ? valuesCount * 2 : valuesCount
readonly property real barSlotSize: totalBars > 0 ? (vertical ? height : width) / totalBars : 0
readonly property bool highQuality: (Settings.data.audio.visualizerType === "low") ? false : true
readonly property real centerY: height / 2
readonly property real centerX: width / 2
Repeater {
model: root.totalBars
Rectangle {
property int valueIndex: root.mirrored ? (index < root.valuesCount ? root.valuesCount - 1 - index : index - root.valuesCount) : index
property real rawAmp: (root.values && root.values[valueIndex] !== undefined) ? root.values[valueIndex] : 0
property real amp: (root.showMinimumSignal && rawAmp === 0) ? root.minimumSignalValue : rawAmp
property real barSize: (vertical ? root.width : root.height) * amp
color: root.fillColor
border.color: root.strokeColor
border.width: root.strokeWidth
antialiasing: root.highQuality
smooth: root.highQuality
width: vertical ? barSize : root.barSlotSize * 0.8
height: vertical ? root.barSlotSize * 0.8 : barSize
x: vertical ? root.centerX - (barSize / 2) : index * root.barSlotSize + (root.barSlotSize * 0.25)
y: vertical ? index * root.barSlotSize + (root.barSlotSize * 0.25) : root.centerY - (barSize / 2)
// Disable updates when invisible to save GPU
visible: root.visible
}
}
}
@@ -0,0 +1,72 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Item {
id: root
property color fillColor: Color.mPrimary
property color strokeColor: Color.mOnSurface
property int strokeWidth: 0
property var values: []
property bool vertical: false
property bool mirrored: true
// Minimum signal properties
property bool showMinimumSignal: false
property real minimumSignalValue: 0.01 // Default to 1% of height
readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0
readonly property bool hasData: valuesCount >= 2
// Data texture: one pixel per value, R channel = amplitude
Item {
id: dataRow
width: Math.max(root.valuesCount, 4)
height: 1
Repeater {
model: dataRow.width
Rectangle {
required property int index
x: index
width: 1
height: 1
color: {
if (index >= root.valuesCount)
return Qt.rgba(0, 0, 0, 1);
var v = root.values[index];
if (v === undefined || v === null || !isFinite(v))
v = 0;
if (root.showMinimumSignal && v === 0)
v = root.minimumSignalValue;
return Qt.rgba(Math.max(0, Math.min(1, v)), 0, 0, 1);
}
}
}
}
ShaderEffectSource {
id: dataTex
sourceItem: dataRow
textureSize: Qt.size(dataRow.width, 1)
live: true
smooth: false
hideSource: true
}
ShaderEffect {
anchors.fill: parent
visible: root.hasData && root.width > 0 && root.height > 0
property variant dataSource: dataTex
property color fillColor: root.fillColor
property real count: root.valuesCount
property real texWidth: dataRow.width
property real vertical: root.vertical ? 1.0 : 0.0
property real mirrored: root.mirrored ? 1.0 : 0.0
fragmentShader: Qt.resolvedUrl(Quickshell.shellDir + "/Shaders/qsb/wave_spectrum.frag.qsb")
blending: true
}
}
@@ -0,0 +1,205 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
// Battery widget with Android 16 style rendering (horizontal or vertical)
Item {
id: root
// Data (must be provided by parent)
required property real percentage
required property bool charging
required property bool pluggedIn
required property bool ready
required property bool low
required property bool critical
// Sizing - baseSize controls overall scaleFactor for bar/panel usage
property real baseSize: Style.fontSizeM
// Styling - no hardcoded colors, only theme colors
property color baseColor: Color.mOnSurface
property color lowColor: Color.mError
property color chargingColor: Color.mPrimary
property color textColor: Color.mSurface
// Display options
property bool showPercentageText: true
property bool vertical: false
// Alternating state icon display (toggles between percentage and icon when charging)
property bool showStateIcon: false
onChargingChanged: {
if (!charging)
showStateIcon = false;
}
// Internal sizing calculations based on baseSize
readonly property real scaleFactor: baseSize / Style.fontSizeM
readonly property real bodyWidth: {
const min = Style.toOdd(22 * scaleFactor);
if (!showPercentageText) {
return min;
}
// increase length when showing 100%
if (percentage > 99) {
const max = Style.toOdd(30 * scaleFactor);
return max;
}
return min;
}
readonly property real bodyHeight: Style.toOdd(14 * scaleFactor)
readonly property real terminalWidth: Math.round(2.5 * scaleFactor)
readonly property real terminalHeight: Math.round(7 * scaleFactor)
readonly property real cornerRadius: Math.round(3 * scaleFactor)
// Total size is just body + terminal (no external icon)
readonly property real totalWidth: vertical ? bodyHeight : bodyWidth + terminalWidth
readonly property real totalHeight: vertical ? bodyWidth + terminalWidth : bodyHeight
// Determine active color based on state
readonly property color activeColor: {
if (!ready) {
return Qt.alpha(baseColor, Style.opacityMedium);
}
if (charging) {
return chargingColor;
}
if (low || critical) {
return lowColor;
}
return baseColor;
}
// Background color for empty portion (semi-transparent)
readonly property color emptyColor: Qt.alpha(baseColor, 0.66)
// State icon logic
readonly property string stateIcon: {
if (!ready)
return "x";
if (charging)
return "bolt-filled";
if (pluggedIn)
return "plug-filled";
return "";
}
// Animated percentage for smooth transitions
property real animatedPercentage: percentage
Behavior on animatedPercentage {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
// Timer to alternate between percentage text and state icon when charging/plugged
Timer {
id: alternateTimer
interval: 4000
repeat: true
running: root.charging && root.showPercentageText
onTriggered: root.showStateIcon = !root.showStateIcon
}
implicitWidth: Math.round(totalWidth)
implicitHeight: Math.round(totalHeight)
Layout.maximumWidth: implicitWidth
Layout.maximumHeight: implicitHeight
// Battery body container
Item {
id: batteryBody
width: root.vertical ? root.bodyHeight : root.bodyWidth + root.terminalWidth
height: root.vertical ? root.bodyWidth + root.terminalWidth : root.bodyHeight
anchors.left: root.vertical ? undefined : parent.left
anchors.bottom: root.vertical ? parent.bottom : undefined
anchors.horizontalCenter: root.vertical ? parent.horizontalCenter : undefined
anchors.verticalCenter: root.vertical ? undefined : parent.verticalCenter
// Battery body background
Rectangle {
id: bodyBackground
y: root.vertical ? root.terminalWidth : 0
width: root.vertical ? root.bodyHeight : root.bodyWidth
height: root.vertical ? root.bodyWidth : root.bodyHeight
radius: root.cornerRadius
color: root.emptyColor
}
// Terminal cap
Rectangle {
x: root.vertical ? (root.bodyHeight - root.terminalHeight) / 2 : root.bodyWidth
y: root.vertical ? 0 : (root.bodyHeight - root.terminalHeight) / 2
width: root.vertical ? root.terminalHeight : root.terminalWidth
height: root.vertical ? root.terminalWidth : root.terminalHeight
radius: root.cornerRadius / 2
color: root.critical ? root.lowColor : root.emptyColor
}
// Fill level
Rectangle {
id: fillRect
visible: root.ready && (root.animatedPercentage > 0 || root.critical)
x: 0
y: root.vertical ? root.terminalWidth + root.bodyWidth * (1 - (root.critical ? 1 : root.animatedPercentage / 100)) : 0
width: root.vertical ? root.bodyHeight : root.bodyWidth * (root.critical ? 1 : root.animatedPercentage / 100)
height: root.vertical ? root.bodyWidth * (root.critical ? 1 : root.animatedPercentage / 100) : root.bodyHeight
radius: root.cornerRadius
color: root.activeColor
}
}
// Percentage text overlaid on battery center
NText {
id: percentageText
visible: opacity > 0
opacity: root.showPercentageText && root.ready && (root.charging ? !root.showStateIcon : !root.pluggedIn) ? 1 : 0
x: batteryBody.x + Style.pixelAlignCenter(bodyBackground.width, width)
y: batteryBody.y + bodyBackground.y + Style.pixelAlignCenter(bodyBackground.height, height)
font.family: Settings.data.ui.fontFixed
font.weight: Style.fontWeightBold
text: root.vertical ? String(Math.round(root.animatedPercentage)).split('').join('\n') : Math.round(root.animatedPercentage)
pointSize: root.baseSize * (root.vertical ? 0.82 : 0.82)
color: Qt.alpha(root.textColor, 0.75)
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
lineHeight: root.vertical ? 0.7 : 1.0
lineHeightMode: Text.ProportionalHeight
Behavior on opacity {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationFast
easing.type: Easing.InOutQuad
}
}
}
// State icon centered inside battery body (shown when alternating)
NIcon {
id: stateIconOverlay
visible: opacity > 0
opacity: !root.ready || (root.charging ? (root.showStateIcon || !root.showPercentageText) : root.pluggedIn) ? 1 : 0
x: batteryBody.x + Style.pixelAlignCenter(bodyBackground.width, width)
y: batteryBody.y + bodyBackground.y + Style.pixelAlignCenter(bodyBackground.height, height)
icon: root.stateIcon
pointSize: Style.toOdd(root.baseSize)
color: Qt.alpha(root.textColor, 0.75)
Behavior on opacity {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationFast
easing.type: Easing.InOutQuad
}
}
}
}
@@ -0,0 +1,30 @@
import QtQuick
import qs.compat.noctalia.Commons
// Rounded group container using the variant surface color.
// To be used in side panels and settings panes to group fields or buttons.
// Opacity is based on panelBackgroundOpacity but clamped to a minimum to avoid full transparency.
Item {
id: root
property color color: Color.mSurfaceVariant
property bool forceOpaque: false
property alias radius: bg.radius
property alias border: bg.border
Rectangle {
id: bg
anchors.fill: parent
radius: Style.radiusM
border.color: Style.boxBorderColor
border.width: Style.borderS
color: {
if (forceOpaque) {
return root.color;
}
return Color.smartAlpha(root.color);
}
}
}
@@ -0,0 +1,66 @@
import QtQuick
import qs.compat.noctalia.Commons
Item {
id: root
property bool running: true
property color color: Color.mPrimary
property int size: Style.baseWidgetSize
property int strokeWidth: Style.borderL
property int duration: Style.animationSlow * 2
implicitWidth: size
implicitHeight: size
onColorChanged: canvas.requestPaint()
// GPU-optimized spinner - draw once, rotate with GPU transform
Item {
id: spinner
anchors.fill: parent
// Static canvas - drawn ONCE, then cached
Canvas {
id: canvas
anchors.fill: parent
renderStrategy: Canvas.Cooperative // Better performance than Threaded for simple shapes
renderTarget: Canvas.FramebufferObject // GPU texture
// Enable layer caching - critical for performance!
layer.enabled: true
layer.smooth: true
Component.onCompleted: {
requestPaint();
}
onPaint: {
var ctx = getContext("2d");
ctx.reset();
var centerX = width / 2;
var centerY = height / 2;
var radius = Math.min(width, height) / 2 - strokeWidth / 2;
ctx.strokeStyle = root.color;
ctx.lineWidth = Math.max(1, root.strokeWidth);
ctx.lineCap = "round";
// Draw arc with gap (270 degrees = 3/4 of circle)
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + Math.PI * 1.5);
ctx.stroke();
}
}
// Smooth rotation animation - uses GPU transform, NO canvas repaints!
RotationAnimation on rotation {
running: root.running
from: 0
to: 360
duration: root.duration
loops: Animation.Infinite
}
}
}
@@ -0,0 +1,184 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
Item {
id: root
// Public properties
property string text: ""
property string icon: ""
property var tooltipText
property color backgroundColor: Color.mPrimary
property color textColor: Color.mOnPrimary
property color hoverColor: Color.mHover
property color textHoverColor: Color.mOnHover
property real fontSize: Style.fontSizeM
property int fontWeight: Style.fontWeightSemiBold
property real iconSize: Style.fontSizeL
property bool outlined: false
property int horizontalAlignment: Qt.AlignHCenter
property real buttonRadius: Style.iRadiusS
// Signals
signal clicked
signal rightClicked
signal middleClicked
signal entered
signal exited
// Internal properties
property bool hovered: false
readonly property color contentColor: {
if (!root.enabled) {
return Color.mOnSurfaceVariant;
}
if (root.hovered) {
return root.textHoverColor;
}
if (root.outlined) {
return root.backgroundColor;
}
return root.textColor;
}
// Dimensions - include margin so border renders cleanly at fractional scales
implicitWidth: bg.implicitWidth + 2 * Style.borderS
implicitHeight: bg.implicitHeight + 2 * Style.borderS
opacity: enabled ? 1.0 : 0.6
Rectangle {
id: bg
anchors.fill: parent
anchors.margins: Style.borderS
implicitWidth: contentRow.implicitWidth + (root.fontSize * 2)
implicitHeight: contentRow.implicitHeight + (root.fontSize)
radius: root.buttonRadius
color: {
if (!root.enabled)
return root.outlined ? "transparent" : Qt.lighter(Color.mSurfaceVariant, 1.2);
if (root.hovered)
return root.hoverColor;
return root.outlined ? "transparent" : root.backgroundColor;
}
border.width: root.outlined ? Style.borderS : 0
border.color: {
if (!root.enabled)
return Color.mOutline;
if (root.hovered)
return root.hoverColor;
return root.outlined ? root.backgroundColor : "transparent";
}
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
Behavior on border.color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
// Content
RowLayout {
id: contentRow
anchors.verticalCenter: parent.verticalCenter
anchors.left: root.horizontalAlignment === Qt.AlignLeft ? parent.left : undefined
anchors.horizontalCenter: root.horizontalAlignment === Qt.AlignHCenter ? parent.horizontalCenter : undefined
anchors.leftMargin: root.horizontalAlignment === Qt.AlignLeft ? Style.marginL : 0
spacing: Style.marginXS
// Icon (optional)
NIcon {
Layout.alignment: Qt.AlignVCenter
visible: root.icon !== ""
icon: root.icon
pointSize: root.iconSize
color: root.contentColor
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
}
// Text
NText {
Layout.alignment: Qt.AlignVCenter
visible: root.text !== ""
text: root.text
pointSize: root.fontSize
font.weight: root.fontWeight
color: root.contentColor
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
}
}
// Mouse interaction
MouseArea {
id: mouseArea
anchors.fill: parent
enabled: root.enabled
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton
cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
onEntered: {
root.hovered = root.enabled ? true : false;
root.entered();
if (root.hovered && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.show(root, root.tooltipText);
}
}
onExited: {
root.hovered = false;
root.exited();
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
onPressed: mouse => {
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
if (mouse.button === Qt.LeftButton) {
root.clicked();
} else if (mouse.button == Qt.RightButton) {
root.rightClicked();
} else if (mouse.button == Qt.MiddleButton) {
root.middleClicked();
}
}
onCanceled: {
root.hovered = false;
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
}
}
}
@@ -0,0 +1,87 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
RowLayout {
id: root
// Public API
property string label: ""
property string description: ""
property bool checked: false
property bool hovering: false
property color activeColor: Color.mPrimary
property color activeOnColor: Color.mOnPrimary
property int baseSize: root.defaultSize
property real labelSize: Style.fontSizeL
readonly property int defaultSize: Style.baseWidgetSize * 0.7
signal toggled(bool checked)
signal entered
signal exited
Layout.fillWidth: true
NLabel {
label: root.label
labelSize: root.labelSize
description: root.description
visible: root.label !== "" || root.description !== ""
}
// Spacer to push the checkbox to the far right
Item {
Layout.fillWidth: true
}
Rectangle {
id: box
opacity: enabled ? 1.0 : 0.6
Layout.margins: Style.borderS
implicitWidth: Style.toOdd(root.baseSize)
implicitHeight: Style.toOdd(root.baseSize)
radius: Style.iRadiusXS * (root.baseSize / root.defaultSize)
color: root.checked ? root.activeColor : Color.mSurface
border.color: Color.mOutline
border.width: Style.borderS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
Behavior on border.color {
ColorAnimation {
duration: Style.animationFast
}
}
NIcon {
visible: root.checked
x: Style.pixelAlignCenter(parent.width, width)
y: Style.pixelAlignCenter(parent.height, height)
icon: "check"
color: root.activeOnColor
pointSize: Style.toOdd(root.baseSize * 0.5)
}
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
hoverEnabled: true
onEntered: {
hovering = true;
root.entered();
}
onExited: {
hovering = false;
root.exited();
}
onClicked: root.toggled(!root.checked)
}
}
}
@@ -0,0 +1,164 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
import qs.compat.noctalia.Widgets
// Compact circular statistic display using Layout management
Item {
id: root
property real ratio: 0 // 0..1 range
property string icon: ""
property string suffix: "%"
property real contentScale: 1.0
property color fillColor: Color.mPrimary
property var tooltipText
property string tooltipDirection: "top"
// Arc geometry constants
readonly property real _gaugeSize: 60 * contentScale
readonly property real _lineWidth: 6 * contentScale
readonly property real _arcRadius: _gaugeSize / 2 - 5 * contentScale
// Arc goes from 150° to 390° (30°), gap at bottom
// Bottom of arc is at y = center + radius * sin(30°) = center + radius * 0.5
// Plus half line width for stroke
readonly property real _arcBottomY: _gaugeSize / 2 + _arcRadius * 0.5 + _lineWidth / 2
// Height needs to include the icon which sits inside the arc gap
// Icon is ~12px tall, positioned 4px below text center, need ~4px more padding
readonly property real _contentHeight: _arcBottomY + 4 * contentScale
implicitWidth: Math.round(_gaugeSize)
implicitHeight: Math.round(_contentHeight)
Layout.maximumWidth: implicitWidth
Layout.maximumHeight: implicitHeight
// Animated ratio for smooth transitions - reduces repaint frequency
property real animatedRatio: ratio
Behavior on animatedRatio {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
// Repaint gauge when animated ratio changes (throttled by animation)
onAnimatedRatioChanged: {
if (!repaintTimer.running) {
repaintTimer.start();
}
}
onFillColorChanged: gauge.requestPaint()
// Throttle timer to limit repaint frequency during animation (~30 FPS)
Timer {
id: repaintTimer
interval: 33
repeat: true
onTriggered: {
gauge.requestPaint();
// Stop repeating once animation settles
if (Math.abs(root.animatedRatio - root.ratio) < 0.001) {
stop();
}
}
}
Canvas {
id: gauge
width: root._gaugeSize
height: root._gaugeSize
anchors.horizontalCenter: parent.horizontalCenter
y: 0
// Optimized Canvas settings for better GPU performance
renderStrategy: Canvas.Cooperative
renderTarget: Canvas.FramebufferObject
// Enable layer caching - critical for performance!
layer.enabled: true
layer.smooth: true
// Hide until first paint to avoid white FBO flash
visible: false
onPainted: visible = true
Component.onCompleted: {
requestPaint();
}
onPaint: {
const ctx = getContext("2d");
const w = width, h = height;
const cx = w / 2, cy = h / 2;
const r = root._arcRadius;
// Rotated 90° to the right: gap at the bottom
// Start at 150° and end at 390° (30°) → bottom opening
const start = Math.PI * 5 / 6; // 150°
const endBg = Math.PI * 13 / 6; // 390° (equivalent to 30°)
ctx.reset();
ctx.lineWidth = root._lineWidth;
ctx.lineCap = Settings.data.general.iRadiusRatio > 0 ? "round" : "butt";
// Track uses outline for contrast against surfaceVariant backgrounds
ctx.strokeStyle = Color.mSurface;
ctx.beginPath();
ctx.arc(cx, cy, r, start, endBg);
ctx.stroke();
// Value arc - only draw if ratio is meaningful (> 0.5%)
const r2 = Math.max(0, Math.min(1, root.animatedRatio));
if (r2 > 0.005) {
const end = start + (endBg - start) * r2;
ctx.strokeStyle = root.fillColor;
ctx.beginPath();
ctx.arc(cx, cy, r, start, end);
ctx.stroke();
}
}
}
// Percent centered in the circle
NText {
id: valueLabel
anchors.horizontalCenter: gauge.horizontalCenter
anchors.verticalCenter: gauge.verticalCenter
anchors.verticalCenterOffset: -4 * root.contentScale
text: `${Math.round(root.animatedRatio * 100)}${root.suffix}`
pointSize: Style.fontSizeM * root.contentScale * 0.9
font.weight: Style.fontWeightBold
color: root.fillColor
horizontalAlignment: Text.AlignHCenter
}
NIcon {
id: iconText
anchors.horizontalCenter: gauge.horizontalCenter
anchors.top: valueLabel.bottom
anchors.topMargin: 4 * root.contentScale
icon: root.icon
color: root.fillColor
pointSize: Style.fontSizeM * root.contentScale
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onEntered: {
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.show(root, root.tooltipText, root.tooltipDirection);
}
}
onExited: {
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
}
}
@@ -0,0 +1,442 @@
import QtQuick
import QtQuick.Layouts
import Quickshell
import "../Helpers/ColorsConvert.js" as ColorsConvert
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
Item {
id: root
property var now: Time.now
// Style: "analog" or "digital"
property string clockStyle: "analog"
// Show seconds progress ring (digital only)
property bool showProgress: true
// Color properties
property color backgroundColor: Color.mPrimary
property color clockColor: Color.mOnPrimary
property color secondHandColor: {
var defaultColor = Color.mError;
var bestContrast = 1.0; // 1.0 is "no contrast"
var bestColor = defaultColor;
var candidates = [Color.mSecondary, Color.mTertiary, Color.mError];
const minContrast = 1.149;
for (var i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
var contrastClock = ColorsConvert.getContrastRatio(candidate.toString(), clockColor.toString());
if (contrastClock < minContrast) {
continue;
}
var contrastBg = ColorsConvert.getContrastRatio(candidate.toString(), backgroundColor.toString());
if (contrastBg < minContrast) {
continue;
}
var currentWorstContrast = Math.min(contrastBg, contrastClock);
if (currentWorstContrast > bestContrast) {
bestContrast = currentWorstContrast;
bestColor = candidate;
}
}
return bestColor;
}
property color progressColor: root.secondHandColor
// Font size properties for digital clock
property real hoursFontSize: Style.fontSizeXS
property real minutesFontSize: Style.fontSizeXXS
property int hoursFontWeight: Style.fontWeightBold
property int minutesFontWeight: Style.fontWeightBold
// Scale ratio for canvas line widths (used by desktop widget scaling)
property real scaleRatio: Style.uiScaleRatio
height: Math.round((Style.fontSizeXXXL * 1.9) / 2 * Style.uiScaleRatio) * 2
width: root.height
Loader {
id: clockLoader
anchors.fill: parent
sourceComponent: {
if (root.clockStyle === "analog")
return analogClockComponent;
if (root.clockStyle === "binary")
return binaryClockComponent;
return digitalClockComponent;
}
onLoaded: {
item.now = Qt.binding(function () {
return root.now;
});
item.backgroundColor = Qt.binding(function () {
return root.backgroundColor;
});
item.clockColor = Qt.binding(function () {
return root.clockColor;
});
if (item.hasOwnProperty("secondHandColor")) {
item.secondHandColor = Qt.binding(function () {
return root.secondHandColor;
});
}
if (item.hasOwnProperty("progressColor")) {
item.progressColor = Qt.binding(function () {
return root.progressColor;
});
}
if (item.hasOwnProperty("hoursFontSize")) {
item.hoursFontSize = Qt.binding(function () {
return root.hoursFontSize;
});
}
if (item.hasOwnProperty("minutesFontSize")) {
item.minutesFontSize = Qt.binding(function () {
return root.minutesFontSize;
});
}
if ("hoursFontWeight" in item) {
item.hoursFontWeight = Qt.binding(function () {
return root.hoursFontWeight;
});
}
if ("minutesFontWeight" in item) {
item.minutesFontWeight = Qt.binding(function () {
return root.minutesFontWeight;
});
}
if (item.hasOwnProperty("scaleRatio")) {
item.scaleRatio = Qt.binding(function () {
return root.scaleRatio;
});
}
if ("showProgress" in item) {
item.showProgress = Qt.binding(function () {
return root.showProgress;
});
}
}
}
// Analog Clock Component
component NClockAnalog: Item {
property var now
property color backgroundColor: Color.mPrimary
property color clockColor: Color.mOnPrimary
property color secondHandColor: Color.mError
property real scaleRatio: Style.uiScaleRatio
anchors.fill: parent
Canvas {
id: clockCanvas
anchors.fill: parent
Connections {
target: Time
function onNowChanged() {
clockCanvas.requestPaint();
}
}
onPaint: {
var currentTime = Time.now;
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
const markAlpha = 0.7;
var ctx = getContext("2d");
ctx.reset();
ctx.translate(width / 2, height / 2);
var radius = Math.min(width, height) / 2;
// Hour marks
ctx.strokeStyle = Qt.alpha(clockColor, markAlpha);
ctx.lineWidth = 2 * scaleRatio;
var scaleFactor = 0.7;
for (var i = 0; i < 12; i++) {
var scaleFactor = 0.8;
if (i % 3 === 0) {
scaleFactor = 0.65;
}
ctx.save();
ctx.rotate(i * Math.PI / 6);
ctx.beginPath();
ctx.moveTo(0, -radius * scaleFactor);
ctx.lineTo(0, -radius);
ctx.stroke();
ctx.restore();
}
// Hour hand
ctx.save();
var hourAngle = (hours % 12 + minutes / 60) * Math.PI / 6;
ctx.rotate(hourAngle);
ctx.strokeStyle = clockColor;
ctx.lineWidth = 3 * scaleRatio;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -radius * 0.6);
ctx.stroke();
ctx.restore();
// Minute hand
ctx.save();
var minuteAngle = (minutes + seconds / 60) * Math.PI / 30;
ctx.rotate(minuteAngle);
ctx.strokeStyle = clockColor;
ctx.lineWidth = 2 * scaleRatio;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -radius * 0.9);
ctx.stroke();
ctx.restore();
// Second hand
ctx.save();
var secondAngle = seconds * Math.PI / 30;
ctx.rotate(secondAngle);
ctx.strokeStyle = secondHandColor;
ctx.lineWidth = 1.6 * scaleRatio;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -radius);
ctx.stroke();
ctx.restore();
// Center dot
ctx.beginPath();
ctx.arc(0, 0, 3 * scaleRatio, 0, 2 * Math.PI);
ctx.fillStyle = clockColor;
ctx.fill();
}
Component.onCompleted: requestPaint()
}
}
// Digital Clock Component
component NClockDigital: Item {
property var now
property color backgroundColor: Color.mPrimary
property color clockColor: Color.mOnPrimary
property color progressColor: Color.mError
property real hoursFontSize: Style.fontSizeXS
property real minutesFontSize: Style.fontSizeXXS
property int hoursFontWeight: Style.fontWeightBold
property int minutesFontWeight: Style.fontWeightBold
property real scaleRatio: Style.uiScaleRatio
property bool showProgress: true
anchors.fill: parent
// Digital clock's seconds circular progress
Canvas {
id: secondsProgress
anchors.fill: parent
visible: showProgress
property real progress: now.getSeconds() / 60
onProgressChanged: requestPaint()
Connections {
target: Time
function onNowChanged() {
const total = now.getSeconds() * 1000 + now.getMilliseconds();
secondsProgress.progress = total / 60000;
}
}
onPaint: {
var ctx = getContext("2d");
var centerX = width / 2;
var centerY = height / 2;
var radius = Math.min(width, height) / 2 - 3 * scaleRatio;
ctx.reset();
// Background circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.lineWidth = 2.5 * scaleRatio;
ctx.strokeStyle = Qt.alpha(clockColor, 0.15);
ctx.stroke();
// Progress arc
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + progress * 2 * Math.PI);
ctx.lineWidth = 2.5 * scaleRatio;
ctx.strokeStyle = progressColor;
ctx.lineCap = "round";
ctx.stroke();
}
}
// Digital clock
ColumnLayout {
anchors.centerIn: parent
spacing: -Style.marginXXS
NText {
text: {
var t = Settings.data.location.use12hourFormat ? I18n.locale.toString(now, "hh AP") : I18n.locale.toString(now, "HH");
return t.split(" ")[0];
}
pointSize: hoursFontSize
font.weight: hoursFontWeight
color: clockColor
family: Settings.data.ui.fontFixed
Layout.alignment: Qt.AlignHCenter
}
NText {
text: Qt.formatTime(now, "mm")
pointSize: minutesFontSize
font.weight: minutesFontWeight
color: clockColor
family: Settings.data.ui.fontFixed
Layout.alignment: Qt.AlignHCenter
}
}
}
// Binary Clock Component
component NClockBinary: Item {
property var now
property color backgroundColor
property color clockColor: Color.mOnPrimary
anchors.fill: parent
readonly property int h: now.getHours()
readonly property int m: now.getMinutes()
readonly property int s: now.getSeconds()
// BCD (Binary Coded Decimal) Format:
// H1 H2 : M1 M2 : S1 S2
// H1 (tens): 0-2 (2 bits)
// H2 (ones): 0-9 (4 bits)
// M1 (tens): 0-5 (3 bits)
// M2 (ones): 0-9 (4 bits)
// S1 (tens): 0-5 (3 bits)
// S2 (ones): 0-9 (4 bits)
RowLayout {
anchors.centerIn: parent
spacing: parent.width * 0.05
// Hours
RowLayout {
spacing: parent.parent.width * 0.02
BinaryColumn {
value: Math.floor(h / 10)
bits: 2
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
BinaryColumn {
value: h % 10
bits: 4
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
}
// Minutes
RowLayout {
spacing: parent.parent.width * 0.02
BinaryColumn {
value: Math.floor(m / 10)
bits: 3
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
BinaryColumn {
value: m % 10
bits: 4
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
}
// Seconds
RowLayout {
spacing: parent.parent.width * 0.02
BinaryColumn {
value: Math.floor(s / 10)
bits: 3
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
BinaryColumn {
value: s % 10
bits: 4
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
}
}
}
component BinaryColumn: Column {
property int value: 0
property int bits: 4
property real dotSize: 10
property color activeColor: "white"
spacing: dotSize * 0.4
Repeater {
model: bits
Rectangle {
property int bitIndex: (bits - 1) - index
property bool isActive: (value >> bitIndex) & 1
width: dotSize
height: dotSize
radius: dotSize / 2
color: isActive ? activeColor : Qt.alpha(activeColor, 0.2)
Behavior on color {
ColorAnimation {
duration: 200
}
}
}
}
}
Component {
id: analogClockComponent
NClockAnalog {}
}
Component {
id: digitalClockComponent
NClockDigital {}
}
Component {
id: binaryClockComponent
NClockBinary {}
}
}
@@ -0,0 +1,191 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
ColumnLayout {
id: root
property string label: ""
property string description: ""
property bool expanded: false
property real contentSpacing: Style.marginM
property bool _userInteracted: false
signal toggled(bool expanded)
Layout.fillWidth: true
spacing: 0
// Default property to accept children
default property alias content: contentLayout.children
// Header with clickable area
Rectangle {
id: headerContainer
Layout.fillWidth: true
Layout.preferredHeight: headerContent.implicitHeight + Style.margin2M
color: root.expanded ? Color.mSecondary : Color.mPrimary
radius: Style.iRadiusM
border.color: root.expanded ? Color.mOnSecondary : Color.mOutline
border.width: Style.borderS
// Smooth color transitions
Behavior on color {
enabled: root._userInteracted
ColorAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
Behavior on border.color {
enabled: root._userInteracted
ColorAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
MouseArea {
id: headerArea
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
hoverEnabled: true
onClicked: {
root._userInteracted = true;
root.expanded = !root.expanded;
root.toggled(root.expanded);
}
// Hover effect overlay
Rectangle {
anchors.fill: parent
color: headerArea.containsMouse ? Color.mOnSurface : "transparent"
opacity: headerArea.containsMouse ? 0.08 : 0
radius: headerContainer.radius // Reference the container's radius directly
Behavior on opacity {
NumberAnimation {
duration: Style.animationFast
}
}
}
}
RowLayout {
id: headerContent
anchors.fill: parent
anchors.margins: Style.marginM
spacing: Style.marginM
// Expand/collapse icon with rotation animation
NIcon {
id: chevronIcon
icon: "chevron-right"
pointSize: Style.fontSizeL
color: root.expanded ? Color.mOnSecondary : Color.mOnPrimary
Layout.alignment: Qt.AlignVCenter
rotation: root.expanded ? 90 : 0
Behavior on rotation {
enabled: root._userInteracted
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
Behavior on color {
enabled: root._userInteracted
ColorAnimation {
duration: Style.animationNormal
}
}
}
// Header text content - properly contained
RowLayout {
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter
spacing: Style.marginL
NText {
text: root.label
pointSize: Style.fontSizeL
font.weight: Style.fontWeightSemiBold
color: root.expanded ? Color.mOnSecondary : Color.mOnPrimary
wrapMode: Text.WordWrap
Behavior on color {
enabled: root._userInteracted
ColorAnimation {
duration: Style.animationNormal
}
}
}
NText {
text: root.description
pointSize: Style.fontSizeS
font.weight: Style.fontWeightRegular
color: root.expanded ? Color.mOnSecondary : Color.mOnPrimary
Layout.fillWidth: true
wrapMode: Text.WordWrap
visible: root.description !== ""
opacity: 0.87
Behavior on color {
enabled: root._userInteracted
ColorAnimation {
duration: Style.animationNormal
}
}
}
}
}
}
// Collapsible content with Material 3 styling
Rectangle {
id: contentContainer
Layout.fillWidth: true
Layout.topMargin: Style.marginS
visible: root.expanded
color: Color.mSurface
radius: Style.iRadiusL
border.color: Color.mOutline
border.width: Style.borderS
// Dynamic height based on content
Layout.preferredHeight: expanded ? contentLayout.implicitHeight + Style.margin2L : 0
// Smooth height animation
Behavior on Layout.preferredHeight {
enabled: root._userInteracted
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
// Content layout
ColumnLayout {
id: contentLayout
anchors.fill: parent
anchors.margins: Style.marginL
spacing: root.contentSpacing
}
// Fade in animation for content
opacity: root.expanded ? 1.0 : 0.0
Behavior on opacity {
enabled: root._userInteracted
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
}
}
@@ -0,0 +1,89 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
RowLayout {
id: root
property string label: I18n.tr("common.select-color")
property string description: I18n.tr("common.select-color-description")
property string tooltip: ""
property string currentKey: ""
property var defaultValue: undefined
property var noneColor: undefined // color declared as var so we can nullify
property var noneOnColor: undefined // color declared as var so we can nullify
readonly property bool isValueChanged: (defaultValue !== undefined) && (currentKey !== defaultValue)
readonly property string indicatorTooltip: {
I18n.tr("panels.indicator.default-value", {
"value": defaultValue === "" ? "(empty)" : String(defaultValue)
});
}
readonly property int diameter: Style.baseWidgetSize * 0.9 * Style.uiScaleRatio
signal selected(string key)
NLabel {
label: root.label
description: root.description
showIndicator: root.isValueChanged
indicatorTooltip: root.indicatorTooltip
}
RowLayout {
id: colourRow
opacity: enabled ? 1.0 : 0.6
Layout.minimumWidth: root.diameter * Color.colorKeyModel.length
Repeater {
model: Color.colorKeyModel
Rectangle {
id: colorCircle
property bool isSelected: root.currentKey === modelData.key
property bool isHovered: circleMouseArea.containsMouse
Layout.alignment: Qt.AlignHCenter
implicitWidth: root.diameter
implicitHeight: root.diameter
radius: root.diameter * 0.5
color: (modelData.key === "none" && root.noneColor !== undefined) ? root.noneColor : Color.resolveColorKey(modelData.key)
border.color: (isSelected || isHovered) ? Color.mOnSurface : Color.mOutline
border.width: Style.borderM
MouseArea {
id: circleMouseArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onEntered: TooltipService.show(parent, modelData.name)
onExited: TooltipService.hide()
onClicked: {
root.currentKey = modelData.key;
root.selected(modelData.key);
}
}
NIcon {
anchors.centerIn: parent
icon: "check"
pointSize: Math.max(Style.fontSizeXS, colorCircle.width * 0.4)
color: (modelData.key === "none" && root.noneOnColor !== undefined) ? root.noneOnColor : Color.resolveOnColorKey(modelData.key)
font.weight: Style.fontWeightBold
visible: colorCircle.isSelected
}
Behavior on border.color {
ColorAnimation {
duration: Style.animationFast
}
}
}
}
}
}
@@ -0,0 +1,76 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
Rectangle {
id: root
property var screen
property color selectedColor: "black"
signal colorSelected(color color)
Layout.margins: Style.borderS
implicitWidth: 150
implicitHeight: Math.round(Style.baseWidgetSize * 1.1)
radius: Style.iRadiusM
color: Color.mSurface
border.color: Color.mOutline
border.width: Style.borderS
// Minimized Look
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
onClicked: {
var dialog = Qt.createComponent("NColorPickerDialog.qml").createObject(root, {
"selectedColor": selectedColor,
"parent": Overlay.overlay,
"screen": root.screen
});
// Connect the dialog's signal to the picker's signal
dialog.colorSelected.connect(function (color) {
root.selectedColor = color;
root.colorSelected(color);
});
dialog.open();
}
RowLayout {
anchors.fill: parent
anchors {
leftMargin: Style.marginL
rightMargin: Style.marginL
}
spacing: Style.marginS
// Color preview circle
Rectangle {
Layout.preferredWidth: root.height * 0.6
Layout.preferredHeight: root.height * 0.6
radius: Math.min(Style.iRadiusL, Layout.preferredWidth / 2)
color: root.selectedColor
border.color: Color.mOutline
border.width: Style.borderS
}
NText {
text: root.selectedColor.toString().toUpperCase()
family: Settings.data.ui.fontFixed
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter
}
NIcon {
icon: "color-picker"
color: Color.mOnSurfaceVariant
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter
}
}
}
}
@@ -0,0 +1,775 @@
import QtQml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "../Helpers/ColorList.js" as ColorList
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
import qs.compat.noctalia.Widgets
Popup {
id: root
property var screen
property color selectedColor: "black"
enum EditMode {
R,
G,
B,
H,
S,
V
}
property int editMode: NColorPickerDialog.EditMode.R
// Code to deal with Hue when color is achromatic
property real stableHue: 0
onSelectedColorChanged: {
if (selectedColor.hsvHue >= 0) {
stableHue = selectedColor.hsvHue;
}
if (liveMode && visible) {
colorSelected(selectedColor);
}
}
readonly property real displayHue: selectedColor.hsvHue < 0 ? stableHue : selectedColor.hsvHue
signal colorSelected(color color)
// When true: hides Cancel/Apply, emits colorSelected on every color change
property bool liveMode: false
width: 580
padding: Style.marginXL
modal: true
closePolicy: Popup.CloseOnEscape | Popup.CloseOnPressOutside
onOpened: {
// Center on screen after popup is opened and parent position is known
if (screen && parent) {
var parentPos = parent.mapToItem(null, 0, 0);
x = Math.round((screen.width - width) / 2 - parentPos.x);
y = Math.round((screen.height - height) / 2 - parentPos.y);
}
}
background: Rectangle {
color: Color.mSurface
radius: Style.iRadiusS
border.color: Color.mPrimary
border.width: Style.borderM
}
contentItem: ColumnLayout {
id: mainContent
spacing: Style.marginL
// Header
RowLayout {
Layout.fillWidth: true
RowLayout {
spacing: Style.marginS
NIcon {
icon: "color-picker"
pointSize: Style.fontSizeXXL
color: Color.mPrimary
}
NText {
text: I18n.tr("widgets.color-picker.title")
pointSize: Style.fontSizeXL
font.weight: Style.fontWeightBold
color: Color.mPrimary
}
}
Item {
Layout.fillWidth: true
}
NIconButton {
icon: "close"
onClicked: root.close()
}
}
// Color preview section
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: 80
radius: Style.iRadiusS
color: root.selectedColor
border.color: Color.mOutline
border.width: Style.borderS
ColumnLayout {
spacing: 0
anchors.fill: parent
Item {
Layout.fillHeight: true
}
NText {
text: root.selectedColor.toString().toUpperCase()
family: Settings.data.ui.fontFixed
pointSize: Style.fontSizeL
font.weight: Style.fontWeightMedium
color: root.selectedColor.r + root.selectedColor.g + root.selectedColor.b > 1.5 ? "black" : "white"
Layout.alignment: Qt.AlignHCenter
}
NText {
text: "RGB(" + Math.round(root.selectedColor.r * 255) + ", " + Math.round(root.selectedColor.g * 255) + ", " + Math.round(root.selectedColor.b * 255) + ")"
family: Settings.data.ui.fontFixed
pointSize: Style.fontSizeM
color: root.selectedColor.r + root.selectedColor.g + root.selectedColor.b > 1.5 ? "black" : "white"
Layout.alignment: Qt.AlignHCenter
}
Item {
Layout.fillHeight: true
}
}
}
// Main Box
NBox {
Layout.fillWidth: true
Layout.preferredHeight: controlsOutterColumn.implicitHeight + Style.margin2L
ButtonGroup {
id: colorValues
}
ColumnLayout {
id: controlsOutterColumn
anchors.fill: parent
anchors.margins: Style.marginL
spacing: Style.marginM
RowLayout {
spacing: Style.marginL // Ensure nice gap between Left and Right groups
// SpinBoxes Column
ColumnLayout {
Layout.fillWidth: true
Layout.fillHeight: true
Layout.alignment: Qt.AlignTop
Layout.preferredWidth: 3
// --- RED ---
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NRadioButton {
ButtonGroup.group: colorValues
text: "R"
font.weight: Style.fontWeightMedium
checked: true
onClicked: root.editMode = NColorPickerDialog.EditMode.R
Layout.fillWidth: false
}
NSpinBox {
id: redSpinBox
from: 0
to: 255
onValueChanged: {
if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.r * 255)) {
root.selectedColor = Qt.rgba(value / 255, root.selectedColor.g, root.selectedColor.b, 1);
}
}
Binding {
target: redSpinBox
property: "value"
value: Math.round(root.selectedColor.r * 255)
}
}
}
// --- GREEN ---
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NRadioButton {
ButtonGroup.group: colorValues
text: "G"
font.weight: Style.fontWeightMedium
onClicked: root.editMode = NColorPickerDialog.EditMode.G
Layout.fillWidth: false
}
NSpinBox {
id: greenSpinBox
from: 0
to: 255
onValueChanged: {
if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.g * 255)) {
root.selectedColor = Qt.rgba(root.selectedColor.r, value / 255, root.selectedColor.b, 1);
}
}
Binding {
target: greenSpinBox
property: "value"
value: Math.round(root.selectedColor.g * 255)
}
}
}
// --- BLUE ---
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NRadioButton {
ButtonGroup.group: colorValues
text: "B"
font.weight: Style.fontWeightMedium
onClicked: root.editMode = NColorPickerDialog.EditMode.B
Layout.fillWidth: false
}
NSpinBox {
id: blueSpinBox
from: 0
to: 255
onValueChanged: {
if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.b * 255)) {
root.selectedColor = Qt.rgba(root.selectedColor.r, root.selectedColor.g, value / 255, 1);
}
}
Binding {
target: blueSpinBox
property: "value"
value: Math.round(root.selectedColor.b * 255)
}
}
}
// Spacer
Item {
Layout.fillHeight: true
Layout.fillWidth: true
}
// --- HUE ---
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NRadioButton {
ButtonGroup.group: colorValues
text: "H"
font.weight: Style.fontWeightMedium
checked: true
onClicked: root.editMode = NColorPickerDialog.EditMode.H
Layout.fillWidth: false
}
NSpinBox {
id: hueSpinBox
from: 0
to: 360
onValueChanged: {
if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.displayHue * 360)) {
var newHue = value / 360;
root.selectedColor = Qt.hsva(newHue, root.selectedColor.hsvSaturation, root.selectedColor.hsvValue, 1);
root.stableHue = newHue;
}
}
Binding {
target: hueSpinBox
property: "value"
value: Math.round(root.displayHue * 360)
}
}
}
// --- SATURATION ---
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NRadioButton {
ButtonGroup.group: colorValues
text: "S"
font.weight: Style.fontWeightMedium
onClicked: root.editMode = NColorPickerDialog.EditMode.S
Layout.fillWidth: false
}
NSpinBox {
id: satSpinBox
from: 0
to: 100
onValueChanged: {
if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.hsvSaturation * 100)) {
root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, value / 100, root.selectedColor.hsvValue, 1);
}
}
Binding {
target: satSpinBox
property: "value"
value: Math.round(root.selectedColor.hsvSaturation * 100)
}
}
}
// --- VALUE ---
RowLayout {
spacing: Style.marginM
NRadioButton {
ButtonGroup.group: colorValues
text: "V"
font.weight: Style.fontWeightMedium
onClicked: root.editMode = NColorPickerDialog.EditMode.V
Layout.fillWidth: false
}
NSpinBox {
id: valSpinBox
from: 0
to: 100
onValueChanged: {
if (!selectedSlider.pressed && !fieldMouse.pressed && !hexInput.activeFocus && value !== Math.round(root.selectedColor.hsvValue * 100)) {
root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, root.selectedColor.hsvSaturation, value / 100, 1);
}
}
Binding {
target: valSpinBox
property: "value"
value: Math.round(root.selectedColor.hsvValue * 100)
}
}
}
// Spacer
Item {
Layout.fillHeight: true
Layout.fillWidth: true
}
// Hex input
RowLayout {
id: hexInput
Layout.fillWidth: true
spacing: Style.marginM
NLabel {
label: "Hex:"
Layout.alignment: Qt.AlignVCenter
}
NTextInput {
text: root.selectedColor.toString().toUpperCase()
fontFamily: Settings.data.ui.fontFixed
Layout.fillWidth: true
Layout.minimumWidth: implicitWidth
onEditingFinished: {
if (/^#[0-9A-F]{6}$/i.test(text)) {
root.selectedColor = text;
}
}
}
}
}
RowLayout {
Layout.fillWidth: true
Layout.fillHeight: true
Layout.preferredWidth: 5
Layout.alignment: Qt.AlignTop
spacing: Style.marginS
Layout.topMargin: Math.round(2 * Style.uiScaleRatio) //Shim to try and line up colorField with SpinBoxes
// --- SLIDER ---
NColorSlider {
id: selectedSlider
Layout.fillHeight: true
rainbowMode: root.editMode === NColorPickerDialog.EditMode.H
topColor: {
if (rainbowMode)
return "transparent";
switch (root.editMode) {
case NColorPickerDialog.EditMode.R:
return "#FF0000";
case NColorPickerDialog.EditMode.G:
return "#00FF00";
case NColorPickerDialog.EditMode.B:
return "#0000FF";
default:
return "#FFFFFF";
}
}
Binding {
target: selectedSlider
property: "value"
when: !selectedSlider.pressed // Only update from model when NOT dragging
value: {
switch (root.editMode) {
case NColorPickerDialog.EditMode.R:
return root.selectedColor.r;
case NColorPickerDialog.EditMode.G:
return root.selectedColor.g;
case NColorPickerDialog.EditMode.B:
return root.selectedColor.b;
case NColorPickerDialog.EditMode.H:
return root.displayHue;
case NColorPickerDialog.EditMode.S:
return root.selectedColor.hsvSaturation;
case NColorPickerDialog.EditMode.V:
return root.selectedColor.hsvValue;
default:
return 0;
}
}
}
onMoved: {
var v = value;
switch (root.editMode) {
case NColorPickerDialog.EditMode.R:
root.selectedColor = Qt.rgba(v, root.selectedColor.g, root.selectedColor.b, 1);
break;
case NColorPickerDialog.EditMode.G:
root.selectedColor = Qt.rgba(root.selectedColor.r, v, root.selectedColor.b, 1);
break;
case NColorPickerDialog.EditMode.B:
root.selectedColor = Qt.rgba(root.selectedColor.r, root.selectedColor.g, v, 1);
break;
case NColorPickerDialog.EditMode.H:
root.selectedColor = Qt.hsva(v, root.selectedColor.hsvSaturation, root.selectedColor.hsvValue, 1);
root.stableHue = v;
break;
case NColorPickerDialog.EditMode.S:
root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, v, root.selectedColor.hsvValue, 1);
break;
case NColorPickerDialog.EditMode.V:
root.selectedColor = Qt.hsva(root.selectedColor.hsvHue, root.selectedColor.hsvSaturation, v, 1);
break;
}
}
}
// Color Field
Rectangle {
id: colorField
Layout.fillWidth: true
Layout.preferredHeight: width
Layout.alignment: Qt.AlignTop
radius: 0
border.color: Color.mOutline
border.width: Style.borderS
clip: true
ShaderEffect {
anchors.fill: parent
anchors.margins: 1 // Avoid drawing over the border
fragmentShader: "../Shaders/qsb/color_picker.frag.qsb"
// Pass which radio is selected
readonly property real fixedVal: {
switch (root.editMode) {
case NColorPickerDialog.EditMode.R:
return root.selectedColor.r;
case NColorPickerDialog.EditMode.G:
return root.selectedColor.g;
case NColorPickerDialog.EditMode.B:
return root.selectedColor.b;
case NColorPickerDialog.EditMode.H:
return root.displayHue;
case NColorPickerDialog.EditMode.S:
return root.selectedColor.hsvSaturation;
case NColorPickerDialog.EditMode.V:
return root.selectedColor.hsvValue;
default:
return 0;
}
}
// Send as one vector because GPUs are so damn picky
property vector4d params: Qt.vector4d(1.0, fixedVal, root.editMode, 0)
}
MouseArea {
id: fieldMouse
anchors.fill: parent
cursorShape: Qt.CrossCursor
// Update color when clicking or dragging
function updateColor(mouse) {
// Normalize X and Y (0.0 to 1.0)
var xVal = Math.max(0, Math.min(1, mouse.x / width));
var yVal = Math.max(0, Math.min(1, 1.0 - (mouse.y / height))); // Flip Y (0 at bottom)
// Get the current fixed value (from the slider)
var fixed = 0.0;
switch (root.editMode) {
case NColorPickerDialog.EditMode.R:
fixed = root.selectedColor.r;
root.selectedColor = Qt.rgba(fixed, xVal, yVal, 1);
break;
case NColorPickerDialog.EditMode.G:
fixed = root.selectedColor.g;
root.selectedColor = Qt.rgba(xVal, fixed, yVal, 1);
break;
case NColorPickerDialog.EditMode.B:
fixed = root.selectedColor.b;
root.selectedColor = Qt.rgba(xVal, yVal, fixed, 1);
break;
case NColorPickerDialog.EditMode.H:
// Use stableHue to prevent flipping to -1
fixed = root.displayHue;
root.selectedColor = Qt.hsva(fixed, xVal, yVal, 1);
root.stableHue = fixed;
break;
case NColorPickerDialog.EditMode.S:
fixed = root.selectedColor.hsvSaturation;
root.selectedColor = Qt.hsva(xVal, fixed, yVal, 1);
// If we dragged Hue (xVal), update stableHue
root.stableHue = yVal;
break;
case NColorPickerDialog.EditMode.V:
fixed = root.selectedColor.hsvValue;
root.selectedColor = Qt.hsva(xVal, yVal, fixed, 1);
// If we dragged Hue (xVal), update stableHue
root.stableHue = xVal;
break;
}
}
onPressed: mouse => updateColor(mouse)
onPositionChanged: mouse => updateColor(mouse)
}
// Color Indicator
Rectangle {
width: 10
height: 10
radius: Math.min(Style.iRadiusXS, width / 2)
color: "transparent"
border.color: root.selectedColor.hsvValue < 0.5 ? "white" : "black"
border.width: 1
// Find position based on the current color
readonly property point selectedPos: {
switch (root.editMode) {
case NColorPickerDialog.EditMode.R:
return Qt.point(root.selectedColor.g, root.selectedColor.b);
case NColorPickerDialog.EditMode.G:
return Qt.point(root.selectedColor.r, root.selectedColor.b);
case NColorPickerDialog.EditMode.B:
return Qt.point(root.selectedColor.r, root.selectedColor.g);
case NColorPickerDialog.EditMode.H:
return Qt.point(root.selectedColor.hsvSaturation, root.selectedColor.hsvValue);
case NColorPickerDialog.EditMode.S:
return Qt.point(root.displayHue, root.selectedColor.hsvValue);
case NColorPickerDialog.EditMode.V:
return Qt.point(root.displayHue, root.selectedColor.hsvSaturation);
default:
return Qt.point(0, 0);
}
}
// Convert values to pixel position
x: (selectedPos.x * parent.width) - width / 2
y: ((1.0 - selectedPos.y) * parent.height) - height / 2
}
// Redraw the border in case Color Indicator is near the edge
Rectangle {
anchors.fill: parent
color: "transparent"
border.color: Color.mOutline
border.width: Style.borderS
antialiasing: false
}
}
}
}
NLabel {
label: I18n.tr("widgets.color-picker.palette-label")
Layout.fillWidth: true
}
NScrollView {
id: paletteScrollView
Layout.fillWidth: true
Layout.preferredHeight: Math.min(paletteGrid.implicitHeight, 200)
verticalPolicy: paletteGrid.implicitHeight > 200 ? ScrollBar.AsNeeded : ScrollBar.AlwaysOff
horizontalPolicy: ScrollBar.AlwaysOff
GridLayout {
id: paletteGrid
width: paletteScrollView.availableWidth
columns: 17
columnSpacing: 6
rowSpacing: 6
NLabel {
Layout.columnSpan: 17
Layout.fillWidth: true
description: I18n.tr("widgets.color-picker.palette-theme-colors")
}
Repeater {
model: [
{
name: "mPrimary",
color: Color.mPrimary
},
{
name: "mSecondary",
color: Color.mSecondary
},
{
name: "mTertiary",
color: Color.mTertiary
},
{
name: "mError",
color: Color.mError
},
{
name: "mSurface",
color: Color.mSurface
},
{
name: "mSurfaceVariant",
color: Color.mSurfaceVariant
},
{
name: "mOutline",
color: Color.mOutline
}
]
Rectangle {
width: 24
height: 24
radius: Style.iRadiusXXS
color: modelData.color
border.color: root.selectedColor.toString() === modelData.color.toString() ? Color.mPrimary : Color.mOutline
border.width: Math.max(1, root.selectedColor.toString() === modelData.color.toString() ? Style.borderM : Style.borderS)
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
hoverEnabled: true
onEntered: {
TooltipService.show(parent, modelData.name + "\n" + parent.color.toString().toUpperCase());
}
onExited: {
TooltipService.hide();
}
onClicked: {
root.selectedColor = modelData.color;
TooltipService.hide();
}
}
}
}
NDivider {
Layout.columnSpan: 17
Layout.fillWidth: true
Layout.topMargin: Style.marginXS
Layout.bottomMargin: 0
}
NLabel {
Layout.columnSpan: 17
Layout.fillWidth: true
description: I18n.tr("widgets.color-picker.palette-description")
}
Repeater {
model: ColorList.colors
Rectangle {
width: 24
height: 24
radius: Math.min(Style.iRadiusXS, width / 2)
color: modelData.color
border.color: root.selectedColor.toString() === modelData.color.toString() ? Color.mPrimary : Color.mOutline
border.width: root.selectedColor.toString() === modelData.color.toString() ? 2 : 1
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
hoverEnabled: true
onEntered: {
TooltipService.show(parent, modelData.name + "\n" + parent.color.toString().toUpperCase(), "auto");
}
onExited: {
TooltipService.hide();
}
onClicked: {
root.selectedColor = modelData.color;
TooltipService.hide();
}
}
}
}
}
}
}
}
RowLayout {
visible: !root.liveMode
Layout.fillWidth: true
Layout.topMargin: 1
Layout.bottomMargin: 1
spacing: 10
Item {
Layout.fillWidth: true
}
NButton {
id: cancelButton
text: I18n.tr("common.cancel")
outlined: cancelButton.hovered ? false : true
onClicked: {
root.close();
}
}
NButton {
text: I18n.tr("common.apply")
icon: "check"
onClicked: {
root.colorSelected(root.selectedColor);
// Delay close to prevent click propagation to elements behind the dialog
Qt.callLater(() => {
root.close();
});
}
}
}
}
}
@@ -0,0 +1,238 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Shapes
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
Slider {
id: root
property color fillColor: "transparent"
property var cutoutColor: Color.mSurface
property bool snapAlways: true
property real widthRatio: 0.7
property var tooltipText
property string tooltipDirection: "auto"
property bool hovering: false
property color topColor: "white"
property color bottomColor: "black"
property bool rainbowMode: false
readonly property real knobDiameter: Math.round((Style.baseWidgetSize * widthRatio * Style.uiScaleRatio) / 2) * 2
readonly property real trackWidth: Math.round((knobDiameter * 0.4 * Style.uiScaleRatio) / 2) * 2
readonly property real trackRadius: Math.min(Style.iRadiusL, trackWidth / 2)
readonly property real cutoutExtra: Math.round((Style.baseWidgetSize * 0.1 * Style.uiScaleRatio) / 2) * 2
orientation: Qt.Vertical
padding: cutoutExtra / 2
snapMode: snapAlways ? Slider.SnapAlways : Slider.SnapOnRelease
implicitWidth: Math.max(trackWidth, knobDiameter)
background: Item {
id: bgContainer
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
width: root.trackWidth
height: root.availableHeight
LinearGradient {
id: standardLinearGradient
x1: 0
y1: 0
x2: 0
y2: root.availableHeight
GradientStop {
position: 0.0
color: root.topColor
}
GradientStop {
position: 1.0
color: root.bottomColor
}
}
LinearGradient {
id: rainbowLinearGradient
x1: 0
y1: 0
x2: 0
y2: root.availableHeight
GradientStop {
position: 0.000
color: "#FF0000"
}
GradientStop {
position: 0.167
color: "#FF00FF"
}
GradientStop {
position: 0.333
color: "#0000FF"
}
GradientStop {
position: 0.500
color: "#00FFFF"
}
GradientStop {
position: 0.667
color: "#00FF00"
}
GradientStop {
position: 0.833
color: "#FFFF00"
}
GradientStop {
position: 1.000
color: "#FF0000"
}
}
Shape {
anchors.centerIn: parent
width: root.trackWidth
height: bgContainer.height
visible: root.trackWidth > 0 && bgContainer.height > 0
preferredRendererType: Shape.CurveRenderer
asynchronous: true
ShapePath {
id: trackPath
strokeColor: Qt.alpha(Color.mOutline, 0.5)
strokeWidth: Style.borderS
fillGradient: root.rainbowMode ? rainbowLinearGradient : standardLinearGradient
readonly property real w: root.trackWidth
readonly property real h: root.availableHeight
readonly property real r: root.trackRadius
startX: r
startY: 0
PathLine {
x: trackPath.w - trackPath.r
y: 0
}
PathArc {
x: trackPath.w
y: trackPath.r
radiusX: trackPath.r
radiusY: trackPath.r
}
PathLine {
x: trackPath.w
y: trackPath.h - trackPath.r
}
PathArc {
x: trackPath.w - trackPath.r
y: trackPath.h
radiusX: trackPath.r
radiusY: trackPath.r
}
PathLine {
x: trackPath.r
y: trackPath.h
}
PathArc {
x: 0
y: trackPath.h - trackPath.r
radiusX: trackPath.r
radiusY: trackPath.r
}
PathLine {
x: 0
y: trackPath.r
}
PathArc {
x: trackPath.r
y: 0
radiusX: trackPath.r
radiusY: trackPath.r
}
}
}
// Circular cutout
Rectangle {
id: knobCutout
implicitWidth: root.knobDiameter + root.cutoutExtra
implicitHeight: root.knobDiameter + root.cutoutExtra
radius: Math.min(Style.iRadiusL, width / 2)
color: root.cutoutColor !== undefined ? root.cutoutColor : Color.mSurface
y: root.visualPosition * (root.availableHeight - root.knobDiameter) - root.cutoutExtra / 2
anchors.horizontalCenter: parent.horizontalCenter
}
}
handle: Item {
implicitWidth: root.knobDiameter
implicitHeight: root.knobDiameter
y: root.topPadding + root.visualPosition * (root.availableHeight - height)
anchors.horizontalCenter: parent.horizontalCenter
Rectangle {
id: knob
implicitWidth: root.knobDiameter
implicitHeight: root.knobDiameter
radius: Math.min(Style.iRadiusL, width / 2)
color: {
if (root.rainbowMode) {
// Hue Logic: Map position (0.0 to 1.0) directly to Hue
return Qt.hsva(1 - root.visualPosition, 1, 1, 1);
} else {
// Linear Interpolation for Standard Gradients
// visualPosition 0.0 = Top, 1.0 = Bottom
var t = root.visualPosition;
var r = root.topColor.r * (1 - t) + root.bottomColor.r * t;
var g = root.topColor.g * (1 - t) + root.bottomColor.g * t;
var b = root.topColor.b * (1 - t) + root.bottomColor.b * t;
return Qt.rgba(r, g, b, 1);
}
}
border.color: root.pressed ? Color.mHover : Color.mPrimary
border.width: Style.borderL
anchors.centerIn: parent
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
MouseArea {
enabled: true
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
hoverEnabled: true
acceptedButtons: Qt.NoButton // Don't accept any mouse buttons - only hover
propagateComposedEvents: true
onEntered: {
root.hovering = true;
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.show(knob, root.tooltipText, root.tooltipDirection);
}
}
onExited: {
root.hovering = false;
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
}
// Hide tooltip when slider is pressed (anywhere on the slider)
Connections {
target: root
function onPressedChanged() {
if (root.pressed && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
}
}
}
@@ -0,0 +1,330 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
import qs.compat.noctalia.Widgets
RowLayout {
id: root
property real minimumWidth: 200
property real popupHeight: 180
property string label: ""
property string description: ""
property string tooltip: ""
property var model
property string currentKey: ""
property string placeholder: ""
property var defaultValue: undefined
property string settingsPath: ""
property real baseSize: 1.0
readonly property real preferredHeight: Math.round(Style.baseWidgetSize * 1.1 * root.baseSize)
readonly property var comboBox: combo
signal selected(string key)
spacing: Style.marginL
// Less strict comparison with != (instead of !==) so it can properly compare int vs string (ex for FPS: 30 and "30")
readonly property bool isValueChanged: (defaultValue !== undefined) && (currentKey != defaultValue)
readonly property string indicatorTooltip: {
if (defaultValue === undefined)
return "";
var displayValue = "";
if (defaultValue === "") {
// Try to find the display name for empty key in the model
var found = false;
if (root.model) {
if (Array.isArray(root.model)) {
for (var i = 0; i < root.model.length; i++) {
var item = root.model[i];
if (item && item.key === "") {
displayValue = item.name || I18n.tr("panels.indicator.system-default");
found = true;
break;
}
}
} else if (typeof root.model.get === 'function') {
for (var i = 0; i < root.itemCount(); i++) {
var item = root.getItem(i);
if (item && item.key === "") {
displayValue = item.name || I18n.tr("panels.indicator.system-default");
found = true;
break;
}
}
}
}
// If not found in model, show "System Default" instead of "(empty)"
if (!found) {
displayValue = I18n.tr("panels.indicator.system-default");
}
} else {
// Try to find the display name for the default key in the model
var found = false;
if (root.model) {
if (Array.isArray(root.model)) {
for (var i = 0; i < root.model.length; i++) {
var item = root.model[i];
if (item && item.key === defaultValue) {
displayValue = item.name || String(defaultValue);
found = true;
break;
}
}
} else if (typeof root.model.get === 'function') {
for (var i = 0; i < root.itemCount(); i++) {
var item = root.getItem(i);
if (item && item.key === defaultValue) {
displayValue = item.name || String(defaultValue);
found = true;
break;
}
}
}
}
if (!found) {
displayValue = String(defaultValue);
}
}
return I18n.tr("panels.indicator.default-value", {
"value": displayValue
});
}
function itemCount() {
if (!root.model)
return 0;
if (typeof root.model.count === 'number')
return root.model.count;
if (Array.isArray(root.model))
return root.model.length;
return 0;
}
function getItem(index) {
if (!root.model)
return null;
if (typeof root.model.get === 'function')
return root.model.get(index);
if (Array.isArray(root.model))
return root.model[index];
return null;
}
function findIndexByKey(key) {
for (var i = 0; i < itemCount(); i++) {
var item = getItem(i);
if (item && item.key === key)
return i;
}
return -1;
}
NLabel {
label: root.label
description: root.description
showIndicator: root.isValueChanged
indicatorTooltip: root.indicatorTooltip
}
ComboBox {
id: combo
opacity: enabled ? 1.0 : 0.6
Layout.margins: Style.borderS
Layout.minimumWidth: Math.round(root.minimumWidth * Style.uiScaleRatio)
Layout.preferredHeight: Math.round(root.preferredHeight * Style.uiScaleRatio)
implicitWidth: Layout.minimumWidth
model: root.model
textRole: "name"
currentIndex: root.findIndexByKey(root.currentKey)
onActivated: {
var item = root.getItem(combo.currentIndex);
if (item && item.key !== undefined)
root.selected(item.key);
}
Keys.onUpPressed: event => {
if (combo.popup.visible) {
if (listView.currentIndex > 0) {
listView.currentIndex--;
listView.positionViewAtIndex(listView.currentIndex, ListView.Contain);
}
event.accepted = true;
} else {
event.accepted = false;
}
}
Keys.onDownPressed: event => {
if (combo.popup.visible) {
if (listView.currentIndex < root.itemCount() - 1) {
listView.currentIndex++;
listView.positionViewAtIndex(listView.currentIndex, ListView.Contain);
}
event.accepted = true;
} else {
event.accepted = false;
}
}
Keys.onReturnPressed: event => {
if (combo.popup.visible) {
var item = root.getItem(listView.currentIndex);
if (item && item.key !== undefined) {
root.selected(item.key);
combo.currentIndex = listView.currentIndex;
combo.popup.close();
}
event.accepted = true;
} else {
event.accepted = false;
}
}
Keys.onEnterPressed: event => {
combo.Keys.returnPressed(event);
}
background: Rectangle {
implicitWidth: Math.round(Style.baseWidgetSize * 3.75 * Style.uiScaleRatio)
implicitHeight: Math.round(root.preferredHeight * Style.uiScaleRatio)
color: Color.mSurface
border.color: combo.activeFocus ? Color.mSecondary : Color.mOutline
border.width: Style.borderS
radius: Style.iRadiusM
Behavior on border.color {
ColorAnimation {
duration: Style.animationFast
}
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.NoButton
onEntered: {
if (root.tooltip != "") {
TooltipService.show(root, root.tooltip);
}
}
onExited: {
if (root.tooltip != "") {
TooltipService.hide();
}
}
}
}
contentItem: NText {
leftPadding: Style.marginL
rightPadding: combo.indicator.width + Style.marginL
pointSize: Style.fontSizeM
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
color: combo.currentIndex >= 0 ? Color.mOnSurface : Color.mOnSurfaceVariant
text: {
if (combo.currentIndex >= 0 && combo.currentIndex < root.itemCount()) {
var item = root.getItem(combo.currentIndex);
return item ? item.name : root.placeholder;
}
return root.placeholder;
}
}
indicator: NIcon {
x: combo.width - width - Style.marginM
y: combo.topPadding + (combo.availableHeight - height) / 2
icon: "caret-down"
pointSize: Style.fontSizeL
}
popup: Popup {
y: combo.height + Style.marginS
implicitWidth: combo.width
implicitHeight: Math.min(Math.round(root.popupHeight * Style.uiScaleRatio), listView.contentHeight + Style.margin2M)
padding: Style.marginM
onOpened: {
listView.currentIndex = combo.currentIndex;
listView.positionViewAtIndex(combo.currentIndex, ListView.Beginning);
}
contentItem: NListView {
id: listView
property var comboBox: combo
model: combo.popup.visible ? root.model : null
highlightMoveDuration: 0
//showGradientMasks: false
delegate: Rectangle {
id: delegateRect
required property int index
property bool isHighlighted: listView.currentIndex === index
width: listView.availableWidth
height: delegateText.implicitHeight + Style.margin2S
radius: Style.iRadiusS
color: isHighlighted ? Color.mHover : "transparent"
NText {
id: delegateText
anchors.fill: parent
anchors.leftMargin: Style.marginM
anchors.rightMargin: Style.marginM
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
pointSize: Style.fontSizeM
color: delegateRect.isHighlighted ? Color.mOnHover : Color.mOnSurface
text: {
var item = root.getItem(delegateRect.index);
return item && item.name ? item.name : "";
}
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onContainsMouseChanged: {
if (containsMouse) {
listView.currentIndex = delegateRect.index;
}
}
onClicked: {
var item = root.getItem(delegateRect.index);
if (item && item.key !== undefined) {
root.selected(item.key);
listView.comboBox.currentIndex = delegateRect.index;
listView.comboBox.popup.close();
}
}
}
}
}
background: Rectangle {
color: Color.mSurfaceVariant
border.color: Color.mOutline
border.width: Style.borderS
radius: Style.iRadiusM
}
}
Connections {
target: root
function onCurrentKeyChanged() {
combo.currentIndex = root.findIndexByKey(root.currentKey);
}
function onModelChanged() {
combo.currentIndex = root.findIndexByKey(root.currentKey);
}
}
}
}
@@ -0,0 +1,182 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
/*
* NContextMenu - Popup-based context menu for use inside panels and dialogs
*
* Use this component when you need a context menu inside:
* - Settings panels
* - Dialogs
* - Repeater delegates
* - Any nested component context
*
* For bar widgets and top-level window contexts, use NPopupContextMenu instead,
* which provides better screen boundary handling and compositor integration.
*
* Usage:
* NContextMenu {
* id: contextMenu
* parent: Overlay.overlay
* model: [
* { "label": "Action 1", "action": "action1", "icon": "icon-name" },
* { "label": "Action 2", "action": "action2" }
* ]
* onTriggered: action => { Logger.i("MyModule", "Selected:", action) }
* }
*
* MouseArea {
* onClicked: contextMenu.openAtItem(parent, mouse.x, mouse.y)
* }
*/
Popup {
id: root
property var model: []
property real itemHeight: 36
property real itemPadding: Style.marginM
property int verticalPolicy: ScrollBar.AsNeeded
property int horizontalPolicy: ScrollBar.AsNeeded
// Optional: explicit item whose bounds the menu must stay within.
// When unset, openAtItem auto-detects the nearest clipping ancestor.
property Item constrainTo: null
property Item _detectedConstraint: null
signal triggered(string action)
// Filter out hidden items to avoid spacing artifacts from zero-height items
readonly property var filteredModel: {
if (!model || model.length === 0)
return [];
var filtered = [];
for (var i = 0; i < model.length; i++) {
if (model[i].visible !== false) {
filtered.push(model[i]);
}
}
return filtered;
}
width: 180
padding: Style.marginS
background: Rectangle {
color: Color.mSurfaceVariant
border.color: Color.mOutline
border.width: Style.borderS
radius: Style.iRadiusM
}
contentItem: NListView {
id: listView
implicitHeight: Math.max(contentHeight, root.itemHeight)
spacing: Style.marginXXS
interactive: contentHeight > root.height
verticalPolicy: root.verticalPolicy
horizontalPolicy: root.horizontalPolicy
reserveScrollbarSpace: false
model: root.filteredModel
delegate: ItemDelegate {
id: menuItem
width: listView.availableWidth
height: root.itemHeight
opacity: modelData.enabled !== false ? 1.0 : 0.5
enabled: modelData.enabled !== false
// Store reference to the popup
property var popup: root
background: Rectangle {
color: menuItem.hovered && menuItem.enabled ? Color.mHover : "transparent"
radius: Style.iRadiusS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
contentItem: RowLayout {
spacing: Style.marginS
// Optional icon
NIcon {
visible: modelData.icon !== undefined
icon: modelData.icon || ""
pointSize: Style.fontSizeM
color: menuItem.hovered && menuItem.enabled ? Color.mOnHover : Color.mOnSurface
Layout.leftMargin: root.itemPadding
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
NText {
text: modelData.label || modelData.text || ""
pointSize: Style.fontSizeM
color: menuItem.hovered && menuItem.enabled ? Color.mOnHover : Color.mOnSurface
verticalAlignment: Text.AlignVCenter
Layout.fillWidth: true
Layout.leftMargin: modelData.icon === undefined ? root.itemPadding : 0
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
}
onClicked: {
if (enabled) {
popup.triggered(modelData.action || modelData.key || index.toString());
popup.close();
}
}
}
}
// Helper function to open at mouse position
function openAt(x, y) {
if (root.parent) {
var menuWidth = root.width;
var itemCount = root.filteredModel.length;
var menuHeight = Math.max(itemCount * root.itemHeight + Math.max(0, itemCount - 1) * listView.spacing, root.itemHeight) + root.topPadding + root.bottomPadding;
var constraint = root.constrainTo || root._detectedConstraint;
if (constraint) {
var tl = constraint.mapToItem(root.parent, 0, 0);
x = Math.max(tl.x, Math.min(x, tl.x + constraint.width - menuWidth));
y = Math.max(tl.y, Math.min(y, tl.y + constraint.height - menuHeight));
} else {
x = Math.max(0, Math.min(x, root.parent.width - menuWidth));
y = Math.max(0, Math.min(y, root.parent.height - menuHeight));
}
}
root.x = x;
root.y = y;
root.open();
}
// Helper function to open at item
function openAtItem(item, mouseX, mouseY) {
if (!root.constrainTo) {
root._detectedConstraint = null;
var p = item;
while (p && p !== root.parent) {
if (p.clip && p.width > 0 && p.height > 0) {
root._detectedConstraint = p;
break;
}
p = p.parent;
}
}
var pos = item.mapToItem(root.parent, mouseX || 0, mouseY || 0);
openAt(pos.x, pos.y);
}
}
@@ -0,0 +1,393 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
Rectangle {
id: root
property date sampleDate: new Date() // Dec 25, 2023, 2:30:45.123 PM
signal tokenClicked(string token)
Layout.margins: Style.borderS
color: Color.mSurface
border.color: Color.mOutline
border.width: Style.borderS
radius: Style.iRadiusM
ColumnLayout {
id: column
anchors.fill: parent
anchors.margins: Style.marginS
spacing: Style.marginS
Flickable {
Layout.fillWidth: true
Layout.fillHeight: true
contentHeight: tokensColumn.implicitHeight
clip: true
Column {
id: tokensColumn
width: parent.width
Repeater {
model: [
// Common format combinations
{
"category": "Common",
"token": "h:mm AP",
"description": I18n.tr("widgets.datetime-tokens.common-12hour-time-minutes"),
"example": "2:30 PM"
},
{
"category": "Common",
"token": "HH:mm",
"description": I18n.tr("widgets.datetime-tokens.common-24hour-time-minutes"),
"example": "14:30"
},
{
"category": "Common",
"token": "HH:mm:ss",
"description": I18n.tr("widgets.datetime-tokens.common-24hour-time-seconds"),
"example": "14:30:45"
},
{
"category": "Common",
"token": "ddd MMM d",
"description": I18n.tr("widgets.datetime-tokens.common-weekday-month-day"),
"example": "Mon Dec 25"
},
{
"category": "Common",
"token": "yyyy-MM-dd",
"description": I18n.tr("widgets.datetime-tokens.common-iso-date"),
"example": "2023-12-25"
},
{
"category": "Common",
"token": "MM/dd/yyyy",
"description": I18n.tr("widgets.datetime-tokens.common-us-date"),
"example": "12/25/2023"
},
{
"category": "Common",
"token": "dd.MM.yyyy",
"description": I18n.tr("widgets.datetime-tokens.common-european-date"),
"example": "25.12.2023"
},
{
"category": "Common",
"token": "ddd, MMM dd",
"description": I18n.tr("widgets.datetime-tokens.common-weekday-date"),
"example": "Fri, Dec 12"
} // Hour tokens
,
{
"category": "Hour",
"token": "H",
"description": I18n.tr("widgets.datetime-tokens.hour-no-leading-zero"),
"example": "14"
},
{
"category": "Hour",
"token": "HH",
"description": I18n.tr("widgets.datetime-tokens.hour-leading-zero"),
"example": "14"
} // Minute tokens
,
{
"category": "Minute",
"token": "m",
"description": I18n.tr("widgets.datetime-tokens.minute-no-leading-zero"),
"example": "30"
},
{
"category": "Minute",
"token": "mm",
"description": I18n.tr("widgets.datetime-tokens.minute-leading-zero"),
"example": "30"
} // Second tokens
,
{
"category": "Second",
"token": "s",
"description": I18n.tr("widgets.datetime-tokens.second-no-leading-zero"),
"example": "45"
},
{
"category": "Second",
"token": "ss",
"description": I18n.tr("widgets.datetime-tokens.second-leading-zero"),
"example": "45"
} // AM/PM tokens
,
{
"category": "AM/PM",
"token": "AP",
"description": I18n.tr("widgets.datetime-tokens.ampm-uppercase"),
"example": "PM"
},
{
"category": "AM/PM",
"token": "ap",
"description": I18n.tr("widgets.datetime-tokens.ampm-lowercase"),
"example": "pm"
} // Timezone tokens
,
{
"category": "Timezone",
"token": "t",
"description": I18n.tr("widgets.datetime-tokens.timezone-abbreviation"),
"example": "UTC"
} // Year tokens
,
{
"category": "Year",
"token": "yy",
"description": I18n.tr("widgets.datetime-tokens.year-two-digit"),
"example": "23"
},
{
"category": "Year",
"token": "yyyy",
"description": I18n.tr("widgets.datetime-tokens.year-four-digit"),
"example": "2023"
} // Month tokens
,
{
"category": "Month",
"token": "M",
"description": I18n.tr("widgets.datetime-tokens.month-number-no-zero"),
"example": "12"
},
{
"category": "Month",
"token": "MM",
"description": I18n.tr("widgets.datetime-tokens.month-number-leading-zero"),
"example": "12"
},
{
"category": "Month",
"token": "MMM",
"description": I18n.tr("widgets.datetime-tokens.month-abbreviated"),
"example": "Dec"
},
{
"category": "Month",
"token": "MMMM",
"description": I18n.tr("widgets.datetime-tokens.month-full"),
"example": "December"
} // Day tokens
,
{
"category": "Day",
"token": "d",
"description": I18n.tr("widgets.datetime-tokens.day-no-leading-zero"),
"example": "25"
},
{
"category": "Day",
"token": "dd",
"description": I18n.tr("widgets.datetime-tokens.day-leading-zero"),
"example": "25"
},
{
"category": "Day",
"token": "ddd",
"description": I18n.tr("widgets.datetime-tokens.day-abbreviated"),
"example": "Mon"
},
{
"category": "Day",
"token": "dddd",
"description": I18n.tr("widgets.datetime-tokens.day-full"),
"example": "Monday"
}
]
delegate: Rectangle {
id: tokenDelegate
width: tokensColumn.width
height: layout.implicitHeight + Style.marginS
radius: Style.iRadiusS
color: {
if (tokenMouseArea.containsMouse) {
return Qt.alpha(Color.mPrimary, 0.1);
}
return index % 2 === 0 ? Color.mSurfaceVariant : Qt.alpha(Color.mSurfaceVariant, 0.6);
}
// Mouse area for the entire delegate
MouseArea {
id: tokenMouseArea
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
root.tokenClicked(modelData.token);
clickAnimation.start();
}
}
// Click animation
SequentialAnimation {
id: clickAnimation
PropertyAnimation {
target: tokenDelegate
property: "color"
to: Qt.alpha(Color.mPrimary, 0.3)
duration: 100
}
PropertyAnimation {
target: tokenDelegate
property: "color"
to: tokenMouseArea.containsMouse ? Qt.alpha(Color.mPrimary, 0.1) : (index % 2 === 0 ? Color.mSurface : Color.mSurfaceVariant)
duration: 200
}
}
RowLayout {
id: layout
anchors.fill: parent
anchors.margins: Style.marginXS
spacing: Style.marginM
// Category badge
Rectangle {
Layout.alignment: Qt.AlignVCenter
width: 70
height: 22
color: getCategoryColor(modelData.category)[0]
radius: Style.iRadiusS
opacity: tokenMouseArea.containsMouse ? 0.9 : 1.0
Behavior on opacity {
NumberAnimation {
duration: Style.animationFast
}
}
NText {
anchors.centerIn: parent
text: modelData.category
color: getCategoryColor(modelData.category)[1]
pointSize: Style.fontSizeXS
}
}
// Token - Made more prominent and clickable
Rectangle {
id: tokenButton
Layout.alignment: Qt.AlignVCenter // Added this line
width: 100
height: 22
color: tokenMouseArea.containsMouse ? Color.mPrimary : Color.mOnSurface
radius: Style.iRadiusS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
NText {
anchors.centerIn: parent
text: modelData.token
color: tokenMouseArea.containsMouse ? Color.mOnPrimary : Color.mSurface
pointSize: Style.fontSizeS
font.weight: Style.fontWeightBold
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
}
// Description
NText {
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter // Added this line
text: modelData.description
color: tokenMouseArea.containsMouse ? Color.mOnSurface : Color.mOnSurfaceVariant
pointSize: Style.fontSizeS
wrapMode: Text.WordWrap
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
// Live example
Rectangle {
Layout.alignment: Qt.AlignVCenter // Added this line
width: 90
height: 22
color: tokenMouseArea.containsMouse ? Color.mPrimary : Color.mOnSurfaceVariant
radius: Style.iRadiusS
border.color: tokenMouseArea.containsMouse ? Color.mPrimary : Color.mOutline
border.width: Style.borderS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
Behavior on border.color {
ColorAnimation {
duration: Style.animationFast
}
}
NText {
anchors.centerIn: parent
text: I18n.locale.toString(root.sampleDate, modelData.token)
color: tokenMouseArea.containsMouse ? Color.mOnPrimary : Color.mSurfaceVariant
pointSize: Style.fontSizeS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
}
}
}
}
}
}
}
function getCategoryColor(category) {
switch (category) {
case "Year":
return [Color.mPrimary, Color.mOnPrimary];
case "Month":
return [Color.mSecondary, Color.mOnSecondary];
case "Day":
return [Color.mTertiary, Color.mOnTertiary];
case "Hour":
return [Color.mPrimary, Color.mOnPrimary];
case "Minute":
return [Color.mSecondary, Color.mOnSecondary];
case "Second":
return [Color.mTertiary, Color.mOnTertiary];
case "AM/PM":
return [Color.mError, Color.mOnError];
case "Timezone":
return [Color.mOnSurface, Color.mSurface];
case "Common":
return [Color.mError, Color.mOnError];
default:
return [Color.mOnSurfaceVariant, Color.mSurfaceVariant];
}
}
}
@@ -0,0 +1,30 @@
import QtQuick
import Quickshell
import Quickshell.Widgets
import qs.compat.noctalia.Commons
Rectangle {
property bool vertical: false
width: vertical ? Style.borderS : parent.width
height: vertical ? parent.height : Style.borderS
gradient: Gradient {
orientation: vertical ? Gradient.Vertical : Gradient.Horizontal
GradientStop {
position: 0.0
color: "transparent"
}
GradientStop {
position: 0.1
color: Color.mOutline
}
GradientStop {
position: 0.9
color: Color.mOutline
}
GradientStop {
position: 1.0
color: "transparent"
}
}
}
@@ -0,0 +1,31 @@
import QtQuick
import QtQuick.Effects
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.Power
// Unified shadow system
Item {
id: root
required property var source
property bool autoPaddingEnabled: false
property real shadowHorizontalOffset: Settings.data.general.shadowOffsetX
property real shadowVerticalOffset: Settings.data.general.shadowOffsetY
property real shadowOpacity: Style.shadowOpacity
property color shadowColor: "black"
property real shadowBlur: Style.shadowBlur
layer.enabled: Settings.data.general.enableShadows && !PowerProfileService.noctaliaPerformanceMode
layer.effect: MultiEffect {
source: root.source
shadowEnabled: true
blurMax: Style.shadowBlurMax
shadowBlur: root.shadowBlur
shadowOpacity: root.shadowOpacity
shadowColor: root.shadowColor
shadowHorizontalOffset: root.shadowHorizontalOffset
shadowVerticalOffset: root.shadowVerticalOffset
autoPaddingEnabled: root.autoPaddingEnabled
}
}
@@ -0,0 +1,817 @@
import Qt.labs.folderlistmodel
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import Quickshell
import Quickshell.Io
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
Popup {
id: root
// Properties
property string title: I18n.tr("widget.file-picker.title")
property string initialPath: Quickshell.env("HOME") || "/home"
property string selectionMode: "files" // "files" or "folders"
property var nameFilters: ["*"]
property bool showDirs: true
property bool showHiddenFiles: false
property bool allowMultiSelection: false
property var selectedPaths: []
property string currentPath: initialPath
property bool shouldResetSelection: false
// Signals
signal accepted(var paths)
signal cancelled
function openFilePicker() {
if (!root.currentPath)
root.currentPath = root.initialPath;
shouldResetSelection = true;
open();
}
function getFileIcon(fileName) {
const ext = fileName.split('.').pop().toLowerCase();
const iconMap = {
"txt": 'filepicker-file-text',
"md": 'filepicker-file-text',
"log": 'filepicker-file-text',
"jpg": 'filepicker-photo',
"jpeg": 'filepicker-photo',
"png": 'filepicker-photo',
"gif": 'filepicker-photo',
"bmp": 'filepicker-photo',
"svg": 'filepicker-photo',
"mp4": 'filepicker-video',
"avi": 'filepicker-video',
"mkv": 'filepicker-video',
"mov": 'filepicker-video',
"mp3": 'filepicker-music',
"wav": 'filepicker-music',
"flac": 'filepicker-music',
"ogg": 'filepicker-music',
"zip": 'filepicker-archive',
"tar": 'filepicker-archive',
"gz": 'filepicker-archive',
"rar": 'filepicker-archive',
"7z": 'filepicker-archive',
"pdf": 'filepicker-text',
"doc": 'filepicker-text',
"docx": 'filepicker-text',
"xls": 'filepicker-table',
"xlsx": 'filepicker-table',
"ppt": 'filepicker-presentation',
"pptx": 'filepicker-presentation',
"html": 'filepicker-code',
"htm": 'filepicker-code',
"css": 'filepicker-code',
"js": 'filepicker-code',
"json": 'filepicker-code',
"xml": 'filepicker-code',
"exe": 'filepicker-settings',
"app": 'filepicker-settings',
"deb": 'filepicker-settings',
"rpm": 'filepicker-settings'
};
return iconMap[ext] || 'filepicker-file';
}
function formatFileSize(bytes) {
if (bytes === 0)
return "0 B";
const k = 1024, sizes = ["B", "KB", "MB", "GB", "TB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}
function confirmSelection() {
if (filePickerPanel.currentSelection.length === 0)
return;
root.selectedPaths = filePickerPanel.currentSelection;
root.accepted(filePickerPanel.currentSelection);
root.close();
}
function updateFilteredModel() {
filteredModel.clear();
const searchText = filePickerPanel.filterText.toLowerCase();
for (var i = 0; i < folderModel.count; i++) {
const fileName = folderModel.get(i, "fileName");
const filePath = folderModel.get(i, "filePath");
const fileIsDir = folderModel.get(i, "fileIsDir");
const fileSize = folderModel.get(i, "fileSize");
// Skip hidden items if showHiddenFiles is false
// This additional check ensures hidden files are properly filtered
if (!root.showHiddenFiles && fileName.startsWith(".")) {
continue;
}
// In folder mode, hide files
if (root.selectionMode === "folders" && !fileIsDir)
continue;
if (searchText === "" || fileName.toLowerCase().includes(searchText)) {
filteredModel.append({
"fileName": fileName,
"filePath": filePath,
"fileIsDir": fileIsDir,
"fileSize": fileSize
});
}
}
}
width: 900
height: 700
modal: true
closePolicy: Popup.CloseOnEscape
anchors.centerIn: Overlay.overlay
background: Rectangle {
color: Color.mSurfaceVariant
radius: Style.iRadiusL
border.color: Color.mOutline
border.width: Style.borderS
}
Rectangle {
id: filePickerPanel
anchors.fill: parent
anchors.margins: Style.marginL
color: "transparent"
property string filterText: ""
property var currentSelection: []
property bool viewMode: true // true = grid, false = list
property string searchText: ""
property bool showSearchBar: false
focus: true
Keys.onPressed: event => {
if (event.modifiers & Qt.ControlModifier && event.key === Qt.Key_F) {
filePickerPanel.showSearchBar = !filePickerPanel.showSearchBar;
if (filePickerPanel.showSearchBar)
Qt.callLater(() => searchInput.forceActiveFocus());
event.accepted = true;
} else if (event.key === Qt.Key_Escape && filePickerPanel.showSearchBar) {
filePickerPanel.showSearchBar = false;
filePickerPanel.searchText = "";
filePickerPanel.filterText = "";
root.updateFilteredModel();
event.accepted = true;
}
}
// Function when an item is clicked, either a folder or a file since both have the same functionality, reduces repetitive code
function itemClicked(modifiers, path) {
var list = currentSelection.slice();
const index = list.indexOf(path);
if (root.allowMultiSelection && (modifiers & Qt.ShiftModifier) && list.length > 0) {
if (index > -1) {
list.splice(index, 1);
currentSelection = list;
} else {
var i = 0;
var toggle = false;
const firstItemPath = list[0];
while (i < filteredModel.count) {
const itemPath = filteredModel.get(i).filePath;
// This should be called twice, when we get to the item selected and when we get to the starting item.
if (itemPath === firstItemPath || itemPath === path) {
toggle = !toggle;
}
// Add all files between the starting item and the item selected.
if (toggle) {
if (!list.includes(itemPath)) {
list.push(itemPath);
}
}
i++;
}
// Add the path selected as well since it's skipped in the while loop
if (!list.includes(path)) {
list.push(path);
}
currentSelection = list;
}
} else if (root.allowMultiSelection && (modifiers & Qt.ControlModifier)) {
if (index > -1) {
list.splice(index, 1);
currentSelection = list;
} else {
list.push(path);
currentSelection = list;
}
} else {
currentSelection = [path];
}
}
ColumnLayout {
anchors.fill: parent
spacing: Style.marginM
// Header
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NIcon {
icon: "filepicker-folder"
color: Color.mPrimary
pointSize: Style.fontSizeXXL
}
NText {
text: root.title
pointSize: Style.fontSizeXL
font.weight: Style.fontWeightBold
color: Color.mPrimary
Layout.fillWidth: true
}
// "Select Current" button only visible in folder selection mode
NButton {
text: I18n.tr("widgets.file-picker.select-current")
icon: "filepicker-folder-current"
visible: root.selectionMode === "folders"
onClicked: {
filePickerPanel.currentSelection = [root.currentPath];
root.confirmSelection();
}
}
NIconButton {
icon: "filepicker-refresh"
tooltipText: I18n.tr("common.refresh")
onClicked: {
// Force a proper refresh by resetting the folder
const currentFolder = folderModel.folder;
folderModel.folder = "";
folderModel.folder = currentFolder;
Qt.callLater(root.updateFilteredModel);
}
}
NIconButton {
icon: "filepicker-close"
tooltipText: I18n.tr("common.close")
onClicked: {
root.cancelled();
root.close();
}
}
}
NDivider {
Layout.fillWidth: true
}
// Navigation toolbar
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: 45
color: Color.mSurfaceVariant
radius: Style.iRadiusS
border.color: Color.mOutline
border.width: Style.borderS
RowLayout {
anchors.left: parent.left
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
anchors.leftMargin: Style.marginS
anchors.rightMargin: Style.marginS
spacing: Style.marginS
NIconButton {
icon: "filepicker-arrow-up"
tooltipText: I18n.tr("tooltips.up")
baseSize: Style.baseWidgetSize * 0.8
enabled: folderModel.folder.toString() !== "file:///"
onClicked: {
const parentPath = folderModel.parentFolder.toString().replace("file://", "");
folderModel.folder = "file://" + parentPath;
root.currentPath = parentPath;
}
}
NIconButton {
icon: "filepicker-home"
tooltipText: I18n.tr("tooltips.home")
baseSize: Style.baseWidgetSize * 0.8
onClicked: {
const homePath = Quickshell.env("HOME") || "/home";
folderModel.folder = "file://" + homePath;
root.currentPath = homePath;
}
}
NIconButton {
icon: filePickerPanel.showSearchBar ? "filepicker-x" : "filepicker-search"
tooltipText: filePickerPanel.showSearchBar ? I18n.tr("tooltips.search-close") : I18n.tr("common.search")
baseSize: Style.baseWidgetSize * 0.8
onClicked: {
filePickerPanel.showSearchBar = !filePickerPanel.showSearchBar;
if (!filePickerPanel.showSearchBar) {
filePickerPanel.searchText = "";
filePickerPanel.filterText = "";
root.updateFilteredModel();
}
}
}
NTextInput {
id: locationInput
text: root.currentPath
placeholderText: I18n.tr("placeholders.enter-path")
Layout.fillWidth: true
visible: !filePickerPanel.showSearchBar
enabled: !filePickerPanel.showSearchBar
onEditingFinished: {
const newPath = text.trim();
if (newPath !== "" && newPath !== root.currentPath) {
folderModel.folder = "file://" + newPath;
root.currentPath = newPath;
} else {
text = root.currentPath;
}
}
Connections {
target: root
function onCurrentPathChanged() {
if (!locationInput.activeFocus)
locationInput.text = root.currentPath;
}
}
}
// Search bar
NTextInput {
id: searchInput
inputIconName: "search"
placeholderText: I18n.tr("placeholders.search")
Layout.fillWidth: true
visible: filePickerPanel.showSearchBar
enabled: filePickerPanel.showSearchBar
text: filePickerPanel.searchText
onTextChanged: {
filePickerPanel.searchText = text;
filePickerPanel.filterText = text;
root.updateFilteredModel();
}
Keys.onEscapePressed: {
filePickerPanel.showSearchBar = false;
filePickerPanel.searchText = "";
filePickerPanel.filterText = "";
root.updateFilteredModel();
}
}
NIconButton {
icon: filePickerPanel.viewMode ? "filepicker-list" : "filepicker-layout-grid"
tooltipText: filePickerPanel.viewMode ? I18n.tr("tooltips.list-view") : I18n.tr("tooltips.grid-view")
baseSize: Style.baseWidgetSize * 0.8
onClicked: filePickerPanel.viewMode = !filePickerPanel.viewMode
}
NIconButton {
icon: root.showHiddenFiles ? "filepicker-eye-off" : "filepicker-eye"
tooltipText: root.showHiddenFiles ? I18n.tr("tooltips.hidden-files-hide") : I18n.tr("tooltips.hidden-files-hide")
baseSize: Style.baseWidgetSize * 0.8
onClicked: {
root.showHiddenFiles = !root.showHiddenFiles;
// Force model refresh by resetting the folder
const currentFolder = folderModel.folder;
folderModel.folder = "";
folderModel.folder = currentFolder;
Qt.callLater(root.updateFilteredModel);
}
}
}
}
// File list area
Rectangle {
Layout.fillWidth: true
Layout.fillHeight: true
color: Color.mSurface
radius: Style.iRadiusM
border.color: Color.mOutline
border.width: Style.borderS
FolderListModel {
id: folderModel
folder: "file://" + root.currentPath
// Use wildcard filters including hidden files when showHiddenFiles is true
nameFilters: root.showHiddenFiles ? ["*", ".*"] : root.nameFilters
showDirs: root.showDirs
showHidden: true // Always true, we'll filter in updateFilteredModel
showDotAndDotDot: false
sortField: FolderListModel.Name
sortReversed: false
onFolderChanged: {
root.currentPath = folder.toString().replace("file://", "");
filePickerPanel.currentSelection = [];
Qt.callLater(root.updateFilteredModel);
}
onStatusChanged: {
if (status === FolderListModel.Error) {
if (root.currentPath !== Quickshell.env("HOME")) {
folder = "file://" + Quickshell.env("HOME");
root.currentPath = Quickshell.env("HOME");
}
} else if (status === FolderListModel.Ready) {
root.updateFilteredModel();
}
}
}
// Update nameFilters when showHiddenFiles changes
Connections {
target: root
function onShowHiddenFilesChanged() {
folderModel.nameFilters = root.showHiddenFiles ? ["*", ".*"] : root.nameFilters;
}
}
ListModel {
id: filteredModel
}
// Grid view
NGridView {
id: gridView
anchors.fill: parent
anchors.margins: Style.marginM
model: filteredModel
visible: filePickerPanel.viewMode
reuseItems: true
gradientColor: Color.mSurface
property int columns: Math.max(1, Math.floor(availableWidth / 120))
property int itemSize: Math.floor((availableWidth - leftMargin - rightMargin - (columns * Style.marginS)) / columns)
cellWidth: Math.floor((availableWidth - leftMargin - rightMargin) / columns)
cellHeight: Math.floor(itemSize * 0.8) + Style.marginXS + Style.fontSizeS + Style.marginM
leftMargin: Style.marginS
rightMargin: Style.marginS
topMargin: Style.marginS
bottomMargin: Style.marginS
delegate: Rectangle {
id: gridItem
width: gridView.itemSize
height: gridView.cellHeight
color: "transparent"
radius: Style.iRadiusM
property bool isSelected: filePickerPanel.currentSelection.includes(model.filePath)
Rectangle {
anchors.fill: parent
color: "transparent"
radius: parent.radius
border.color: isSelected ? Color.mSecondary : Color.mSurface
border.width: Style.borderL
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
Rectangle {
anchors.fill: parent
color: (mouseArea.containsMouse && !isSelected) ? Color.mHover : "transparent"
radius: parent.radius
border.color: (mouseArea.containsMouse && !isSelected) ? Color.mHover : "transparent"
border.width: Style.borderS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
Behavior on border.color {
ColorAnimation {
duration: Style.animationFast
}
}
}
ColumnLayout {
anchors.fill: parent
anchors.margins: Style.marginS
spacing: Style.marginXS
Rectangle {
id: iconContainer
Layout.fillWidth: true
Layout.preferredHeight: Math.round(gridView.itemSize * 0.67)
color: "transparent"
property bool isImage: {
if (model.fileIsDir)
return false;
const ext = model.fileName.split('.').pop().toLowerCase();
return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico'].includes(ext);
}
Image {
id: thumbnail
anchors.fill: parent
anchors.margins: Style.marginXS
source: iconContainer.isImage ? "file://" + model.filePath : ""
fillMode: Image.PreserveAspectFit
visible: iconContainer.isImage && status === Image.Ready
smooth: false
cache: true
asynchronous: true
sourceSize.width: 120
sourceSize.height: 120
onStatusChanged: {
if (status === Image.Error)
visible = false;
}
Rectangle {
anchors.fill: parent
color: Color.mSurfaceVariant
radius: Style.iRadiusS
visible: thumbnail.status === Image.Loading
NIcon {
icon: "filepicker-photo"
pointSize: Style.fontSizeL
color: Color.mOnSurfaceVariant
anchors.centerIn: parent
}
}
}
NIcon {
icon: model.fileIsDir ? "filepicker-folder" : root.getFileIcon(model.fileName)
pointSize: Style.fontSizeXXL * 2
color: {
if (isSelected)
return Color.mSecondary;
else if (mouseArea.containsMouse)
return Color.mOnHover;
else
return model.fileIsDir ? Color.mPrimary : Color.mOnSurfaceVariant;
}
anchors.centerIn: parent
visible: !iconContainer.isImage || thumbnail.status !== Image.Ready
}
Rectangle {
anchors.top: parent.top
anchors.right: parent.right
anchors.margins: Style.marginS
width: 24
height: 24
radius: Math.min(Style.iRadiusL, width / 2)
color: Color.mSecondary
border.color: Color.mOutline
border.width: Style.borderS
visible: isSelected
NIcon {
icon: "filepicker-check"
pointSize: Style.fontSizeS
color: Color.mOnSecondary
anchors.centerIn: parent
}
}
}
NText {
text: model.fileName
color: {
if (isSelected)
return Color.mSecondary;
else if (mouseArea.containsMouse)
return Color.mOnHover;
else
return Color.mOnSurfaceVariant;
}
pointSize: Style.fontSizeS
font.weight: isSelected ? Style.fontWeightBold : Style.fontWeightRegular
Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
wrapMode: Text.WrapAnywhere
elide: Text.ElideRight
maximumLineCount: 2
}
}
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: mouse => {
if (mouse.button === Qt.LeftButton) {
if (model.fileIsDir) {
// In folder mode, single click selects the folder
if (root.selectionMode === "folders") {
filePickerPanel.itemClicked(mouse.modifiers, model.filePath);
}
// In file mode, single click on folder does nothing (must double-click to enter)
} else {
// Single click on file selects it (only in file mode)
if (root.selectionMode === "files") {
filePickerPanel.itemClicked(mouse.modifiers, model.filePath);
}
}
}
}
onDoubleClicked: mouse => {
if (mouse.button === Qt.LeftButton) {
if (model.fileIsDir) {
// Double-click on folder always navigates into it
folderModel.folder = "file://" + model.filePath;
root.currentPath = model.filePath;
} else {
// Double-click on file selects and confirms (only in file mode)
if (root.selectionMode === "files") {
filePickerPanel.currentSelection = [model.filePath];
root.confirmSelection();
}
}
}
}
}
}
}
// List view
NListView {
id: listView
anchors.fill: parent
anchors.margins: Style.marginS
model: filteredModel
visible: !filePickerPanel.viewMode
gradientColor: Color.mSurface
delegate: Rectangle {
id: listItem
width: listView.width
height: 40
color: {
if (filePickerPanel.currentSelection.includes(model.filePath))
return Color.mSecondary;
if (mouseArea.containsMouse)
return Color.mHover;
return "transparent";
}
radius: Style.iRadiusS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
RowLayout {
anchors.fill: parent
anchors.leftMargin: Style.marginM
anchors.rightMargin: Style.marginM
spacing: Style.marginM
NIcon {
icon: model.fileIsDir ? "filepicker-folder" : root.getFileIcon(model.fileName)
pointSize: Style.fontSizeL
color: model.fileIsDir ? (filePickerPanel.currentSelection.includes(model.filePath) ? Color.mOnSecondary : Color.mPrimary) : Color.mOnSurfaceVariant
}
NText {
text: model.fileName
color: filePickerPanel.currentSelection.includes(model.filePath) ? Color.mOnSecondary : Color.mOnSurface
pointSize: Style.fontSizeM
font.weight: filePickerPanel.currentSelection.includes(model.filePath) ? Style.fontWeightBold : Style.fontWeightRegular
Layout.fillWidth: true
elide: Text.ElideRight
}
NText {
text: model.fileIsDir ? "" : root.formatFileSize(model.fileSize)
color: filePickerPanel.currentSelection.includes(model.filePath) ? Color.mOnSecondary : Color.mOnSurfaceVariant
pointSize: Style.fontSizeS
visible: !model.fileIsDir
Layout.preferredWidth: implicitWidth
}
}
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: mouse => {
if (mouse.button === Qt.LeftButton) {
if (model.fileIsDir) {
// In folder mode, single click selects the folder
if (root.selectionMode === "folders") {
filePickerPanel.itemClicked(mouse.modifiers, model.filePath);
}
// In file mode, single click on folder does nothing (must double-click to enter)
} else {
// Single click on file selects it (only in file mode)
if (root.selectionMode === "files") {
filePickerPanel.itemClicked(mouse.modifiers, model.filePath);
}
}
}
}
onDoubleClicked: mouse => {
if (mouse.button === Qt.LeftButton) {
if (model.fileIsDir) {
// Double-click on folder always navigates into it
folderModel.folder = "file://" + model.filePath;
root.currentPath = model.filePath;
} else {
// Double-click on file selects and confirms (only in file mode)
if (root.selectionMode === "files") {
filePickerPanel.currentSelection = [model.filePath];
root.confirmSelection();
}
}
}
}
}
}
}
}
// Footer
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NText {
text: {
if (filePickerPanel.searchText.length > 0) {
return "Searching for: \"" + filePickerPanel.searchText + "\" (" + filteredModel.count + " matches)";
} else if (filePickerPanel.currentSelection.length > 0) {
const selectedName = filePickerPanel.currentSelection[0].split('/').pop();
return I18n.tr("widgets.file-picker.selected") + " " + selectedName;
} else {
return filteredModel.count + " " + (filteredModel.count === 1 ? I18n.tr("widgets.file-picker.item") : I18n.tr("widgets.file-picker.items"));
}
}
color: filePickerPanel.searchText.length > 0 ? Color.mPrimary : Color.mOnSurfaceVariant
pointSize: Style.fontSizeS
Layout.fillWidth: true
}
NButton {
text: I18n.tr("common.cancel")
outlined: true
onClicked: {
root.cancelled();
root.close();
}
}
NButton {
text: root.selectionMode === "folders" ? I18n.tr("widgets.file-picker.select-folder") : I18n.tr("widgets.file-picker.select-file")
icon: "filepicker-check"
enabled: filePickerPanel.currentSelection.length > 0
onClicked: root.confirmSelection()
}
}
}
Connections {
target: root
function onShouldResetSelectionChanged() {
if (root.shouldResetSelection) {
filePickerPanel.currentSelection = [];
root.shouldResetSelection = false;
}
}
}
Component.onCompleted: {
if (!root.currentPath)
root.currentPath = root.initialPath;
folderModel.folder = "file://" + root.currentPath;
}
}
}
@@ -0,0 +1,234 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Item {
id: root
clip: true
// Primary line
property var values: []
property color color: Color.mPrimary
// Optional secondary line
property var values2: []
property color color2: Color.mError
// Range settings for primary line
property real minValue: 0
property real maxValue: 100
// Range settings for secondary line (defaults to primary range)
property real minValue2: minValue
property real maxValue2: maxValue
// Style settings
property real strokeWidth: 1
property bool fill: true
property real fillOpacity: 0.15
property real antialiasing: 0.5
// Smooth scrolling interval (how often data updates)
property int updateInterval: 1000
// Animate scale changes (for network graphs with dynamic max)
property bool animateScale: false
// Vertical padding (percentage of range) to keep values from touching edges
readonly property real curvePadding: 0.12
readonly property bool hasData: values.length >= 4
readonly property bool hasData2: values2.length >= 4
// Scale animation state
property real _targetMax1: maxValue
property real _targetMax2: maxValue2
property real _animMax1: maxValue
property real _animMax2: maxValue2
onMaxValueChanged: {
_targetMax1 = maxValue;
if (animateScale && _ready1) {
_scaleTimer.start();
} else {
_animMax1 = maxValue;
}
}
onMaxValue2Changed: {
_targetMax2 = maxValue2;
if (animateScale && _ready2) {
_scaleTimer.start();
} else {
_animMax2 = maxValue2;
}
}
// Effective max values (animated or direct)
readonly property real _effectiveMax1: animateScale ? _animMax1 : maxValue
readonly property real _effectiveMax2: animateScale ? _animMax2 : maxValue2
// Scroll state (driven by NumberAnimation)
property real _t1: 1.0
property bool _ready1: false
property real _pred1: 0
property real _t2: 1.0
property bool _ready2: false
property real _pred2: 0
// Frame-accurate scroll animations tied to Qt's render loop
NumberAnimation {
id: _scrollAnim1
target: root
property: "_t1"
from: 0
to: 1
duration: root.updateInterval
}
NumberAnimation {
id: _scrollAnim2
target: root
property: "_t2"
from: 0
to: 1
duration: root.updateInterval
}
onValuesChanged: {
if (values.length < 4)
return;
const last = values[values.length - 1];
const prev = values[values.length - 2];
_pred1 = Math.max(minValue, last + (last - prev) * 0.5);
if (!_ready1)
_ready1 = true;
_scrollAnim1.restart();
}
onValues2Changed: {
if (values2.length < 4)
return;
const last = values2[values2.length - 1];
const prev = values2[values2.length - 2];
_pred2 = Math.max(minValue2, last + (last - prev) * 0.5);
if (!_ready2)
_ready2 = true;
_scrollAnim2.restart();
}
// Scale animation timer (only needed for animateScale mode)
Timer {
id: _scaleTimer
interval: 16
repeat: true
onTriggered: {
const scaleLerp = 0.15;
const threshold = 0.5;
let stillAnimating = false;
if (Math.abs(root._animMax1 - root._targetMax1) > threshold) {
root._animMax1 += (root._targetMax1 - root._animMax1) * scaleLerp;
stillAnimating = true;
} else if (root._animMax1 !== root._targetMax1) {
root._animMax1 = root._targetMax1;
}
if (Math.abs(root._animMax2 - root._targetMax2) > threshold) {
root._animMax2 += (root._targetMax2 - root._animMax2) * scaleLerp;
stillAnimating = true;
} else if (root._animMax2 !== root._targetMax2) {
root._animMax2 = root._targetMax2;
}
if (!stillAnimating)
stop();
}
}
// Normalize a value to [0, 1] with padding applied
function _normalize(val, minVal, maxVal) {
let range = maxVal - minVal;
if (range <= 0)
return 0.5;
let padding = range * curvePadding;
let paddedMin = minVal - padding;
let paddedRange = (maxVal + padding) - paddedMin;
return Math.max(0, Math.min(1, (val - paddedMin) / paddedRange));
}
// Data texture built from Rectangles instead of Canvas.
// Each Rectangle is one data point, color-coded with normalized values.
// R channel = primary, G channel = secondary.
Item {
id: _dataRow
width: Math.max(root.values.length + 1, root.values2.length + 1, 4)
height: 1
Repeater {
model: _dataRow.width
Rectangle {
required property int index
x: index
width: 1
height: 1
color: {
let r = 0, g = 0;
let n1 = root.values.length;
let n2 = root.values2.length;
let eMax1 = root._effectiveMax1;
let eMax2 = root._effectiveMax2;
if (index < n1)
r = root._normalize(root.values[index], root.minValue, eMax1);
else if (n1 > 0)
r = root._normalize(root._pred1, root.minValue, eMax1);
if (index < n2)
g = root._normalize(root.values2[index], root.minValue2, eMax2);
else if (n2 > 0)
g = root._normalize(root._pred2, root.minValue2, eMax2);
return Qt.rgba(r, g, 0, 1);
}
}
}
}
ShaderEffectSource {
id: _dataTex
sourceItem: _dataRow
textureSize: Qt.size(_dataRow.width, 1)
live: true
smooth: false
hideSource: true
}
ShaderEffect {
anchors.fill: parent
visible: (root.hasData || root.hasData2) && width > 0 && height > 0
property variant dataSource: _dataTex
property color lineColor1: root.color
property color lineColor2: root.color2
property real count1: root.values.length
property real count2: root.values2.length
property real scroll1: root._t1
property real scroll2: root._t2
property real lineWidth: root.strokeWidth
property real graphFillOpacity: root.fill ? root.fillOpacity : 0.0
property real texWidth: _dataRow.width
property real resY: height
property real aaSize: root.antialiasing
fragmentShader: Qt.resolvedUrl(Quickshell.shellDir + "/Shaders/qsb/graph.frag.qsb")
blending: true
}
}
@@ -0,0 +1,430 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Templates as T
import qs.compat.noctalia.Commons
Item {
id: root
// Signal for key press events when keyNavigationEnabled is true
signal keyPressed(var event)
property color handleColor: Qt.alpha(Color.mHover, 0.8)
property color handleHoverColor: handleColor
property color handlePressedColor: handleColor
property color trackColor: "transparent"
property real handleWidth: 6
property real handleRadius: Style.iRadiusM
property int verticalPolicy: ScrollBar.AsNeeded
property int horizontalPolicy: ScrollBar.AlwaysOff
readonly property bool verticalScrollBarActive: {
if (gridView.ScrollBar.vertical.policy === ScrollBar.AlwaysOff)
return false;
return gridView.contentHeight > gridView.height;
}
readonly property bool contentOverflows: gridView.contentHeight > gridView.height
// Gradient properties
property bool showGradientMasks: true
property color gradientColor: Color.mSurfaceVariant
property int gradientHeight: 16
property bool reserveScrollbarSpace: true
// Keep scrollbars visible whenever overflow exists (without forcing visibility when not scrollable)
property bool showScrollbarWhenScrollable: Settings.data.ui.scrollbarAlwaysVisible
// Available width for content (excludes scrollbar space when reserveScrollbarSpace is true)
// Note: Always reserves space when enabled to avoid binding loops with cellWidth calculations
readonly property real availableWidth: width - (reserveScrollbarSpace ? handleWidth + Style.marginXS : 0)
// Expose activeFocus from internal gridView
readonly property bool hasActiveFocus: gridView.activeFocus
// Forward GridView properties
property alias model: gridView.model
property alias delegate: gridView.delegate
property alias cellWidth: gridView.cellWidth
property alias cellHeight: gridView.cellHeight
property alias leftMargin: gridView.leftMargin
property alias rightMargin: gridView.rightMargin
property alias topMargin: gridView.topMargin
property alias bottomMargin: gridView.bottomMargin
property alias currentIndex: gridView.currentIndex
property alias count: gridView.count
property alias contentHeight: gridView.contentHeight
property alias contentWidth: gridView.contentWidth
property alias contentY: gridView.contentY
property alias contentX: gridView.contentX
property alias currentItem: gridView.currentItem
property alias highlightItem: gridView.highlightItem
property alias highlightFollowsCurrentItem: gridView.highlightFollowsCurrentItem
property alias preferredHighlightBegin: gridView.preferredHighlightBegin
property alias preferredHighlightEnd: gridView.preferredHighlightEnd
property alias highlightRangeMode: gridView.highlightRangeMode
property alias snapMode: gridView.snapMode
property alias keyNavigationEnabled: gridView.keyNavigationEnabled
property alias keyNavigationWraps: gridView.keyNavigationWraps
property alias cacheBuffer: gridView.cacheBuffer
property alias displayMarginBeginning: gridView.displayMarginBeginning
property alias displayMarginEnd: gridView.displayMarginEnd
property alias layoutDirection: gridView.layoutDirection
property alias effectiveLayoutDirection: gridView.effectiveLayoutDirection
property alias flow: gridView.flow
property alias boundsBehavior: gridView.boundsBehavior
property alias flickableDirection: gridView.flickableDirection
property alias interactive: gridView.interactive
property alias moving: gridView.moving
property alias flicking: gridView.flicking
property alias dragging: gridView.dragging
property alias horizontalVelocity: gridView.horizontalVelocity
property alias verticalVelocity: gridView.verticalVelocity
property alias reuseItems: gridView.reuseItems
// Animate items when the model is reordered (e.g. ListModel.move())
property bool animateMovement: false
// Scroll speed multiplier for mouse wheel (1.0 = default, higher = faster)
property real wheelScrollMultiplier: 2.0
property int smoothWheelAnimationDuration: Style.animationNormal
property real _wheelTargetY: 0
function clampScrollY(value) {
return Math.max(0, Math.min(value, gridView.contentHeight - gridView.height));
}
function applyWheelScroll(delta) {
if (!root.contentOverflows)
return;
const step = delta * root.wheelScrollMultiplier;
if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled) {
gridView.contentY = root.clampScrollY(gridView.contentY - step);
root._wheelTargetY = gridView.contentY;
return;
}
if (!wheelScrollAnimation.running)
root._wheelTargetY = gridView.contentY;
root._wheelTargetY = root.clampScrollY(root._wheelTargetY - step);
wheelScrollAnimation.to = root._wheelTargetY;
wheelScrollAnimation.restart();
}
function animateToContentY(targetY) {
const clampedY = root.clampScrollY(targetY);
if (!Settings.data.general.smoothScrollEnabled || Settings.data.general.animationDisabled || gridView.dragging || gridView.flicking) {
gridView.contentY = clampedY;
root._wheelTargetY = clampedY;
return;
}
root._wheelTargetY = clampedY;
wheelScrollAnimation.to = clampedY;
wheelScrollAnimation.restart();
}
// Track selection index for gradient visibility (set externally)
property int trackedSelectionIndex: -1
// Check if selection is on first visible row
readonly property bool selectionOnFirstVisibleRow: {
if (trackedSelectionIndex < 0 || cellHeight <= 0 || cellWidth <= 0)
return false;
// Calculate columns per row
var cols = Math.floor(gridView.width / cellWidth);
if (cols <= 0)
cols = 1;
// Calculate the row of the selection
var selectionRow = Math.round(trackedSelectionIndex / cols);
// Calculate the first visible row
var firstVisibleRow = Math.round(gridView.contentY / cellHeight);
return selectionRow === firstVisibleRow;
}
// Check if selection is on last visible row
readonly property bool selectionOnLastVisibleRow: {
if (trackedSelectionIndex < 0 || cellHeight <= 0 || cellWidth <= 0)
return false;
// Calculate columns per row
var cols = Math.floor(gridView.width / cellWidth);
if (cols <= 0)
cols = 1;
// Calculate the row of the selection
var selectionRow = Math.round(trackedSelectionIndex / cols);
// Calculate the last visible row (might be partially visible)
var lastVisibleRow = Math.round((gridView.contentY + gridView.height - 1) / cellHeight);
return selectionRow === lastVisibleRow;
}
// Forward GridView methods
function positionViewAtIndex(index, mode) {
const shouldAnimate = mode === GridView.Contain;
if (!shouldAnimate) {
gridView.positionViewAtIndex(index, mode);
root._wheelTargetY = gridView.contentY;
return;
}
const previousY = gridView.contentY;
gridView.positionViewAtIndex(index, mode);
const targetY = root.clampScrollY(gridView.contentY);
if (Math.abs(targetY - previousY) < 0.5) {
root._wheelTargetY = targetY;
return;
}
gridView.contentY = previousY;
root._wheelTargetY = previousY;
root.animateToContentY(targetY);
}
function positionViewAtBeginning() {
gridView.positionViewAtBeginning();
}
function positionViewAtEnd() {
gridView.positionViewAtEnd();
}
function forceLayout() {
gridView.forceLayout();
}
function forceActiveFocus() {
gridView.forceActiveFocus();
}
function cancelFlick() {
gridView.cancelFlick();
}
function flick(xVelocity, yVelocity) {
gridView.flick(xVelocity, yVelocity);
}
function incrementCurrentIndex() {
gridView.incrementCurrentIndex();
}
function decrementCurrentIndex() {
gridView.decrementCurrentIndex();
}
function indexAt(x, y) {
return gridView.indexAt(x, y);
}
function itemAt(x, y) {
return gridView.itemAt(x, y);
}
function itemAtIndex(index) {
return gridView.itemAtIndex(index);
}
function moveCurrentIndexUp() {
gridView.moveCurrentIndexUp();
}
function moveCurrentIndexDown() {
gridView.moveCurrentIndexDown();
}
function moveCurrentIndexLeft() {
gridView.moveCurrentIndexLeft();
}
function moveCurrentIndexRight() {
gridView.moveCurrentIndexRight();
}
// Set reasonable implicit sizes for Layout usage
implicitWidth: 200
implicitHeight: 200
Component.onCompleted: {
_wheelTargetY = gridView.contentY;
createGradients();
}
// Dynamically create gradient overlays
function createGradients() {
if (!showGradientMasks)
return;
Qt.createQmlObject(`
import QtQuick
import qs.compat.noctalia.Commons
Rectangle {
x: 0
y: 0
width: root.availableWidth
height: root.gradientHeight
z: 1
visible: root.showGradientMasks && root.contentOverflows
opacity: (gridView.contentY <= 1 || root.selectionOnFirstVisibleRow) ? 0 : 1
Behavior on opacity {
NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad }
}
gradient: Gradient {
GradientStop { position: 0.0; color: root.gradientColor }
GradientStop { position: 1.0; color: "transparent" }
}
}
`, root, "topGradient");
Qt.createQmlObject(`
import QtQuick
import qs.compat.noctalia.Commons
Rectangle {
x: 0
anchors.bottom: parent.bottom
anchors.bottomMargin: -1
width: root.availableWidth
height: root.gradientHeight + 1
z: 1
visible: root.showGradientMasks && root.contentOverflows
opacity: ((gridView.contentY + gridView.height >= gridView.contentHeight - 1) || root.selectionOnLastVisibleRow) ? 0 : 1
Behavior on opacity {
NumberAnimation { duration: Style.animationFast; easing.type: Easing.InOutQuad }
}
gradient: Gradient {
GradientStop { position: 0.0; color: "transparent" }
GradientStop { position: 1.0; color: root.gradientColor }
}
}
`, root, "bottomGradient");
}
GridView {
id: gridView
anchors.fill: parent
anchors.rightMargin: root.reserveScrollbarSpace ? root.handleWidth + Style.marginXS : 0
move: root.animateMovement ? moveTransitionImpl : null
displaced: root.animateMovement ? displacedTransitionImpl : null
Transition {
id: moveTransitionImpl
NumberAnimation {
properties: "x,y"
duration: Style.animationNormal
easing.type: Easing.InOutQuad
}
}
Transition {
id: displacedTransitionImpl
NumberAnimation {
properties: "x,y"
duration: Style.animationNormal
easing.type: Easing.InOutQuad
}
}
// Enable clipping to keep content within bounds
clip: true
// Enable flickable for smooth scrolling
boundsBehavior: Flickable.StopAtBounds
NumberAnimation {
id: wheelScrollAnimation
target: gridView
property: "contentY"
duration: root.smoothWheelAnimationDuration
easing.type: Easing.OutCubic
}
onDraggingChanged: {
if (dragging) {
wheelScrollAnimation.stop();
root._wheelTargetY = contentY;
}
}
onFlickingChanged: {
if (flicking) {
wheelScrollAnimation.stop();
root._wheelTargetY = contentY;
}
}
onContentHeightChanged: root._wheelTargetY = root.clampScrollY(root._wheelTargetY)
onHeightChanged: root._wheelTargetY = root.clampScrollY(root._wheelTargetY)
// Focus handling depends on keyNavigationEnabled
focus: keyNavigationEnabled
activeFocusOnTab: keyNavigationEnabled
// Emit keyPressed signal for custom key handling
Keys.onPressed: event => {
if (keyNavigationEnabled) {
root.keyPressed(event);
}
}
WheelHandler {
enabled: root.wheelScrollMultiplier !== 1.0
acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
onWheel: event => {
const delta = event.pixelDelta.y !== 0 ? event.pixelDelta.y : event.angleDelta.y / 2;
root.applyWheelScroll(delta);
event.accepted = true;
}
}
ScrollBar.vertical: ScrollBar {
parent: root
x: root.mirrored ? 0 : root.width - width
y: 0
height: root.height
policy: root.verticalPolicy
contentItem: Rectangle {
implicitWidth: root.handleWidth
implicitHeight: 100
radius: root.handleRadius
color: parent.pressed ? root.handlePressedColor : parent.hovered ? root.handleHoverColor : root.handleColor
opacity: parent.policy === ScrollBar.AlwaysOn ? 1.0 : root.verticalScrollBarActive ? ((root.showScrollbarWhenScrollable || parent.active) ? 1.0 : 0.0) : 0.0
Behavior on opacity {
NumberAnimation {
duration: Style.animationFast
}
}
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
}
background: Rectangle {
implicitWidth: root.handleWidth
implicitHeight: 100
color: root.trackColor
opacity: parent.policy === ScrollBar.AlwaysOn ? 0.3 : root.verticalScrollBarActive ? ((root.showScrollbarWhenScrollable || parent.active) ? 0.3 : 0.0) : 0.0
radius: root.handleRadius / 2
Behavior on opacity {
NumberAnimation {
duration: Style.animationFast
}
}
}
}
}
}
@@ -0,0 +1,34 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
ColumnLayout {
id: root
property string label: ""
property string description: ""
property bool enableDescriptionRichText: false
opacity: enabled ? 1.0 : 0.6
spacing: Style.marginXXS
Layout.fillWidth: true
Layout.bottomMargin: Style.marginM
NText {
text: root.label
pointSize: Style.fontSizeXL
font.weight: Style.fontWeightSemiBold
color: Color.mPrimary
visible: root.label !== ""
}
NText {
text: root.description
pointSize: Style.fontSizeM
color: Color.mOnSurfaceVariant
wrapMode: Text.WordWrap
Layout.fillWidth: true
visible: root.description !== ""
richTextEnabled: root.enableDescriptionRichText
}
}
@@ -0,0 +1,30 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
Text {
id: root
property string icon: Icons.defaultIcon
property real pointSize: Style.fontSizeL
property bool applyUiScale: true
visible: (icon !== undefined) && (icon !== "")
text: {
if ((icon === undefined) || (icon === "")) {
return "";
}
if (Icons.get(icon) === undefined) {
Logger.w("Icon", `"${icon}"`, "doesn't exist in the icons font");
Logger.callStack();
return Icons.get(Icons.defaultIcon);
}
return Icons.get(icon);
}
font.family: Icons.fontFamily
font.pointSize: Math.max(1, applyUiScale ? root.pointSize * Style.uiScaleRatio : root.pointSize)
color: Color.mOnSurface
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
@@ -0,0 +1,133 @@
import QtQuick
import Quickshell
import Quickshell.Widgets
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
Item {
id: root
property real baseSize: Style.baseWidgetSize
property bool applyUiScale: true
property string icon
property var tooltipText
property string tooltipDirection: "auto"
property bool allowClickWhenDisabled: false
property bool handleWheel: false
property bool hovering: false
property color colorBg: Color.smartAlpha(Color.mSurfaceVariant)
property color colorFg: Color.mPrimary
property color colorBgHover: Color.mHover
property color colorFgHover: Color.mOnHover
property color colorBorder: Color.mOutline
property color colorBorderHover: Color.mOutline
property real customRadius: -1 // -1 means use default (iRadiusL), otherwise use this value
// Expose border properties for backwards compatibility (aliases to visualButton)
property alias border: visualButton.border
property alias radius: visualButton.radius
property alias color: visualButton.color
signal entered
signal exited
signal clicked
signal rightClicked
signal middleClicked
signal wheel(int angleDelta)
// Calculate button size based on settings
readonly property real buttonSize: applyUiScale ? Style.toOdd(baseSize * Style.uiScaleRatio) : Style.toOdd(baseSize)
// Size: use implicit width/height which layout can override
// BarWidgetLoader sets explicit width/height to extend click area
implicitWidth: buttonSize
implicitHeight: buttonSize
opacity: enabled ? 1.0 : 0.6
// Visual button - stays at buttonSize, centered in parent
Rectangle {
id: visualButton
width: root.buttonSize
height: root.buttonSize
anchors.centerIn: parent
color: root.enabled && root.hovering ? colorBgHover : colorBg
radius: Math.min((customRadius >= 0 ? customRadius : Style.iRadiusL), width / 2)
border.color: root.enabled && root.hovering ? colorBorderHover : colorBorder
border.width: Style.borderS
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.InOutQuad
}
}
NIcon {
icon: root.icon
pointSize: Style.toOdd(visualButton.width * 0.48)
applyUiScale: root.applyUiScale
color: root.enabled && root.hovering ? colorFgHover : colorFg
// Pixel-perfect centering
x: Style.pixelAlignCenter(visualButton.width, width)
y: Style.pixelAlignCenter(visualButton.height, contentHeight)
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.InOutQuad
}
}
}
}
// MouseArea fills root (extends beyond visual button for bar click area)
MouseArea {
// Always enabled to allow hover/tooltip even when the button is disabled
enabled: true
anchors.fill: parent
cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton
hoverEnabled: true
onEntered: {
hovering = root.enabled ? true : false;
if (hovering && tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) {
TooltipService.show(root, tooltipText, tooltipDirection);
}
root.entered();
}
onExited: {
hovering = false;
if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) {
TooltipService.hide(root);
}
root.exited();
}
onClicked: mouse => {
if (tooltipText && (!Array.isArray(tooltipText) || tooltipText.length > 0)) {
TooltipService.hide(root);
}
if (!root.enabled && !allowClickWhenDisabled) {
return;
}
if (mouse.button === Qt.LeftButton) {
root.clicked();
} else if (mouse.button === Qt.RightButton) {
root.rightClicked();
} else if (mouse.button === Qt.MiddleButton) {
root.middleClicked();
}
}
onWheel: wheel => {
if (root.handleWheel) {
root.wheel(wheel.angleDelta.y);
}
wheel.accepted = false;
}
}
}
Loaded 100 of 433 files, more files were not shown because too many files have changed in this diff. Show more