summaryrefslogtreecommitdiffstats
path: root/src/menu.cpp
blob: 302eab3b16f2fef4b230635e5f2fda2d504754ed (plain) (blame)
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
// menu.cpp — menu state, rendering, input, config, paint hook, X11 mouse
#include "hl2h.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>

// ---------------------------------------------------------------------------
// ConMsg (tier0 console printer — prints to in-game console)
// ---------------------------------------------------------------------------

void (*g_conmsg)(const char *fmt, ...) = nullptr;

void init_conmsg() {
  g_conmsg = (decltype(g_conmsg))dlsym(RTLD_DEFAULT, "_Z6ConMsgPKcz");
  if (g_conmsg)
    return;
  // fallback: dlopen libtier0.so from the engine directory
  size_t slash = g_engine.path.find_last_of('/');
  if (slash == std::string::npos)
    return;
  std::string tier0 = g_engine.path.substr(0, slash + 1) + "libtier0.so";
  void *h = dlopen(tier0.c_str(), RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
  if (!h)
    h = dlopen(tier0.c_str(), RTLD_LAZY | RTLD_GLOBAL);
  if (h)
    g_conmsg = (decltype(g_conmsg))dlsym(h, "_Z6ConMsgPKcz");
}
// ---------------------------------------------------------------------------
// menu tree structure
// ---------------------------------------------------------------------------

enum NodeType { NODE_ROOT, NODE_FEATURE, NODE_TOGGLE, NODE_BIND };

struct MenuNode {
  NodeType type;
  const char *label;
  bool expanded;     // for root/feature: whether children are visible
  int child_count;
  MenuNode *children[4]; // max children per node

  // leaf data
  bool *active_ptr;  // NODE_TOGGLE: pointer to the active flag
  int *bind_ptr;     // NODE_BIND: pointer to the key binding (SDL scancode)
  const char *bind_name; // NODE_BIND: current bind display name
};

// feature data
struct FeatureState {
  bool active;
  int bind; // SDL scancode, 0 = none
};

static FeatureState g_bhop{true, 0};

static FeatureState g_abh{true, 0};
static FeatureState g_esp{true, 0};
// tree
static MenuNode g_root{NODE_ROOT, "HL2hake", true, 0, {}, nullptr, nullptr, nullptr};
static MenuNode g_bhop_feat{NODE_FEATURE, "Bunnyhop", true, 1, {}, nullptr, nullptr, nullptr};
static MenuNode g_bhop_active{NODE_TOGGLE, "Active", false, 0, {}, &g_bhop.active, nullptr, nullptr};
static MenuNode g_abh_feat{NODE_FEATURE, "ABH", true, 1, {}, nullptr, nullptr, nullptr};
static MenuNode g_abh_active{NODE_TOGGLE, "Active", false, 0, {}, &g_abh.active, nullptr, nullptr};
static MenuNode g_esp_feat{NODE_FEATURE, "ESP", true, 1, {}, nullptr, nullptr, nullptr};
static MenuNode g_esp_active{NODE_TOGGLE, "Active", false, 0, {}, &g_esp.active, nullptr, nullptr};

static MenuNode *g_visible[16]; // flattened visible nodes for arrow navigation
static int g_visible_count = 0;
static int g_selected = 0;
bool g_menu_open = false;

static bool g_bind_mode = false;
static void build_tree() {
  g_bhop_feat.children[0] = &g_bhop_active;
  g_abh_feat.children[0] = &g_abh_active;
  g_esp_feat.children[0] = &g_esp_active;
  g_root.children[0] = &g_bhop_feat;
  g_root.children[1] = &g_abh_feat;
  g_root.children[2] = &g_esp_feat;
  g_root.child_count = 3;
}

static int g_depth[16]; // depth of each visible row (for indentation)

static void flatten(MenuNode *node, int depth) {
  if (g_visible_count >= 16)
    return;
  node->type = (depth == 0) ? NODE_ROOT
              : (node->child_count > 0) ? NODE_FEATURE
              : (node->active_ptr) ? NODE_TOGGLE
              : NODE_BIND;
  g_depth[g_visible_count] = depth;
  g_visible[g_visible_count++] = node;
  if (node->expanded) {
    for (int i = 0; i < node->child_count; i++)
      flatten(node->children[i], depth + 1);
  }
}

static void rebuild_visible() {
  g_visible_count = 0;
  flatten(&g_root, 0);
  if (g_selected >= g_visible_count)
    g_selected = g_visible_count - 1;
  if (g_selected < 0)
    g_selected = 0;
}

// ---------------------------------------------------------------------------
// config persistence (INI format)
// ---------------------------------------------------------------------------

static std::string config_path() {
  size_t slash = g_engine.path.find_last_of('/');
  if (slash == std::string::npos)
    return "hl2hake.cfg";
  return g_engine.path.substr(0, slash + 1) + "hl2hake.cfg";
}

[[maybe_unused]] static const char *sdl_scancode_name(int sc) {
  if (sc == 0)
    return "None";
  static char buf[32];
  snprintf(buf, sizeof(buf), "Key%d", sc);
  return buf;
}

[[maybe_unused]] static int parse_sdl_scancode(const char *s) {
  if (strcmp(s, "None") == 0 || strcmp(s, "") == 0)
    return 0;
  if (strncmp(s, "Key", 3) == 0)
    return atoi(s + 3);
  return 0;
}

static void config_save() {
  FILE *f = fopen(config_path().c_str(), "w");
  if (!f)
    return;
  fprintf(f, "[bhop]\nactive=%d\nbind=%d\n", g_bhop.active, g_bhop.bind);
  fprintf(f, "[abh]\nactive=%d\nbind=%d\n", g_abh.active, g_abh.bind);
  fprintf(f, "[esp]\nactive=%d\nbind=%d\n", g_esp.active, g_esp.bind);
  fclose(f);
}

static void config_load() {
  FILE *f = fopen(config_path().c_str(), "r");
  if (!f)
    return;
  char line[256];
  FeatureState *cur = nullptr;
  while (fgets(line, sizeof(line), f)) {
    line[strcspn(line, "\r\n")] = 0;
    if (line[0] == '[') {
      if (strstr(line, "[bhop]"))
        cur = &g_bhop;
      else if (strstr(line, "[abh]"))
        cur = &g_abh;
      else if (strstr(line, "[esp]"))
        cur = &g_esp;
      else
        cur = nullptr;
    } else if (cur) {
      char *eq = strchr(line, '=');
      if (!eq)
        continue;
      *eq = 0;
      const char *key = line, *val = eq + 1;
      if (strcmp(key, "active") == 0)
        cur->active = atoi(val) != 0;
      else if (strcmp(key, "bind") == 0)
        cur->bind = atoi(val);
    }
  }
  fclose(f);
}

// ---------------------------------------------------------------------------
// menu input handling
// ---------------------------------------------------------------------------

// SDL scancodes for navigation keys (matches the game's scancode set)
static constexpr int SCAN_INSERT = 73;
static constexpr int SCAN_UP = 82;    // these are SDL scancodes
static constexpr int SCAN_DOWN = 81;
static constexpr int SCAN_LEFT = 80;
static constexpr int SCAN_RIGHT = 79;
static constexpr int SCAN_ENTER = 40;
static constexpr int SCAN_ESCAPE = 41;

// simplified scancode-to-name for common keys
static const char *scancode_name(int sc) {
  switch (sc) {
  case 0: return "None";
  case 4: return "A"; case 5: return "B"; case 6: return "C";
  case 7: return "D"; case 8: return "E"; case 9: return "F";
  case 10: return "G"; case 11: return "H"; case 12: return "I";
  case 13: return "J"; case 14: return "K"; case 15: return "L";
  case 16: return "M"; case 17: return "N"; case 18: return "O";
  case 19: return "P"; case 20: return "Q"; case 21: return "R";
  case 22: return "S"; case 23: return "T"; case 24: return "U";
  case 25: return "V"; case 26: return "W"; case 27: return "X";
  case 28: return "Y"; case 29: return "Z";
  case 30: return "1"; case 31: return "2"; case 32: return "3";
  case 33: return "4"; case 34: return "5"; case 35: return "6";
  case 36: return "7"; case 37: return "8"; case 38: return "9";
  case 39: return "0";
  case 40: return "Enter"; case 41: return "Escape"; case 42: return "Backspace";
  case 43: return "Tab"; case 44: return "Space";
  case 79: return "Right"; case 80: return "Left";
  case 81: return "Down"; case 82: return "Up";
  case 87: return "F1"; case 88: return "F2"; case 89: return "F3";
  case 90: return "F4"; case 91: return "F5"; case 92: return "F6";
  case 93: return "F7"; case 94: return "F8";
  case 600: return "MouseL"; case 601: return "MouseR";
  case 602: return "MouseM"; case 603: return "Mouse4";
  case 604: return "Mouse5";
  default: return scancode_name(0); // "None" for unmapped
  }
}

// get a snapshot of key states: returns array of currently-held scancodes
static bool g_prev_key_state[608] = {};
static bool g_key_down[608] = {}; // true for ONE frame on press

// read SDL_GetKeyboardState — the game's own SDL is in-process
using SDL_GetKeyboardState_fn = const uint8_t *(*)(int *);
static SDL_GetKeyboardState_fn SDL_GetKeyboardState_real = nullptr;

// mouse buttons map to pseudo-scancodes 600..604
static constexpr int MOUSE_BASE = 600; // 600=L 601=R 602=M 603=X1 604=X2
using SDL_GetMouseState_fn = unsigned (*)(int *, int *);
static SDL_GetMouseState_fn SDL_GetMouseState_real = nullptr;

static void poll_mouse() {
  if (!SDL_GetMouseState_real)
    SDL_GetMouseState_real =
        (SDL_GetMouseState_fn)dlsym(RTLD_DEFAULT, "SDL_GetMouseState");
  if (!SDL_GetMouseState_real)
    return;
  int mx, my;
  unsigned mask = SDL_GetMouseState_real(&mx, &my);

  for (int b = 0; b < 5; b++) {
    bool down = (mask & (1u << b)) != 0; // SDL buttons 1..5 = bits 0..4
    int sc = MOUSE_BASE + b;
    g_key_down[sc] = down && !g_prev_key_state[sc];
    g_prev_key_state[sc] = down;
  }
}

static void poll_keyboard() {
  if (!SDL_GetKeyboardState_real)
    SDL_GetKeyboardState_real =
        (SDL_GetKeyboardState_fn)dlsym(RTLD_DEFAULT, "SDL_GetKeyboardState");
  if (!SDL_GetKeyboardState_real)
    return;
  int numkeys = 0;
  const uint8_t *state = SDL_GetKeyboardState_real(&numkeys);
  if (state)
    for (int i = 0; i < numkeys && i < MOUSE_BASE; i++) {
      g_key_down[i] = state[i] && !g_prev_key_state[i];
      g_prev_key_state[i] = state[i];
    }
  poll_mouse();
}

static bool key_pressed(int sc) {
  return sc >= 0 && sc < MOUSE_BASE + 5 && g_key_down[sc];
}

[[maybe_unused]] static bool key_held(int sc) {
  return sc >= 0 && sc < MOUSE_BASE + 5 && g_prev_key_state[sc];
}

// feature gate queried from hl2h.cpp do_move(): feature must be Active AND
// its bind key held (always-on when unbound).
bool feature_active(int feature) {
  static FeatureState *feats[3] = {&g_bhop, &g_abh, &g_esp};
  if (feature < 0 || feature > 2)
    return false;
  FeatureState *f = feats[feature];
  if (!f->active)
    return false;
  return f->bind == 0 || key_held(f->bind);
}

static void menu_handle_input() {
  poll_keyboard();

  if (!g_menu_open) {
    if (key_pressed(SCAN_INSERT)) {
      std::logf("insert pressed");
      g_menu_open = true;
      g_bind_mode = false;
      rebuild_visible();
    }
    return;
  }

  // menu is open
  if (g_bind_mode) {
    // wait for any key press (except Insert, Up, Down, Escape, Enter)
    for (int i = 0; i < MOUSE_BASE + 5; i++) {
      if (!g_key_down[i])
        continue;
      if (i == SCAN_INSERT || i == SCAN_UP || i == SCAN_DOWN ||
          i == SCAN_LEFT || i == SCAN_RIGHT) {
        g_bind_mode = false;
        return; // cancel bind select
      }
      if (i == SCAN_ESCAPE) {
        // set bind to None
        MenuNode *n = g_visible[g_selected];
        if (n->bind_ptr)
          *n->bind_ptr = 0;
        g_bind_mode = false;
        config_save();
        rebuild_visible();
        return;
      }
      if (i == SCAN_ENTER) {
        g_bind_mode = false;
        return; // cancel, keep old bind
      }
      // any other key = new bind
      MenuNode *n = g_visible[g_selected];
      if (n->bind_ptr) {
        // clear same bind from other features
        FeatureState *features[] = {&g_bhop, &g_abh};
        for (auto *f : features)
          if (&f->bind != n->bind_ptr && f->bind == i)
            f->bind = 0;
        *n->bind_ptr = i;
      }
      g_bind_mode = false;
      config_save();
      rebuild_visible();
      return;
    }
    return; // no key pressed yet
  }

  // normal navigation
  if (key_pressed(SCAN_INSERT) || key_pressed(SCAN_ESCAPE)) {
    g_menu_open = false;
    return;
  }
  if (key_pressed(SCAN_UP) && g_selected > 0) {
    g_selected--;
    return;
  }
  if (key_pressed(SCAN_DOWN) && g_selected < g_visible_count - 1) {
    g_selected++;
    return;
  }
  if (key_pressed(SCAN_ENTER)) {
    MenuNode *n = g_visible[g_selected];
    if (n->child_count > 0) {
      n->expanded = !n->expanded;
      rebuild_visible();
    } else if (n->type == NODE_TOGGLE && n->active_ptr) {
      *n->active_ptr = !(*n->active_ptr);
      config_save();
    } else if (n->type == NODE_BIND) {
      g_bind_mode = true;
    }
  }
}

// ---------------------------------------------------------------------------
// menu rendering (VGUI ISurface)
// ---------------------------------------------------------------------------

// VGUI surface interface
struct ISurface;
using HFont = unsigned long;

ISurface *g_surface = nullptr;
static HFont g_font = 0;

// VGUI_Surface030 vtable slots (confirmed via binary disassembly of vguimatsurface.so):
//  8 = PushMakeCurrent(VPANEL, bool useInsets) — reads args at 0xc/0x10(%ebp)
//  9 = PopMakeCurrent(VPANEL) — pops the make-current stack at this+0x264/0x270
// 10 = DrawSetColor(int r, int g, int b, int a) — stores rgba at this+0x24
// 12 = DrawFilledRect(int x0, int y0, int x1, int y1) — alpha check at this+0x27
// 17 = DrawSetTextFont(HFont), 18 = DrawSetTextColor(int r,g,b,a)
// 20 = DrawSetTextPos(int x, int y), 22 = DrawPrintText(wchar_t*, len, drawType)
// 66 = CreateFont(), 67 = AddGlyphSetToFont(font, name, tall, weight,
//      blur, scanlines, flags, rangeMin, rangeMax)
static constexpr int SURF_GetEmbeddedPanel = 6;
static constexpr int SURF_PushMakeCurrent = 8;
static constexpr int SURF_PopMakeCurrent = 9;
static constexpr int SURF_DrawSetColor = 10;
static constexpr int SURF_DrawFilledRect = 12;
static constexpr int SURF_DrawSetTextFont = 17;
static constexpr int SURF_DrawSetTextColor = 18;
static constexpr int SURF_DrawSetTextPos = 20;
static constexpr int SURF_DrawPrintText = 22;
static constexpr int SURF_CreateFont = 66;
static constexpr int SURF_AddGlyphSetToFont = 67;

static int surf_get_embedded_panel() {
  using Fn = int (*)(void *);
  return vfunc<Fn>(g_surface, SURF_GetEmbeddedPanel)(g_surface);
}
static void surf_push_make_current(int panel, bool use_insets) {
  using Fn = void (*)(void *, int, bool);
  vfunc<Fn>(g_surface, SURF_PushMakeCurrent)(g_surface, panel, use_insets);
}
static void surf_pop_make_current(int panel) {
  using Fn = void (*)(void *, int);
  vfunc<Fn>(g_surface, SURF_PopMakeCurrent)(g_surface, panel);
}
static void surf_draw_set_color(int r, int g, int b, int a) {
  using Fn = void (*)(void *, int, int, int, int);
  vfunc<Fn>(g_surface, SURF_DrawSetColor)(g_surface, r, g, b, a);
}
static void surf_draw_filled_rect(int x0, int y0, int x1, int y1) {
  using Fn = void (*)(void *, int, int, int, int);
  vfunc<Fn>(g_surface, SURF_DrawFilledRect)(g_surface, x0, y0, x1, y1);
}
static void surf_draw_set_text_color(int r, int g, int b, int a) {
  using Fn = void (*)(void *, int, int, int, int);
  vfunc<Fn>(g_surface, SURF_DrawSetTextColor)(g_surface, r, g, b, a);
}
static void surf_draw_set_text_font(HFont f) {
  using Fn = void (*)(void *, HFont);
  vfunc<Fn>(g_surface, SURF_DrawSetTextFont)(g_surface, f);
}
static void surf_draw_set_text_pos(int x, int y) {
  using Fn = void (*)(void *, int, int);
  vfunc<Fn>(g_surface, SURF_DrawSetTextPos)(g_surface, x, y);
}
static void surf_draw_print_text(const wchar_t *text, int count) {
  using Fn = void (*)(void *, const wchar_t *, int, int);
  vfunc<Fn>(g_surface, SURF_DrawPrintText)(g_surface, text, count, 0); // 0 = FONT_DRAW_DEFAULT
}
static HFont surf_create_font() {
  using Fn = HFont (*)(void *);
  return vfunc<Fn>(g_surface, SURF_CreateFont)(g_surface);
}
static bool surf_set_font_glyph_set(HFont f, const char *name, int tall,
                                    int weight, int blur, int scanlines,
                                    int flags, int range_min = 0,
                                    int range_max = 0) {
  using Fn = bool (*)(void *, HFont, const char *, int, int, int, int, int, int,
                      int);
  return vfunc<Fn>(g_surface, SURF_AddGlyphSetToFont)(g_surface, f, name, tall,
                                                     weight, blur, scanlines,
                                                     flags, range_min,
                                                     range_max);
}

// wide string conversion for DrawPrintText
static void draw_text(int x, int y, const char *text) {
  wchar_t wtext[256];
  mbstowcs(wtext, text, 255);
  wtext[255] = 0;
  int len = (int)wcslen(wtext);
  surf_draw_set_text_font(g_font);
  surf_draw_set_text_color(255, 255, 255, 255);
  surf_draw_set_text_pos(x, y);
  surf_draw_print_text(wtext, len);
}
void draw_text_col(int x, int y, const char *text, int r, int g, int b) {
  wchar_t wtext[256];
  mbstowcs(wtext, text, 255);
  wtext[255] = 0;
  surf_draw_set_text_font(g_font);
  surf_draw_set_text_color(r, g, b, 255);
  surf_draw_set_text_pos(x, y);
  surf_draw_print_text(wtext, (int)wcslen(wtext));
}

// Draw overlay. MUST be called from inside the ISurface paint path
// (see hkdDrawPrintText hook in hl2h.cpp): we wrap our draws in
// PushMakeCurrent/PopMakeCurrent so they are submitted with a clean clip.
void outer_draw() {
  menu_handle_input();
  // HL2H_DRAW_TEST=1 draws a probe rect without needing the menu open
  static bool draw_test = getenv("HL2H_DRAW_TEST") != nullptr;
  bool esp_on = feature_active(FEAT_ESP);
  if (!g_surface || (!g_menu_open && !draw_test && !esp_on))
    return;
  if (!g_font) {
    g_font = surf_create_font();
    if (!g_font) {
      logf("outer_draw: CreateFont failed");
      return;
    }
    // FONTFLAG_CUSTOM only; Liberation Sans is an installed real TTF (Verdana
    // substitutes to Noto). Raw glyphs, ASCII range pinned.
    if (!surf_set_font_glyph_set(g_font, "Liberation Sans", 16, 400, 0, 0,
                                 0x400, 0x20, 0xFF)) {
      logf("outer_draw: SetFontGlyphSet failed");
      g_font = 0;
      return;
    }
  }
  int panel = surf_get_embedded_panel();
  if (!panel)
    return;
  surf_push_make_current(panel, false);
  if (esp_on)
    esp_draw();
  if (draw_test) {
    surf_draw_set_color(255, 0, 0, 255);
    surf_draw_filled_rect(20, 20, 180, 60);
    surf_draw_set_color(255, 255, 255, 255);
    draw_text(28, 36, "HL2H DRAW TEST");
  }
  if (!g_menu_open) {
    surf_pop_make_current(panel);
    return;
  }
  for (int i = 0; i < g_visible_count; i++) {
    MenuNode *n = g_visible[i];
    char line[96];
    int x = 12 + g_depth[i] * 12;
    snprintf(line, sizeof(line), "%s %s",
             (i == g_selected) ? ">" : (n->child_count ? "-" : " "), n->label);
    draw_text(x, 10 + i * 20, line);
    // right-aligned state
    if (n->type == NODE_TOGGLE) {
      draw_text(200, 10 + i * 20, *n->active_ptr ? "[on]" : "[off]");
    } else if (n->type == NODE_BIND) {
      if (g_bind_mode && i == g_selected)
        draw_text(200, 10 + i * 20, "[press key]");
      else {
        /* stable name for current bind */
        static char bn[2][32];
        static FeatureState *feats[] = {&g_bhop, &g_abh};
        int fi = 0;
        for (int k = 0; k < 2; k++)
          if (n->bind_ptr == &feats[k]->bind)
            fi = k;
        snprintf(bn[fi], 32, "[%s]", scancode_name(*n->bind_ptr));
        draw_text(200, 10 + i * 20, bn[fi]);
      }
    }
  }
  surf_pop_make_current(panel);
}

// Call an arbitrary ISurface vtable slot with up to 2 long args (cdecl thiscall
// on i386: this first, rest on stack).
long surf_call_slot(void *surf, int slot, long a1, long a2) {
  void **vt = *(void ***)surf;
  using Fn = long (*)(void *, long, long);
  return ((Fn)vt[slot])(surf, a1, a2);
}

// ---------------------------------------------------------------------------
// ISurface discovery — try known modules and all loaded .so files
// ---------------------------------------------------------------------------

static ISurface *find_surface_interface() {
  static const char *known[] = {"engine.so", "client.so", nullptr};
  static const char *iface_names[] = {
    "VGUI_Surface030", "VGUI_Surface001",
    "MatSystemSurface008", "MatSystemSurface001",
    "VGUI_Surface002", "VGUI_SURFACE001",
    nullptr,
  };
  // try known modules
  for (const char **p = known; *p; p++) {
    void *h = dlopen(*p, RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
    if (!h) continue;
    auto fn = (CreateInterfaceFn)dlsym(h, "CreateInterface");
    if (!fn) continue;
    for (const char **n = iface_names; *n; n++) {
      int ret = 0;
      ISurface *s = (ISurface *)fn(*n, &ret);
      if (s) { logf("ISurface found: %s via %s (ret=%d)", *n, *p, ret); return s; }
    }
  }
  // 2) scan /proc/self/maps for every loaded .so, try CreateInterface on each
  FILE *maps = fopen("/proc/self/maps", "r");
  if (!maps) return nullptr;
  char line[1024];
  while (fgets(line, sizeof(line), maps)) {
    char *p = strchr(line, '/');
    if (!p) continue;
    size_t pl = strlen(p);
    while (pl && (p[pl-1] == '\n' || p[pl-1] == '\r')) p[--pl] = 0;
    if (!strstr(p, ".so")) continue;
    void *h = dlopen(p, RTLD_NOLOAD | RTLD_LAZY | RTLD_GLOBAL);
    if (!h) continue;
    auto fn = (CreateInterfaceFn)dlsym(h, "CreateInterface");
    if (!fn) continue;
    for (const char **n = iface_names; *n; n++) {
      int ret = 0;
      ISurface *s = (ISurface *)fn(*n, &ret);
      if (s) {
        logf("ISurface found: %s via %s", *n, p);
        fclose(maps);
        return s;
      }
    }
  }
  fclose(maps);
  return nullptr;
}

void install_menu() {
  build_tree();
  config_load();
  // resolve ISurface once (used by the DrawPrintText hook in hl2h.cpp and
  // by outer_draw). DrawPrintText hook is installed from hkdCreateMove.
  g_surface = find_surface_interface();
  if (!g_surface) {
    logf("ISurface not found; menu disabled");
    return;
  }
  logf("ISurface = %p", g_surface);
}