Files
ags/widget/modules/Ram.tsx
T
2025-03-10 21:51:05 +07:00

45 lines
1.4 KiB
TypeScript

import { Variable, GLib } from "astal";
const calculateRamUsage = (): string => {
try {
const [success, meminfoBytes] = GLib.file_get_contents('/proc/meminfo');
if (!success || !meminfoBytes) {
throw new Error('Failed to read /proc/meminfo or file content is null.');
}
const meminfo = new TextDecoder('utf-8').decode(meminfoBytes);
const totalMatch = meminfo.match(/MemTotal:\s+(\d+)/);
const availableMatch = meminfo.match(/MemAvailable:\s+(\d+)/);
if (!totalMatch || !availableMatch) {
throw new Error('Failed to parse /proc/meminfo for memory values.');
}
const totalRamInBytes = parseInt(totalMatch[1], 10) * 1024;
const availableRamInBytes = parseInt(availableMatch[1], 10) * 1024;
let usedRam = totalRamInBytes - availableRamInBytes;
usedRam = isNaN(usedRam) || usedRam < 0 ? 0 : usedRam;
const ramstring = " " + Math.floor(usedRam / totalRamInBytes * 100) + "%"
return ramstring
} catch (error) {
console.error('Error calculating RAM usage:', error);
return "";
}
};
export default function Ram() {
const ram_usage = Variable<string>("").poll(5000, () =>
calculateRamUsage())
return <box className="ram">
<label
className="Ram"
onDestroy={() => ram_usage.drop()}
label={ram_usage()} />
</box>
}