Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/components/bar/modules/cpu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import CpuUsageService from 'src/services/system/cpuUsage';

const inputHandler = InputHandlerService.getInstance();

const { label, round, leftClick, rightClick, middleClick, scrollUp, scrollDown, pollingInterval, icon } =
const { label, round, showPerCoreUsage, leftClick, rightClick, middleClick, scrollUp, scrollDown, pollingInterval, icon } =
options.bar.customModules.cpu;

const cpuService = new CpuUsageService({ frequency: pollingInterval });
Expand All @@ -23,12 +23,31 @@ export const Cpu = (): BarBoxChild => {
},
);

const tooltipBinding = Variable.derive(
[bind(cpuService.cpu), bind(cpuService.perCoreUsage), bind(round), bind(showPerCoreUsage)],
(cpuUsg: number, perCoreUsage: number[], round: boolean, showPerCore: boolean) => {
if (!showPerCore) {
const displayUsage = round ? Math.round(cpuUsg) : cpuUsg.toFixed(2);
return `CPU: ${displayUsage}%`;
}

if (perCoreUsage.length === 0) return 'CPU';

const coreLines = perCoreUsage.map((usage, index) => {
const displayUsage = round ? Math.round(usage) : usage.toFixed(2);
return `Core ${index}: ${displayUsage}%`;
}).join('\n');

return `${coreLines}`;
},
);

let inputHandlerBindings: Variable<void>;

