-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPF_ConsoleCommandHotkeys.cpp
More file actions
924 lines (771 loc) · 41.2 KB
/
SPF_ConsoleCommandHotkeys.cpp
File metadata and controls
924 lines (771 loc) · 41.2 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
/**
* @file SPF_ConsoleCommandHotkeys.cpp
* @brief The main implementation file for the SPF_ConsoleCommandHotkeys.
* @details This file contains the minimal implementation for a plugin to be loaded
* and recognized by the SPF framework. It serves as a basic template for new plugins,
* with clear explanations and commented-out sections for optional features.
*/
#include "SPF_ConsoleCommandHotkeys.hpp" // Always include your own header first
#include <cstring> // For C-style string manipulation functions like strncpy_s.
namespace SPF_ConsoleCommandHotkeys
{
// =================================================================================================
// 1. Constants & Global State
// =================================================================================================
/**
* @brief A constant for the plugin's name.
* @details This MUST match the name used in `Cfg_GetContext` calls for various APIs
* and the plugin's directory name.
*/
const char *PLUGIN_NAME = "SPF_ConsoleCommandHotkeys";
/**
* @brief The single, global instance of the plugin's context.
* @details This is the central point for accessing all plugin state.
*/
PluginContext g_ctx;
// =================================================================================================
// 2. Manifest Implementation
// =================================================================================================
void BuildManifest(SPF_Manifest_Builder_Handle *h, const SPF_Manifest_Builder_API *api)
{
// This function defines all the metadata for your plugin. The framework calls this
// function *before* loading your plugin DLL to understand what it is.
// --- 2.1. Plugin Information ---
// This section provides the basic identity of your plugin.
{
// `name`: (Optional) A unique name for the plugin (e.g., "SPF_ConsoleCommandHotkeys").
// If not specified, the framework will use the name of your DLL file, but specifying it
// here is recommended to avoid potential conflicts.
api->Info_SetName(h, PLUGIN_NAME);
// `version`: (Optional) The plugin's version string (e.g., "1.0.0").
api->Info_SetVersion(h, "1.0.0");
// Recommended to fill in
// The minimum SPF Framework version required for this plugin to work correctly (e.g. "1.0.0").
// If the user's framework version is lower than this, the plugin will be disabled. And a warning will be shown
// This prevents crashes due to API changes.
api->Info_SetMinFrameworkVersion(h, "1.1.7");
// `author`: (Optional) The name of the author or organization.
api->Info_SetAuthor(h, "Track & Truck Devs");
// `descriptionLiteral`: (Optional) A simple, hardcoded description for your plugin.
// This is used as a fallback if the localized description key is not found.
//api->Info_SetDescriptionLiteral(h, "This is a plugin that allows you to send commands to the game using keybinds.");
// `descriptionKey`: (Optional) A key for a localized description string.
// This requires using the Localization API and having corresponding translation files.
api->Info_SetDescriptionKey(h, "plugin.description");
// --- Optional Social and Project Links ---
// Uncomment any of the following lines to provide contact or project URLs.
// These will be displayed in the plugin's information panel in the UI.
api->Info_SetDiscordUrl(h, "https://discord.gg/kadd8AQuMt");
api->Info_SetGithubUrl(h, "https://github.com/TrackAndTruckDevs/SPF_ConsoleCommandHotkeys");
api->Info_SetYoutubeUrl(h, "https://www.youtube.com/@TrackAndTruck");
api->Info_SetPatreonUrl(h, "https://www.patreon.com/TrackAndTruckDevs");
}
// --- 2.2. Configuration Policy ---
// This section defines how your plugin interacts with the framework's configuration system.
{
// `allowUserConfig`: Set to `true` if you want a `settings.json` file to be created
// for your plugin, allowing users (or the framework UI) to override default settings.
api->Policy_SetAllowUserConfig(h, true);
// To enable configurable systems, uncomment the calls below.
// api->Policy_AddConfigurableSystem(h, "logging");
api->Policy_AddConfigurableSystem(h, "settings");
api->Policy_AddConfigurableSystem(h, "localization");
// api->Policy_AddConfigurableSystem(h, "ui");
// To enable required hooks, uncomment the line below.
api->Policy_AddRequiredHook(h, "GameConsole"); // Example: Requires GameConsole hook
}
// --- 2.3. Custom Settings (settingsJson) ---
// A JSON string literal that defines the default values for your plugin's custom settings.
// If `Policy_SetAllowUserConfig` is true, the framework creates a `settings.json` file.
// The JSON object you provide here will be inserted under a top-level key named "settings".
// Example: Define some default custom settings.
api->Settings_SetJson(h, R"json(
{
"options": {
"show_notifications": true
},
"commands": []
}
)json");
// --- 2.4. Default Settings for Framework Systems ---
// Here you can provide default configurations for various framework systems.
// --- Logging ---
// Requires: SPF_Logger_API.h
{
// `level`: Default minimum log level for this plugin (e.g., "trace", "debug", "info", "warn", "error", "critical").
api->Defaults_SetLogging(h, "trace", false);
}
// --- Localization ---
// Requires: SPF_Localization_API.h
// Uncomment if your plugin uses localized strings.
{
// `language`: Default language code (e.g., "en", "de", "uk").
api->Defaults_SetLocalization(h, "en");
}
// --- Keybinds ---
// Requires: SPF_KeyBinds_API.h
// Uncomment and configure if your plugin needs custom keybinds.
{
// --- Action 0: A sample keybind to toggle a window ---
// `groupName`: Logical grouping for actions, used to avoid name collisions.
// Best practice: "{PluginName}.{Feature}".
// `actionName`: (e.g., "toggle", "activate").
// Define one or more default key combinations for this action.
// `type`: "keyboard", "gamepad", "gamepad_axis", "joystick", "joystick_axis", "mouse", "mouse_axis".
// `key`: Key name (see VirtualKeyMapping.cpp or GamepadButtonMapping.cpp).
// `consume`: When to consume input: "never", "on_ui_focus", "always", "manual".
api->Defaults_AddKeybind(h, "MainWindow", "toggle", "chord", "keyboard:KEY_LCONTROL+keyboard:KEY_Q", "never");
}
// --- UI ---
// Requires: SPF_UI_API.h
// Uncomment and configure if your plugin needs GUI windows.
{
// --- Window 0: The main window for the plugin ---
// `name`: Unique ID for this window within the plugin.
// `isVisible`: Default visibility state.
// `isInteractive`: If false, mouse clicks pass through the window to the game.
// Default position and size on screen.
// `isCollapsed`: Default collapsed state.
// `autoScroll`: If the window should auto-scroll to the bottom on new content.
api->Defaults_AddWindow(h, "MainWindow", false, true, 500, 200, 650, 450, false, false);
}
// =============================================================================================
// 2.5. Metadata for UI Display (Optional)
// =============================================================================================
// These sections are used to provide human-readable names and descriptions for your
// settings, keybinds, and UI windows in the framework's settings panel.
// If you don't provide metadata for an item, the framework will use its raw key as a label.
//==============================================================================================
// --- Custom Settings Metadata ---
// Provide titles and descriptions for the settings defined in `settingsJson`.
{
//--- Metadata for "some_number" ---
// Can be a localization key or literal text.
// Optional: Specify a UI widget (e.g., "slider") and its parameters.
api->Meta_AddCustomSetting(h, "options.show_notifications", "options.show_notifications.title", "options.show_notifications.desc", nullptr, nullptr, false);
//--- Example of a hidden setting ---
// No title or description needed, as it won't be shown
api->Meta_AddCustomSetting(h, "commands", nullptr, nullptr, nullptr, nullptr, true);
}
// --- Keybinds Metadata ---
// Provide titles and descriptions for the actions defined in `keybinds`.
{
// `groupName`: Must match the action's groupName.
// `actionName`: Must match the action's actionName.
api->Meta_AddKeybind(h, "MainWindow", "toggle", "keybinds.main_window.title", "keybinds.main_window.desc");
// Add metadata for the main window to support localized titles
api->Meta_AddWindow(h, "MainWindow", "ui.MainWindow.title", nullptr);
}
}
// =================================================================================================
// 3. Plugin Lifecycle Implementations
// =================================================================================================
// The following functions are the core lifecycle events for the plugin.
void OnLoad(const SPF_Load_API *load_api)
{
// Cache the provided API pointers in our global context.
g_ctx.loadAPI = load_api;
// --- Essential API Initialization ---
// Get and cache the logger and formatting API handles.
if (g_ctx.loadAPI)
{
g_ctx.loggerHandle = g_ctx.loadAPI->logger->Log_GetContext(PLUGIN_NAME);
g_ctx.formattingAPI = g_ctx.loadAPI->formatting;
if (load_api->config)
{
g_ctx.configHandle = load_api->config->Cfg_GetContext(PLUGIN_NAME);
}
if (g_ctx.loggerHandle && g_ctx.formattingAPI && g_ctx.configHandle)
{
char log_buffer[256];
g_ctx.formattingAPI->Fmt_Format(log_buffer, sizeof(log_buffer), "%s has been loaded!", PLUGIN_NAME);
g_ctx.loadAPI->logger->Log(g_ctx.loggerHandle, SPF_LOG_INFO, log_buffer);
}
}
}
void OnActivated(const SPF_Core_API *core_api)
{
g_ctx.coreAPI = core_api;
if (g_ctx.loggerHandle && g_ctx.formattingAPI)
{
char log_buffer[256];
g_ctx.formattingAPI->Fmt_Format(log_buffer, sizeof(log_buffer), "%s has been activated!", PLUGIN_NAME);
g_ctx.loadAPI->logger->Log(g_ctx.loggerHandle, SPF_LOG_INFO, log_buffer);
}
if (g_ctx.coreAPI)
{
g_ctx.uiAPI = core_api->ui;
g_ctx.gameConsoleAPI = core_api->console;
g_ctx.jsonReaderAPI = core_api->json_reader;
}
if (g_ctx.coreAPI->localization) {
g_ctx.localizationHandle = g_ctx.coreAPI->localization->Loc_GetContext(PLUGIN_NAME);
}
LoadCommands();
if (g_ctx.coreAPI && g_ctx.coreAPI->keybinds)
{
g_ctx.keybindsHandle = g_ctx.coreAPI->keybinds->Kbind_GetContext(PLUGIN_NAME);
core_api->keybinds->Kbind_Register(g_ctx.keybindsHandle, "MainWindow.toggle", OnToggleMainWindow);
for (auto const &[id, action] : g_ctx.userCommands)
{
g_ctx.coreAPI->keybinds->Kbind_RegisterActionMetadata(
g_ctx.keybindsHandle,
id.c_str(),
action.title.c_str(),
action.description.c_str(),
OnDynamicCommandAction,
nullptr);
}
}
}
void OnUpdate()
{
// This function is called every frame while the plugin is active.
// Avoid performing heavy or blocking operations here, as it will directly impact game performance.
// --- Optional API Usage (Uncomment if needed) ---
// Remember to also uncomment the relevant #include directives in SPF_ConsoleCommandHotkeys.hpp/SPF_ConsoleCommandHotkeys.cpp
// and add corresponding members to the PluginContext struct.
/*
// Example: Polling Telemetry data
// Requires: SPF_Telemetry_API.h (and corresponding types in PluginContext)
*/
/*
// Example: Simulating Virtual Input (e.g., holding a button)
// Requires: SPF_VirtInput_API.h (and corresponding types in PluginContext)
*/
}
void OnUnload()
{
// Perform cleanup. Nullify cached API pointers to prevent use-after-free
// and ensure a clean shutdown. This is the last chance for cleanup.
if (g_ctx.loadAPI && g_ctx.loggerHandle && g_ctx.formattingAPI)
{
char log_buffer[256];
g_ctx.formattingAPI->Fmt_Format(log_buffer, sizeof(log_buffer), "%s is being unloaded.", PLUGIN_NAME);
g_ctx.loadAPI->logger->Log(g_ctx.loggerHandle, SPF_LOG_INFO, log_buffer);
}
// --- Optional API Cleanup (Uncomment if needed) ---
// Example: Unregistering keybinds (often handled by framework, but good practice if explicitly registered).
// Requires: SPF_KeyBinds_API.h
// Nullify all cached API pointers and handles.
g_ctx.coreAPI = nullptr;
g_ctx.loadAPI = nullptr;
g_ctx.loggerHandle = nullptr;
g_ctx.formattingAPI = nullptr;
// --- Optional Handles (Nullify if used) ---
g_ctx.configHandle = nullptr;
// g_ctx.localizationHandle = nullptr;
g_ctx.keybindsHandle = nullptr;
if (g_ctx.uiAPI) {
if (g_ctx.styleAddBtn) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleAddBtn);
if (g_ctx.styleSaveBtn) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleSaveBtn);
if (g_ctx.styleExitBtn) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleExitBtn);
if (g_ctx.styleBold) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleBold);
if (g_ctx.styleTableTitle) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleTableTitle);
if (g_ctx.styleTableHeader) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleTableHeader);
if (g_ctx.styleTableCell) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleTableCell);
if (g_ctx.styleDeleteBtn) g_ctx.uiAPI->UI_Style_Destroy(g_ctx.styleDeleteBtn);
g_ctx.styleAddBtn = nullptr;
g_ctx.styleSaveBtn = nullptr;
g_ctx.styleExitBtn = nullptr;
g_ctx.styleBold = nullptr;
g_ctx.styleTableTitle = nullptr;
g_ctx.styleTableHeader = nullptr;
g_ctx.styleTableCell = nullptr;
g_ctx.styleDeleteBtn = nullptr;
}
g_ctx.uiAPI = nullptr;
g_ctx.mainWindowHandle = nullptr;
// g_ctx.telemetryHandle = nullptr;
// g_ctx.hooksAPI = nullptr;
g_ctx.gameConsoleAPI = nullptr;
// g_ctx.virtualDeviceHandle = nullptr;
// g_ctx.cameraAPI = nullptr;
// g_ctx.vehicleAPI = nullptr;
// g_ctx.gameLogCallbackHandle = nullptr;
//
// // Telemetry Subscriptions (Nullify if used)
// g_ctx.gameStateSubscription = nullptr;
// g_ctx.timestampsSubscription = nullptr;
// g_ctx.commonDataSubscription = nullptr;
// g_ctx.truckConstantsSubscription = nullptr;
// g_ctx.trailerConstantsSubscription = nullptr;
// g_ctx.truckDataSubscription = nullptr;
// g_ctx.trailersSubscription = nullptr;
// g_ctx.jobConstantsSubscription = nullptr;
// g_ctx.jobDataSubscription = nullptr;
// g_ctx.navigationDataSubscription = nullptr;
// g_ctx.controlsSubscription = nullptr;
// g_ctx.specialEventsSubscription = nullptr;
// g_ctx.gameplayEventsSubscription = nullptr;
// g_ctx.gearboxConstantsSubscription = nullptr;
}
// =================================================================================================
// 4. Optional Callback Implementations (Commented Out)
// =================================================================================================
// Implement these functions if your plugin needs to react to specific events.
// Remember to also uncomment their prototypes in SPF_ConsoleCommandHotkeys.hpp and register them
// in OnActivated or OnRegisterUI as appropriate.
void OnSettingChanged(SPF_Config_Handle *h, const char *keyPath)
{
if (!g_ctx.coreAPI || !g_ctx.coreAPI->config || !keyPath)
return;
if (strcmp(keyPath, "settings.options.show_notifications") == 0)
{
g_ctx.showNotifications = g_ctx.coreAPI->config->Cfg_GetBool(h, keyPath, true);
}
}
void OnLanguageChanged(const char* langCode) {
if (!g_ctx.coreAPI || !g_ctx.coreAPI->localization || !langCode) return;
SPF_Localization_Handle* h = g_ctx.coreAPI->localization->Loc_GetContext(PLUGIN_NAME);
if (h && g_ctx.coreAPI->localization->Loc_HasLanguage(h, langCode)) {
g_ctx.coreAPI->localization->Loc_SetLanguage(h, langCode);
}
}
void OnRegisterUI(SPF_UI_API *ui_api)
{
if (ui_api)
{
g_ctx.uiAPI = ui_api;
ui_api->UI_RegisterDrawCallback(PLUGIN_NAME, "MainWindow", RenderMainWindow, nullptr);
g_ctx.mainWindowHandle = g_ctx.uiAPI->UI_GetWindowHandle(PLUGIN_NAME, "MainWindow");
// Initialize styles
if (!g_ctx.styleAddBtn) {
g_ctx.styleAddBtn = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleAddBtn, SPF_FONT_BOLD);
ui_api->UI_Style_SetAlign(g_ctx.styleAddBtn, SPF_TEXT_ALIGN_CENTER);
ui_api->UI_Style_SetColor(g_ctx.styleAddBtn, 1.0f, 0.75f, 0.0f, 1.0f); // Gold
ui_api->UI_Style_SetHoverColor(g_ctx.styleAddBtn, 1.0f, 0.75f, 0.0f, 1.0f); // Gold on hover
ui_api->UI_Style_SetActiveColor(g_ctx.styleAddBtn, 1.0f, 1.0f, 1.0f, 1.0f); // White on click
}
if (!g_ctx.styleSaveBtn) {
g_ctx.styleSaveBtn = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleSaveBtn, SPF_FONT_BOLD);
ui_api->UI_Style_SetColor(g_ctx.styleSaveBtn, 0.4f, 1.0f, 0.4f, 1.0f); // Greenish
}
if (!g_ctx.styleExitBtn) {
g_ctx.styleExitBtn = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleExitBtn, SPF_FONT_BOLD);
ui_api->UI_Style_SetColor(g_ctx.styleExitBtn, 1.0f, 0.4f, 0.4f, 1.0f); // Reddish
}
if (!g_ctx.styleBold) {
g_ctx.styleBold = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleBold, SPF_FONT_BOLD);
}
if (!g_ctx.styleTableTitle) {
g_ctx.styleTableTitle = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleTableTitle, SPF_FONT_BOLD);
ui_api->UI_Style_SetColor(g_ctx.styleTableTitle, 1.00f, 0.75f, 0.00f, 1.0f); // Gold
ui_api->UI_Style_SetAlign(g_ctx.styleTableTitle, SPF_TEXT_ALIGN_CENTER);
}
if (!g_ctx.styleTableHeader) {
g_ctx.styleTableHeader = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleTableHeader, SPF_FONT_BOLD);
ui_api->UI_Style_SetColor(g_ctx.styleTableHeader, 0.75f, 0.75f, 0.75f, 1.0f); // Silver
ui_api->UI_Style_SetAlign(g_ctx.styleTableHeader, SPF_TEXT_ALIGN_CENTER);
}
if (!g_ctx.styleTableCell) {
g_ctx.styleTableCell = ui_api->UI_Style_Create();
ui_api->UI_Style_SetFont(g_ctx.styleTableCell, SPF_FONT_H3);
ui_api->UI_Style_SetColor(g_ctx.styleTableCell, 1.0f, 1.0f, 1.0f, 1.0f); // White
}
if (!g_ctx.styleDeleteBtn) {
g_ctx.styleDeleteBtn = ui_api->UI_Style_Create();
ui_api->UI_Style_SetColor(g_ctx.styleDeleteBtn, 1.0f, 0.25f, 0.25f, 1.0f); // Red
}
}
}
const char *GetLocStr(const char *key, const char *fallback)
{
static char loc_bufs[8][512];
static int cur_buf = 0;
char* loc_buf = loc_bufs[cur_buf];
cur_buf = (cur_buf + 1) % 8;
if (g_ctx.coreAPI && g_ctx.coreAPI->localization && g_ctx.localizationHandle)
{
if (g_ctx.coreAPI->localization->Loc_GetString(g_ctx.localizationHandle, key, loc_buf, 512) > 0)
return loc_buf;
}
return fallback;
}
void RenderMainWindow(SPF_UI_API *ui, void *user_data)
{
float windowWidth = ui->UI_GetWindowWidth();
float spacing = 10.0f;
float pureWidth = windowWidth - (spacing * 4.0f);
if (g_ctx.showAddForm)
{
ui->UI_Text(GetLocStr("ui.form.title", "Creating a new action:"));
ui->UI_Spacing();
ui->UI_Checkbox(GetLocStr("ui.form.cycle_mode", "Cycle Mode"), &g_ctx.newIsCycle);
if (ui->UI_IsItemHovered(SPF_HOVERED_FLAG_NONE)) {
ui->UI_SetTooltip(GetLocStr("ui.form.cycle_mode_tooltip", "Cycle mode tooltip"));
}
ui->UI_Spacing();
float wName = pureWidth * 0.25f;
float wDesc = pureWidth * 0.50f;
float wCmd = pureWidth * 0.25f;
float col1X = spacing;
float col2X = col1X + wName + spacing;
float col3X = col2X + wDesc + spacing;
auto CenterLabel = [&](const char* label, const char* tooltip, float startX, float width) {
float tx, ty;
ui->UI_CalcTextSize(label, &tx, &ty);
ui->UI_SetCursorPosX(startX + (width - tx) * 0.5f);
ui->UI_Text(label);
if (tooltip && ui->UI_IsItemHovered(SPF_HOVERED_FLAG_NONE)) {
ui->UI_SetTooltip(tooltip);
}
};
CenterLabel(GetLocStr("ui.form.action_name", "Name"), GetLocStr("ui.form.action_name_tooltip", nullptr), col1X, wName);
ui->UI_SameLine(0, 0);
CenterLabel(GetLocStr("ui.form.action_desc", "Description"), GetLocStr("ui.form.action_desc_tooltip", nullptr), col2X, wDesc);
ui->UI_SameLine(0, 0);
CenterLabel(g_ctx.newIsCycle ? GetLocStr("ui.form.cmd_1", "Cmd 1") : GetLocStr("ui.form.cmd_simple", "Command"),
GetLocStr("ui.form.cmd_tooltip", nullptr), col3X, wCmd);
ui->UI_SetCursorPosX(col1X);
ui->UI_SetNextItemWidth(wName);
ui->UI_InputText("##Name", g_ctx.newTitleBuf, sizeof(g_ctx.newTitleBuf), SPF_INPUT_TEXT_FLAG_NONE);
ui->UI_SameLine(0, spacing);
ui->UI_SetNextItemWidth(wDesc);
ui->UI_InputText("##Desc", g_ctx.newDescBuf, sizeof(g_ctx.newDescBuf), SPF_INPUT_TEXT_FLAG_NONE);
ui->UI_SameLine(0, spacing);
ui->UI_SetNextItemWidth(wCmd);
ui->UI_InputText("##Cmd1", g_ctx.newCmd1Buf, sizeof(g_ctx.newCmd1Buf), SPF_INPUT_TEXT_FLAG_NONE);
if (g_ctx.newIsCycle)
{
ui->UI_Spacing();
CenterLabel(GetLocStr("ui.form.cmd_2", "Cmd 2"), GetLocStr("ui.form.cmd_tooltip", nullptr), col3X, wCmd);
ui->UI_SetCursorPosX(col3X);
ui->UI_SetNextItemWidth(wCmd);
ui->UI_InputText("##Cmd2", g_ctx.newCmd2Buf, sizeof(g_ctx.newCmd2Buf), SPF_INPUT_TEXT_FLAG_NONE);
}
ui->UI_Spacing();
ui->UI_Spacing();
float btnWidth = 150.0f;
float totalBtnsWidth = (btnWidth * 2.0f) + spacing;
ui->UI_SetCursorPosX((windowWidth - totalBtnsWidth) * 0.5f);
char saveText[128], cancelText[128];
g_ctx.formattingAPI->Fmt_Format(saveText, sizeof(saveText), "%s %s", ICON_FA_FLOPPY_DISK, GetLocStr("ui.btn_save", "Save"));
g_ctx.formattingAPI->Fmt_Format(cancelText, sizeof(cancelText), "%s %s", ICON_FA_CIRCLE_XMARK, GetLocStr("ui.btn_cancel", "Cancel"));
if (ui->UI_ButtonEx(saveText, btnWidth, 35, GetLocStr("ui.btn_save_tooltip", "Save action"), g_ctx.styleSaveBtn))
{
if (strlen(g_ctx.newTitleBuf) > 0 && strlen(g_ctx.newCmd1Buf) > 0)
{
int maxNum = 0;
for (const auto &pair : g_ctx.userCommands)
{
int currentNum = 0;
if (sscanf(pair.first.c_str(), "cmd%d", ¤tNum) == 1)
{
if (currentNum > maxNum) maxNum = currentNum;
}
}
char id_buf[32];
g_ctx.coreAPI->formatting->Fmt_Format(id_buf, sizeof(id_buf), "cmd%d", maxNum + 1);
std::string newId = id_buf;
CommandAction action;
action.title = g_ctx.newTitleBuf;
action.description = g_ctx.newDescBuf;
action.isCycle = g_ctx.newIsCycle;
action.currentIndex = 0;
action.commands.push_back(g_ctx.newCmd1Buf);
if (g_ctx.newIsCycle && strlen(g_ctx.newCmd2Buf) > 0) action.commands.push_back(g_ctx.newCmd2Buf);
g_ctx.userCommands[newId] = action;
if (g_ctx.coreAPI->keybinds && g_ctx.keybindsHandle)
{
g_ctx.coreAPI->keybinds->Kbind_RegisterActionMetadata(
g_ctx.keybindsHandle, newId.c_str(), action.title.c_str(), action.description.c_str(), OnDynamicCommandAction, nullptr);
}
SaveCommandsToConfig();
if (g_ctx.uiAPI)
{
char msg[256];
g_ctx.coreAPI->formatting->Fmt_Format(msg, sizeof(msg), GetLocStr("ui.notif.added", "Command '%s' successfully added!"), action.title.c_str());
SPF_Notification_Params p = {SPF_NOTIFICATION_SUCCESS, msg, SPF_NOTIF_MODE_STACK, -1.0f};
g_ctx.uiAPI->UI_ShowNotification(&p);
}
g_ctx.showAddForm = false;
}
}
ui->UI_SameLine(0, spacing);
if (ui->UI_ButtonEx(cancelText, btnWidth, 35, GetLocStr("ui.btn_cancel_tooltip", "Cancel"), g_ctx.styleExitBtn))
{
g_ctx.showAddForm = false;
}
}
else
{
char addText[128];
g_ctx.formattingAPI->Fmt_Format(addText, sizeof(addText), "%s %s", ICON_FA_FILE_CIRCLE_PLUS, GetLocStr("ui.btn_add", "Add a new command"));
ui->UI_SetCursorPosY(ui->UI_GetCursorPosY() + 20);
float addBtnWidth = windowWidth * 0.35f;
ui->UI_SetCursorPosX((windowWidth - addBtnWidth) * 0.5f);
if (ui->UI_ButtonEx(addText, addBtnWidth, 35, nullptr, g_ctx.styleAddBtn))
{
g_ctx.showAddForm = true;
memset(g_ctx.newTitleBuf, 0, sizeof(g_ctx.newTitleBuf));
memset(g_ctx.newDescBuf, 0, sizeof(g_ctx.newDescBuf));
memset(g_ctx.newCmd1Buf, 0, sizeof(g_ctx.newCmd1Buf));
memset(g_ctx.newCmd2Buf, 0, sizeof(g_ctx.newCmd2Buf));
g_ctx.newIsCycle = false;
}
if (ui->UI_IsItemHovered(SPF_HOVERED_FLAG_NONE))
{
ui->UI_BeginTooltip();
ui->UI_TextColored(1.0f, 1.0f, 0.0f, 1.0f, GetLocStr("ui.btn_add_tooltip", "Add a new command hotkey"));
ui->UI_EndTooltip();
}
ui->UI_SetCursorPosY(ui->UI_GetCursorPosY() + 20);
}
ui->UI_Separator();
const char* tableTitle = GetLocStr("ui.table.header", "Your Commands:");
ui->UI_TextStyled(g_ctx.styleTableTitle, "%s", tableTitle);
ui->UI_Spacing();
if (ui->UI_BeginTable("CommandsTable", 3, (SPF_TableFlags)(SPF_TABLE_FLAG_BORDERS | SPF_TABLE_FLAG_ROW_BG), 0, 0, 0))
{
ui->UI_TableSetupColumn("Name", SPF_TABLE_COLUMN_FLAG_WIDTH_STRETCH, 0, 0);
ui->UI_TableSetupColumn("Command", SPF_TABLE_COLUMN_FLAG_WIDTH_STRETCH, 0, 0);
ui->UI_TableSetupColumn("Action", SPF_TABLE_COLUMN_FLAG_WIDTH_FIXED, 50, 0);
// Custom Header Row
ui->UI_TableNextRow(SPF_TABLE_ROW_FLAG_HEADERS, 0);
ui->UI_TableNextColumn();
ui->UI_TextStyled(g_ctx.styleTableHeader, "%s", GetLocStr("ui.table.col_name", "Name"));
ui->UI_TableNextColumn();
ui->UI_TextStyled(g_ctx.styleTableHeader, "%s", GetLocStr("ui.table.col_cmd", "Command"));
ui->UI_TableNextColumn();
ui->UI_TextStyled(g_ctx.styleTableHeader, "%s", GetLocStr("ui.table.col_action", "Action"));
std::string idToDelete = "";
for (auto const &[id, action] : g_ctx.userCommands)
{
ui->UI_TableNextRow(SPF_TABLE_ROW_FLAG_NONE, 0);
ui->UI_TableNextColumn();
ui->UI_TextStyled(g_ctx.styleTableCell, "%s", action.title.c_str());
if (strlen(action.description.c_str()) > 0)
{
if (ui->UI_IsItemHovered(SPF_HOVERED_FLAG_NONE)) ui->UI_SetTooltip(action.description.c_str());
}
ui->UI_TableNextColumn();
if (!action.commands.empty())
{
if (action.isCycle)
{
char cycle_suffix[64];
g_ctx.coreAPI->formatting->Fmt_Format(cycle_suffix, sizeof(cycle_suffix),
GetLocStr("ui.table.cycle_info", "[Cycle: %d]"), (int)action.commands.size());
char cycle_info[512];
g_ctx.coreAPI->formatting->Fmt_Format(cycle_info, sizeof(cycle_info),
"%s %s", action.commands[action.currentIndex].c_str(), cycle_suffix);
ui->UI_TextStyled(g_ctx.styleTableCell, "%s", cycle_info);
if (ui->UI_IsItemHovered(SPF_HOVERED_FLAG_NONE))
{
ui->UI_BeginTooltip();
ui->UI_Text(GetLocStr("ui.table.cycle_order", "Order of commands:"));
for (size_t i = 0; i < action.commands.size(); ++i)
{
if (i == action.currentIndex)
ui->UI_TextColored(1.0f, 0.84f, 0.0f, 1.0f, ("> " + action.commands[i]).c_str());
else
ui->UI_TextDisabled((" " + action.commands[i]).c_str());
}
ui->UI_EndTooltip();
}
}
else
{
ui->UI_TextStyled(g_ctx.styleTableCell, "%s", action.commands[0].c_str());
}
}
ui->UI_TableNextColumn();
// Button centering in cell
ui->UI_SetCursorPosX(ui->UI_GetCursorPosX() + (50.0f - 30.0f) * 0.5f);
ui->UI_PushID_Str(id.c_str());
if (ui->UI_ButtonEx(ICON_FA_TRASH_CAN, 0, 0, GetLocStr("ui.btn_delete_tooltip", "Delete this action"), g_ctx.styleDeleteBtn))
{
idToDelete = id;
}
ui->UI_PopID();
}
ui->UI_EndTable();
if (!idToDelete.empty())
{
std::string titleToLog = g_ctx.userCommands[idToDelete].title;
if (g_ctx.coreAPI->keybinds && g_ctx.keybindsHandle)
{
g_ctx.coreAPI->keybinds->Kbind_UnregisterActionMetadata(g_ctx.keybindsHandle, idToDelete.c_str());
}
g_ctx.userCommands.erase(idToDelete);
SaveCommandsToConfig();
char msg[256];
g_ctx.coreAPI->formatting->Fmt_Format(msg, sizeof(msg), GetLocStr("ui.notif.deleted", "Command '%s' deleted!"), titleToLog.c_str());
SPF_Notification_Params p = {SPF_NOTIFICATION_WARNING, msg, SPF_NOTIF_MODE_STACK, -1.0f};
ui->UI_ShowNotification(&p);
}
}
}
void OnToggleMainWindow()
{
if (g_ctx.uiAPI && g_ctx.mainWindowHandle)
{
bool isVisible = g_ctx.uiAPI->UI_IsVisible(g_ctx.mainWindowHandle);
g_ctx.uiAPI->UI_SetVisibility(g_ctx.mainWindowHandle, !isVisible);
}
}
void LoadCommands()
{
if (!g_ctx.loadAPI || !g_ctx.configHandle || !g_ctx.jsonReaderAPI)
return;
auto *cfg = g_ctx.loadAPI->config;
auto *json = g_ctx.jsonReaderAPI;
g_ctx.showNotifications = cfg->Cfg_GetBool(g_ctx.configHandle, "settings.options.show_notifications", true);
g_ctx.userCommands.clear();
const SPF_JsonValue_Handle *commands_h = cfg->Cfg_GetJsonValueHandle(g_ctx.configHandle, "settings.commands");
if (commands_h && json->Json_GetType(commands_h) == SPF_JSON_TYPE_ARRAY)
{
int commandsCount = json->Json_GetArraySize(commands_h);
for (int i = 0; i < commandsCount; ++i)
{
const SPF_JsonValue_Handle *item_h = json->Json_GetArrayItem(commands_h, i);
if (item_h && json->Json_GetType(item_h) == SPF_JSON_TYPE_OBJECT)
{
char id_buf[64] = {0}, title_buf[128] = {0}, desc_buf[256] = {0};
auto GetValStr = [&](const SPF_JsonValue_Handle *parent, const char *key, char *buf, int size)
{
const SPF_JsonValue_Handle *member = json->Json_GetMember(parent, key);
if (member && json->Json_GetType(member) == SPF_JSON_TYPE_STRING)
{
json->Json_GetString(member, buf, size);
}
};
GetValStr(item_h, "id", id_buf, sizeof(id_buf));
GetValStr(item_h, "title", title_buf, sizeof(title_buf));
GetValStr(item_h, "description", desc_buf, sizeof(desc_buf));
if (strlen(id_buf) > 0)
{
CommandAction action;
action.title = title_buf;
action.description = desc_buf;
action.currentIndex = 0;
const SPF_JsonValue_Handle *cycle_h = json->Json_GetMember(item_h, "isCycle");
action.isCycle = cycle_h ? json->Json_GetBool(cycle_h, false) : false;
const SPF_JsonValue_Handle *actions_h = json->Json_GetMember(item_h, "actions");
if (actions_h && json->Json_GetType(actions_h) == SPF_JSON_TYPE_ARRAY)
{
int actionsSize = json->Json_GetArraySize(actions_h);
for (int j = 0; j < actionsSize; ++j)
{
const SPF_JsonValue_Handle *cmd_node = json->Json_GetArrayItem(actions_h, j);
if (cmd_node && json->Json_GetType(cmd_node) == SPF_JSON_TYPE_STRING)
{
char cmd_buf[512] = {0};
json->Json_GetString(cmd_node, cmd_buf, sizeof(cmd_buf));
action.commands.push_back(cmd_buf);
}
}
}
g_ctx.userCommands[id_buf] = action;
}
}
}
}
}
void OnDynamicCommandAction(const char *action_id, void *user_data)
{
if (!action_id || !g_ctx.coreAPI || !g_ctx.gameConsoleAPI)
return;
const char *short_id = action_id;
const char *last_dot = strrchr(action_id, '.');
if (last_dot)
short_id = last_dot + 1;
auto it = g_ctx.userCommands.find(short_id);
if (it != g_ctx.userCommands.end())
{
auto &action = it->second;
if (action.commands.empty())
return;
const std::string &cmdToRun = action.commands[action.currentIndex];
g_ctx.gameConsoleAPI->GCon_ExecuteCommand(cmdToRun.c_str());
if (action.isCycle)
{
action.currentIndex = (action.currentIndex + 1) % (int)action.commands.size();
}
if (g_ctx.showNotifications && g_ctx.uiAPI)
{
char msg[256];
g_ctx.coreAPI->formatting->Fmt_Format(msg, sizeof(msg), GetLocStr("ui.notif.activated", "Activated: **%s**"),
cmdToRun.c_str());
SPF_Notification_Params p = {SPF_NOTIFICATION_INFO, msg, SPF_NOTIF_MODE_TOP, -1.0f};
g_ctx.uiAPI->UI_ShowNotification(&p);
}
}
}
void SaveCommandsToConfig()
{
if (!g_ctx.coreAPI || !g_ctx.configHandle || !g_ctx.coreAPI->formatting)
return;
auto *cfg = g_ctx.coreAPI->config;
auto *fmt = g_ctx.coreAPI->formatting;
// 1. Clear the old list before writing the new one to avoid leftovers
cfg->Cfg_RemoveKey(g_ctx.configHandle, "settings.commands");
int index = 0;
for (auto const &[id, action] : g_ctx.userCommands)
{
char path[256];
fmt->Fmt_Format(path, sizeof(path), "settings.commands.%d.id", index);
cfg->Cfg_SetString(g_ctx.configHandle, path, id.c_str());
fmt->Fmt_Format(path, sizeof(path), "settings.commands.%d.title", index);
cfg->Cfg_SetString(g_ctx.configHandle, path, action.title.c_str());
fmt->Fmt_Format(path, sizeof(path), "settings.commands.%d.description", index);
cfg->Cfg_SetString(g_ctx.configHandle, path, action.description.c_str());
fmt->Fmt_Format(path, sizeof(path), "settings.commands.%d.isCycle", index);
cfg->Cfg_SetBool(g_ctx.configHandle, path, action.isCycle);
for (size_t cmdIdx = 0; cmdIdx < action.commands.size(); ++cmdIdx)
{
fmt->Fmt_Format(path, sizeof(path), "settings.commands.%d.actions.%d", index, (int)cmdIdx);
cfg->Cfg_SetString(g_ctx.configHandle, path, action.commands[cmdIdx].c_str());
}
index++;
}
// 2. Force save changes to disk
cfg->Cfg_Save(g_ctx.configHandle);
}
extern "C"
{
/**
* @brief Exports the manifest API to the framework.
* @details This function is mandatory for the framework to properly identify and configure the plugin.
*/
SPF_PLUGIN_EXPORT bool SPF_GetManifestAPI(SPF_Manifest_API *out_api)
{
if (out_api)
{
out_api->BuildManifest = BuildManifest;
return true;
}
return false;
}
/**
* @brief Exports the plugin's main lifecycle and callback functions to the framework.
* @details This function is mandatory for the framework to interact with the plugin's lifecycle.
*/
SPF_PLUGIN_EXPORT bool SPF_GetPlugin(SPF_Plugin_Exports *exports)
{
if (exports)
{
// Connect the internal C++ functions to the C-style export struct.
exports->OnLoad = OnLoad;
exports->OnActivated = OnActivated;
exports->OnUnload = OnUnload;
exports->OnUpdate = OnUpdate;
// Optional callbacks are set to nullptr by default.
// Uncomment and assign your implementation if you use them.
// exports->OnGameWorldReady = OnGameWorldReady; // Assign your OnGameWorldReady function for game-world-dependent logic.
exports->OnRegisterUI = OnRegisterUI; // Assign your OnRegisterUI function if you have UI windows.
exports->OnSettingChanged = OnSettingChanged; // Assign your OnSettingChanged function if you implement it.
exports->OnLanguageChanged = OnLanguageChanged; // Assign your OnLanguageChanged function for auto-sync.
return true;
}
return false;
}
} // extern "C"
} // namespace SPF_ConsoleCommandHotkeys