Repository navigation
Expand file tree
/
Copy pathvramtop_gui.cpp
More file actions
635 lines (594 loc) · 26.8 KB
/
Copy pathvramtop_gui.cpp
File metadata and controls
635 lines (594 loc) · 26.8 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// vramtop · vramtop_gui.cpp — the human glass: a live WizTree-style treemap of the card.
// One band per adapter (VRAM bar · engine load · temps · a history sparkline), then the
// card as a treemap: every process by resident VRAM, an "unattributed" tile for what the
// driver holds, and a dark "free" tile — so the picture is the whole 16 GB, not just the
// tenants. Hover for detail. Keys: G group-by-name · T pin on top · F5 refresh now.
// Collection runs on its own thread with a persistent Collector; the UI thread only paints.
#include "app_util.h"
#include "treemap.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <windowsx.h>
#include <cmath>
namespace vramtop {
namespace {
// ---- theme ----
constexpr COLORREF kBg = RGB(15, 15, 19);
constexpr COLORREF kBandBg = RGB(22, 22, 28);
constexpr COLORREF kTrack = RGB(43, 43, 52);
constexpr COLORREF kText = RGB(236, 236, 240);
constexpr COLORREF kDim = RGB(148, 148, 160);
constexpr COLORREF kGrn = RGB(64, 199, 106);
constexpr COLORREF kAmb = RGB(244, 180, 66);
constexpr COLORREF kRed = RGB(238, 92, 92);
constexpr COLORREF kOther = RGB(64, 64, 74);
constexpr COLORREF kUnattr = RGB(78, 78, 92);
constexpr COLORREF kFree = RGB(20, 20, 27);
constexpr COLORREF kLoadLine = RGB(120, 190, 240);
COLORREF pct_color(double p) { return p < 60 ? kGrn : (p < 85 ? kAmb : kRed); }
COLORREF mix(COLORREF a, COLORREF b, double t) {
auto ch = [&](int x, int y) { return (BYTE)std::lround(x + (y - x) * t); };
return RGB(ch(GetRValue(a), GetRValue(b)), ch(GetGValue(a), GetGValue(b)), ch(GetBValue(a), GetBValue(b)));
}
COLORREF hsl_rgb(double h, double s, double l) {
auto f = [&](double n) {
const double k = fmod(n + h / 30.0, 12.0);
const double a = s * std::min(l, 1 - l);
return l - a * std::max(-1.0, std::min({ k - 3, 9 - k, 1.0 }));
};
return RGB((BYTE)(f(0) * 255), (BYTE)(f(8) * 255), (BYTE)(f(4) * 255));
}
COLORREF name_color(const std::string& n) {
uint32_t h = 2166136261u;
for (unsigned char c : n) { h ^= c; h *= 16777619u; }
return hsl_rgb((double)(h % 360u), 0.46, 0.46);
}
bool light_color(COLORREF c) {
return 0.299 * GetRValue(c) + 0.587 * GetGValue(c) + 0.114 * GetBValue(c) > 168;
}
// ---- layout ----
enum class Kind { Proc, Other, Unattr, Free };
struct Tile {
RECT rc{};
Kind kind = Kind::Proc;
COLORREF col = kOther;
std::wstring l1, l2, l3;
std::string status;
};
struct Band {
RECT rc{};
int adapter = -1;
bool compact = false;
};
struct Layout {
std::vector<Band> bands;
std::vector<Tile> tiles;
};
constexpr size_t kIdOther = SIZE_MAX - 1, kIdUnattr = SIZE_MAX - 2, kIdFree = SIZE_MAX - 3;
// ---- state ----
struct Gui {
Opts opts;
HWND hwnd = nullptr;
SRWLOCK lock = SRWLOCK_INIT;
Snapshot snap; // written by the collector thread
bool have = false;
Snapshot cur; // UI-thread copy of the latest snapshot
HANDLE quit = nullptr, kick = nullptr, thread = nullptr;
bool group = true; // grouped by default — the WizTree glance
bool topmost = false;
int hover = -1;
Layout lay;
bool lay_valid = false;
int lay_w = 0, lay_h = 0;
bool lay_group = true;
std::vector<std::vector<std::pair<float, float>>> hist; // per adapter: (used frac, load %)
int dpi = 96;
HFONT fTitle = nullptr, fBold = nullptr, fNorm = nullptr, fSmall = nullptr;
HICON icon_big = nullptr, icon_small = nullptr;
};
Gui* g = nullptr;
constexpr UINT WM_APP_SNAP = WM_APP + 1;
constexpr size_t kHistMax = 360;
void make_fonts(Gui& s) {
for (HFONT* f : { &s.fTitle, &s.fBold, &s.fNorm, &s.fSmall })
if (*f) { DeleteObject(*f); *f = nullptr; }
auto mk = [&](int px, int weight) {
return CreateFontW(-MulDiv(px, s.dpi, 96), 0, 0, 0, weight, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI");
};
s.fTitle = mk(16, FW_SEMIBOLD);
s.fBold = mk(13, FW_SEMIBOLD);
s.fNorm = mk(12, FW_NORMAL);
s.fSmall = mk(11, FW_NORMAL);
}
int px(const Gui& s, int v) { return MulDiv(v, s.dpi, 96); }
// A small treemap as the window icon — generated at runtime, no asset to ship.
HICON make_icon(int sz) {
BITMAPINFO bi{};
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = sz;
bi.bmiHeader.biHeight = -sz;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
void* bits = nullptr;
HBITMAP color = CreateDIBSection(nullptr, &bi, DIB_RGB_COLORS, &bits, nullptr, 0);
if (!color || !bits) return nullptr;
auto* p = (uint32_t*)bits;
auto put = [&](int x0, int y0, int x1, int y1, uint32_t argb) {
for (int y = std::max(0, y0); y < std::min(sz, y1); ++y)
for (int x = std::max(0, x0); x < std::min(sz, x1); ++x) p[y * sz + x] = argb;
};
const int gp = std::max(1, sz / 16);
const int xm = sz * 11 / 20, ym = sz * 3 / 5, xc = xm + (sz - xm) / 2;
put(0, 0, sz, sz, 0xFF14141A);
put(gp, gp, xm, sz - gp, 0xFFB23C50); // crimson: the big tenant
put(xm + gp, gp, sz - gp, ym, 0xFF5F3CAA); // purple
put(xm + gp, ym + gp, xc, sz - gp, 0xFF3CA05A); // green
put(xc + gp, ym + gp, sz - gp, sz - gp, 0xFFAA3C82); // magenta
HBITMAP mask = CreateBitmap(sz, sz, 1, 1, nullptr);
ICONINFO ii{};
ii.fIcon = TRUE;
ii.hbmMask = mask;
ii.hbmColor = color;
HICON h = CreateIconIndirect(&ii);
DeleteObject(mask);
DeleteObject(color);
return h;
}
Layout build_layout(const Gui& s, const Snapshot& snap, RECT client) {
Layout L;
const int statusH = px(s, 26);
client.bottom -= statusH;
struct ARef { int idx; DispResult rows; bool compact; double share; };
std::vector<ARef> ads;
Opts o = s.opts;
o.group = s.group;
double shareSum = 0;
for (size_t i = 0; i < snap.adapters.size(); ++i) {
const auto& a = snap.adapters[i];
if (a.software) continue;
ARef r;
r.idx = (int)i;
r.rows = display_rows(snap, o, (int)i);
r.compact = trivial_adapter(a, !r.rows.rows.empty());
if (r.compact && a.vram_total == 0 && a.vram_used == 0) continue; // phantom, nothing to say
r.share = r.compact ? 0.0 : (double)std::max<uint64_t>(std::max(a.vram_total, a.vram_used), 1);
shareSum += r.share;
ads.push_back(std::move(r));
}
const int bandH = px(s, 80), compactH = px(s, 32);
int mapSpace = client.bottom - client.top;
for (const auto& a : ads) mapSpace -= a.compact ? compactH : bandH;
int y = client.top;
for (auto& a : ads) {
const auto& ast = snap.adapters[(size_t)a.idx];
Band b;
b.adapter = a.idx;
b.compact = a.compact;
b.rc = { client.left, y, client.right, y + (a.compact ? compactH : bandH) };
L.bands.push_back(b);
y = b.rc.bottom;
if (a.compact || shareSum <= 0 || mapSpace < px(s, 40)) continue;
const int h = (int)std::lround(mapSpace * (a.share / shareSum));
RECT map = { client.left, y, client.right, std::min<LONG>(client.bottom, (LONG)(y + h)) };
y = map.bottom;
// the card: tenants + unattributed + free, with a sliver tail folded into "other"
const auto& rows = a.rows.rows;
uint64_t rows_sum = a.rows.hidden_weight;
for (const auto& r : rows) rows_sum += r.weight;
const uint64_t used = ast.vram_used;
const uint64_t unattr = used > rows_sum ? used - rows_sum : 0;
const uint64_t freeb = ast.vram_total > used ? ast.vram_total - used : 0;
const double card = (double)std::max<uint64_t>(std::max(ast.vram_total, used), std::max<uint64_t>(rows_sum, 1));
std::vector<TmItem> items;
uint64_t other_w = a.rows.hidden_weight;
int other_n = a.rows.hidden;
for (size_t ri = 0; ri < rows.size(); ++ri) {
const double frac = (double)rows[ri].weight / card;
if ((frac < 0.004 || items.size() >= 48) && ri > 0) {
other_w += rows[ri].weight;
other_n++;
continue;
}
items.push_back({ (double)rows[ri].weight, ri });
}
if (other_w) items.push_back({ (double)other_w, kIdOther });
if (unattr >= (16ull << 20)) items.push_back({ (double)unattr, kIdUnattr });
if (freeb >= (16ull << 20)) items.push_back({ (double)freeb, kIdFree });
auto placed = squarify(std::move(items), { (double)map.left, (double)map.top,
(double)(map.right - map.left), (double)(map.bottom - map.top) });
for (const auto& pl : placed) {
Tile t;
t.rc.left = std::clamp((LONG)std::lround(pl.r.x), map.left, map.right);
t.rc.top = std::clamp((LONG)std::lround(pl.r.y), map.top, map.bottom);
t.rc.right = std::clamp((LONG)std::lround(pl.r.x + pl.r.w), map.left, map.right);
t.rc.bottom = std::clamp((LONG)std::lround(pl.r.y + pl.r.h), map.top, map.bottom);
if (pl.id == kIdOther) {
t.kind = Kind::Other;
t.col = kOther;
t.l1 = L"other";
t.l2 = widen(ssprintf("%s · %d procs", human_bytes(other_w).c_str(), other_n));
t.status = ssprintf("%s: %d smaller processes · %s together", ast.name.c_str(), other_n,
human_bytes(other_w).c_str());
} else if (pl.id == kIdUnattr) {
t.kind = Kind::Unattr;
t.col = kUnattr;
t.l1 = L"unattributed";
t.l2 = widen(human_bytes(unattr));
t.status = ssprintf("%s: %s resident but charged to no process (driver/kernel "
"reservations, shared surfaces)", ast.name.c_str(), human_bytes(unattr).c_str());
} else if (pl.id == kIdFree) {
t.kind = Kind::Free;
t.col = kFree;
t.l1 = L"free";
t.l2 = widen(human_bytes(freeb));
t.status = ssprintf("%s: %s of %s free · app budget %s", ast.name.c_str(),
human_bytes(freeb).c_str(), human_bytes(ast.vram_total).c_str(),
human_bytes(ast.vram_budget).c_str());
} else {
const auto& r = rows[pl.id];
t.kind = Kind::Proc;
t.col = name_color(r.name);
std::string nm = r.name;
if (r.count > 1) nm += ssprintf(" ×%d", r.count);
t.l1 = widen(nm);
t.l2 = widen(human_bytes(r.weight) + (r.resident_known ? "" : "*"));
std::string l3;
if (r.util >= 0.5) l3 = ssprintf("%.0f%% %s", r.util, short_engine(r.eng).c_str());
if (r.sysmem >= (32ull << 20)) l3 += (l3.empty() ? "" : " · ") + ssprintf("spill %s", human_bytes(r.sysmem).c_str());
t.l3 = widen(l3);
t.status = ssprintf("pid %u · %s · %s %s· spill %s in RAM · %s%s", r.pid, r.name.c_str(),
human_bytes(r.weight).c_str(), r.resident_known ? "resident " : "committed* ",
human_bytes(r.sysmem).c_str(),
r.util >= 0.5 ? ssprintf("%.0f%% %s · ", r.util, r.eng.c_str()).c_str() : "",
r.path.empty() ? "(path n/a)" : r.path.c_str());
}
L.tiles.push_back(std::move(t));
}
}
return L;
}
void fill(HDC dc, const RECT& rc, COLORREF c) {
HBRUSH b = CreateSolidBrush(c);
FillRect(dc, &rc, b);
DeleteObject(b);
}
void draw_bar(HDC dc, RECT rc, double frac, COLORREF fillc) {
fill(dc, rc, kTrack);
RECT fr = rc;
fr.right = fr.left + (LONG)std::lround((rc.right - rc.left) * std::clamp(frac, 0.0, 1.0));
fill(dc, fr, fillc);
}
void draw_text(HDC dc, HFONT f, COLORREF c, RECT rc, const std::wstring& t, UINT flags) {
HGDIOBJ of = SelectObject(dc, f);
SetTextColor(dc, c);
RECT r = rc;
DrawTextW(dc, t.c_str(), (int)t.size(), &r, flags | DT_NOPREFIX | DT_SINGLELINE);
SelectObject(dc, of);
}
int text_width(HDC dc, HFONT f, const std::wstring& t) {
HGDIOBJ of = SelectObject(dc, f);
SIZE sz{};
GetTextExtentPoint32W(dc, t.c_str(), (int)t.size(), &sz);
SelectObject(dc, of);
return sz.cx;
}
// VRAM-used history as filled columns, engine load as a line — Task Manager's graph, tiny.
void draw_spark(const Gui& s, HDC dc, RECT r, const std::vector<std::pair<float, float>>& h) {
fill(dc, r, RGB(26, 26, 33));
const int step = std::max(1, px(s, 2));
const int hgt = r.bottom - r.top;
const int cap = (r.right - r.left) / step;
const int n = (int)h.size();
const int start = std::max(0, n - cap);
std::vector<POINT> line;
for (int i = start; i < n; ++i) {
const int x = r.right - (n - i) * step;
const double frac = std::clamp((double)h[(size_t)i].first, 0.0, 1.0);
RECT c = { x, r.bottom - (LONG)std::lround(hgt * frac), x + step, r.bottom };
if (c.bottom > c.top) fill(dc, c, mix(kBandBg, pct_color(frac * 100), 0.55));
line.push_back({ x + step / 2, r.bottom - 1 - (LONG)std::lround((hgt - 2) * std::clamp((double)h[(size_t)i].second, 0.0, 100.0) / 100.0) });
}
if (line.size() >= 2) {
HPEN pen = CreatePen(PS_SOLID, 1, kLoadLine);
HGDIOBJ op = SelectObject(dc, pen);
Polyline(dc, line.data(), (int)line.size());
SelectObject(dc, op);
DeleteObject(pen);
}
}
void paint(Gui& s, HDC dc, RECT client) {
fill(dc, client, kBg);
SetBkMode(dc, TRANSPARENT);
const int statusH = px(s, 26);
RECT status = { client.left, client.bottom - statusH, client.right, client.bottom };
if (!s.have) {
draw_text(dc, s.fTitle, kDim, client, L"vramtop — reading the GPU…", DT_CENTER | DT_VCENTER);
return;
}
const Snapshot& snap = s.cur;
if (!s.lay_valid || s.lay_w != client.right || s.lay_h != client.bottom || s.lay_group != s.group) {
s.lay = build_layout(s, snap, client);
s.lay_valid = true;
s.lay_w = client.right;
s.lay_h = client.bottom;
s.lay_group = s.group;
s.hover = -1;
}
const int m = px(s, 10);
for (const auto& b : s.lay.bands) {
const auto& a = snap.adapters[(size_t)b.adapter];
fill(dc, b.rc, kBandBg);
const RECT brc = b.rc;
if (b.compact) {
RECT r1 = { brc.left + m, brc.top, brc.right - m, brc.bottom };
draw_text(dc, s.fTitle, kText, r1, widen(short_adapter(a.name)), DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
draw_text(dc, s.fNorm, kDim, r1,
widen(ssprintf("idle · %s / %s", human_bytes(a.vram_used).c_str(), human_bytes(a.vram_total).c_str())),
DT_RIGHT | DT_VCENTER);
continue;
}
RECT r1 = { brc.left + m, brc.top + px(s, 6), brc.right - m, brc.top + px(s, 26) };
std::string extras;
auto sep = [&]() { return extras.empty() ? "" : " · "; };
if (a.temp_c >= 0) extras += ssprintf("%.0f°C", a.temp_c);
if (a.fan_rpm > 0) extras += sep() + ssprintf("fan %d rpm", a.fan_rpm);
if (a.power_pct >= 0) extras += sep() + ssprintf("power %.0f%%", a.power_pct);
if (a.mem_clock_mhz > 0) extras += sep() + ssprintf("mem %.0f MHz", a.mem_clock_mhz);
if (snap.sample_ms > 0) extras += sep() + ssprintf("load %.0f%%", a.util_pct);
RECT rt = r1;
if (!extras.empty()) {
const std::wstring we = widen(extras);
rt.right = std::max(rt.left, r1.right - text_width(dc, s.fNorm, we) - px(s, 16));
draw_text(dc, s.fNorm, kDim, r1, we, DT_RIGHT | DT_VCENTER);
}
draw_text(dc, s.fTitle, kText, rt, widen(short_adapter(a.name)), DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
const double vfrac = a.vram_total ? (double)a.vram_used / (double)a.vram_total : 0.0;
const int barW = std::max(px(s, 160), (int)((brc.right - brc.left) * 0.40));
RECT bar = { brc.left + m, brc.top + px(s, 32), brc.left + m + barW, brc.top + px(s, 44) };
draw_bar(dc, bar, vfrac, pct_color(vfrac * 100));
RECT bt = { bar.right + px(s, 10), bar.top - px(s, 4), brc.right - m, bar.bottom + px(s, 4) };
std::string vs = ssprintf("%s / %s", human_bytes(a.vram_used).c_str(), human_bytes(a.vram_total).c_str());
if (a.vram_total) vs += ssprintf(" · %.0f%%", vfrac * 100);
if (a.sysmem_used >= (64ull << 20)) vs += ssprintf(" spill %s", human_bytes(a.sysmem_used).c_str());
else if (a.shared_used >= (256ull << 20)) vs += ssprintf(" shared %s", human_bytes(a.shared_used).c_str());
std::string engs;
int shown = 0;
for (const auto& e : a.engines) {
if (shown >= 2 || e.pct < 0.5) break;
engs += (shown ? " · " : "") + short_engine(e.name) + ssprintf(" %.0f%%", e.pct);
shown++;
}
if (!engs.empty()) vs += " " + engs;
draw_text(dc, s.fNorm, kText, bt, widen(vs), DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
RECT sp = { brc.left + m, brc.top + px(s, 52), brc.right - m, brc.bottom - px(s, 6) };
if ((size_t)b.adapter < s.hist.size()) draw_spark(s, dc, sp, s.hist[(size_t)b.adapter]);
}
for (size_t i = 0; i < s.lay.tiles.size(); ++i) {
const Tile& t = s.lay.tiles[i];
const bool hov = ((int)i == s.hover);
COLORREF c = t.col;
if (hov) c = mix(c, RGB(255, 255, 255), t.kind == Kind::Free ? 0.05 : 0.12);
const RECT rc = t.rc;
fill(dc, rc, c);
HBRUSH fb = CreateSolidBrush(t.kind == Kind::Free ? kTrack : kBg);
FrameRect(dc, &rc, fb);
DeleteObject(fb);
const int w = rc.right - rc.left, h = rc.bottom - rc.top;
if (w >= px(s, 52) && h >= px(s, 30)) {
const bool light = light_color(c);
const COLORREF tc = t.kind == Kind::Free ? kDim : (light ? RGB(18, 18, 22) : kText);
const COLORREF ts = t.kind == Kind::Free ? kDim : (light ? RGB(52, 52, 60) : RGB(208, 208, 216));
RECT tr = { rc.left + px(s, 6), rc.top + px(s, 3), rc.right - px(s, 6), rc.top + px(s, 20) };
draw_text(dc, s.fBold, tc, tr, t.l1, DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
RECT tr2 = { tr.left, tr.top + px(s, 17), tr.right, tr.top + px(s, 33) };
if (tr2.bottom <= rc.bottom - px(s, 2))
draw_text(dc, s.fNorm, ts, tr2, t.l2, DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
RECT tr3 = { tr.left, tr2.top + px(s, 16), tr.right, tr2.top + px(s, 31) };
if (!t.l3.empty() && tr3.bottom <= rc.bottom - px(s, 2))
draw_text(dc, s.fSmall, ts, tr3, t.l3, DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
}
}
fill(dc, status, kBandBg);
std::string st;
if (s.hover >= 0 && s.hover < (int)s.lay.tiles.size()) st = s.lay.tiles[(size_t)s.hover].status;
if (st.empty()) {
uint64_t used = 0, total = 0, spill = 0;
for (const auto& a : snap.adapters)
if (!a.software) { used += a.vram_used; total += a.vram_total; spill += a.sysmem_used; }
st = ssprintf("%s / %s resident", human_bytes(used).c_str(), human_bytes(total).c_str());
if (spill >= (64ull << 20)) st += ssprintf(" · %s spilled to RAM", human_bytes(spill).c_str());
st += ssprintf(" · %zu rows · [G] %s · [T] %s · [F5] refresh", snap.procs.size(),
s.group ? "grouped" : "per-pid", s.topmost ? "pinned" : "pin");
if (!snap.error.empty()) st = "! " + snap.error;
}
RECT str = { status.left + m, status.top, status.right - m, status.bottom };
draw_text(dc, s.fNorm, snap.error.empty() ? kDim : kRed, str, widen(st), DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS);
}
void update_title(Gui& s) {
std::string t = "vramtop";
for (const auto& a : s.cur.adapters) {
if (a.software || a.vram_total == 0) continue;
t += ssprintf(" — %s %.1f/%.1f GB", short_adapter(a.name).c_str(),
a.vram_used / 1073741824.0, a.vram_total / 1073741824.0);
if (s.cur.sample_ms > 0) t += ssprintf(" · %.0f%%", a.util_pct);
break;
}
SetWindowTextW(s.hwnd, widen(t).c_str());
}
void take_snapshot(Gui& s) {
AcquireSRWLockShared(&s.lock);
s.cur = s.snap;
s.have = true;
ReleaseSRWLockShared(&s.lock);
if (s.hist.size() < s.cur.adapters.size()) s.hist.resize(s.cur.adapters.size());
for (size_t i = 0; i < s.cur.adapters.size(); ++i) {
const auto& a = s.cur.adapters[i];
auto& h = s.hist[i];
h.emplace_back(a.vram_total ? (float)((double)a.vram_used / (double)a.vram_total) : 0.f,
(float)a.util_pct);
if (h.size() > kHistMax) h.erase(h.begin(), h.begin() + (long)(h.size() - kHistMax));
}
s.lay_valid = false;
update_title(s);
}
DWORD WINAPI collector_thread(LPVOID) {
Gui& s = *g;
Collector c(true, true);
c.prime();
HANDLE hs[2] = { s.quit, s.kick };
if (WaitForMultipleObjects(2, hs, FALSE, 300) == WAIT_OBJECT_0) return 0; // first frame fast
for (;;) {
Snapshot sn = c.sample();
AcquireSRWLockExclusive(&s.lock);
s.snap = std::move(sn);
ReleaseSRWLockExclusive(&s.lock);
if (s.hwnd) PostMessageW(s.hwnd, WM_APP_SNAP, 0, 0);
if (WaitForMultipleObjects(2, hs, FALSE, s.opts.interval_ms) == WAIT_OBJECT_0) return 0;
}
}
LRESULT CALLBACK wndproc(HWND h, UINT m, WPARAM wp, LPARAM lp) {
Gui& s = *g;
switch (m) {
case WM_APP_SNAP:
take_snapshot(s);
InvalidateRect(h, nullptr, FALSE);
return 0;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC dc = BeginPaint(h, &ps);
RECT rc;
GetClientRect(h, &rc);
HDC mem = CreateCompatibleDC(dc);
HBITMAP bmp = CreateCompatibleBitmap(dc, std::max<LONG>(rc.right, 1), std::max<LONG>(rc.bottom, 1));
HGDIOBJ ob = SelectObject(mem, bmp);
paint(s, mem, rc);
BitBlt(dc, 0, 0, rc.right, rc.bottom, mem, 0, 0, SRCCOPY);
SelectObject(mem, ob);
DeleteObject(bmp);
DeleteDC(mem);
EndPaint(h, &ps);
return 0;
}
case WM_ERASEBKGND:
return 1;
case WM_SIZE:
s.lay_valid = false;
InvalidateRect(h, nullptr, FALSE);
return 0;
case WM_MOUSEMOVE: {
const POINT p = { GET_X_LPARAM(lp), GET_Y_LPARAM(lp) };
int hov = -1;
for (size_t i = 0; i < s.lay.tiles.size(); ++i)
if (PtInRect(&s.lay.tiles[i].rc, p)) { hov = (int)i; break; }
if (hov != s.hover) {
s.hover = hov;
InvalidateRect(h, nullptr, FALSE);
}
TRACKMOUSEEVENT tme{ sizeof(tme), TME_LEAVE, h, 0 };
TrackMouseEvent(&tme);
return 0;
}
case WM_MOUSELEAVE:
if (s.hover != -1) {
s.hover = -1;
InvalidateRect(h, nullptr, FALSE);
}
return 0;
case WM_KEYDOWN:
if (wp == 'G') {
s.group = !s.group;
s.lay_valid = false;
InvalidateRect(h, nullptr, FALSE);
} else if (wp == 'T') {
s.topmost = !s.topmost;
SetWindowPos(h, s.topmost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
InvalidateRect(h, nullptr, FALSE);
} else if (wp == VK_F5) {
SetEvent(s.kick);
}
return 0;
case WM_GETMINMAXINFO: {
auto* mmi = (MINMAXINFO*)lp;
mmi->ptMinTrackSize = { 560, 380 };
return 0;
}
case WM_DPICHANGED: {
s.dpi = HIWORD(wp);
make_fonts(s);
s.lay_valid = false;
const RECT* r = (const RECT*)lp;
SetWindowPos(h, nullptr, r->left, r->top, r->right - r->left, r->bottom - r->top,
SWP_NOZORDER | SWP_NOACTIVATE);
InvalidateRect(h, nullptr, FALSE);
return 0;
}
case WM_DESTROY:
SetEvent(s.quit);
if (s.thread) WaitForSingleObject(s.thread, 3000);
PostQuitMessage(0);
return 0;
default:
return DefWindowProcW(h, m, wp, lp);
}
}
} // namespace
int run_gui(const Opts& o) {
// the manifest declares PerMonitorV2; this is the fallback for a manifest-less build
HMODULE u32 = GetModuleHandleW(L"user32.dll");
using PFN_SetCtx = BOOL(WINAPI*)(HANDLE);
if (auto p = (PFN_SetCtx)GetProcAddress(u32, "SetProcessDpiAwarenessContext"))
p((HANDLE)-4 /* PER_MONITOR_AWARE_V2 */);
else
SetProcessDPIAware();
static Gui state;
g = &state;
state.opts = o;
if (state.opts.interval_ms < 250) state.opts.interval_ms = 250;
state.quit = CreateEventW(nullptr, TRUE, FALSE, nullptr);
state.kick = CreateEventW(nullptr, FALSE, FALSE, nullptr);
state.icon_big = make_icon(32);
state.icon_small = make_icon(16);
WNDCLASSW wc{};
wc.lpfnWndProc = wndproc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.hCursor = LoadCursorW(nullptr, (LPCWSTR)IDC_ARROW);
wc.lpszClassName = L"vramtopGui";
wc.hIcon = state.icon_big ? state.icon_big : LoadIconW(nullptr, (LPCWSTR)IDI_APPLICATION);
RegisterClassW(&wc);
const int sw = GetSystemMetrics(SM_CXSCREEN), sh = GetSystemMetrics(SM_CYSCREEN);
const int W = std::min(1240, sw - 120), H = std::min(820, sh - 120);
state.hwnd = CreateWindowExW(0, wc.lpszClassName, L"vramtop", WS_OVERLAPPEDWINDOW,
(sw - W) / 2, (sh - H) / 2, W, H, nullptr, nullptr,
wc.hInstance, nullptr);
if (!state.hwnd) return 1;
if (state.icon_small) SendMessageW(state.hwnd, WM_SETICON, ICON_SMALL, (LPARAM)state.icon_small);
if (state.icon_big) SendMessageW(state.hwnd, WM_SETICON, ICON_BIG, (LPARAM)state.icon_big);
{
using PFN_GetDpi = UINT(WINAPI*)(HWND);
if (auto p = (PFN_GetDpi)GetProcAddress(u32, "GetDpiForWindow")) state.dpi = (int)p(state.hwnd);
}
make_fonts(state);
ShowWindow(state.hwnd, SW_SHOW);
state.thread = CreateThread(nullptr, 0, collector_thread, nullptr, 0, nullptr);
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
CloseHandle(state.quit);
CloseHandle(state.kick);
if (state.thread) CloseHandle(state.thread);
if (state.icon_big) DestroyIcon(state.icon_big);
if (state.icon_small) DestroyIcon(state.icon_small);
return 0;
}
} // namespace vramtop