VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
ChatInput.cpp
Go to the documentation of this file.
3#include <utility>
4
5namespace VoltMod
6{
7
9 : _scheduler(scheduler),
10 // Slot changes cancel captures so a new occupant cannot inherit the previous occupant's prompt.
11 _slotListener(slots.Changed += [this](int slot) { CancelCapture(slot); })
12{}
13
15{
16 if (!IsValidSlot(slot) || !callback)
17 {
18 return;
19 }
20
22
23 Pending pending{.Prompt = std::move(prompt), .Callback = std::move(callback)};
24 if (timeoutMs > 0)
25 {
26 pending.Timeout = _scheduler.Delay(timeoutMs, [this, slot] { CancelCapture(slot); });
27 }
28
29 _pending[slot] = std::move(pending);
30}
31
33{
34 if (!IsValidSlot(slot))
35 {
36 return false;
37 }
38 return _pending[slot].has_value();
39}
40
41bool ChatInput::TryConsume(int slot, std::string_view text)
42{
43 if (!IsValidSlot(slot))
44 {
45 return false;
46 }
47
48 auto& opt = _pending[slot];
49 if (!opt.has_value())
50 {
51 return false;
52 }
53
54 // Move the capture out before the callback so redraws see no prompt and callbacks can start another capture.
55 Pending pending = std::move(*opt);
56 opt.reset();
57
58 const bool accepted = pending.Callback(slot, text);
59
60 // Restore rejected input unless the callback already installed a replacement capture.
61 if (!accepted && !_pending[slot].has_value())
62 {
63 _pending[slot] = std::move(pending);
64 }
65
66 // Captured input is never forwarded as chat, even when rejected.
67 return true;
68}
69
71{
72 if (!IsValidSlot(slot))
73 {
74 return;
75 }
76
77 _pending[slot].reset();
78}
79
80std::optional<std::string> ChatInput::GetPrompt(int slot) const
81{
82 if (!IsValidSlot(slot))
83 {
84 return std::nullopt;
85 }
86 const auto& opt = _pending[slot];
87 if (!opt)
88 {
89 return std::nullopt;
90 }
91 return opt->Prompt;
92}
93
94} // namespace VoltMod
std::function< bool(int slot, std::string_view text)> Callback
Definition ChatInput.hpp:35
void CancelCapture(int slot)
Definition ChatInput.cpp:70
bool TryConsume(int slot, std::string_view text)
Definition ChatInput.cpp:41
ChatInput(Scheduler &scheduler, SlotEvents &slots)
Definition ChatInput.cpp:8
void BeginCapture(int slot, std::string prompt, Callback callback, int timeoutMs=60000)
Definition ChatInput.cpp:14
std::optional< std::string > GetPrompt(int slot) const
Definition ChatInput.cpp:80
bool IsCapturing(int slot) const
Definition ChatInput.cpp:32
One-shot delays and repeating timers, run on the game thread.
Definition Scheduler.hpp:18
Subscription Delay(int64_t delayMs, std::function< void()> callback)
Definition Scheduler.cpp:20
"The occupant of this slot changed" - raised by PlayerManager, consumed below it.
static std::string ReadFile(const std::filesystem::path &path)
Definition Loader.cpp:56
constexpr bool IsValidSlot(int slot)
Definition Slot.hpp:13