add unsub and sr

This commit is contained in:
Green Sky 2024-10-24 12:30:37 +02:00
parent 7cd6a2b0de
commit 050f7abf89
No known key found for this signature in database
4 changed files with 44 additions and 2 deletions

View File

@ -3,6 +3,7 @@
#include <tox/tox_events.h>
#include <string_view>
#include <vector>
// defines the full event interface for tox event subscription
struct ToxEventI {
@ -63,12 +64,41 @@ struct ToxEventI {
};
// defines the interface where to subscribe
// tox event enum is defined differently than what we expect for utils
struct ToxEventProviderI {
static constexpr const char* version {"2"};
using enumType = Tox_Event_Type;
// TODO: keep in sync with utils
struct SubscriptionReference {
ToxEventProviderI& _ep;
ToxEventI* _object {nullptr};
std::vector<enumType> _subs;
SubscriptionReference(ToxEventProviderI& ep, ToxEventI* object) :
_ep(ep), _object(object)
{
}
~SubscriptionReference(void) {
for (const enumType et : _subs) {
_ep.unsubscribe(_object, et);
}
}
SubscriptionReference& subscribe(const enumType event_type) {
_ep.subscribe(_object, event_type);
_subs.push_back(event_type);
return *this;
}
};
virtual ~ToxEventProviderI(void) {}
// TODO: unsub
virtual void subscribe(ToxEventI* object, const Tox_Event_Type event_type) = 0;
virtual void unsubscribe(ToxEventI* object, const Tox_Event_Type event_type) = 0;
};
constexpr Tox_Event_Type tox_event_from_string(const std::string_view str) {

View File

@ -176,7 +176,8 @@ bool ToxEventLogger::onToxEvent(const Tox_Event_Group_Custom_Packet*) {
}
bool ToxEventLogger::onToxEvent(const Tox_Event_Group_Custom_Private_Packet*) {
_out << "TOX_EVENT: " << tox_event_to_string(TOX_EVENT_GROUP_CUSTOM_PRIVATE_PACKET) << "\n";
// too spammy for now
//_out << "TOX_EVENT: " << tox_event_to_string(TOX_EVENT_GROUP_CUSTOM_PRIVATE_PACKET) << "\n";
return false;
}

View File

@ -77,3 +77,13 @@ void ToxEventProviderBase::subscribe(ToxEventI* object, const Tox_Event_Type eve
_subscribers.at(event_type).push_back(object);
}
void ToxEventProviderBase::unsubscribe(ToxEventI* object, const Tox_Event_Type event_type) {
auto& o_vec = _subscribers.at(static_cast<size_t>(event_type));
for (auto o_it = o_vec.cbegin(); o_it != o_vec.cend(); o_it++) {
if (*o_it == object) {
o_vec.erase(o_it);
break;
}
}
}

View File

@ -12,6 +12,7 @@ struct ToxEventProviderBase : public ToxEventProviderI {
public: // event provider
virtual void subscribe(ToxEventI* object, const Tox_Event_Type event_type) override;
virtual void unsubscribe(ToxEventI* object, const Tox_Event_Type event_type) override;
protected:
std::array<std::vector<ToxEventI*>, 256> _subscribers; // rn 39 event types