const cpuModule = Module({
textIcon: bind(icon),
label: labelBinding(),
tooltipText: 'CPU',
tooltipText: tooltipBinding(),
boxClass: 'cpu',
showLabelBinding: bind(label),
props: {
Expand All @@ -54,6 +73,7 @@ export const Cpu = (): BarBoxChild => {
onDestroy: () => {
inputHandlerBindings.drop();
labelBinding.drop();
tooltipBinding.drop();
cpuService.destroy();
},
},
Expand Down
14 changes: 11 additions & 3 deletions src/components/bar/modules/ram/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,19 @@ export const Ram = (): BarBoxChild => {

let inputHandlerBindings: Variable<void>;

const tooltipBinding = Variable.derive(
[bind(ramService.ram), bind(round)],
(rmUsg: GenericResourceData, round: boolean) => {
const usedLabel = renderResourceLabel('used', rmUsg, round);
const totalLabel = renderResourceLabel('used', { ...rmUsg, used: rmUsg.total }, round);
return `RAM: ${usedLabel} / ${totalLabel}`;
},
);

const ramModule = Module({
textIcon: bind(icon),
label: labelBinding(),
tooltipText: bind(labelType).as((lblTyp) => {
return formatTooltip('RAM', lblTyp);
}),
tooltipText: tooltipBinding(),
boxClass: 'ram',
showLabelBinding: bind(label),
props: {
Expand Down Expand Up @@ -73,6 +80,7 @@ export const Ram = (): BarBoxChild => {
onDestroy: () => {
inputHandlerBindings.drop();
labelBinding.drop();
tooltipBinding.drop();
ramService.destroy();
},
},
Expand Down
1 change: 1 addition & 0 deletions src/components/bar/settings/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export const CustomModuleSettings = (): JSX.Element => {
<Option opt={options.bar.customModules.cpu.label} title="Show Label" type="boolean" />
<Option opt={options.theme.bar.buttons.modules.cpu.spacing} title="Spacing" type="string" />
<Option opt={options.bar.customModules.cpu.round} title="Round" type="boolean" />
<Option opt={options.bar.customModules.cpu.showPerCoreUsage} title="Show Tooltip Per-Core Usage" type="boolean" />
<Option
opt={options.bar.customModules.cpu.pollingInterval}
title="Polling Interval"
Expand Down
3 changes: 2 additions & 1 deletion src/components/bar/utils/systemResource/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ export const renderResourceLabel = (
return SizeConverter.fromBytes(free).formatAuto(precision);
}

return `${percentage}%`;
const roundedPercentage = round ? Math.round(percentage) : percentage.toFixed(2);
return `${roundedPercentage}%`;
};

/**
Expand Down
3 changes: 2 additions & 1 deletion src/configuration/modules/config/bar/cpu/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { opt } from 'src/lib/options';

export default {
icon: opt(''),
icon: opt(''),
label: opt(true),
round: opt(true),
showPerCoreUsage: opt(true),
pollingInterval: opt(2000),
leftClick: opt(''),
rightClick: opt(''),
Expand Down
107 changes: 106 additions & 1 deletion src/services/system/cpuUsage/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { bind, Variable } from 'astal';
import { bind, GLib, Variable } from 'astal';
import GTop from 'gi://GTop';
import { FunctionPoller } from 'src/lib/poller/FunctionPoller';
import { CpuServiceCtor } from './types';

interface CoreStat {
total: number;
idle: number;
}

/**
* Service for monitoring CPU usage percentage
*/
Expand All @@ -11,13 +16,17 @@ class CpuUsageService {
private _previousCpuData = new GTop.glibtop_cpu();
private _cpuPoller: FunctionPoller<number, []>;
private _isInitialized = false;
private _previousPerCoreData: CoreStat[] = [];

private _cpu = Variable(0);
private _perCoreUsage = Variable<number[]>([]);

constructor({ frequency }: CpuServiceCtor = {}) {
this._updateFrequency = frequency ?? Variable(2000);
GTop.glibtop_get_cpu(this._previousCpuData);

this._initializePerCoreData();

this._calculateUsage = this._calculateUsage.bind(this);

this._cpuPoller = new FunctionPoller<number, []>(
Expand All @@ -28,6 +37,41 @@ class CpuUsageService {
);
}

/**
* Initializes per-core CPU data from /proc/stat
*/
private _initializePerCoreData(): void {
try {
const [success, statBytes] = GLib.file_get_contents('/proc/stat');
if (!success || !statBytes) return;

const statContent = new TextDecoder('utf-8').decode(statBytes);
const lines = statContent.split('\n');

this._previousPerCoreData = [];

for (const line of lines) {
if (/^cpu\d+/.test(line)) {
const parts = line.trim().split(/\s+/);
if (parts.length >= 5) {
const user = parseInt(parts[1], 10) || 0;
const nice = parseInt(parts[2], 10) || 0;
const system = parseInt(parts[3], 10) || 0;
const idle = parseInt(parts[4], 10) || 0;
const iowait = parseInt(parts[5] || '0', 10) || 0;

const total = user + nice + system + idle + iowait;
this._previousPerCoreData.push({ total, idle });
} else {
this._previousPerCoreData.push({ total: 0, idle: 0 });
}
}
}
} catch (error) {
console.error('Error initializing per-core CPU data:', error);
}
}

/**
* Manually refreshes the CPU usage reading
*/
Expand All @@ -44,6 +88,15 @@ class CpuUsageService {
return this._cpu;
}

/**
* Gets the per-core CPU usage percentages
*
* @returns Variable containing array of CPU usage percentages for each core
*/
public get perCoreUsage(): Variable<number[]> {
return this._perCoreUsage;
}

/**
* Calculates the current CPU usage percentage based on CPU time deltas
*
Expand All @@ -58,11 +111,62 @@ class CpuUsageService {

const cpuUsagePercentage = totalDiff > 0 ? ((totalDiff - idleDiff) / totalDiff) * 100 : 0;

this._calculatePerCoreUsage();

this._previousCpuData = currentCpuData;

return cpuUsagePercentage;
}

/**
* Calculates per-core CPU usage from /proc/stat
*/
private _calculatePerCoreUsage(): void {
try {
const [success, statBytes] = GLib.file_get_contents('/proc/stat');
if (!success || !statBytes) return;

const statContent = new TextDecoder('utf-8').decode(statBytes);
const lines = statContent.split('\n');
const perCoreUsages: number[] = [];
let coreIndex = 0;

for (const line of lines) {
if (/^cpu\d+/.test(line)) {
const parts = line.trim().split(/\s+/);
if (parts.length >= 5 && coreIndex < this._previousPerCoreData.length) {
const user = parseInt(parts[1], 10) || 0;
const nice = parseInt(parts[2], 10) || 0;
const system = parseInt(parts[3], 10) || 0;
const idle = parseInt(parts[4], 10) || 0;
const iowait = parseInt(parts[5] || '0', 10) || 0;

const currentTotal = user + nice + system + idle + iowait;
const currentIdle = idle;

const prevData = this._previousPerCoreData[coreIndex];
const totalDiff = currentTotal - prevData.total;
const idleDiff = currentIdle - prevData.idle;

const coreUsage = totalDiff > 0 ? ((totalDiff - idleDiff) / totalDiff) * 100 : 0;
perCoreUsages.push(parseFloat(coreUsage.toFixed(2)));

this._previousPerCoreData[coreIndex] = { total: currentTotal, idle: currentIdle };
} else {
perCoreUsages.push(0);
}
coreIndex++;
}
}

if (perCoreUsages.length > 0) {
this._perCoreUsage.set(perCoreUsages);
}
} catch (error) {
console.error('Error calculating per-core CPU usage:', error);
}
}

/**
* Updates the polling frequency for CPU usage monitoring
*
Expand Down Expand Up @@ -102,6 +206,7 @@ class CpuUsageService {
public destroy(): void {
this._cpuPoller.stop();
this._cpu.drop();
this._perCoreUsage.drop();
this._updateFrequency.drop();
}
}
Expand Down