-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
433 lines (382 loc) · 14.4 KB
/
Program.cs
File metadata and controls
433 lines (382 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
/// <summary>
/// QuickSheet System Monitor Extension — shows CPU, RAM, and disk usage in cells.
/// Registers the "sys" prefix. Usage: "sys: cpu", "sys: mem", "sys: disk", "sys: all".
/// Refreshes every 2 seconds with live metrics.
/// </summary>
class Program
{
private static readonly JsonSerializerOptions JsonOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = false
};
private static readonly HashSet<string> ActiveMonitors = new();
private static readonly object Lock = new();
private static TimeSpan _prevCpuTime = TimeSpan.Zero;
private static DateTime _prevSampleTime = DateTime.UtcNow;
private static double _lastCpuPercent = 0;
// Track idle time separately for proper CPU calculation on Linux
private static long _prevIdleJiffies = 0;
private static long _prevTotalJiffies = 0;
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
// Initialize CPU baseline
InitCpuBaseline();
// Background thread to push updates every 2 seconds
var updateTimer = new System.Timers.Timer(2000);
updateTimer.Elapsed += OnTimerTick;
updateTimer.AutoReset = true;
updateTimer.Start();
string? line;
while ((line = Console.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line)) continue;
try
{
using var doc = JsonDocument.Parse(line);
string? type = doc.RootElement.TryGetProperty("type", out var tp) ? tp.GetString() : null;
switch (type)
{
case "init":
HandleInit();
break;
case "activate":
HandleActivate(doc.RootElement);
break;
case "deactivate":
HandleDeactivate(doc.RootElement);
break;
}
}
catch (Exception ex)
{
SendError("", $"Parse error: {ex.Message}");
}
}
}
static void HandleInit()
{
var register = new
{
type = "register",
prefix = "sys",
name = "System Monitor",
version = "1.0.0"
};
SendJson(register);
SendLog("System Monitor extension registered with prefix 'sys'");
}
static void HandleActivate(JsonElement root)
{
string id = root.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? "" : "";
string[] extParams = [];
if (root.TryGetProperty("params", out var paramsProp) && paramsProp.ValueKind == JsonValueKind.Array)
{
extParams = paramsProp.EnumerateArray()
.Select(p => p.GetString() ?? "")
.ToArray();
}
string param = extParams.Length > 0 ? extParams[0].Trim().ToLowerInvariant() : "all";
lock (Lock)
{
ActiveMonitors.Add(id + ":" + param);
}
SendMetrics(id, param);
}
static void HandleDeactivate(JsonElement root)
{
string id = root.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? "" : "";
lock (Lock)
{
// Remove all monitors for this id
ActiveMonitors.RemoveWhere(m => m.StartsWith(id + ":"));
}
}
static void OnTimerTick(object? sender, System.Timers.ElapsedEventArgs e)
{
SampleCpu();
List<string> monitors;
lock (Lock)
{
if (ActiveMonitors.Count == 0) return;
monitors = ActiveMonitors.ToList();
}
foreach (var entry in monitors)
{
var parts = entry.Split(':', 2);
if (parts.Length == 2)
{
try { SendMetrics(parts[0], parts[1]); }
catch { }
}
}
}
static void SendMetrics(string id, string metric)
{
var cells = new List<object>();
switch (metric)
{
case "cpu":
AddCpuCells(cells, 0);
break;
case "mem":
case "ram":
case "memory":
AddMemoryCells(cells, 0);
break;
case "disk":
AddDiskCells(cells, 0);
break;
case "all":
default:
AddCpuCells(cells, 0);
AddMemoryCells(cells, 1);
AddDiskCells(cells, 2);
AddUptimeCells(cells, 3);
break;
}
SendJson(new { type = "write", id, cells });
}
static void AddCpuCells(List<object> cells, int row)
{
double cpuPercent = _lastCpuPercent;
string bar = RenderBar(cpuPercent, 20);
string emoji = cpuPercent > 80 ? "🔴" : cpuPercent > 50 ? "🟡" : "🟢";
int cores = Environment.ProcessorCount;
cells.Add(new { r = row, c = 0, v = $"{emoji} CPU" });
cells.Add(new { r = row, c = 1, v = $"{cpuPercent:F1}% {bar}" });
cells.Add(new { r = row, c = 2, v = $"{cores} cores" });
}
static void AddMemoryCells(List<object> cells, int row)
{
var (usedMB, totalMB) = GetMemoryInfo();
double percent = totalMB > 0 ? (usedMB / totalMB) * 100 : 0;
string bar = RenderBar(percent, 20);
string emoji = percent > 80 ? "🔴" : percent > 50 ? "🟡" : "🟢";
cells.Add(new { r = row, c = 0, v = $"{emoji} RAM" });
cells.Add(new { r = row, c = 1, v = $"{percent:F1}% {bar}" });
cells.Add(new { r = row, c = 2, v = $"{usedMB / 1024:F1}/{totalMB / 1024:F1} GB" });
}
static void AddDiskCells(List<object> cells, int row)
{
try
{
string rootPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? @"C:\" : "/";
var drive = new DriveInfo(rootPath);
double totalGB = drive.TotalSize / (1024.0 * 1024 * 1024);
double freeGB = drive.AvailableFreeSpace / (1024.0 * 1024 * 1024);
double usedGB = totalGB - freeGB;
double percent = totalGB > 0 ? (usedGB / totalGB) * 100 : 0;
string bar = RenderBar(percent, 20);
string emoji = percent > 80 ? "🔴" : percent > 50 ? "🟡" : "🟢";
cells.Add(new { r = row, c = 0, v = $"{emoji} Disk" });
cells.Add(new { r = row, c = 1, v = $"{percent:F1}% {bar}" });
cells.Add(new { r = row, c = 2, v = $"{usedGB:F1}/{totalGB:F1} GB" });
}
catch
{
cells.Add(new { r = row, c = 0, v = "💾 Disk" });
cells.Add(new { r = row, c = 1, v = "unavailable" });
}
}
static void AddUptimeCells(List<object> cells, int row)
{
try
{
TimeSpan uptime = TimeSpan.FromMilliseconds(Environment.TickCount64);
string uptimeStr = uptime.Days > 0
? $"{uptime.Days}d {uptime.Hours}h {uptime.Minutes}m"
: $"{uptime.Hours}h {uptime.Minutes}m {uptime.Seconds}s";
cells.Add(new { r = row, c = 0, v = "⏱️ Uptime" });
cells.Add(new { r = row, c = 1, v = uptimeStr });
cells.Add(new { r = row, c = 2, v = DateTime.Now.ToString("HH:mm:ss") });
}
catch
{
cells.Add(new { r = row, c = 0, v = "⏱️ Uptime" });
cells.Add(new { r = row, c = 1, v = "unavailable" });
}
}
static string RenderBar(double percent, int width)
{
int filled = (int)Math.Round(percent / 100 * width);
filled = Math.Clamp(filled, 0, width);
return "[" + new string('█', filled) + new string('░', width - filled) + "]";
}
// ── CPU ──────────────────────────────────────────────────────────
static void InitCpuBaseline()
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
ReadLinuxCpuJiffies(out _prevIdleJiffies, out _prevTotalJiffies);
}
else
{
_prevCpuTime = Process.GetCurrentProcess().TotalProcessorTime;
}
_prevSampleTime = DateTime.UtcNow;
}
catch { }
}
static void SampleCpu()
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
SampleCpuLinux();
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
SampleCpuWindows();
}
}
catch { }
}
static void SampleCpuLinux()
{
if (ReadLinuxCpuJiffies(out long idle, out long total))
{
long deltaIdle = idle - _prevIdleJiffies;
long deltaTotal = total - _prevTotalJiffies;
if (deltaTotal > 0)
{
_lastCpuPercent = Math.Clamp((1.0 - (double)deltaIdle / deltaTotal) * 100, 0, 100);
}
_prevIdleJiffies = idle;
_prevTotalJiffies = total;
}
}
static bool ReadLinuxCpuJiffies(out long idle, out long total)
{
idle = 0; total = 0;
try
{
string[] lines = File.ReadAllLines("/proc/stat");
string? cpuLine = lines.FirstOrDefault(l => l.StartsWith("cpu "));
if (cpuLine == null) return false;
var parts = cpuLine.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 5) return false;
// cpu user nice system idle [iowait irq softirq steal]
long user = long.Parse(parts[1]);
long nice = long.Parse(parts[2]);
long system = long.Parse(parts[3]);
idle = long.Parse(parts[4]);
long iowait = parts.Length > 5 ? long.Parse(parts[5]) : 0;
long irq = parts.Length > 6 ? long.Parse(parts[6]) : 0;
long softirq = parts.Length > 7 ? long.Parse(parts[7]) : 0;
long steal = parts.Length > 8 ? long.Parse(parts[8]) : 0;
idle += iowait;
total = user + nice + system + idle + irq + softirq + steal;
return true;
}
catch { return false; }
}
static void SampleCpuWindows()
{
// Use GetSystemTimes via P/Invoke for system-wide CPU on Windows
if (GetSystemTimes(out long idleTime, out long kernelTime, out long userTime))
{
long totalTime = kernelTime + userTime; // kernel includes idle
long deltaIdle = idleTime - _prevIdleJiffies;
long deltaTotal = totalTime - _prevTotalJiffies;
if (deltaTotal > 0)
{
_lastCpuPercent = Math.Clamp((1.0 - (double)deltaIdle / deltaTotal) * 100, 0, 100);
}
_prevIdleJiffies = idleTime;
_prevTotalJiffies = totalTime;
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetSystemTimes(out long idleTime, out long kernelTime, out long userTime);
// ── Memory ──────────────────────────────────────────────────────
static (double usedMB, double totalMB) GetMemoryInfo()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
try
{
string[] lines = File.ReadAllLines("/proc/meminfo");
long totalKB = 0, availKB = 0;
foreach (var line in lines)
{
if (line.StartsWith("MemTotal:"))
totalKB = ParseMemInfoValue(line);
else if (line.StartsWith("MemAvailable:"))
availKB = ParseMemInfoValue(line);
}
double totalMB = totalKB / 1024.0;
double usedMB = (totalKB - availKB) / 1024.0;
return (usedMB, totalMB);
}
catch { }
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
var memStatus = new MEMORYSTATUSEX { dwLength = 64 };
if (GlobalMemoryStatusEx(ref memStatus))
{
double totalMB = memStatus.ullTotalPhys / (1024.0 * 1024);
double availMB = memStatus.ullAvailPhys / (1024.0 * 1024);
return (totalMB - availMB, totalMB);
}
}
catch { }
}
// Last resort fallback
var gcInfo = GC.GetGCMemoryInfo();
return (gcInfo.HeapSizeBytes / (1024.0 * 1024), gcInfo.TotalAvailableMemoryBytes / (1024.0 * 1024));
}
[StructLayout(LayoutKind.Sequential)]
private struct MEMORYSTATUSEX
{
public int dwLength;
public int dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
static long ParseMemInfoValue(string line)
{
var parts = line.Split(':', 2);
if (parts.Length == 2)
{
string val = parts[1].Trim().Replace("kB", "").Trim();
if (long.TryParse(val, out long result)) return result;
}
return 0;
}
// ── JSON helpers ────────────────────────────────────────────────
static void SendJson(object obj)
{
string json = JsonSerializer.Serialize(obj, JsonOpts);
Console.WriteLine(json);
Console.Out.Flush();
}
static void SendLog(string message)
{
SendJson(new { type = "log", message });
}
static void SendError(string id, string message)
{
SendJson(new { type = "error", id, message });
}
}