[noctalia] Init

This commit is contained in:
aloslider committed 2026-07-04 20:58:10 +03:00
1 parent 60e546e2b8
commit 337028ce7c
112 files changed
+12125

No files matched your search

@@ -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,124 @@
import QtQuick
import QtQuick.Layouts
import Quickshell
import qs.Commons
import qs.Widgets
import qs.Services.UI
Item {
id: root
property var pluginApi: null
property ShellScreen screen
property string widgetId: ""
property string section: ""
property int sectionWidgetIndex: -1
property int sectionWidgetsCount: 0
readonly property var mainInst: pluginApi?.mainInstance ?? null
readonly property bool isPanelOpen: pluginApi?.isPanelOpen ?? false
readonly property bool isSelected: isPanelOpen
readonly property string screenName: screen ? screen.name : ""
readonly property string barPosition: Settings.getBarPositionForScreen(screenName)
readonly property bool isVertical: barPosition === "left" || barPosition === "right"
readonly property real capsuleHeight: Style.getCapsuleHeightForScreen(screenName)
readonly property string badge: mainInst?.badgeText ?? ""
readonly property color capsuleBgColor: {
if (isSelected) {
return mouseArea.containsMouse ? Qt.darker(Color.mPrimary, 1.08) : Color.mPrimary;
}
return mouseArea.containsMouse ? Color.mHover : Style.capsuleColor;
}
readonly property color contentColor: isSelected
? Color.mOnPrimary
: (mouseArea.containsMouse ? Color.mOnHover : Color.mOnSurface)
implicitWidth: visualCapsule.width
implicitHeight: visualCapsule.height
NPopupContextMenu {
id: contextMenu
model: [
{
"label": pluginApi?.tr("bar.clear"),
"action": "clear",
"icon": "trash"
},
{
"label": pluginApi?.tr("bar.settings"),
"action": "settings",
"icon": "settings"
}
]
onTriggered: action => {
contextMenu.close();
PanelService.closeContextMenu(root.screen);
if (action === "clear") {
mainInst?.clearAll();
} else if (action === "settings") {
BarService.openPluginSettings(root.screen, pluginApi.manifest);
}
}
}
Rectangle {
id: visualCapsule
anchors.centerIn: parent
width: Math.max(root.capsuleHeight, iconRow.implicitWidth + Style.marginM * 2)
height: root.capsuleHeight
radius: Style.radiusL
color: root.capsuleBgColor
border.color: root.isSelected ? Color.mPrimary : Style.capsuleBorderColor
border.width: Style.capsuleBorderWidth
Row {
id: iconRow
anchors.centerIn: parent
spacing: badge !== "" ? Style.marginS : 0
NIcon {
icon: "calculator"
color: root.contentColor
}
NText {
text: badge
visible: text !== ""
font.bold: true
pointSize: Style.fontSizeS
color: root.contentColor
}
}
}
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton
cursorShape: Qt.PointingHandCursor
onClicked: mouse => {
TooltipService.hide();
if (mouse.button === Qt.RightButton) {
PanelService.showContextMenu(contextMenu, root, root.screen);
} else if (pluginApi) {
pluginApi.togglePanel(root.screen, root);
}
}
onEntered: {
TooltipService.show(
root,
pluginApi?.tr("bar.tooltip-title"),
BarService.getTooltipDirection(root)
);
}
onExited: TooltipService.hide()
}
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Pir0c0pter0
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.
@@ -0,0 +1,391 @@
import QtQuick
import Quickshell
import Quickshell.Io
import "AdvancedMath.js" as AdvancedMath
import qs.Services.UI
Item {
id: root
property var pluginApi: null
readonly property var settings: pluginApi?.pluginSettings ?? ({})
readonly property var defaults: pluginApi?.manifest?.metadata?.defaultSettings ?? ({})
readonly property bool showBarValue: settings.showBarValue ?? defaults.showBarValue ?? true
readonly property int precision: Math.max(0, Math.min(settings.precision ?? defaults.precision ?? 8, 10))
// Max digits before JS double precision loses accuracy
readonly property int _maxInputLength: 18
property var tokens: []
property string currentInput: "0"
property bool shouldResetInput: false
property bool justEvaluated: false
property bool errorState: false
property string lastExpression: ""
readonly property bool hasExpression: tokens.length > 0 || currentInput !== "0" || justEvaluated
readonly property string displayText: errorState ? pluginApi?.tr("state.error") : currentInput
readonly property string expressionText: expressionPreview()
readonly property string badgeText: !showBarValue ? "" : compactDisplay(displayText, 9)
readonly property bool hasCopyableResult: !errorState && displayText !== "" && (justEvaluated || displayText !== "0" || tokens.length > 0)
function _isOperator(token) {
return token === "+" || token === "-" || token === "*" || token === "/";
}
function _normalizeOperator(op) {
if (op === "x" || op === "X") return "*";
if (_isOperator(op)) return op;
return "";
}
function _sanitizeCurrentInput() {
if (currentInput === "" || currentInput === "-") return "0";
if (currentInput.endsWith(".")) return currentInput + "0";
return currentInput;
}
function _numberToString(value) {
if (!Number.isFinite(value)) return null;
let rounded = value;
if (precision >= 0) {
rounded = Number(value.toFixed(precision));
}
if (Object.is(rounded, -0)) rounded = 0;
let text = rounded.toString();
if (text.indexOf("e") >= 0 || text.indexOf("E") >= 0) {
return text.replace("e+", "e");
}
if (text.length > 16 && rounded !== 0) {
text = rounded.toExponential(Math.max(0, Math.min(precision, 6))).replace("e+", "e");
}
return text;
}
function compactDisplay(text, maxLength) {
if (!text) return "";
if (text.length <= maxLength) return text;
const numeric = Number(text);
if (!Number.isNaN(numeric) && Number.isFinite(numeric)) {
const exp = numeric.toExponential(Math.max(0, Math.min(precision, 3))).replace("e+", "e");
if (exp.length <= maxLength) return exp;
}
return text.slice(0, Math.max(1, maxLength - 1)) + "~";
}
function clearAll() {
tokens = [];
currentInput = "0";
shouldResetInput = false;
justEvaluated = false;
errorState = false;
lastExpression = "";
}
function _setError() {
tokens = [];
currentInput = "0";
shouldResetInput = false;
justEvaluated = false;
errorState = true;
lastExpression = "";
}
function appendDigit(digit) {
if (errorState) clearAll();
if (justEvaluated && tokens.length === 0 && !shouldResetInput) {
clearAll();
}
if (shouldResetInput) {
currentInput = digit;
shouldResetInput = false;
justEvaluated = false;
errorState = false;
return;
}
if (currentInput === "0") {
currentInput = digit;
} else if (currentInput === "-0") {
currentInput = "-" + digit;
} else if (currentInput.length < _maxInputLength) {
currentInput += digit;
}
justEvaluated = false;
errorState = false;
}
function appendDecimal() {
if (errorState) clearAll();
if (justEvaluated && tokens.length === 0 && !shouldResetInput) {
clearAll();
}
if (shouldResetInput) {
currentInput = "0.";
shouldResetInput = false;
justEvaluated = false;
return;
}
if (currentInput.indexOf(".") === -1) {
currentInput += ".";
}
justEvaluated = false;
}
function deleteLastChar() {
if (errorState) {
clearAll();
return;
}
if (justEvaluated) {
clearAll();
return;
}
if (shouldResetInput) {
currentInput = "0";
shouldResetInput = false;
return;
}
if (currentInput.length <= 1 || (currentInput.length === 2 && currentInput.startsWith("-"))) {
currentInput = "0";
return;
}
currentInput = currentInput.slice(0, currentInput.length - 1);
}
function toggleSign() {
if (errorState) return;
if (shouldResetInput) {
currentInput = "0";
shouldResetInput = false;
}
if (currentInput.startsWith("-")) {
currentInput = currentInput.slice(1);
} else {
currentInput = "-" + currentInput;
}
if (currentInput === "-0") {
justEvaluated = false;
return;
}
justEvaluated = false;
}
function applyPercent() {
if (errorState) return;
const numeric = Number(_sanitizeCurrentInput());
if (Number.isNaN(numeric)) {
_setError();
return;
}
const formatted = _numberToString(numeric / 100);
if (formatted === null) {
_setError();
return;
}
currentInput = formatted;
shouldResetInput = false;
justEvaluated = false;
}
function applyOperator(op) {
if (errorState) return;
const operator = _normalizeOperator(op);
if (!operator) return;
if (justEvaluated && tokens.length === 0) {
tokens = [currentInput, operator];
shouldResetInput = true;
justEvaluated = false;
lastExpression = "";
return;
}
if (shouldResetInput) {
if (tokens.length > 0 && _isOperator(tokens[tokens.length - 1])) {
const updated = tokens.slice(0, tokens.length - 1);
updated.push(operator);
tokens = updated;
} else {
tokens = tokens.concat([operator]);
}
lastExpression = "";
return;
}
tokens = tokens.concat([_sanitizeCurrentInput(), operator]);
shouldResetInput = true;
justEvaluated = false;
lastExpression = "";
}
function _buildEvaluationTokens() {
const built = Array.from(tokens);
if (!shouldResetInput || built.length === 0 || !_isOperator(built[built.length - 1])) {
built.push(_sanitizeCurrentInput());
}
while (built.length > 0 && _isOperator(built[built.length - 1])) {
built.pop();
}
return built;
}
function _buildDisplayTokens() {
const built = Array.from(tokens);
if (!shouldResetInput || built.length === 0 || !_isOperator(built[built.length - 1])) {
built.push(_sanitizeCurrentInput());
}
return built;
}
function _evaluateExpression(expressionStr) {
try {
return AdvancedMath.evaluate(expressionStr);
} catch (e) {
return null;
}
}
function _formatExpression(tokensToFormat) {
const parts = [];
for (let i = 0; i < tokensToFormat.length; i++) {
const token = tokensToFormat[i];
if (token === "*") parts.push("x");
else parts.push(String(token));
}
return parts.join(" ");
}
function expressionPreview() {
if (errorState) return lastExpression || "";
if (justEvaluated && lastExpression) return lastExpression;
const built = _buildDisplayTokens();
if (built.length === 0 || (built.length === 1 && built[0] === "0" && !hasExpression)) {
return "";
}
return _formatExpression(built);
}
function evaluate() {
if (errorState) return;
const evaluationTokens = _buildEvaluationTokens();
if (evaluationTokens.length === 0) return;
const expression = _formatExpression(evaluationTokens);
const expressionStr = evaluationTokens.join(" ");
const result = _evaluateExpression(expressionStr);
if (result === null) {
_setError();
return;
}
const formatted = _numberToString(result);
if (formatted === null) {
_setError();
return;
}
currentInput = formatted;
tokens = [];
shouldResetInput = false;
justEvaluated = true;
errorState = false;
lastExpression = expression;
}
function pressButton(action) {
if (action >= "0" && action <= "9") {
appendDigit(action);
return;
}
if (action === "decimal") appendDecimal();
else if (action === "add") applyOperator("+");
else if (action === "subtract") applyOperator("-");
else if (action === "multiply") applyOperator("*");
else if (action === "divide") applyOperator("/");
else if (action === "equals") evaluate();
else if (action === "percent") applyPercent();
else if (action === "sign") toggleSign();
else if (action === "clear") clearAll();
else if (action === "delete") deleteLastChar();
}
readonly property var _operatorActionMap: ({
"+": "add", "-": "subtract", "/": "divide",
"*": "multiply", "x": "multiply", "X": "multiply"
})
function actionForKeyEvent(event) {
if ((event.modifiers & Qt.ControlModifier) || (event.modifiers & Qt.MetaModifier)) {
return "";
}
const text = event.text ?? "";
if (text >= "0" && text <= "9") return text;
if (text === "." || text === ",") return "decimal";
if (text in _operatorActionMap) return _operatorActionMap[text];
if (text === "%") return "percent";
if (text === "=") return "equals";
if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) return "equals";
if (event.key === Qt.Key_Backspace) return "delete";
if (event.key === Qt.Key_Escape || event.key === Qt.Key_Delete) return "clear";
if (event.key === Qt.Key_F9) return "sign";
return "";
}
function handleKeyEvent(event) {
const action = actionForKeyEvent(event);
if (action === "") return false;
pressButton(action);
return true;
}
function copyResult() {
if (!hasCopyableResult) return;
const value = displayText;
const escaped = value.replace(/'/g, "'\\''");
Quickshell.execDetached(["sh", "-c", "printf '%s' '" + escaped + "' | wl-copy"]);
const shown = value.length > 24 ? value.slice(0, 24) + "…" : value;
if (pluginApi) {
ToastService.showNotice(pluginApi.tr("toast.copied", { "value": shown }));
}
}
IpcHandler {
target: "plugin:noctalia-calculator"
function toggle() {
if (pluginApi) {
pluginApi.withCurrentScreen(screen => {
pluginApi.togglePanel(screen);
});
}
}
}
}
@@ -0,0 +1,286 @@
import QtQuick
import QtQuick.Layouts
import qs.Commons
import qs.Widgets
import qs.Services.UI
FocusScope {
id: root
property var pluginApi: null
readonly property var geometryPlaceholder: panelContainer
property real contentPreferredWidth: 360 * Style.uiScaleRatio
property real contentPreferredHeight: Math.ceil(panelCard.implicitHeight + (Style.marginM * 2))
readonly property bool allowAttach: true
anchors.fill: parent
focus: visible
readonly property var mainInst: pluginApi?.mainInstance ?? null
property string flashedAction: ""
readonly property var buttonModel: [
{ "label": "AC", "action": "clear", "tone": "danger", "span": 1 },
{ "label": "+/-", "action": "sign", "tone": "operator", "span": 1 },
{ "label": "%", "action": "percent", "tone": "operator", "span": 1 },
{ "label": "DEL", "action": "delete", "tone": "operator", "span": 1 },
{ "label": "7", "action": "7", "tone": "number", "span": 1 },
{ "label": "8", "action": "8", "tone": "number", "span": 1 },
{ "label": "9", "action": "9", "tone": "number", "span": 1 },
{ "label": "/", "action": "divide", "tone": "operator", "span": 1 },
{ "label": "4", "action": "4", "tone": "number", "span": 1 },
{ "label": "5", "action": "5", "tone": "number", "span": 1 },
{ "label": "6", "action": "6", "tone": "number", "span": 1 },
{ "label": "x", "action": "multiply", "tone": "operator", "span": 1 },
{ "label": "1", "action": "1", "tone": "number", "span": 1 },
{ "label": "2", "action": "2", "tone": "number", "span": 1 },
{ "label": "3", "action": "3", "tone": "number", "span": 1 },
{ "label": "-", "action": "subtract", "tone": "operator", "span": 1 },
{ "label": "0", "action": "0", "tone": "number", "span": 2 },
{ "label": ".", "action": "decimal", "tone": "number", "span": 1 },
{ "label": "+", "action": "add", "tone": "operator", "span": 1 },
{ "label": "=", "action": "equals", "tone": "accent", "span": 4 }
]
Timer {
id: flashTimer
interval: 140
repeat: false
onTriggered: root.flashedAction = ""
}
Component.onCompleted: {
if (visible) root.forceActiveFocus();
}
onVisibleChanged: {
if (visible) root.forceActiveFocus();
}
Keys.onPressed: event => {
const action = mainInst?.actionForKeyEvent(event) ?? "";
if (action !== "") {
root.flashButton(action);
}
if (mainInst?.handleKeyEvent(event)) {
event.accepted = true;
}
}
function flashButton(action) {
flashedAction = action;
flashTimer.restart();
}
function buttonFill(buttonData, hovered, active) {
if (active) {
if (buttonData.tone === "accent") return Qt.darker(Color.mPrimary, 1.12);
if (buttonData.tone === "danger") return Qt.alpha(Color.mError, 0.22);
if (buttonData.tone === "operator") return Qt.alpha(Color.mPrimary, 0.28);
return Qt.alpha(Color.mOnSurface, 0.16);
}
if (buttonData.tone === "accent") {
return hovered ? Qt.darker(Color.mPrimary, 1.05) : Color.mPrimary;
}
if (buttonData.tone === "danger") {
return hovered ? Qt.alpha(Color.mError, 0.18) : Qt.alpha(Color.mError, 0.12);
}
if (buttonData.tone === "operator") {
return hovered ? Qt.alpha(Color.mPrimary, 0.22) : Qt.alpha(Color.mPrimary, 0.15);
}
return hovered ? Qt.alpha(Color.mOnSurface, 0.10) : Color.mSurfaceVariant;
}
function buttonBorder(buttonData, hovered, active) {
if (active) {
if (buttonData.tone === "danger") return Qt.alpha(Color.mError, 0.85);
return Color.mPrimary;
}
if (buttonData.tone === "accent") return Color.mPrimary;
if (buttonData.tone === "danger") return Qt.alpha(Color.mError, 0.65);
return hovered ? Color.mPrimary : Qt.alpha(Color.mOutline, 0.7);
}
function buttonTextColor(buttonData) {
if (buttonData.tone === "accent") return Color.mOnPrimary;
if (buttonData.tone === "danger") return Color.mError;
if (buttonData.tone === "operator") return Color.mPrimary;
return Color.mOnSurface;
}
Rectangle {
id: panelContainer
anchors.fill: parent
color: "transparent"
ColumnLayout {
anchors.fill: parent
anchors.margins: Style.marginM
spacing: Style.marginM
NBox {
id: panelCard
Layout.fillWidth: true
implicitHeight: Math.ceil(cardContent.implicitHeight + (Style.marginM * 2))
ColumnLayout {
id: cardContent
anchors.fill: parent
anchors.margins: Style.marginM
spacing: Style.marginM
RowLayout {
Layout.fillWidth: true
spacing: Style.marginM
NIcon {
icon: "calculator"
pointSize: Style.fontSizeL
color: Color.mPrimary
Layout.alignment: Qt.AlignVCenter
}
ColumnLayout {
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter
spacing: Style.marginS
NText {
text: pluginApi?.tr("panel.title")
pointSize: Style.fontSizeL
font.bold: true
color: Color.mOnSurface
}
NText {
Layout.fillWidth: true
text: pluginApi?.tr("panel.subtitle")
color: Qt.alpha(Color.mOnSurface, 0.68)
}
}
}
Rectangle {
Layout.fillWidth: true
Layout.preferredHeight: Math.round((expressionLabel.visible ? 92 : 72) * Style.uiScaleRatio)
Layout.minimumHeight: Layout.preferredHeight
radius: Style.radiusL
color: Qt.alpha(Color.mPrimary, 0.08)
border.color: root.activeFocus ? Qt.alpha(Color.mPrimary, 0.8) : Qt.alpha(Color.mOutline, 0.65)
border.width: Style.borderS
ColumnLayout {
anchors.fill: parent
anchors.margins: Style.marginM
spacing: Style.marginS
NText {
id: expressionLabel
Layout.fillWidth: true
text: mainInst?.expressionText ?? ""
visible: text !== ""
pointSize: Style.fontSizeS
color: Qt.alpha(Color.mOnSurface, 0.68)
elide: Text.ElideLeft
horizontalAlignment: Text.AlignRight
}
RowLayout {
Layout.fillWidth: true
spacing: Style.marginS
NText {
Layout.fillWidth: true
text: mainInst?.displayText ?? "0"
pointSize: Math.round(Style.fontSizeL * 1.85)
font.bold: true
color: (mainInst?.errorState ?? false) ? Color.mError : Color.mOnSurface
elide: Text.ElideLeft
horizontalAlignment: Text.AlignRight
}
Item {
Layout.preferredWidth: copyIcon.implicitWidth + Style.marginS
Layout.preferredHeight: copyIcon.implicitHeight
Layout.alignment: Qt.AlignVCenter
visible: mainInst?.hasCopyableResult ?? false
NIcon {
id: copyIcon
anchors.centerIn: parent
icon: "copy"
pointSize: Style.fontSizeM
color: copyMouse.containsMouse ? Color.mPrimary : Qt.alpha(Color.mOnSurface, 0.55)
Behavior on color { ColorAnimation { duration: Style.animationFast } }
}
MouseArea {
id: copyMouse
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: mainInst?.copyResult()
onEntered: TooltipService.show(parent, pluginApi?.tr("panel.copy-result-tooltip"))
onExited: TooltipService.hide()
}
}
}
}
}
GridLayout {
Layout.fillWidth: true
columns: 4
rowSpacing: Style.marginS
columnSpacing: Style.marginS
Repeater {
model: root.buttonModel
delegate: Rectangle {
required property var modelData
Layout.fillWidth: true
Layout.columnSpan: modelData.span
Layout.preferredHeight: Math.round((modelData.action === "equals" ? 58 : 52) * Style.uiScaleRatio)
Layout.minimumHeight: Layout.preferredHeight
readonly property bool isFlashed: root.flashedAction === modelData.action
radius: Style.radiusL
color: root.buttonFill(modelData, buttonMouse.containsMouse, isFlashed)
border.color: root.buttonBorder(modelData, buttonMouse.containsMouse, isFlashed)
border.width: Style.borderS
scale: isFlashed ? 0.96 : 1.0
Behavior on color { ColorAnimation { duration: Style.animationFast } }
Behavior on border.color { ColorAnimation { duration: Style.animationFast } }
Behavior on scale { NumberAnimation { duration: 90 } }
NText {
anchors.centerIn: parent
text: modelData.label
pointSize: modelData.action === "equals" ? Style.fontSizeL : Style.fontSizeM
font.bold: true
color: root.buttonTextColor(modelData)
}
MouseArea {
id: buttonMouse
anchors.fill: parent
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: {
mainInst?.pressButton(modelData.action);
root.forceActiveFocus();
}
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,51 @@
# noctalia-calculator
A theme-aware calculator plugin for Noctalia on Niri, with a bar widget, floating panel, keyboard support, and a clean UI that follows the active shell colors.
## Preview
![Calculator Preview](preview.png)
## Features
- Full expression evaluation with operator precedence via bundled `AdvancedMath.js`
- Bar widget with optional live result badge
- Floating panel with 21-button grid
- Mouse and keyboard input
- Theme-aware colors and spacing
- 10-language i18n (en, pt, es, fr, de, it, ru, zh, ja, ko)
- Configurable decimal precision (0-10)
## Usage
- Left click the bar widget to open the calculator
- Right click the bar widget for the context menu
- Keyboard:
- `0-9` for digits
- `+ - * /` for operators
- `.` or `,` for decimal input
- `Enter` for equals
- `Backspace` for delete
- `Esc` or `Delete` for clear
- `F9` for sign toggle
- `%` for percent
## Files
- `AdvancedMath.js`: math evaluation library (from noctalia-shell Helpers)
- `Main.qml`: calculator logic
- `BarWidget.qml`: bar widget entry point
- `Panel.qml`: floating calculator panel
- `Settings.qml`: plugin settings UI
- `i18n/`: translations (en, pt, es, fr, de, it, ru, zh, ja, ko)
## Copying the result
When the panel is open and a value is showing, a small copy icon appears to the right of the result. Click it to copy the value to the system clipboard. A toast confirms the copy.
Requires `wl-copy` (from `wl-clipboard`) on `PATH`. The icon is hidden in the resting `0` state and while an error is displayed.
## Author
Pir0c0pter0
`pir0c0pter0000@gmail.com`
@@ -0,0 +1,61 @@
import QtQuick
import QtQuick.Layouts
import qs.Commons
import qs.Widgets
ColumnLayout {
id: root
property var pluginApi: null
property bool valueShowBarValue: pluginApi?.pluginSettings?.showBarValue ?? true
property int valuePrecision: pluginApi?.pluginSettings?.precision ?? 8
spacing: Style.marginM
function saveSettings() {
if (!pluginApi?.pluginSettings) return;
pluginApi.pluginSettings.showBarValue = valueShowBarValue;
pluginApi.pluginSettings.precision = valuePrecision;
pluginApi.saveSettings();
}
NToggle {
Layout.fillWidth: true
label: pluginApi?.tr("settings.show-bar")
description: pluginApi?.tr("settings.show-bar-desc")
checked: root.valueShowBarValue
onToggled: checked => {
root.valueShowBarValue = checked;
root.saveSettings();
}
}
ColumnLayout {
Layout.fillWidth: true
spacing: Style.marginS
NLabel {
label: pluginApi?.tr("settings.precision", { "value": root.valuePrecision })
description: pluginApi?.tr("settings.precision-desc")
}
NSlider {
Layout.fillWidth: true
from: 0
to: 10
stepSize: 1
value: root.valuePrecision
onMoved: {
root.valuePrecision = Math.round(value);
root.saveSettings();
}
}
}
NLabel {
Layout.fillWidth: true
label: pluginApi?.tr("settings.about")
description: pluginApi?.tr("settings.developed-by", { "version": pluginApi?.manifest?.version ?? "1.0.0" })
}
}
@@ -0,0 +1,26 @@
{
"state": {
"error": "Fehler"
},
"bar": {
"clear": "Loeschen",
"settings": "Einstellungen",
"tooltip-title": "Rechner"
},
"panel": {
"title": "Rechner",
"subtitle": "Schnellrechnung in der Leiste",
"copy-result-tooltip": "Ergebnis kopieren"
},
"toast": {
"copied": "Kopiert: {value}"
},
"settings": {
"about": "Über",
"show-bar": "Wert in der Leiste anzeigen",
"show-bar-desc": "Zeigt den aktuellen Wert neben dem Rechner-Symbol an",
"precision": "Dezimalgenauigkeit: {value}",
"precision-desc": "Maximale Dezimalstellen bei der Ergebnisformatierung",
"developed-by": "Entwickelt von Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,26 @@
{
"state": {
"error": "Error"
},
"bar": {
"clear": "Clear",
"settings": "Settings",
"tooltip-title": "Calculator"
},
"panel": {
"title": "Calculator",
"subtitle": "Quick math in the bar",
"copy-result-tooltip": "Copy result"
},
"toast": {
"copied": "Copied: {value}"
},
"settings": {
"about": "About",
"show-bar": "Show value in bar",
"show-bar-desc": "Display the current value next to the calculator icon",
"precision": "Decimal precision: {value}",
"precision-desc": "Maximum decimals used when formatting results",
"developed-by": "Developed by Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "Error"
},
"bar": {
"clear": "Limpiar",
"settings": "Ajustes",
"tooltip-title": "Calculadora"
},
"panel": {
"title": "Calculadora",
"subtitle": "Calculo rapido en la barra"
},
"settings": {
"about": "Acerca de",
"show-bar": "Mostrar valor en la barra",
"show-bar-desc": "Muestra el valor actual junto al icono de la calculadora",
"precision": "Precision decimal: {value}",
"precision-desc": "Maximo de decimales al formatear resultados",
"developed-by": "Desarrollado por Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "Erreur"
},
"bar": {
"clear": "Effacer",
"settings": "Paramètres",
"tooltip-title": "Calculatrice"
},
"panel": {
"title": "Calculatrice",
"subtitle": "Calcul rapide dans la barre"
},
"settings": {
"about": "À propos",
"show-bar": "Afficher la valeur dans la barre",
"show-bar-desc": "Affiche la valeur actuelle à côté de l'icone de la calculatrice",
"precision": "Précision décimale : {value}",
"precision-desc": "Nombre maximal de décimales pour le formatage des résultats",
"developed-by": "Développé par Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "Errore"
},
"bar": {
"clear": "Cancella",
"settings": "Impostazioni",
"tooltip-title": "Calcolatrice"
},
"panel": {
"title": "Calcolatrice",
"subtitle": "Calcolo rapido nella barra"
},
"settings": {
"about": "Informazioni",
"show-bar": "Mostra valore nella barra",
"show-bar-desc": "Visualizza il valore corrente accanto all'icona della calcolatrice",
"precision": "Precisione decimale: {value}",
"precision-desc": "Numero massimo di decimali nella formattazione dei risultati",
"developed-by": "Sviluppato da Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "エラー"
},
"bar": {
"clear": "クリア",
"settings": "設定",
"tooltip-title": "電卓"
},
"panel": {
"title": "電卓",
"subtitle": "バーで素早く計算"
},
"settings": {
"about": "このプラグインについて",
"show-bar": "バーに数値を表示",
"show-bar-desc": "電卓アイコンの横に現在の値を表示します",
"precision": "小数精度: {value}",
"precision-desc": "結果のフォーマット時の最大小数桁数",
"developed-by": "Pir0c0pter0 が開発<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "오류"
},
"bar": {
"clear": "지우기",
"settings": "설정",
"tooltip-title": "계산기"
},
"panel": {
"title": "계산기",
"subtitle": "바에서 빠른 계산"
},
"settings": {
"about": "정보",
"show-bar": "바에 값 표시",
"show-bar-desc": "계산기 아이콘 옆에 현재 값을 표시합니다",
"precision": "소수점 정밀도: {value}",
"precision-desc": "결과 포맷 시 최대 소수 자릿수",
"developed-by": "Pir0c0pter0 개발<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "Erro"
},
"bar": {
"clear": "Limpar",
"settings": "Configuracoes",
"tooltip-title": "Calculadora"
},
"panel": {
"title": "Calculadora",
"subtitle": "Conta rapida direto na barra"
},
"settings": {
"about": "Sobre",
"show-bar": "Mostrar valor na barra",
"show-bar-desc": "Exibe o valor atual ao lado do icone da calculadora",
"precision": "Precisao decimal: {value}",
"precision-desc": "Maximo de casas decimais ao formatar resultados",
"developed-by": "Desenvolvido por Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "Ошибка"
},
"bar": {
"clear": "Очистить",
"settings": "Настройки",
"tooltip-title": "Калькулятор"
},
"panel": {
"title": "Калькулятор",
"subtitle": "Быстрый расчёт в панели"
},
"settings": {
"about": "О плагине",
"show-bar": "Показывать значение в панели",
"show-bar-desc": "Отображает текущее значение рядом с иконкой калькулятора",
"precision": "Десятичная точность: {value}",
"precision-desc": "Максимальное количество десятичных знаков при форматировании результатов",
"developed-by": "Разработано Pir0c0pter0<br>v{version}"
}
}
@@ -0,0 +1,22 @@
{
"state": {
"error": "错误"
},
"bar": {
"clear": "清除",
"settings": "设置",
"tooltip-title": "计算器"
},
"panel": {
"title": "计算器",
"subtitle": "栏内快速计算"
},
"settings": {
"about": "关于",
"show-bar": "在栏中显示数值",
"show-bar-desc": "在计算器图标旁显示当前数值",
"precision": "小数精度: {value}",
"precision-desc": "格式化结果时的最大小数位数",
"developed-by": "由 Pir0c0pter0 开发<br>v{version}"
}
}
@@ -0,0 +1,26 @@
{
"id": "noctalia-calculator",
"name": "Calculator",
"version": "1.1.1",
"minNoctaliaVersion": "4.4.0",
"author": "pir0c0pter0",
"license": "MIT",
"repository": "https://github.com/noctalia-dev/noctalia-plugins",
"description": "Theme-aware calculator plugin for Noctalia on Niri with bar widget, floating panel and keyboard support",
"tags": ["Bar", "Panel", "Utility"],
"entryPoints": {
"main": "Main.qml",
"barWidget": "BarWidget.qml",
"panel": "Panel.qml",
"settings": "Settings.qml"
},
"dependencies": {
"plugins": []
},
"metadata": {
"defaultSettings": {
"showBarValue": true,
"precision": 8
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB