CS2-Kit
C++23 library for CS2 Metamod:Source plugin development
Loading...
Searching...
No Matches
ChatInputCapture.cpp
Go to the documentation of this file.
1#include <CS2Kit/Core/Scheduler.hpp>
2#include <CS2Kit/Sdk/ChatInputCapture.hpp>
3
4#include <utility>
5
6namespace CS2Kit::Sdk
7{
8
9void ChatInputCapture::BeginCapture(int slot, std::string prompt, Callback callback, int timeoutMs)
10{
11 if (slot < 0 || slot >= 64 || !callback)
12 return;
13
14 CancelCapture(slot); // drops any existing prompt + scheduled timeout
15
16 Pending p{
17 .Prompt = std::move(prompt),
18 .Cb = std::move(callback),
19 .TimeoutHandle = 0,
20 };
21
22 if (timeoutMs > 0)
23 {
24 p.TimeoutHandle = Core::Scheduler::Instance().Delay(timeoutMs, [slot]() {
25 ChatInputCapture::Instance().CancelCapture(slot);
26 });
27 }
28
29 _pending[slot] = std::move(p);
30}
31
32bool ChatInputCapture::IsCapturing(int slot) const
33{
34 if (slot < 0 || slot >= 64)
35 return false;
36 return _pending[slot].has_value();
37}
38
39bool ChatInputCapture::TryConsume(int slot, std::string_view text)
40{
41 if (slot < 0 || slot >= 64)
42 return false;
43
44 auto& opt = _pending[slot];
45 if (!opt.has_value())
46 return false;
47
48 auto cb = opt->Cb;
49 auto timeoutHandle = opt->TimeoutHandle;
50
51 bool accepted = cb && cb(slot, text);
52 if (accepted)
53 {
54 if (timeoutHandle != 0)
55 Core::Scheduler::Instance().Cancel(timeoutHandle);
56 opt.reset();
57 }
58 // Either way we suppress the chat broadcast — the player typed a value, not a chat message.
59 return true;
60}
61
62void ChatInputCapture::CancelCapture(int slot)
63{
64 if (slot < 0 || slot >= 64)
65 return;
66
67 auto& opt = _pending[slot];
68 if (!opt.has_value())
69 return;
70
71 if (opt->TimeoutHandle != 0)
72 Core::Scheduler::Instance().Cancel(opt->TimeoutHandle);
73
74 opt.reset();
75}
76
77const std::string* ChatInputCapture::GetPrompt(int slot) const
78{
79 if (slot < 0 || slot >= 64)
80 return nullptr;
81 const auto& opt = _pending[slot];
82 return opt.has_value() ? &opt->Prompt : nullptr;
83}
84
85void ChatInputCapture::OnPlayerDisconnect(int slot)
86{
87 CancelCapture(slot);
88}
89
90} // namespace CS2Kit::Sdk